# x402-avm documentation (full text)
> Pay-per-call MCP tools and HTTP APIs settled on Algorand with the x402 protocol: ai-economy-sdk, x402-algorand and x402-avm-js.
---
# x402-avm
> Let AI agents and apps pay for your tools and APIs per call, in ALGO or USDC, with no accounts and no API keys.
An AI agent that finds a useful tool can't use it if the tool wants a sign-up form, a credit card and an API key. And a tool worth a tenth of a cent per call can't be sold on card rails at all.
x402-avm fixes both. Your server answers a call with **HTTP 402 Payment Required** and a price. The caller's wallet pays it on Algorand and retries, and the call goes through. There are no accounts, no keys to issue and no invoices. Payment and result come back in the same request, in about three seconds.
## What you can build
- [Sell an MCP tool](https://x402-avm.github.io/build/sell-mcp-tools.md)
Put a price on each tool of a FastMCP server. Any MCP client with a wallet can call it.
- [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api.md)
Charge per request on a FastAPI or Flask route, using the official x402 SDK.
- [Let your agent pay](https://x402-avm.github.io/build/ai-agents.md)
Give an agent a wallet and a budget. It pays for tools on its own and refuses anything over its limits.
## Why it works for both sides
**For the seller,** a price is one line of code: `prices={"summarize": 5000}`. Payments land directly in your Algorand account, in ALGO or USDC, with nothing in between taking a cut. The payment is checked before your tool runs.
**For the buyer,** you pay only when the call succeeds. The server checks the payment, runs the tool, and submits the payment to the chain only if the tool returned a result. If the tool fails, nothing is charged. The seller pays the network fee, so the buyer's balance goes down by exactly the price shown.
**For whoever owns the agent,** spend limits are checked before anything is signed: a maximum per call, and which assets, networks and recipients may be paid. Both clients apply a limit even if you set none, refusing anything over 1 ALGO or 1 USDC per call until you raise it.
## How it looks in code
```python
from fastmcp import FastMCP
from ai_economy_sdk import PaymentGate
mcp = FastMCP("Summarizer")
@mcp.tool()
def summarize(text: str) -> str:
return text[:200]
gate = PaymentGate(
signer=signer, # your server's key; it pays the network fee
network="testnet",
pay_to=my_address, # where the money goes
prices={"summarize": 5000}, # 0.005 ALGO per call
)
app = gate.wrap(mcp, transport="streamable-http")
```
```python
from ai_economy_sdk import paid_mcp_session
async with paid_mcp_session(url, wallet_key, "testnet") as session:
result = await session.call_tool("summarize", {"text": article})
```
```ts
import { algodClient, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
const res = await fetch(url);
if (res.status === 402) {
const required = decodePaymentRequired(res.headers.get('PAYMENT-REQUIRED')!);
const payment = await payForRequirement(required, address, algodClient('testnet'),
(txns, idx) => wallet.signTransactions(txns, idx));
await fetch(url, { headers: { 'PAYMENT-SIGNATURE': payment } });
}
```
The [Quickstart](https://x402-avm.github.io/quickstart) runs a complete version on your machine in about five minutes, with test money.
## What's in the box
x402-avm is three open-source packages. Most projects need only one.
| Package | Install | Use it to |
|---|---|---|
| [`ai-economy-sdk`](https://x402-avm.github.io/build/sell-mcp-tools) | `pip install ai-economy-sdk` | Sell MCP tools, and pay for them from Python and agents |
| [`x402-algorand`](https://x402-avm.github.io/build/paywall-http-api) | `pip install x402-algorand` | Add Algorand to the official [x402](https://www.x402.org) SDK, for HTTP APIs and facilitators |
| [`x402-avm-js`](https://x402-avm.github.io/build/pay-from-browser) | `npm install x402-avm-js algosdk` | Pay from a browser wallet or Node.js |
All three follow the open x402 standard and the official [Algorand `exact` scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme), so they work with any other x402 software on Algorand.
> **Note:**
x402-avm is an independent open-source project. It is not affiliated with GoPlausible's x402-avm packages, from which x402-algorand is derived (see [NOTICE](https://github.com/x402-avm/x402-algorand/blob/main/NOTICE)).
---
# Quickstart
> In about five minutes, run a paid MCP tool on a local Algorand network and pay for it from Python and from JavaScript.
In five minutes you will have an MCP server whose `echo` tool costs 5,000 microALGO per call, a Python client that pays for it, and a JavaScript client that pays an HTTP endpoint. Everything runs on LocalNet, a private Algorand network on your machine, so no real money is involved.
## Prerequisites
- Python 3.10 or newer
- Node.js 20 or newer (for the JavaScript step)
- [AlgoKit](https://github.com/algorandfoundation/algokit-cli) and Docker, to run LocalNet
### Start LocalNet
```bash
algokit localnet start
```
algod listens on `http://localhost:4001` and the indexer on `http://localhost:8980`. The examples fund new accounts from LocalNet's built-in dispenser, so you need no keys.
### Get the examples
```bash
git clone https://github.com/x402-avm/examples.git
cd examples
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
npm install
```
This installs `ai-economy-sdk` 0.5.1, `x402-algorand` 0.3.0 and `x402-avm-js` 0.4.1 with their dependencies.
### Run the paid MCP server
```python
"""FastMCP server payment-gated with ai-economy-sdk on Algorand LocalNet.
Runs a FastMCP server with a single paid 'echo' tool priced at 5,000 microALGO.
Funds a server account from LocalNet dispenser and serves Streamable HTTP (/mcp) on port 9201.
How to run:
python localnet/quickstart_server.py
What it prints:
pay_to: <44-character Algorand address>
"""
import sys
from pathlib import Path
# Add current directory to path so _localnet can be imported
sys.path.insert(0, str(Path(__file__).resolve().parent))
import uvicorn
from fastmcp import FastMCP
from ai_economy_sdk import DefaultAvmSigner, PaymentGate
from _localnet import ALGOD, new_funded_account
SERVER_PORT = 9201
TOOL_PRICE_MICROALGO = 5000
def main() -> None:
server_sk, server_addr = new_funded_account(algos=10)
print(f"pay_to: {server_addr}", flush=True)
mcp = FastMCP("QuickstartServer")
@mcp.tool()
def echo(text: str) -> str:
"""Echo back input text."""
return f"echo: {text}"
gate = PaymentGate(
signer=DefaultAvmSigner(server_sk, algod_client=ALGOD),
network="localnet",
pay_to=server_addr,
asset_id=0,
prices={"echo": TOOL_PRICE_MICROALGO},
)
app = gate.wrap(mcp, transport="streamable-http")
uvicorn.run(app, host="127.0.0.1", port=SERVER_PORT, log_level="warning")
if __name__ == "__main__":
main()
```
Source: [examples/localnet/quickstart_server.py](https://github.com/x402-avm/examples/blob/main/localnet/quickstart_server.py)
```bash
python localnet/quickstart_server.py
```
```text
pay_to: GL4IOGTXMILQYI2UOSYORNW4LHB4SULTDRYCA4AMFQUGKTEYN3ZUDQG6XE
```
That address receives the payments; it is new on every run. The server answers MCP calls at `http://127.0.0.1:9201/mcp`.
### Pay for a call from Python
In a second terminal:
```python
"""Paid MCP client session using ai-economy-sdk on Algorand LocalNet.
Funds a fresh buyer account via the LocalNet dispenser, establishes a paid MCP
session to http://127.0.0.1:9201/mcp, calls the 'echo' tool, and verifies the on-chain
charge.
How to run:
1. Start quickstart_server.py in the background
2. python localnet/quickstart_client.py
What it prints:
Result: echo: hello world
Balance drop: 5000 microALGO
"""
import asyncio
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from ai_economy_sdk import AIEconomyError, paid_mcp_session
from _localnet import ALGOD, new_funded_account
SERVER_URL = "http://127.0.0.1:9201/mcp"
async def main() -> None:
buyer_sk, buyer_addr = new_funded_account(algos=5)
before_balance = ALGOD.account_info(buyer_addr)["amount"]
try:
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
result = await session.call_tool("echo", {"text": "hello world"})
print(f"Result: {result.content[0].text}")
except AIEconomyError as err: # spend controls refused the price (SpendLimitExceededError, 0.5.1+), settlement failed, bad config ...
raise SystemExit(f"Paid call failed: {err}")
after_balance = ALGOD.account_info(buyer_addr)["amount"]
drop = before_balance - after_balance
print(f"Balance drop: {drop} microALGO")
if __name__ == "__main__":
asyncio.run(main())
```
Source: [examples/localnet/quickstart_client.py](https://github.com/x402-avm/examples/blob/main/localnet/quickstart_client.py)
```bash
python localnet/quickstart_client.py
```
```text
Result: echo: hello world
Balance drop: 5000 microALGO
```
The buyer paid exactly the price. The server paid the 2,000 microALGO network fee.
### Pay from JavaScript
`x402-avm-js` pays any x402 endpoint on Algorand. Start a small FastAPI paywall (`GET /paid` on port 9221, 5,000 microALGO), then run the client:
```bash
python localnet/server_for_js.py
```
```bash
node localnet/js_pay.mjs
```
```javascript
/**
* Pay an x402 paywall from JavaScript on LocalNet (start server_for_js.py first, port 9221).
*
* node localnet/js_pay.mjs
*
* Fetch -> 402 -> decodePaymentRequired -> payForRequirement (with explicit spend controls)
* -> retry with PAYMENT-SIGNATURE -> check the exact 5000 microALGO balance drop.
*/
import { SpendLimitExceededError, X402AvmError, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
import { algod, newFundedAccount, signerFor } from './_localnet.mjs';
const URL = 'http://127.0.0.1:9221/paid';
const balance = async (addr) => (await algod.accountInformation(addr).do()).amount;
const buyer = await newFundedAccount();
const before = await balance(buyer.address);
const res402 = await fetch(URL);
if (res402.status !== 402) throw new Error(`Expected 402, got ${res402.status}`);
const challenge = decodePaymentRequired(res402.headers.get('payment-required'));
const [req] = challenge.accepts;
console.log(`Server asks ${req.amount} units of asset ${req.asset} -> ${req.payTo}`);
// Spend controls are checked before anything is signed. The default cap is 1,000,000 base units;
// here we tighten it and pin the asset, network and recipient.
const controls = {
maxAmount: 10_000n,
allowedAssets: ['0'],
allowedNetworks: [req.network],
allowedPayTo: [req.payTo],
};
try {
const signature = await payForRequirement(challenge, buyer.address, algod, signerFor(buyer.sk), controls);
const paid = await fetch(URL, { headers: { 'payment-signature': signature } });
console.log(`Paid response: ${paid.status}`, await paid.json());
} catch (err) {
if (err instanceof SpendLimitExceededError) throw new Error(`Refused to overpay: ${err.message}`);
if (err instanceof X402AvmError) throw new Error(`x402 error ${err.code}: ${err.message}`);
throw err;
}
const drop = before - (await balance(buyer.address));
console.log(`Balance drop: ${drop} microALGO`);
if (drop !== 5000n) throw new Error(`Expected a drop of 5000 microALGO, got ${drop}`);
// A 50,000 microALGO demand would exceed the 10,000 cap and is refused without signing.
const greedy = { ...challenge, accepts: [{ ...req, amount: '50000' }] };
await payForRequirement(greedy, buyer.address, algod, signerFor(buyer.sk), controls).then(
() => { throw new Error('Spend cap did not trigger'); },
(err) => console.log(`Over-cap request rejected: ${err.constructor.name}`),
);
```
Source: [examples/localnet/js_pay.mjs](https://github.com/x402-avm/examples/blob/main/localnet/js_pay.mjs)
```text
Server asks 5000 units of asset 0 -> UR633JM3BS4KZMBELB7COIFAN65JOL5JLSDMHKT34FX4NXHJATFOFTQRWA
Paid response: 200 {
status: 'ok',
data: 'Access granted to premium resource',
txid: 'B3UQGJQZVSHVNNTS6TZ7H4ONG6DRJVTBBRI2V6CDTM45MLFBYLZA',
payer: 'PVGZFLS3MLQRRH2QJMRQUMH75ZOQQYNSPKFKXFN2URPIJ4MSTFBAZI6WB4'
}
Balance drop: 5000 microALGO
Over-cap request rejected: SpendLimitExceededError
```
The last line is a spend limit at work: the script caps payments at 10,000 microALGO, so a 50,000 microALGO demand is refused before the wallet signs anything.
To run every LocalNet example in order, with the servers they need started and stopped for you:
```bash
bash scripts/run_all_localnet.sh
```
## What just happened
Your client called `echo`, the server answered `402 Payment Required` with a price, the client signed a payment for exactly that price and retried, and the server ran the tool and then settled the payment on chain. [How it works](https://x402-avm.github.io/how-it-works) walks through each step.
## Next
- [Sell your own MCP tools](https://x402-avm.github.io/build/sell-mcp-tools.md)
Price tools by input, serve them, and test with a paying client.
- [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api.md)
Charge per request on FastAPI or Flask.
- [Let your agent pay](https://x402-avm.github.io/build/ai-agents.md)
A budget wallet, spend limits and price checks.
- [Move to TestNet](https://x402-avm.github.io/production/networks.md#testnet)
Real transactions with free TestNet ALGO.
---
# How it works
> What happens between a 402 and a result: the payment flow, the two-transaction group, settle-on-success, replay protection, identity proofs and passes.
Read this page once and the rest of the docs will make sense: every Build page assumes the flow below and links back here instead of repeating it.
## The x402 flow
[x402](https://www.x402.org) sells a resource per request with HTTP status `402 Payment Required`. For an MCP server wrapped with `PaymentGate`, a tool call goes like this:
1. The client sends a JSON-RPC `tools/call`: `POST /mcp` on the Streamable HTTP transport, or `POST /messages/?session_id=...` after `GET /sse` on the legacy SSE transport. Connecting, initializing and listing tools are free.
2. The gate prices the call (tool, arguments, caller) and answers `402` with a `PAYMENT-REQUIRED` header: scheme, network, asset, amount, recipient (`payTo`) and fee payer.
3. The client builds and signs a payment that matches.
4. The client retries with the signed transactions in a `PAYMENT-SIGNATURE` header.
5. The server verifies the payment, reserves it against replay, runs the tool, settles on chain if the tool succeeded, and returns the result with a `PAYMENT-RESPONSE` header.
A call priced at 0 (free, or covered by a [pass](#passes)) goes straight through. HTTP APIs protected with `x402-algorand` follow the same steps for an ordinary request. Every header, decoded field by field: [HTTP 402 reference](https://x402-avm.github.io/reference/protocol/http-402).
```mermaid
sequenceDiagram
autonumber
actor Client
participant Gate as Resource server (PaymentGate)
participant Fac as Facilitator (in process)
participant Algod as Algorand node (algod)
Client->>Gate: Tool call (POST /mcp, or POST /messages/ on SSE)
Gate-->>Client: 402 + PAYMENT-REQUIRED
Note over Client: Build the 2-transaction group, sign transaction 1
Client->>Gate: Retry with PAYMENT-SIGNATURE
Gate->>Fac: verify(payload, requirements)
Fac->>Algod: simulate the group
Algod-->>Fac: Simulation result
Fac-->>Gate: Valid
Note over Gate: Reserve replay key, run the tool
alt Tool succeeded
Gate->>Fac: settle(payload, requirements)
Fac->>Algod: Submit the signed group
Algod-->>Fac: Confirmed
Gate-->>Client: Tool result + PAYMENT-RESPONSE
else Tool raised or returned isError
Note over Gate: Release the reservation, nothing submitted
Gate-->>Client: MCP error result
else Settlement failed
Note over Gate: Release the reservation
Gate-->>Client: SettlementError "payment settlement failed: ..."
end
```
The facilitator is the part that verifies and settles. `PaymentGate` runs one in the same process (an `x402Facilitator` with the Algorand scheme and your signer). With `x402-algorand` you can also [run it separately](https://x402-avm.github.io/build/facilitator).
## The two-transaction atomic group
When the server sponsors fees (it advertises `extra.feePayer`, which `PaymentGate` always does), the payment is an [atomic group](https://x402-avm.github.io/resources/glossary#atomic-group) of two transactions, as the official [Algorand exact scheme](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_algo.md) specifies:
| Index | Type | Sender | Receiver | Amount | Fee | Signed by |
|---|---|---|---|---|---|---|
| 0 | `pay` | Fee payer | Fee payer | 0 | 2,000 microALGO | Server (fee payer), at settlement |
| 1 | `pay` (ALGO) or `axfer` (ASA) | Buyer | `payTo` | The price | 0 | Buyer |
Algorand pools fees within a group. The minimum is 1,000 microALGO per transaction, so transaction 0 pays 2,000 for both and transaction 1 pays nothing. The buyer's balance drops by exactly the price, even in USDC, because network fees are always paid in ALGO and the fee payer pays them.
The buyer signs only transaction 1. Because the group is atomic, the server cannot submit its fee transaction without the buyer's payment, and the payment cannot go through without the fee transaction.
Without a fee payer, the payment is one transaction signed by the buyer, who pays the normal 1,000 microALGO fee.
ALGO prices must cover the 2,000 microALGO the server pays per call; `PaymentGate` enforces a [fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor).
## Settle-on-success
Most payment flows charge first and refund on failure. `PaymentGate` does it the other way round:
1. **Verify.** The facilitator checks the group against the requirement (scheme, network, recipient, asset, exact amount, group id, signature, fee payer rules) and simulates it on algod with `allow_empty_signatures=True`. Nothing is broadcast.
2. **Reserve and run.** The payment is reserved against replay and the signed group is held while the tool runs.
3. **On failure, discard.** If the tool raises or returns an MCP error result (`isError`), the reservation is released and the group is never submitted. The buyer is not charged.
4. **On success, settle.** The server signs the fee payer transaction, submits the group and waits for confirmation. If that fails (the transactions expired, the fee payer is out of ALGO), the client gets `SettlementError("payment settlement failed: ")`, a FastMCP `ToolError`, instead of the result, and is not charged.
5. **Respond.** The replay entry is committed and the result returned.
A reservation that is never settled or released is released after 300 seconds.
The example [localnet/failed_call_not_charged.py](https://github.com/x402-avm/examples/blob/main/localnet/failed_call_not_charged.py) calls a tool that always raises:
```text
Tool call returned (isError=True): Error calling tool 'fail_tool': Deliberate tool failure: computation error
Balance drop: 0 microALGO
```
## Replay protection
A signed payment buys one call. `PaymentGate` hashes each payment payload with SHA-256 and tracks the hash in a replay store:
| Operation | When | Effect |
|---|---|---|
| `reserve(hash)` | After verification, before the tool runs | Fails if the hash is already reserved or settled; the request gets `402` with `{"error": "Replay detected"}` and the tool does not run. |
| `commit(hash)` | After settlement succeeds | Marks the hash settled. |
| `release(hash)` | After a tool or settlement failure | Deletes the reservation, so the buyer can pay again. |
The default store lives in one process's memory. With several workers, [share it in SQLite](https://x402-avm.github.io/production/security#replay-store).
## Identity proofs
A caller can prove which Algorand address it controls without paying. Servers use the address for passes, subscriptions, bulk discounts and per-caller prices. Two formats exist:
- **`X-Identity-Txn` (recommended).** A signed payment transaction that can never execute: a 0-amount self-payment with fee 0, an expired validity window and the note `x402-identity::`. It is bound to one network by its genesis hash, and browser wallets can sign it because it is an ordinary transaction.
- **Legacy `x-sender-*` headers.** An Ed25519 signature over `x402-identity::`. `paid_mcp_session` sends these on every request by default.
Proofs more than 120 seconds from the server's clock are rejected. Building and verifying them: [Identity](https://x402-avm.github.io/build/identity).
## Passes
A pass gives a buyer free calls for a period (30 days by default) after one on-chain purchase. It is an ordinary payment from the buyer to the vendor's `pay_to` address with the note:
```text
x402-pass:
```
for example `x402-pass:listing:echo-1` or `x402-pass:vendor:acme-corp`. A gate configured with `pass_scopes={scope: price}` looks up the caller's recent payments on the indexer. If it finds an unexpired pass for one of its scopes, of at least that scope's price, the call costs 0 and no challenge is sent. Positive lookups are cached for 20 seconds. The caller is identified by its identity proof. Setting it up: [Pricing and passes](https://x402-avm.github.io/build/pricing#passes).
## Network binding
Every Algorand transaction carries its network's genesis hash, so a payment signed on TestNet cannot be used on MainNet: the client refuses to build it and the facilitator rejects it. Network ids and how they are derived: [Networks](https://x402-avm.github.io/production/networks).
---
# Sell MCP tools
> Put a price on the tools of a FastMCP server, serve it, and confirm a paid call lands on chain.
By the end of this page you will have a FastMCP server whose `summarize` tool charges by input length, and a client that pays for a call and finds the payment on the indexer. Any MCP client with an Algorand wallet can then call your tools, with no accounts or API keys.
```bash
pip install ai-economy-sdk==0.5.1
```
You need an Algorand account for the server: it receives payments and pays the network fee of each call. The code below runs on [LocalNet](https://x402-avm.github.io/production/networks#localnet), where the examples fund accounts for you.
## Write the server
```python
"""Paid MCP tool server tutorial.
Starts a FastMCP server offering a paid summarize tool, protected by PaymentGate
on port 9231 with dynamic length-based pricing (1,000 microALGO per 100 characters,
minimum 3,000 microALGO).
How to run:
python localnet/paid_mcp_tool/server.py
Expected output:
Server starting on http://127.0.0.1:9231/mcp
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import uvicorn
from ai_economy_sdk import DefaultAvmSigner, PaymentGate
from fastmcp import FastMCP
from _localnet import ALGOD, new_funded_account
def price_summarize(tool: str, args: dict, sender: str | None = None) -> int:
"""Calculate price based on text length: 1,000 microALGO per 100 chars, min 3,000."""
if tool == "summarize":
text = args.get("text", "")
units = (len(text) + 99) // 100
return max(3000, units * 1000)
return 3000
def create_app():
# Fund server account on LocalNet
server_sk, server_addr = new_funded_account(algos=5)
signer = DefaultAvmSigner(server_sk, algod_client=ALGOD)
mcp = FastMCP("Summarizer")
@mcp.tool()
def summarize(text: str) -> str:
"""Summarize text by extracting the primary sentences."""
sentences = [s.strip() for s in text.split(".") if s.strip()]
if len(sentences) <= 2:
return text.strip()
return sentences[0] + ". " + sentences[1] + "."
gate = PaymentGate(
signer=signer,
network="localnet",
pay_to=server_addr,
asset_id=0,
prices=price_summarize,
)
return gate.wrap(mcp, transport="streamable-http")
if __name__ == "__main__":
app = create_app()
print("Server starting on http://127.0.0.1:9231/mcp ...", flush=True)
uvicorn.run(app, host="127.0.0.1", port=9231, log_level="warning")
```
Source: [examples/localnet/paid_mcp_tool/server.py](https://github.com/x402-avm/examples/blob/main/localnet/paid_mcp_tool/server.py)
`summarize` costs 1,000 microALGO per started block of 100 characters, with a minimum of 3,000 microALGO. The pricing function runs before the `402` is sent, so the caller is quoted the exact price for its input. The minimum stays above the 2,000 microALGO fee the server pays per call; see [the fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor).
## Pay for a call
```python
"""Paid MCP tool client tutorial.
Connects to the paid summarize tool on port 9231 via paid_mcp_session, pays the
x402 payment on Algorand LocalNet, and confirms the transaction via Indexer.
How to run:
python localnet/paid_mcp_tool/client.py
Expected output:
Calling summarize tool...
Result: Algorand is a pure proof-of-stake blockchain. It achieves immediate finality without forks.
Price paid: 3000 microALGO
Confirmed TxID: (confirmed at round )
"""
import asyncio
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from ai_economy_sdk import AIEconomyError, paid_mcp_session
from algosdk.v2client import indexer
from _localnet import ALGOD, ALGOD_TOKEN, ALGOD_URL, INDEXER_URL, new_funded_account
INDEXER = indexer.IndexerClient("", INDEXER_URL)
async def main():
print("Generating funded buyer account on LocalNet...")
buyer_sk, buyer_addr = new_funded_account(algos=5)
test_text = (
"Algorand is a pure proof-of-stake blockchain. "
"It achieves immediate finality without forks. "
"Smart contracts run directly on the AVM with predictable micro-cent fees."
)
start_round = ALGOD.status()["last-round"]
print("Opening paid MCP session to http://127.0.0.1:9231/mcp ...")
async with paid_mcp_session(
"http://127.0.0.1:9231/mcp", buyer_sk, "localnet", algod_url=ALGOD_URL, algod_token=ALGOD_TOKEN
) as session:
print("Calling summarize tool...")
res = await session.call_tool("summarize", {"text": test_text})
print(f"Result: {res.content[0].text}")
# Look up payment transaction on Indexer by buyer address
# Give indexer up to 5 seconds to ingest
found_txn = None
for _ in range(10):
time.sleep(0.5)
resp = INDEXER.search_transactions(address=buyer_addr, txn_type="pay", min_round=start_round)
txns = resp.get("transactions", [])
if txns:
found_txn = txns[0]
break
if not found_txn:
raise RuntimeError(f"Payment transaction for {buyer_addr} not found in indexer")
txid = found_txn["id"]
price = found_txn["payment-transaction"]["amount"]
confirmed_round = found_txn.get("confirmed-round")
print(f"Price paid: {price} microALGO")
print(f"Confirmed TxID: {txid} (confirmed at round {confirmed_round})")
if __name__ == "__main__":
asyncio.run(main())
```
Source: [examples/localnet/paid_mcp_tool/client.py](https://github.com/x402-avm/examples/blob/main/localnet/paid_mcp_tool/client.py)
```bash
python localnet/paid_mcp_tool/server.py
```
In a second terminal:
```bash
python localnet/paid_mcp_tool/client.py
```
```text
Generating funded buyer account on LocalNet...
Opening paid MCP session to http://127.0.0.1:9231/mcp ...
Calling summarize tool...
Result: Algorand is a pure proof-of-stake blockchain. It achieves immediate finality without forks.
Price paid: 3000 microALGO
Confirmed TxID: 6IFBD2KO35L4ZYXEHIW4TXYDQXCGWZL663TEWIIYYD3YUEKOGEDQ (confirmed at round 1767)
```
The 153-character input is two blocks (2,000 microALGO), below the minimum, so the call cost 3,000. The transaction id and round differ on every run. The client side is covered in [Pay from Python](https://x402-avm.github.io/build/pay-from-python).
## Configure PaymentGate
`PaymentGate` intercepts each `tools/call`. When the call has a price above 0 and no valid payment, it answers `402`.
| Parameter | Default | Description |
|---|---|---|
| `signer` | required | Signer for the fee payer account, usually `DefaultAvmSigner(private_key, algod_client=...)`. Its algod client is also used to resolve `"localnet"`. |
| `network` | required | `"mainnet"`, `"testnet"`, `"localnet"` or a CAIP-2 id. |
| `pay_to` | required | Address that receives payments. |
| `asset_id` | `0` | `0` for ALGO, or an ASA id such as [USDC](https://x402-avm.github.io/production/mainnet#accept-usdc). |
| `prices` | `None` | `dict` of tool name to price, or a callable `(tool, args, sender) -> int`. |
| `default_price` | `0` | Price for tools not in `prices`. 0 means free. |
| `chain` | `None` | `ChainReader` for indexer lookups (passes, subscriptions, bulk discounts). |
| `pass_scopes`, `pass_days` | `None`, `30.0` | [Passes](https://x402-avm.github.io/build/pricing#passes). |
| `subscription_asset_id`, `subscription_max_age_days`, `subscription_issuer` | `None`, `30.0`, `None` | [Subscription tokens](https://x402-avm.github.io/build/pricing#subscription-tokens). |
| `bulk_threshold`, `bulk_discount`, `bulk_days` | `None`, `0.5`, `30` | [Bulk discounts](https://x402-avm.github.io/build/pricing#bulk-discounts). |
| `min_fee_per_txn` | `1000` | Network minimum fee; the fee floor is twice this. |
| `allow_loss` | `False` | Allow ALGO prices at or below the fee floor. |
| `replay_db` | `None` | SQLite path for a [replay store shared by several workers](https://x402-avm.github.io/production/security#replay-store). |
| `replay_cache_size` | `5000` | Documented as the in-memory replay cache size; the replay store does not read it. |
Every parameter, with types: [`PaymentGate` reference](https://x402-avm.github.io/reference/python/ai-economy-sdk/payment-gate).
## Choose a transport
`gate.wrap(mcp, transport=...)` returns an ASGI app. Serve it with any ASGI server, for example `uvicorn.run(app, host="127.0.0.1", port=9201)`.
| `transport=` | Endpoints | Use it for |
|---|---|---|
| `"streamable-http"` (alias `"http"`) | `POST /mcp` | Recommended. Stateless by default; pass `stateless_http=False` for MCP sessions. |
| `"sse"` | `GET /sse`, `POST /messages/` | MCP clients that only speak the legacy HTTP+SSE transport. |
Always pass `transport=`. Without it, `wrap()` still serves SSE, as 0.4 did, and emits a `FutureWarning`: the default will change to `"streamable-http"` in a future release. `path=` changes the endpoint path, and other keyword arguments go to `FastMCP.http_app()`.
> **Warning:**
ai-economy-sdk 0.4.x served priced tools without payment on Streamable HTTP and on SSE apps mounted under a path prefix. Use 0.5.0 or later. See [Security](https://x402-avm.github.io/production/security#unpaid-tool-calls).
### What wrap() adds
1. **The gate's ASGI middleware.** It inspects the JSON-RPC body of every HTTP `POST`, whatever its path or transport. Other requests and non-tool messages (`initialize`, `tools/list`) pass through. For a `tools/call` it reads the caller's identity, computes the price, and passes the call through (price 0), answers `402`, or verifies the attached payment and reserves it. JSON-RPC batches containing a `tools/call` are rejected with HTTP `400`.
2. **`SettleOnSuccessMiddleware`**, a FastMCP middleware. After the tool returns, it [settles or releases](https://x402-avm.github.io/how-it-works#settle-on-success) the payment. It refuses, with `PaymentRequiredError`, any priced call that did not pass through the gate, so a transport the gate does not wrap cannot serve paid tools for free.
### Mount the app yourself
To mount the MCP app inside a larger Starlette or FastAPI app, install both layers. Without `SettleOnSuccessMiddleware` the gate refuses priced calls with HTTP `500`.
```python
from ai_economy_sdk import SettleOnSuccessMiddleware
mcp.add_middleware(SettleOnSuccessMiddleware(gate))
app = mcp.http_app(transport="http", middleware=gate.middleware())
```
## Register tools with a decorator
`AIEconomySDK` bundles a FastMCP server and a `PaymentGate`; each tool is registered with its own pricing function.
```python
from ai_economy_sdk import AIEconomySDK, DefaultAvmSigner
sdk = AIEconomySDK(
server_signer=DefaultAvmSigner(server_private_key, algod_client=algod_client),
network="localnet",
asset_id=0,
pay_to_address=server_address,
name="DecoratedServer",
)
@sdk.add_tool(name="analyze", description="Analyze input data", pricing_func=lambda args, sender: 10_000)
def analyze(data: str) -> str:
return f"analyzed: {data}"
app = sdk.build_app(transport="streamable-http")
```
`pricing_func` receives the tool arguments and the caller's verified address (or `None`). A function that accepts only `args` also works; one that accepts neither raises `ConfigurationError` when the tool is registered. `build_app(transport=...)` forwards to `PaymentGate.wrap()`. See the [`AIEconomySDK` reference](https://x402-avm.github.io/reference/python/ai-economy-sdk/ai-economy-sdk).
## Next
- [Pricing and passes](https://x402-avm.github.io/build/pricing): per-tool, dynamic and bulk prices, prepaid access.
- [Go to MainNet](https://x402-avm.github.io/production/mainnet): USDC, keys, fee funding and several workers.
---
# Pricing and passes
> Set fixed, per-tool, dynamic and bulk-discount prices on PaymentGate, and sell passes and subscriptions that make calls free for a period.
Use this page to decide what each call costs and who gets it for free. Every option is a `PaymentGate` argument; the gate prices each call before it sends the `402`, so the caller always sees the exact amount.
Prices are integers in the base units of the gate's asset: microALGO when `asset_id=0`, or the ASA's base units (for USDC, 10-6 USDC). A price of 0 makes a call free and skips the challenge.
## Fixed and per-tool prices
```python
gate = PaymentGate(
signer=signer,
network="localnet",
pay_to=server_address,
asset_id=0,
prices={
"status": 0, # free
"generate_text": 15000, # 0.015 ALGO
"render_chart": 25000, # 0.025 ALGO
},
default_price=5000, # every tool not listed
)
```
With only `default_price`, every tool costs the same.
## Dynamic prices
Pass a callable instead of a dictionary. It receives the tool name, the call's arguments and the caller's verified address (`None` when the caller sent no valid [identity proof](https://x402-avm.github.io/build/identity)), and returns the price.
```python
def dynamic_price(tool: str, args: dict, sender: str | None) -> int:
if tool == "transcribe":
seconds = float(args.get("duration", 0))
return 3000 + int(seconds * 50) # base + 50 microALGO per second
if tool == "inference":
tokens = int(args.get("max_tokens", 100))
rate = 10 if sender == PARTNER_ADDRESS else 25
return 4000 + tokens * rate
return 5000
gate = PaymentGate(signer=signer, network="localnet", pay_to=server_address, asset_id=0, prices=dynamic_price)
```
## Bulk discounts
With a `ChainReader`, the gate looks up how much the caller has paid to `pay_to` in a recent window. Above `bulk_threshold`, the price is multiplied by `bulk_discount`. The caller is identified by its identity proof.
```python
from ai_economy_sdk import ChainReader
gate = PaymentGate(
signer=signer,
network="localnet",
pay_to=server_address,
asset_id=0,
prices={"heavy_task": 10000},
chain=ChainReader("http://localhost:8980"),
bulk_threshold=50_000, # more than 50,000 microALGO paid ...
bulk_days=30, # ... in the last 30 days
bulk_discount=0.5, # gets 50% off
)
```
`ChainReader.for_network("testnet")` creates a reader for a public network's default indexer.
### Example
This server (port 9202) has a dictionary price, a price per word, and a 50% discount above 10,000 microALGO of past spend. It makes three calls:
```python
"""Pricing strategies in ai-economy-sdk: fixed per-tool, dynamic arguments, and bulk discounts.
Starts an in-process FastMCP server on port 9202 and exercises three calls from a
buyer account:
1. Fixed price from a tool dictionary (compute = 6,000 microALGO).
2. Dynamic price computed from call arguments (echo = 5,000 base + 100 per word).
3. Bulk discount (50% off) automatically applied once past usage exceeds 10,000 microALGO.
How to run:
python localnet/pricing.py
What it prints:
Call 1 (compute - fixed dict price): charge = 6000 microALGO, result = 42
Call 2 (echo - dynamic price 5 words): charge = 5500 microALGO, result = echo: one two three four five
Call 3 (compute - bulk discount 50%): charge = 3000 microALGO, result = 84
"""
import asyncio
import socket
import sys
import threading
import time
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import uvicorn
from fastmcp import FastMCP
from ai_economy_sdk import DefaultAvmSigner, PaymentGate, paid_mcp_session
from ai_economy_sdk.chain import ChainReader
from _localnet import ALGOD, INDEXER_URL, new_funded_account
SERVER_PORT = 9202
SERVER_URL = f"http://127.0.0.1:{SERVER_PORT}/mcp"
TOOL_PRICES = {"compute": 6000}
def get_price(tool: str, args: dict[str, Any], sender: str | None) -> int:
"""Determine price based on tool name, arguments, and sender address."""
if tool in TOOL_PRICES:
return TOOL_PRICES[tool]
if tool == "echo":
words = len(args.get("text", "").split())
return 5000 + words * 100
return 5000
def main() -> None:
server_sk, server_addr = new_funded_account(algos=10)
buyer_sk, buyer_addr = new_funded_account(algos=10)
mcp = FastMCP("PricingServer")
@mcp.tool()
def compute(n: int) -> int:
"""Double the input number."""
return n * 2
@mcp.tool()
def echo(text: str) -> str:
"""Echo text back to the caller."""
return f"echo: {text}"
gate = PaymentGate(
signer=DefaultAvmSigner(server_sk, algod_client=ALGOD),
network="localnet",
pay_to=server_addr,
asset_id=0,
prices=get_price,
chain=ChainReader(INDEXER_URL),
bulk_threshold=10_000,
bulk_discount=0.5,
)
app = gate.wrap(mcp, transport="streamable-http")
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=SERVER_PORT, log_level="warning"))
server_thread = threading.Thread(target=server.run, daemon=True)
server_thread.start()
# Wait for server to bind port
for _ in range(50):
try:
socket.create_connection(("127.0.0.1", SERVER_PORT), 0.2).close()
break
except OSError:
time.sleep(0.1)
async def execute_client_calls() -> None:
# Call 1: compute (fixed price: 6,000 microALGO)
b0 = ALGOD.account_info(buyer_addr)["amount"]
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
res1 = await session.call_tool("compute", {"n": 21})
b1 = ALGOD.account_info(buyer_addr)["amount"]
charge1 = b0 - b1
print(f"Call 1 (compute - fixed dict price): charge = {charge1} microALGO, result = {res1.content[0].text}")
# Call 2: echo with 5 words (dynamic price: 5,000 + 500 = 5,500 microALGO)
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
res2 = await session.call_tool("echo", {"text": "one two three four five"})
b2 = ALGOD.account_info(buyer_addr)["amount"]
charge2 = b1 - b2
print(f"Call 2 (echo - dynamic price 5 words): charge = {charge2} microALGO, result = {res2.content[0].text}")
# Allow indexer to index preceding payments so cumulative usage exceeds 10,000 microALGO
time.sleep(1.0)
# Call 3: compute with bulk discount (6,000 * 0.5 = 3,000 microALGO)
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
res3 = await session.call_tool("compute", {"n": 42})
b3 = ALGOD.account_info(buyer_addr)["amount"]
charge3 = b2 - b3
print(f"Call 3 (compute - bulk discount 50%): charge = {charge3} microALGO, result = {res3.content[0].text}")
try:
asyncio.run(execute_client_calls())
finally:
server.should_exit = True
server_thread.join(timeout=5)
if __name__ == "__main__":
main()
```
Source: [examples/localnet/pricing.py](https://github.com/x402-avm/examples/blob/main/localnet/pricing.py)
```text
Call 1 (compute - fixed dict price): charge = 6000 microALGO, result = 42
Call 2 (echo - dynamic price 5 words): charge = 5500 microALGO, result = echo: one two three four five
Call 3 (compute - bulk discount 50%): charge = 3000 microALGO, result = 84
```
After two calls the buyer had paid 11,500 microALGO, above the threshold, so the third cost half of 6,000.
## The fee floor
The server's fee payer pays 2,000 microALGO per settled call ([why](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group)). An ALGO price at or below that loses money on every call, so the gate guards against it:
- A fixed price (`prices` dict or `default_price`) in `0 < price <= 2000` raises `ConfigurationError` (a `ValueError`) when the gate is created.
- A price that lands in that range at call time (from a callable or after a discount) is raised to 2,001 microALGO, with a warning logged once per tool.
- `allow_loss=True` turns both checks off, for deliberate subsidies.
- The floor applies only when `asset_id=0`. USDC and other ASA prices are not compared with ALGO fees, although the server still pays the fees in ALGO.
```text
ai_economy_sdk.exceptions.ConfigurationError: price 1000 for tool 'summarize' does not cover facilitator fees (2000 microalgos); raise it or pass allow_loss=True
```
3,000 microALGO is a sensible minimum ALGO price.
## Passes
A pass lets a buyer pay once and then call your tools for free for `pass_days` (30 by default). [How passes work](https://x402-avm.github.io/how-it-works#passes). Passes need an indexer, because the gate finds them in the caller's payment history.
```python
from ai_economy_sdk import ChainReader, PaymentGate
gate = PaymentGate(
signer=signer,
network="localnet",
pay_to=vendor_address,
asset_id=0,
prices={"transcribe": 8000, "summarize": 12000},
chain=ChainReader("http://localhost:8980"),
pass_scopes={
"listing:audio-tools": 100_000, # 0.1 ALGO for this service
"vendor:acme-corp": 500_000, # 0.5 ALGO for the whole vendor
},
pass_days=30.0,
)
```
Scope names are yours to choose. A pass counts only on gates whose `pay_to` received it, in the gate's asset, and whose `pass_scopes` include its scope, so one vendor's pass never unlocks another vendor's tools. The note prefix is the constant `PASS_NOTE_PREFIX` (`x402-pass:`).
### Buy a pass
Any wallet can buy one: send at least the scope's price, in the gate's asset, to `pay_to` with the note `x402-pass:`.
```python
from algosdk import transaction
from algosdk.atomic_transaction_composer import AccountTransactionSigner
sp = algod_client.suggested_params()
txn = transaction.PaymentTxn(
buyer_address, sp, vendor_address, 100_000,
note=b"x402-pass:listing:audio-tools",
)
txid = algod_client.send_transaction(AccountTransactionSigner(buyer_private_key).sign_transactions([txn], [0])[0])
transaction.wait_for_confirmation(algod_client, txid, 4)
```
The buyer's later calls must carry an identity proof; `paid_mcp_session` sends one by default.
### Example
On port 9203, a buyer pays 5,000 microALGO for `echo`, buys a pass with the note `x402-pass:listing:echo-1`, waits for the indexer to see it, and calls again for free:
```python
"""Passes in ai-economy-sdk: grant free tool access via on-chain receipt notes.
Demonstrates vendor-scoped passes on port 9203:
1. Buyer calls 'echo' without a pass, paying the standard 5,000 microALGO fee.
2. Buyer buys a pass by sending an on-chain payment with note 'x402-pass:' to the vendor.
3. Buyer calls 'echo' again; the server's PaymentGate verifies the active pass via the indexer and charges 0 microALGO.
How to run:
python localnet/passes.py
What it prints:
Call 1 (without pass): charge = 5000 microALGO, result = echo: without pass
Bought pass on-chain (txid: ...)
Call 2 (with pass): charge = 0 microALGO, result = echo: with pass
"""
import asyncio
import socket
import sys
import threading
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import algosdk.atomic_transaction_composer
import algosdk.transaction
import uvicorn
from fastmcp import FastMCP
from ai_economy_sdk import DefaultAvmSigner, PaymentGate, paid_mcp_session
from ai_economy_sdk.chain import ChainReader
from _localnet import ALGOD, INDEXER_URL, new_funded_account
SERVER_PORT = 9203
SERVER_URL = f"http://127.0.0.1:{SERVER_PORT}/mcp"
SCOPE = "listing:echo-1"
PASS_PRICE = 50_000
TOOL_PRICE = 5_000
def main() -> None:
server_sk, server_addr = new_funded_account(algos=10)
buyer_sk, buyer_addr = new_funded_account(algos=10)
mcp = FastMCP("PassServer")
@mcp.tool()
def echo(text: str) -> str:
"""Echo text back to the caller."""
return f"echo: {text}"
gate = PaymentGate(
signer=DefaultAvmSigner(server_sk, algod_client=ALGOD),
network="localnet",
pay_to=server_addr,
asset_id=0,
prices={"echo": TOOL_PRICE},
chain=ChainReader(INDEXER_URL),
pass_scopes={SCOPE: PASS_PRICE},
pass_days=30.0,
)
app = gate.wrap(mcp, transport="streamable-http")
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=SERVER_PORT, log_level="warning"))
server_thread = threading.Thread(target=server.run, daemon=True)
server_thread.start()
for _ in range(50):
try:
socket.create_connection(("127.0.0.1", SERVER_PORT), 0.2).close()
break
except OSError:
time.sleep(0.1)
async def execute_client_calls() -> None:
# 1. Call before acquiring pass
b0 = ALGOD.account_info(buyer_addr)["amount"]
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
res1 = await session.call_tool("echo", {"text": "without pass"})
b1 = ALGOD.account_info(buyer_addr)["amount"]
charge1 = b0 - b1
print(f"Call 1 (without pass): charge = {charge1} microALGO, result = {res1.content[0].text}")
# 2. Buy pass via on-chain payment with x402-pass: note
sp = ALGOD.suggested_params()
note = f"x402-pass:{SCOPE}".encode("utf-8")
pass_txn = algosdk.transaction.PaymentTxn(buyer_addr, sp, server_addr, PASS_PRICE, note=note)
signer = algosdk.atomic_transaction_composer.AccountTransactionSigner(buyer_sk)
stxn = signer.sign_transactions([pass_txn], [0])[0]
txid = ALGOD.send_transaction(stxn)
algosdk.transaction.wait_for_confirmation(ALGOD, txid, 10)
print(f"Bought pass on-chain (txid: {txid[:8]}...)")
# Wait for indexer to detect the pass transaction
reader = ChainReader(INDEXER_URL)
for _ in range(20):
time.sleep(0.5)
active = reader.active_passes(buyer_addr, server_addr, 0, {SCOPE: PASS_PRICE})
if active:
break
# 3. Call after pass is active
b2 = ALGOD.account_info(buyer_addr)["amount"]
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
res2 = await session.call_tool("echo", {"text": "with pass"})
b3 = ALGOD.account_info(buyer_addr)["amount"]
charge2 = b2 - b3
print(f"Call 2 (with pass): charge = {charge2} microALGO, result = {res2.content[0].text}")
try:
asyncio.run(execute_client_calls())
finally:
server.should_exit = True
server_thread.join(timeout=5)
if __name__ == "__main__":
main()
```
Source: [examples/localnet/passes.py](https://github.com/x402-avm/examples/blob/main/localnet/passes.py)
```text
Call 1 (without pass): charge = 5000 microALGO, result = echo: without pass
Bought pass on-chain (txid: LRLDZTVU...)
Call 2 (with pass): charge = 0 microALGO, result = echo: with pass
```
## Subscription tokens
The gate can also treat holders of an ASA as subscribers. If the caller holds `subscription_asset_id` and received it within `subscription_max_age_days`, calls are free. Set `subscription_issuer` to count only tokens received from your own issuing account.
```python
gate = PaymentGate(
signer=signer,
network="localnet",
pay_to=vendor_address,
asset_id=0,
prices={"echo": 5000},
chain=ChainReader("http://localhost:8980"),
subscription_asset_id=12345678,
subscription_max_age_days=30.0,
subscription_issuer=issuer_address,
)
```
## Order of evaluation
For each call, `PaymentGate.price_for`:
1. Takes the base price from `prices` (dict or callable) or `default_price`.
2. If it is 0, the call is free.
3. If the caller holds a valid pass for one of `pass_scopes`, or a valid subscription token, the call is free.
4. If the caller's past spend is above `bulk_threshold`, applies `bulk_discount`.
5. For ALGO prices, applies the fee floor.
Lookups that fail (indexer or algod errors) count as "no usage, subscription or pass", and are logged.
## Next
- [Identity](https://x402-avm.github.io/build/identity): how the gate learns who is calling.
- [`ChainReader` reference](https://x402-avm.github.io/reference/python/ai-economy-sdk/chain-reader)
---
# Paywall an HTTP API
> Charge per request on a FastAPI or Flask route with the official x402 SDK and the Algorand scheme from x402-algorand.
By the end of this page, `GET /weather` on your FastAPI or Flask app costs 10,000 microALGO per request, and any x402 client on Algorand can pay it. You use the official [x402 Python SDK](https://github.com/x402-foundation/x402) for the HTTP side, and `x402-algorand` adds Algorand to it.
```bash
pip install x402-algorand==0.3.0 fastapi uvicorn # or: x402-algorand "x402[flask]"
```
This installs the official `x402` package (2.28 or later, below 3) and `py-algorand-sdk`.
## FastAPI
The server below is the payee, the fee payer and an in-process facilitator, so the buyer pays exactly the price. It runs on [LocalNet](https://x402-avm.github.io/production/networks#localnet), port 9211.
```python
"""FastAPI paywall: GET /weather costs 10,000 microALGO on LocalNet (port 9211).
The server is payee, fee payer and in-process facilitator, so the buyer pays exactly the price.
python localnet/fastapi_paywall.py
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import uvicorn
from fastapi import FastAPI
from x402 import x402Facilitator, x402ResourceServer
from x402.http.middleware.fastapi import payment_middleware
from x402_algorand import ServerAvmSigner, caip2_from_genesis_hash
from x402_algorand.exact import register_exact_avm_facilitator, register_exact_avm_server
from _localnet import ALGOD, new_funded_account
network = caip2_from_genesis_hash(ALGOD.suggested_params().gh)
signer = ServerAvmSigner.from_private_key(new_funded_account()[0], ALGOD)
facilitator = x402Facilitator()
register_exact_avm_facilitator(facilitator, signer, network)
server = x402ResourceServer(facilitator)
register_exact_avm_server(server)
routes = {"GET /weather": {"accepts": [{
"scheme": "exact", "price": {"amount": "10000", "asset": "0"},
"network": network, "pay_to": signer.address,
}]}}
app = FastAPI()
app.middleware("http")(payment_middleware(routes, server))
@app.get("/weather")
async def weather():
return {"city": "Boston", "temperature": 68, "network": network}
if __name__ == "__main__":
print(f"FastAPI paywall on http://127.0.0.1:9211/weather, pay to {signer.address}")
uvicorn.run(app, host="127.0.0.1", port=9211, log_level="warning")
```
Source: [examples/localnet/fastapi_paywall.py](https://github.com/x402-avm/examples/blob/main/localnet/fastapi_paywall.py)
```bash
python localnet/fastapi_paywall.py
```
```text
FastAPI paywall on http://127.0.0.1:9211/weather, pay to
```
## Flask
Flask is synchronous, so it uses the sync classes `x402FacilitatorSync` and `x402ResourceServerSync`, and `payment_middleware(app, routes, server)` from `x402.http.middleware.flask`, which wraps `app.wsgi_app`. Same route, port 9212:
```python
"""Flask paywall: GET /weather costs 10,000 microALGO on LocalNet (port 9212).
Uses the synchronous x402 classes; the server is payee, fee payer and facilitator.
python localnet/flask_paywall.py
"""
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from flask import Flask, jsonify
from werkzeug.serving import run_simple
from x402 import x402FacilitatorSync, x402ResourceServerSync
from x402.http.middleware.flask import payment_middleware
from x402_algorand import ServerAvmSigner, caip2_from_genesis_hash
from x402_algorand.exact import register_exact_avm_facilitator, register_exact_avm_server
from _localnet import ALGOD, new_funded_account
network = caip2_from_genesis_hash(ALGOD.suggested_params().gh)
signer = ServerAvmSigner.from_private_key(new_funded_account()[0], ALGOD)
facilitator = x402FacilitatorSync()
register_exact_avm_facilitator(facilitator, signer, network)
server = x402ResourceServerSync(facilitator)
register_exact_avm_server(server)
routes = {"GET /weather": {"accepts": [{
"scheme": "exact", "price": {"amount": "10000", "asset": "0"},
"network": network, "pay_to": signer.address,
}]}}
app = Flask(__name__)
payment_middleware(app, routes, server)
@app.get("/weather")
def weather():
return jsonify(city="Boston", temperature=68, network=network)
if __name__ == "__main__":
print(f"Flask paywall on http://127.0.0.1:9212/weather, pay to {signer.address}")
logging.getLogger("werkzeug").setLevel(logging.ERROR) # quiet dev-server banner and access log
run_simple("127.0.0.1", 9212, app)
```
Source: [examples/localnet/flask_paywall.py](https://github.com/x402-avm/examples/blob/main/localnet/flask_paywall.py)
## Test it with a paying client
```bash
python localnet/flask_paywall.py
```
In a second terminal (drop `--url` to pay the FastAPI server on 9211):
```bash
python localnet/httpx_client.py --url http://127.0.0.1:9212/weather
```
```text
200 {'city': 'Boston', 'network': 'algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY', 'temperature': 68}
Paid exactly 10000 microALGO.
```
The network id is your LocalNet's and differs between machines. The client is explained in [Pay from Python](https://x402-avm.github.io/build/pay-from-python#pay-http-apis); from JavaScript, use [x402-avm-js](https://x402-avm.github.io/build/pay-from-node).
## What the middleware does
1. A request to a protected route without payment gets `402` with `PAYMENT-REQUIRED`; the route does not run.
2. A request with `PAYMENT-SIGNATURE` is verified through the facilitator.
3. If verification succeeds, the route runs.
4. After the route returns, the middleware settles the payment and adds a `PAYMENT-RESPONSE` header.
## Set the price of a route
The resource server turns each route into payment requirements. The Algorand scheme accepts these price forms:
| `price` | Meaning |
|---|---|
| `{"amount": "10000", "asset": "0"}` | 10,000 microALGO |
| `{"amount": "50000", "asset": "31566704"}` | 50,000 base units of USDC (0.05 USDC) on MainNet |
| `{"amount": "50000"}` | No asset: the network's USDC |
| `"$0.01"`, `0.01` | A dollar amount, converted to the network's USDC (6 decimals) unless a custom money parser handles it |
```python
routes = {
"GET /api/reports": {
"accepts": [
{
"scheme": "exact",
"price": {"amount": "50000", "asset": "0"}, # 50,000 microALGO
"network": "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k",
"pay_to": "YOUR_ALGORAND_ADDRESS",
}
]
}
}
```
Register a parser for dollar amounts with `ExactAvmServerScheme().register_money_parser(parser)`; see the [reference](https://x402-avm.github.io/reference/python/x402-algorand/exact-avm-server-scheme). To take USDC, the receiving account must [opt in](https://x402-avm.github.io/production/mainnet#accept-usdc).
When it builds requirements, the Algorand scheme's `enhance_payment_requirements` adds:
- `extra.decimals`: 6, unless the route set it.
- `extra.feePayer`: a fee payer address of the facilitator. If its signer manages several addresses, one is picked at random, which spreads fee costs. Without a fee payer, the client pays its own fee.
- `extra.genesisHash` and `extra.genesisId`, when the network is registered.
## The parts and where they come from
| Package | Provides |
|---|---|
| `x402` (official SDK) | `x402Client`, `x402ResourceServer`, `x402Facilitator` and their sync variants; payment schemas; spend controls; header encoding; FastAPI and Flask middleware; httpx and requests clients. |
| `x402_algorand` | Client, server and facilitator implementations of the Algorand exact scheme; `register_exact_avm_*` helpers; signer protocols and the ready-made `PayerAvmSigner` and `ServerAvmSigner`; exceptions; CAIP-2 utilities; transaction decoding and security checks; constants and error codes. |
```python
from x402 import x402Facilitator, x402ResourceServer
from x402_algorand.exact import register_exact_avm_facilitator, register_exact_avm_server
facilitator = x402Facilitator()
register_exact_avm_facilitator(facilitator, facilitator_signer, network) # verifies, settles, sponsors fees
server = x402ResourceServer(facilitator)
register_exact_avm_server(server) # registers the scheme for "algorand:*"
```
`x402ResourceServer` also accepts a client for a remote facilitator; see the upstream `x402` documentation and [Run a facilitator](https://x402-avm.github.io/build/facilitator). The facilitator's signer is covered there too.
The upstream SDK also ships EVM and SVM schemes; `x402-algorand` adds the AVM. It is derived from GoPlausible's [`x402-avm`](https://github.com/GoPlausible/x402-avm) 2.0.2 (Apache-2.0) and ships a `NOTICE` file that reproduces the upstream notices and lists the changed files. Licence: Apache License 2.0.
## Next
- [Pay from Python](https://x402-avm.github.io/build/pay-from-python#pay-http-apis) or [from the browser](https://x402-avm.github.io/build/pay-from-browser).
- [Errors and error codes](https://x402-avm.github.io/reference/errors) for every reason a payment is refused.
---
# Pay from Python
> Call paid MCP tools with paid_mcp_session, and pay x402 HTTP APIs with the official x402 client, within spend limits you set.
Use this page when Python code needs to pay: an MCP client calling paid tools, or a script calling a paywalled HTTP API. In both cases your code makes ordinary calls; the client answers each `402` with a signed payment and retries.
You need a funded Algorand account on the server's network. Its private key is the base64 string returned by `algosdk.account.generate_account()` or `algosdk.mnemonic.to_private_key()`.
## Call paid MCP tools
```bash
pip install ai-economy-sdk==0.5.1
```
```python
"""Paid MCP client session using ai-economy-sdk on Algorand LocalNet.
Funds a fresh buyer account via the LocalNet dispenser, establishes a paid MCP
session to http://127.0.0.1:9201/mcp, calls the 'echo' tool, and verifies the on-chain
charge.
How to run:
1. Start quickstart_server.py in the background
2. python localnet/quickstart_client.py
What it prints:
Result: echo: hello world
Balance drop: 5000 microALGO
"""
import asyncio
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from ai_economy_sdk import AIEconomyError, paid_mcp_session
from _localnet import ALGOD, new_funded_account
SERVER_URL = "http://127.0.0.1:9201/mcp"
async def main() -> None:
buyer_sk, buyer_addr = new_funded_account(algos=5)
before_balance = ALGOD.account_info(buyer_addr)["amount"]
try:
async with paid_mcp_session(SERVER_URL, buyer_sk, "localnet") as session:
result = await session.call_tool("echo", {"text": "hello world"})
print(f"Result: {result.content[0].text}")
except AIEconomyError as err: # spend controls refused the price (SpendLimitExceededError, 0.5.1+), settlement failed, bad config ...
raise SystemExit(f"Paid call failed: {err}")
after_balance = ALGOD.account_info(buyer_addr)["amount"]
drop = before_balance - after_balance
print(f"Balance drop: {drop} microALGO")
if __name__ == "__main__":
asyncio.run(main())
```
Source: [examples/localnet/quickstart_client.py](https://github.com/x402-avm/examples/blob/main/localnet/quickstart_client.py)
`paid_mcp_session` yields an initialized `mcp.ClientSession`, so every MCP client method works. Listing tools is free; only `tools/call` is priced. Run it against the [Quickstart](https://x402-avm.github.io/quickstart) server.
| Parameter | Default | Description |
|---|---|---|
| `sse_url` | required | The server's MCP endpoint: `.../mcp` for Streamable HTTP or `.../sse` for SSE. The name is kept from 0.4; it takes either. |
| `private_key` | required | Base64 Algorand private key of the buyer. |
| `network` | required | `"mainnet"`, `"testnet"`, `"localnet"`, or a CAIP-2 id. |
| `algod_url`, `algod_token` | `None` | algod endpoint. Defaults to AlgoNode for MainNet and TestNet, `http://localhost:4001` for LocalNet. |
| `identity` | `True` | Send [identity headers](https://x402-avm.github.io/how-it-works#identity-proofs) on every request, so the server can apply passes, subscriptions and per-caller prices. |
| `timeout` | `30.0` | HTTP timeout in seconds. Stream reads allow up to 300 seconds. |
| `spend_controls` | `None` | Limits checked before signing; see [below](#spend-controls). |
| `transport` | `None` | Keyword-only: `"streamable-http"` or `"sse"`. When omitted, URLs whose path ends in `/mcp` use Streamable HTTP and all others SSE. Any other value raises `ConfigurationError`. |
Use the transport the server serves: `.../mcp` for `transport="streamable-http"`, `.../sse` for `transport="sse"`. Full reference: [`paid_mcp_session`](https://x402-avm.github.io/reference/python/ai-economy-sdk/paid-mcp-session).
## Spend controls
Both clients on this page use the official `x402` client, which checks every payment against spend controls **before signing**. A refused payment signs nothing:
- `paid_mcp_session` raises `SpendLimitExceededError` (an `AIEconomyError`, exported from `ai_economy_sdk`) from the `async with` block. Its message includes the amount and asset the server asked for; x402's `PaymentError` (caused by `NoMatchingRequirementsError`) is the `__cause__`. In 0.5.0 the refusal arrived as an `ExceptionGroup` and over SSE the session could hang; fixed in 0.5.1.
- `x402Client` raises `NoMatchingRequirementsError`; through the httpx and requests wrappers it surfaces as the wrapper's `PaymentError`.
**Defaults:** ALGO (`"0"`) on every Algorand network and USDC on MainNet (`"31566704"`) and TestNet (`"10458941"`), at most `$1` per payment (`DEFAULT_MAX_AMOUNT_PER_PAYMENT`). A dollar cap is converted with 6 decimals, so `$1` is 1,000,000 base units: 1 USDC, and also 1 ALGO whatever ALGO's market price is.
| `spend_controls=` | Effect |
|---|---|
| `None` (default) | The defaults above. |
| `{"max_amount_per_payment": "$0.25"}` | Same assets, cap of 250,000 base units. |
| `{"max_amount_per_payment": False}` | Same assets, no cap. |
| `{"allowed_assets": True}` | Any asset; the cap still applies to the default assets. |
| `{"allowed_assets": [{...}]}` | The default assets plus the listed ones, each with an optional cap in base units. |
| `False` | No controls at all. Never use this for an agent. |
Allow another ASA with its own cap. A per-asset cap is an integer string in base units; a dollar value raises `ValueError`:
```python
spend_controls = {
"allowed_assets": [{
"network": "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k",
"asset": "12345678", # ASA id
"max_amount_per_payment": "5000000", # base units, not dollars
}]
}
async with paid_mcp_session(url, key, "mainnet", spend_controls=spend_controls) as session: ...
```
With an `x402Client`, pass the same dictionary to `client.set_spend_controls(...)` (or `False` to turn them off), or use `x402Client.from_config(x402ClientConfig(schemes=..., spend_controls=...))`. `x402Client.__init__` takes only `payment_requirements_selector`.
> **Warning:**
Spend controls cap each payment, not the total. Fund the paying account with only what it may spend. For agents, see [AI agents](https://x402-avm.github.io/build/ai-agents#set-limits).
## Pay HTTP APIs
```bash
pip install x402-algorand==0.3.0
```
Register the Algorand scheme on an `x402Client` with a signer, then wrap `httpx`. This pays the [FastAPI paywall](https://x402-avm.github.io/build/paywall-http-api) on port 9211:
```python
"""HTTPX client that pays x402 paywalls automatically on LocalNet.
Start fastapi_paywall.py (port 9211) or flask_paywall.py (9212) first, then:
python localnet/httpx_client.py [--url http://127.0.0.1:9211/weather]
"""
import argparse
import asyncio
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from x402 import x402Client
from x402.http.clients.httpx import wrapHttpxWithPayment
from x402_algorand import PayerAvmSigner
from x402_algorand.exact import register_exact_avm_client
from _localnet import ALGOD, ALGOD_TOKEN, ALGOD_URL, new_funded_account
async def main(url: str) -> None:
sk, addr = new_funded_account(5)
before = ALGOD.account_info(addr)["amount"]
client = x402Client() # default spend controls allow ALGO up to 1,000,000 microALGO
register_exact_avm_client(
client, PayerAvmSigner.from_private_key(sk), algod_url=ALGOD_URL, algod_token=ALGOD_TOKEN
)
async with wrapHttpxWithPayment(client) as http:
response = await http.get(url, timeout=30.0)
print(response.status_code, response.json())
spent = before - ALGOD.account_info(addr)["amount"]
assert response.status_code == 200 and spent == 10_000, (response.status_code, spent)
print(f"Paid exactly {spent} microALGO.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default="http://127.0.0.1:9211/weather")
asyncio.run(main(parser.parse_args().url))
```
Source: [examples/localnet/httpx_client.py](https://github.com/x402-avm/examples/blob/main/localnet/httpx_client.py)
```text
200 {'city': 'Boston', 'temperature': 68, 'network': 'algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY'}
Paid exactly 10000 microALGO.
```
`wrapHttpxWithPayment` returns an `httpx.AsyncClient` with an `x402AsyncTransport`. `x402HttpxClient(x402_client, ...)` is an `httpx.AsyncClient` subclass that does the same and accepts the usual httpx arguments; `paid_mcp_session` uses it. The client does not loop: after a bounded number of paid retries it returns the server's answer, so a `402` after paying reaches your code.
For synchronous code, use `x402ClientSync` and a `requests.Session` (install the extra with `pip install "x402[requests]"`):
```python
import os
import requests
from x402 import x402ClientSync
from x402.http.clients import wrapRequestsWithPayment
from x402_algorand import PayerAvmSigner
from x402_algorand.exact import register_exact_avm_client
x402_client = x402ClientSync()
register_exact_avm_client(x402_client, PayerAvmSigner.from_mnemonic(os.environ["PAYER_MNEMONIC"]),
algod_url="http://localhost:4001", algod_token="a" * 64)
session = wrapRequestsWithPayment(requests.Session(), x402_client)
response = session.get("http://127.0.0.1:9211/weather")
```
> **Note:**
`wrapRequestsWithPayment` comes from the official `x402` package and follows its documented usage. The examples repository runs the httpx client, not the requests variant.
### Registration options and policies
| Argument | Default | Meaning |
|---|---|---|
| `networks` | `None` | Network ids to register. `None` registers the wildcard `algorand:*`. |
| `policies` | `None` | x402 payment policies, registered with `client.register_policy`. |
| `algod_url`, `algod_token` | `None` | The algod used for suggested parameters. Without them the scheme uses the network's configured endpoint. |
It also registers the scheme for the x402 v1 names `algorand-mainnet` and `algorand-testnet`.
A policy is a function `(x402_version, requirements) -> requirements` that sees every offer before one is chosen. If it removes them all, the client raises `NoMatchingRequirementsError` and pays nothing:
```python
MAX_BASE_UNITS = 20_000
def cheap_only(version, requirements):
return [r for r in requirements if int(r.amount) <= MAX_BASE_UNITS]
register_exact_avm_client(client, signer, policies=[cheap_only])
```
`paid_mcp_session` builds its own client and takes `spend_controls`, not policies.
### Signers
The client signs with an object that implements [`ClientAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/client-avm-signer): an `address`, and a method that signs the transactions at the given indexes of a group and returns `None` for the others. [`PayerAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/payer-avm-signer) is backed by a private key: `PayerAvmSigner.from_private_key(key)` or `PayerAvmSigner.from_mnemonic(words)`.
The key stays in a private attribute and never appears in `repr()`, exception messages or logs. A malformed key or mnemonic raises `SigningError`, and so does a request to sign a transaction sent by another account. To sign with a KMS, a hardware wallet or a remote service, implement the protocol yourself. `DefaultAvmSigner(private_key, algod_client=...)` from `ai-economy-sdk` also implements it.
### Pay a challenge by hand
```python
from x402.http import decode_payment_required_header, encode_payment_signature_header
payment_required = decode_payment_required_header(response.headers["payment-required"])
payment_payload = await client.create_payment_payload(payment_required)
retry = await http_client.get(url, headers={"payment-signature": encode_payment_signature_header(payment_payload)})
```
`create_payment_payload`:
1. Fetches suggested parameters from algod and checks that algod is on the requirement's network. If not, it raises `NetworkMismatchError("algod is on but the payment is for ")` (a `ValueError`). A network with no configured algod and no `algod_url` raises `NetworkError`.
2. Builds the [two-transaction group](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group) if the requirement has `extra.feePayer` (the fee payer's transaction unsigned, yours with fee 0 and signed), or a single payment with the normal fee if not. Your payment is a `pay` for ALGO, an `axfer` for an ASA.
3. Returns only signed transaction bytes; the private key never leaves the signer.
## Next
- [AI agents](https://x402-avm.github.io/build/ai-agents): a budget wallet, limits and price checks for unattended callers.
- [Networks](https://x402-avm.github.io/production/networks): move from LocalNet to TestNet.
---
# Pay from the browser
> Unlock paid content in a web app: the visitor's Algorand wallet signs the payment with x402-avm-js, within spend limits you set.
By the end of this page you will have a web page whose premium report unlocks after the visitor pays 4,000 microALGO from their wallet, and you will know how to plug in any Algorand wallet. `x402-avm-js` decodes the `402`, builds the payment group, has the wallet sign its part, and encodes the `PAYMENT-SIGNATURE` header. It works with ALGO or any ASA, on every network.
```bash
npm install x402-avm-js@0.4.1 algosdk
```
## The whole flow in one call
```ts
import { algodClient, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
const algod = algodClient('mainnet'); // or 'testnet', or algodClient(network, url, token)
const res = await fetch(url);
if (res.status === 402) {
const required = decodePaymentRequired(res.headers.get('PAYMENT-REQUIRED')!);
const header = await payForRequirement(
required,
myAddress,
algod,
(txns, indexes) => wallet.signTransactions(txns, indexes), // Pera, Defly, Lute, KMD, a local key...
{ maxAmount: 50_000n, allowedNetworks: ['mainnet'] }, // spend controls, checked before signing
);
const paid = await fetch(url, { headers: { 'PAYMENT-SIGNATURE': header } });
}
```
`payForRequirement`:
1. Fetches suggested parameters from algod (`algod.getTransactionParams().do()`).
2. Picks the `exact` offer for algod's network with `selectRequirement`. A server can offer several networks (say MainNet USDC and TestNet ALGO); if none matches the wallet's, it throws `NetworkMismatchError` instead of signing a useless payment.
3. Checks the offer against the [spend controls](#spend-controls).
4. Builds the group with `buildExactAvmGroup`: the [two-transaction group](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group) when the offer has `extra.feePayer`, otherwise one payment that pays the normal fee.
5. Asks your signing function to sign only the buyer's transaction.
6. Encodes the signed and unsigned transactions into the `PAYMENT-SIGNATURE` value.
The browser submits nothing to the chain. The server verifies, runs the service and settles.
## Build the paywall
The files are in `localnet/browser_paywall/` of the [examples repository](https://github.com/x402-avm/examples); run `pip install -r requirements.txt` and `npm install` from its root. They run on [LocalNet](https://x402-avm.github.io/production/networks#localnet).
### The server
A FastAPI app that serves the page at `/` and protects `GET /api/premium` with the official `x402` middleware, as on [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api).
```python
"""Browser paywall server: serves the static page and charges 4,000 microALGO for /api/premium.
python localnet/browser_paywall/server.py # http://127.0.0.1:9232
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from x402 import x402Facilitator, x402ResourceServer
from x402.http.middleware.fastapi import payment_middleware
from x402_algorand import ServerAvmSigner, caip2_from_genesis_hash
from x402_algorand.exact import register_exact_avm_facilitator, register_exact_avm_server
from _localnet import ALGOD, new_funded_account
def create_app() -> FastAPI:
network = caip2_from_genesis_hash(ALGOD.suggested_params().gh)
signer = ServerAvmSigner.from_private_key(new_funded_account()[0], ALGOD)
facilitator = x402Facilitator()
register_exact_avm_facilitator(facilitator, signer, network)
server = x402ResourceServer(facilitator)
register_exact_avm_server(server)
routes = {"GET /api/premium": {
"accepts": [{"scheme": "exact", "pay_to": signer.address,
"price": {"amount": "4000", "asset": "0"}, "network": network}],
"description": "Deep sea exploration premium report",
}}
app = FastAPI(title="Browser Paywall")
app.middleware("http")(payment_middleware(routes, server))
@app.get("/api/premium")
def premium():
return {
"title": "Deep Sea Hydrothermal Vent Survey",
"findings": "Dense polymetallic sulfides discovered at depth 2,400m.",
"status": "unlocked",
}
app.mount("/", StaticFiles(directory=Path(__file__).parent, html=True), name="static")
return app
if __name__ == "__main__":
print("Browser paywall on http://127.0.0.1:9232", flush=True)
uvicorn.run(create_app(), host="127.0.0.1", port=9232, log_level="warning")
```
Source: [examples/localnet/browser_paywall/server.py](https://github.com/x402-avm/examples/blob/main/localnet/browser_paywall/server.py)
### The page's client code
`app.js` requests the report, and on `402` pays with the visitor's signing function and retries. The page ([index.html](https://github.com/x402-avm/examples/blob/main/localnet/browser_paywall/index.html)) imports `fetchPremiumContent` from the bundle.
```javascript
/**
* Browser paywall client (x402-avm-js): fetch /api/premium, pay the 402 challenge with the
* caller's wallet signer, retry with PAYMENT-SIGNATURE.
*/
import algosdk from 'algosdk';
import { PaymentNotAllowedError, SpendLimitExceededError, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
// Never pay more than 0.01 ALGO per request, whatever the server asks for.
const SPEND_CONTROLS = { maxAmount: 10_000n, allowedAssets: ['0'] };
export async function fetchPremiumContent(
payerAddress,
signTxns,
algodUrl = 'http://localhost:4001',
algodToken = 'a'.repeat(64),
) {
const first = await fetch('/api/premium');
if (first.status === 200) return first.json();
if (first.status !== 402) throw new Error(`Unexpected server response: HTTP ${first.status}`);
const challenge = decodePaymentRequired(first.headers.get('payment-required'));
const algod = new algosdk.Algodv2(algodToken, algodUrl, '');
let signature;
try {
signature = await payForRequirement(challenge, payerAddress, algod, signTxns, SPEND_CONTROLS);
} catch (err) {
if (err instanceof SpendLimitExceededError || err instanceof PaymentNotAllowedError) {
throw new Error(`Payment refused by spend controls: ${err.message}`);
}
throw err;
}
const paid = await fetch('/api/premium', { headers: { 'payment-signature': signature } });
if (paid.status !== 200) throw new Error(`Payment refused by server: HTTP ${paid.status}`);
return paid.json();
}
```
Source: [examples/localnet/browser_paywall/app.js](https://github.com/x402-avm/examples/blob/main/localnet/browser_paywall/app.js)
Bundle it with esbuild (the repository's npm script writes `localnet/browser_paywall/bundle.js`, an ES module containing `algosdk` and `x402-avm-js`):
```bash
npm run build:paywall
```
### Check it from Node
`verify.mjs` runs the same calls as `app.js`, with a LocalNet account instead of a browser wallet. It does not drive a browser.
```javascript
/**
* Runs the same x402 client flow as app.js from Node against the paywall on port 9232
* (start browser_paywall/server.py first):
*
* node localnet/browser_paywall/verify.mjs
*/
import { decodePaymentRequired, payForRequirement } from 'x402-avm-js';
import { algod, newFundedAccount, signerFor } from '../_localnet.mjs';
const URL = 'http://127.0.0.1:9232/api/premium';
const balance = async (addr) => (await algod.accountInformation(addr).do()).amount;
const buyer = await newFundedAccount(5);
const before = await balance(buyer.address);
const res402 = await fetch(URL);
if (res402.status !== 402) throw new Error(`Expected 402, got ${res402.status}`);
const challenge = decodePaymentRequired(res402.headers.get('payment-required'));
const [req] = challenge.accepts;
console.log(`402: ${req.amount} units of asset ${req.asset} to ${req.payTo} on ${req.network}`);
const signature = await payForRequirement(challenge, buyer.address, algod, signerFor(buyer.sk));
const paid = await fetch(URL, { headers: { 'payment-signature': signature } });
if (paid.status !== 200) throw new Error(`Expected 200, got ${paid.status}: ${await paid.text()}`);
console.log('Unlocked:', await paid.json());
const drop = before - (await balance(buyer.address));
console.log(`Balance drop: ${drop} microALGO`);
if (drop !== BigInt(req.amount)) throw new Error(`Expected a drop of ${req.amount}, got ${drop}`);
console.log('Browser paywall verified.');
```
Source: [examples/localnet/browser_paywall/verify.mjs](https://github.com/x402-avm/examples/blob/main/localnet/browser_paywall/verify.mjs)
```bash
python localnet/browser_paywall/server.py # http://127.0.0.1:9232
node localnet/browser_paywall/verify.mjs # in a second terminal
```
```text
402: 4000 units of asset 0 to P4MQF6EJEYT3W4MA2OS2M6JLPYV2JXNFGLT2ER6S3UNII7JDOM3SJRHPDU on algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY
Unlocked: {
title: 'Deep Sea Hydrothermal Vent Survey',
findings: 'Dense polymetallic sulfides discovered at depth 2,400m.',
status: 'unlocked'
}
Balance drop: 4000 microALGO
Browser paywall verified.
```
## Connect a wallet
`payForRequirement` hands signing to a callback:
```ts
signTxns: (txns: Uint8Array[], indexes: number[]) => Promise<(Uint8Array | null)[]>
```
`txns` are the encoded unsigned transactions of the group and `indexes` the ones the buyer must sign. Return an array as long as `txns`, with signed bytes at each index in `indexes` and `null` elsewhere; unsigned positions are sent as they are, for the server to sign.
Wallets return signatures either as the full group (as long as `txns`, `null` where unsigned) or sparse (as long as `indexes`). This function, written for `@txnlab/use-wallet-react` (Pera, Defly, Lute, KMD and others), normalizes both:
```typescript
/**
* React browser wallet integration using use-wallet-react v5 and x402-avm-js.
*
* Demonstrates:
* 1. Connecting to active wallet account, algod client, and signTransactions hook.
* 2. Normalizing the signTransactions return contract across different wallet providers.
* 3. Calling payForRequirement() to fulfill an x402 payment challenge.
*
* How to type-check:
* npx tsc --noEmit localnet/browser_wallet.ts
*/
import { useWallet } from '@txnlab/use-wallet-react';
import { payForRequirement, type PaymentRequired, type SpendControls } from 'x402-avm-js';
/**
* Execute an x402 payment challenge using the connected browser wallet.
*
* Different wallet providers implement the signTransactions contract in two ways:
* - Full-group mapping: Returns an array of length equal to txns.length, with null at un-signed indexes.
* - Sparse mapping: Returns an array of length equal to indexes.length, containing only requested signatures.
*
* The wrapper normalizes both behaviors to match payForRequirement's expectation:
* an array of length txns.length with Uint8Array at signed indexes and null elsewhere.
*
* @param challenge - Decoded PaymentRequired challenge from HTTP 402 response.
* @param wallet - useWallet() hook return value.
* @param controls - Spend controls; without them the default cap of 1,000,000 base units applies.
* Throws SpendLimitExceededError / PaymentNotAllowedError (both X402AvmError) before the wallet is asked to sign.
* @returns Promise resolving to the base64-encoded PAYMENT-SIGNATURE header.
*/
export async function payWithBrowserWallet(
challenge: PaymentRequired,
wallet: ReturnType,
controls: SpendControls = { maxAmount: 100_000n, allowedAssets: ['0'] },
): Promise {
const { activeAddress, algodClient, signTransactions } = wallet;
if (!activeAddress) {
throw new Error('No active wallet connected. Please connect your wallet first.');
}
// Normalize wallet signing response to full group length
const safeSignTxns = async (
txns: Uint8Array[],
indexes: number[]
): Promise<(Uint8Array | null)[]> => {
const signed = await signTransactions(txns, indexes);
if (!signed) {
return new Array(txns.length).fill(null);
}
const mapped: (Uint8Array | null)[] = new Array(txns.length).fill(null);
if (signed.length === indexes.length) {
indexes.forEach((txnIdx, signIdx) => {
mapped[txnIdx] = signed[signIdx];
});
} else {
signed.forEach((signedBytes, idx) => {
if (signedBytes) {
mapped[idx] = signedBytes;
}
});
}
return mapped;
};
return await payForRequirement(challenge, activeAddress, algodClient, safeSignTxns, controls);
}
```
Source: [examples/localnet/browser_wallet.ts](https://github.com/x402-avm/examples/blob/main/localnet/browser_wallet.ts)
```bash
npm install x402-avm-js algosdk @txnlab/use-wallet-react
```
To let returning visitors prove who they are without paying, sign an [identity proof](https://x402-avm.github.io/build/identity) with the same wallet.
## Spend controls
The server chooses the amount in a `402`, so a compromised or buggy server could ask for anything. `payForRequirement` and `buildExactAvmGroup` check every offer **before anything is built or signed**. By default, any payment above 1,000,000 base units (1 ALGO or 1 USDC; `DEFAULT_MAX_AMOUNT`) is refused, matching the Python client. Unlike the Python client, any asset is allowed unless you set `allowedAssets`.
Pass the options as the last argument:
```ts
import { payForRequirement, SpendLimitExceededError, PaymentNotAllowedError } from 'x402-avm-js';
try {
const header = await payForRequirement(required, address, algod, signTxns, {
maxAmount: 50_000n, // base units; bigint, safe integer or numeric string
allowedAssets: [0, 31566704], // ALGO and MainNet USDC
allowedNetworks: ['mainnet'], // names or CAIP-2 ids
allowedPayTo: [TRUSTED_VENDOR_ADDRESS], // recipients you trust
});
} catch (e) {
if (e instanceof SpendLimitExceededError) console.warn(`asked for ${e.amount}, limit ${e.limit}`);
else if (e instanceof PaymentNotAllowedError) console.warn(`${e.field} ${e.value} not allowed`);
else throw e;
}
```
| Option | Meaning |
|---|---|
| `maxAmount` | Per-payment cap in base units. One value applies to every asset; a record such as `{ '0': 2_000_000, '31566704': 5_000_000, '*': 100_000 }` sets it per asset id, with `'*'` as fallback. Assets not covered use the 1,000,000 default. `Infinity` removes the cap. |
| `allowedAssets` | If set, only these asset ids (`0` is ALGO). |
| `allowedNetworks` | If set, only these networks. LocalNet has no name here: use its CAIP-2 id from `networkFromAlgod(algod)`. |
| `allowedPayTo` | If set, only these recipient addresses. |
`checkSpendControls(requirement, controls)` runs the same check on its own, for example to show a price before asking the wallet to sign. A malformed option throws `InvalidOptionsError`. Every error class and its `code`: [Errors](https://x402-avm.github.io/reference/errors#x402-avm-js-errors).
## Next
- [Pay from Node.js](https://x402-avm.github.io/build/pay-from-node): scripts, services and agents.
- [`payForRequirement` reference](https://x402-avm.github.io/reference/js/pay-for-requirement)
---
# Pay from Node.js
> Pay x402 endpoints from Node.js services, scripts and agents with x402-avm-js and a key from the environment or KMD.
Use this page when a Node.js process, not a person, holds the wallet: a backend calling a paid API, a CI job, an agent. The flow is the same as [in the browser](https://x402-avm.github.io/build/pay-from-browser); only the signing function changes.
```bash
npm init -y
npm pkg set type=module
npm install x402-avm-js@0.4.1 algosdk
```
## Sign with a key from the environment
```ts
import algosdk from 'algosdk';
import { algodClient, decodePaymentRequired, payForRequirement } from 'x402-avm-js';
const algod = algodClient('mainnet');
const account = algosdk.mnemonicToSecretKey(process.env.AGENT_MNEMONIC!);
const res = await fetch('https://api.example.com/data');
if (res.status === 402) {
const challenge = decodePaymentRequired(res.headers.get('PAYMENT-REQUIRED')!);
const paymentHeader = await payForRequirement(
challenge,
account.addr.toString(),
algod,
async (unsignedTxns, signIndexes) =>
unsignedTxns.map((bytes, i) =>
signIndexes.includes(i) ? algosdk.decodeUnsignedTransaction(bytes).signTxn(account.sk) : null
),
{ maxAmount: 100_000n } // refuse anything above 0.1 ALGO / 0.1 USDC (default cap: 1,000,000 base units)
);
const paid = await fetch('https://api.example.com/data', {
headers: { 'PAYMENT-SIGNATURE': paymentHeader },
});
}
```
Any offer above the cap is refused with `SpendLimitExceededError` before your signing function runs. You can also restrict assets, networks and recipients: [spend controls](https://x402-avm.github.io/build/pay-from-browser#spend-controls).
## A runnable LocalNet example
[Quickstart](https://x402-avm.github.io/quickstart) step 5 runs `localnet/js_pay.mjs`: it funds an account from LocalNet's KMD, pays a `402` from [`localnet/server_for_js.py`](https://github.com/x402-avm/examples/blob/main/localnet/server_for_js.py) (5,000 microALGO on port 9221), checks the exact balance drop, and shows an over-cap demand being refused.
```bash
python localnet/server_for_js.py
node localnet/js_pay.mjs
```
The server answers `200` with a `PAYMENT-RESPONSE` header that carries the settlement result, including the transaction id.
## Calling MCP tools from Node
`x402-avm-js` builds and signs payments; it has no MCP client transport. To call paid MCP tools, use [`paid_mcp_session`](https://x402-avm.github.io/build/pay-from-python) from Python, or [read the tool call's `402`](https://x402-avm.github.io/build/ai-agents#check-a-price-before-paying) and pay it yourself.
## Next
- [Networks](https://x402-avm.github.io/production/networks): presets, LocalNet ids and private networks.
- [Identity](https://x402-avm.github.io/build/identity): prove which address is calling.
---
# AI agents
> Give an AI agent a wallet and a budget: it calls paid MCP tools on its own, checks prices, and refuses anything over its limits.
By the end of this page your agent can call paid tools without anyone provisioning accounts or API keys, and it cannot spend more than you allow. All it needs is a funded Algorand address and a `paid_mcp_session`.
## Give the agent a paid session
```python
import asyncio
import os
from ai_economy_sdk import paid_mcp_session
SERVER = "https://tools.example.com/mcp" # a paid MCP server (Streamable HTTP)
async def run_agent() -> None:
async with paid_mcp_session(
SERVER,
os.environ["AGENT_PRIVATE_KEY"], # base64 Algorand private key of a budget wallet
"mainnet",
spend_controls={"max_amount_per_payment": "$0.10"}, # tighter than the $1 default
) as session:
tools = await session.list_tools()
# Hand `tools.tools` to your model as callable tools; for each tool call it makes:
result = await session.call_tool("summarize", {"text": "..."})
if result.isError:
# The tool failed: the payment was not settled. Decide whether to retry.
...
print(result.content[0].text)
asyncio.run(run_agent())
```
The session is an `mcp.ClientSession`, so it plugs into any agent framework that accepts one; payments are invisible to the framework. Tool discovery works as usual. If a price is outside the spend controls, nothing is signed and the session raises `SpendLimitExceededError`. Every parameter: [Pay from Python](https://x402-avm.github.io/build/pay-from-python#call-paid-mcp-tools).
Develop with `"testnet"` and free [TestNet ALGO](https://x402-avm.github.io/production/networks#testnet), then switch to `"mainnet"`. The session uses AlgoNode's public algod unless you pass `algod_url`.
## What the agent pays for
| Event | Charged? |
|---|---|
| Opening the session, listing tools | No |
| A call priced 0, or covered by a pass | No |
| A paid call that succeeds | Yes, exactly the quoted price |
| A paid call whose tool raises or returns `isError` | No ([settle-on-success](https://x402-avm.github.io/how-it-works#settle-on-success)) |
| A paid call whose settlement fails (`SettlementError: payment settlement failed`) | No |
| The network fee | No: the server's fee payer pays it |
| Resending the same signed payment | Rejected with `402` (`Replay detected` while the first use is in progress, `transaction_simulation_failed` once it has settled), never charged twice |
With `identity=True` (the default) the session proves the agent's address on every request, so a server can honour a [pass](https://x402-avm.github.io/build/pricing#passes) the agent bought, a subscription, a bulk discount or a per-caller price. The proof moves no funds and reveals nothing else. With `identity=False` the agent stays anonymous and pays the standard price.
## Set limits
An agent that can pay needs limits it cannot talk itself out of. No single control bounds total spend, so combine them:
### Use a dedicated budget wallet
Give the agent its own account and fund it with only what it may spend in a period. The balance is the hard limit on total spend. Top it up on a schedule rather than holding a large balance.
### Keep spend controls on, and tight
Set the cap to the most you would pay for any single call, for example `spend_controls={"max_amount_per_payment": "$0.05"}`. A `$` cap is 1,000,000 base units per dollar for ALGO too, so `$1` means 1 ALGO whatever its market price. Never pass `spend_controls=False` to an autonomous agent. [All options](https://x402-avm.github.io/build/pay-from-python#spend-controls).
### Pin the network
Pass the network explicitly. The session registers the payment scheme for that network only, and refuses an offer for a network other than its algod's.
### Allow only the assets you hold
The default allow-list is ALGO and USDC (MainNet and TestNet). Add another ASA only with its own cap, in base units.
### Protect the key
Inject it from a secret store at start-up. Keep it out of prompts, tool arguments, logs and the agent's memory. If the agent's context could leak it, treat it as compromised and rotate it.
### Watch the wallet
Payments are public on chain. Alert on the budget wallet's balance and on unexpected recipients.
Spend controls do not cap the **total** (an agent in a loop can make many payments under the cap), they do not judge **value** (a vendor can price any call up to your cap, so prefer vendors you trust), and they do not apply to **passes** the agent buys directly, which are ordinary payments outside x402.
Whatever the client does, the server side also protects the agent: failed calls are free, a payment is used once, the amount and recipient must equal the quote, and groups that close or rekey accounts are rejected. See [Security](https://x402-avm.github.io/production/security).
## Check a price before paying
x402 has no price list. The price of a call is in the `402` response to that call, and with `PaymentGate` it can depend on the arguments and the caller. MCP's `tools/list` returns no prices; a vendor may mention them in tool descriptions, but the `402` is authoritative.
With `paid_mcp_session` the agent never sees the price, only the result, and the spend cap is its upper bound. That is the right setup for most agents. When an agent must decide per call (to compare vendors, or to ask a person), read the challenge without paying. For a `PaymentGate` server on Streamable HTTP (stateless, the default), one plain HTTP request is enough, without the MCP `initialize` handshake:
```python
import base64, json
import httpx
call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "echo", "arguments": {"text": "hi"}}}
r = httpx.post("http://127.0.0.1:9201/mcp", json=call,
headers={"Accept": "application/json, text/event-stream"})
if r.status_code == 402:
offer = json.loads(base64.b64decode(r.headers["payment-required"]))["accepts"][0]
print(offer["amount"], offer["asset"], offer["payTo"])
```
Nothing is paid or signed. The MCP SDK's client does not expose this HTTP response, which is why the request is made by hand. On the legacy SSE transport the same request goes to the session's `/messages/?session_id=...` endpoint, so you would have to speak SSE at the HTTP level; unless you need per-call approval, rely on spend controls.
For an HTTP API, send the request with a client that does not pay:
```python
import httpx
from x402.http import decode_payment_required_header
response = httpx.get(url)
if response.status_code == 402:
required = decode_payment_required_header(response.headers["payment-required"])
for offer in required.accepts:
print(offer.network, offer.asset, offer.amount, offer.pay_to)
```
```ts
import { decodePaymentRequired, selectRequirement } from 'x402-avm-js';
const res = await fetch(url);
if (res.status === 402) {
const required = decodePaymentRequired(res.headers.get('PAYMENT-REQUIRED')!);
const offer = selectRequirement(required, 'mainnet'); // throws if nothing is offered on MainNet
console.log(offer.amount, offer.asset, offer.payTo);
}
```
An offer such as `"asset": "31566704", "amount": "50000"` on MainNet means 0.05 USDC (6 decimals). `accepts` can hold several offers, for example one per network; a client pays one. Every field: [HTTP 402 reference](https://x402-avm.github.io/reference/protocol/http-402). To filter offers automatically with the official Python client, use a [payment policy](https://x402-avm.github.io/build/pay-from-python#registration-options-and-policies).
## Agents in JavaScript
`x402-avm-js` has no MCP session wrapper. A Node agent that calls x402 HTTP APIs uses `decodePaymentRequired` and `payForRequirement` with [spend controls](https://x402-avm.github.io/build/pay-from-browser#spend-controls); see [Pay from Node.js](https://x402-avm.github.io/build/pay-from-node).
---
# Identity
> Prove which Algorand address is calling, from Python or any wallet, and verify the proof on your server.
Use this page when your server needs to know who is calling, for passes, subscriptions, bulk discounts or per-caller prices, or when your client needs to tell it. The caller signs a proof with its key; nothing is submitted and nothing is paid. [Why the proof is a transaction](https://x402-avm.github.io/how-it-works#identity-proofs).
## Create and verify a proof
```python
from ai_economy_sdk import genesis_hash_for, sign_identity_txn, verify_identity_txn
gh = genesis_hash_for("mainnet")
# Client: one header, {"X-Identity-Txn": "..."}
headers = sign_identity_txn(client_private_key, gh)
# Server: the address, or None
address = verify_identity_txn(headers["X-Identity-Txn"], gh)
```
```ts
import algosdk from 'algosdk';
import { buildIdentityTxn, encodeIdentityHeader, MAINNET } from 'x402-avm-js';
const txn = buildIdentityTxn(myAddress, MAINNET.genesisHash);
// With a browser wallet
const [signed] = await wallet.signTransactions([algosdk.encodeUnsignedTransaction(txn)], [0]);
// Or with a local key: const signed = txn.signTxn(account.sk);
const headers = { 'X-Identity-Txn': encodeIdentityHeader(signed!) };
```
`x402-avm-js` creates proofs but does not verify them; verify on the server with `ai-economy-sdk`. On LocalNet, read the genesis hash from algod instead of using a preset. In algosdk v3 it is a `Uint8Array`, so encode it: `algosdk.bytesToBase64((await algod.getTransactionParams().do()).genesisHash!)`.
`PaymentGate` verifies identity on every tool call with `verify_identity`: it checks `X-Identity-Txn` first, against the gate's network, and falls back to the legacy headers. In your own server:
```python
from ai_economy_sdk import verify_identity_txn
address = verify_identity_txn(request.headers.get("X-Identity-Txn"), GENESIS_HASH_B64, max_skew=120)
if address is None:
raise HTTPException(status_code=401, detail="invalid identity proof")
```
## The two formats
| Format | Headers | Create with | Used by |
|---|---|---|---|
| Identity transaction (recommended) | `X-Identity-Txn` | `sign_identity_txn` (Python), `buildIdentityTxn` + `encodeIdentityHeader` (JavaScript) | Browser wallets and any client that can sign Algorand transactions |
| Legacy signature | `x-sender-address`, `x-sender-timestamp`, `x-sender-signature` | `sign_identity` (Python, deprecated since 0.5.0) | `paid_mcp_session` (on every request when `identity=True`) |
`sign_identity(private_key)` signs the message `x402-identity::` with Ed25519 (algosdk's `sign_bytes`) and returns the three headers. It emits a `DeprecationWarning`: use `sign_identity_txn()`, which binds the proof to one network. Servers keep accepting the legacy headers, and `paid_mcp_session` still sends them.
## The identity transaction
`make_identity_txn` (Python) and `buildIdentityTxn(address, genesisHashB64, ts?)` (JavaScript) build:
| Field | Value | Why |
|---|---|---|
| type | `pay` | An ordinary payment the wallet can display and sign |
| sender, receiver | the caller | A self-payment moves nothing |
| amount | 0 | |
| fee | 0 (flat) | Below the network minimum, so it cannot be confirmed |
| first valid, last valid | 1, 1000 | A window every live network has passed |
| genesis hash | the network's | Binds the proof to one network |
| note | `x402-identity::` | Binds the proof to the caller and a time |
The caller signs it, msgpack-encodes the signed transaction, base64-encodes the bytes and sends them as `X-Identity-Txn`.
`verify_identity_txn(header_value, expected_genesis_hash_b64, max_skew=120)` returns the address, or `None` if any check fails:
1. The header decodes to a signed transaction with a plain Ed25519 signature: no multisig, no logic signature, no rekeyed (authorized) signer.
2. Type `pay`, sender equals receiver, amount 0, fee 0, no close-to, no rekey-to.
3. The genesis hash equals the expected one.
4. The validity window is at most 1,000 rounds.
5. The note is `x402-identity::` and the timestamp is within `max_skew` seconds of the server's clock.
6. The signature verifies against the sender's public key.
For the legacy headers, `verify_identity` checks the address, the 120-second skew and the signature.
## Examples
Python: sign a proof for the current LocalNet, verify it, and show that a different genesis hash is rejected.
```python
"""Identity proof verification via zero-fee self-signed Algorand transactions.
Demonstrates sign_identity_txn and verify_identity_txn:
1. Generates an account and constructs an X-Identity-Txn header bound to the network genesis hash.
2. Verifies the header on the receiver side, asserting the recovered address matches the signer.
3. Proves that verifying with a mismatched genesis hash rejects the signature (returns None).
How to run:
python localnet/identity.py
What it prints:
Address: <44-character Algorand address>
Verified address matches: True
Wrong genesis hash rejected: True
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from algosdk import account
from ai_economy_sdk import sign_identity_txn, verify_identity_txn
from _localnet import ALGOD
WRONG_GENESIS_HASH = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
def main() -> None:
sk, addr = account.generate_account()
print(f"Address: {addr}")
# Read current LocalNet genesis hash
sp = ALGOD.suggested_params()
current_gh = sp.gh
# 1. Sign identity proof for the current network
headers = sign_identity_txn(sk, current_gh)
# 2. Verify with matching genesis hash
verified_address = verify_identity_txn(headers["X-Identity-Txn"], current_gh)
matches = verified_address == addr
print(f"Verified address matches: {matches}")
# 3. Attempt verification with mismatched genesis hash
rejected = verify_identity_txn(headers["X-Identity-Txn"], WRONG_GENESIS_HASH)
print(f"Wrong genesis hash rejected: {rejected is None}")
if __name__ == "__main__":
main()
```
Source: [examples/localnet/identity.py](https://github.com/x402-avm/examples/blob/main/localnet/identity.py)
```text
Address: TWSYBERPSVZVWDBE4PCHVFCIPUKWCLGKD6LI56AEX5K7PVDPNCMSAMTTZE
Verified address matches: True
Wrong genesis hash rejected: True
```
JavaScript: build and sign a proof, then verify it with the Python SDK in a subprocess.
```javascript
/**
* Build an X-Identity-Txn proof in JavaScript and verify it with the Python SDK.
*
* node localnet/identity.mjs # set PYTHON to a interpreter that has ai-economy-sdk
*
* The proof is an unsubmitted, zero-fee self-payment signed by the wallet and bound to one
* network's genesis hash.
*/
import { execFileSync } from 'node:child_process';
import algosdk from 'algosdk';
import { MAINNET, buildIdentityTxn, encodeIdentityHeader } from 'x402-avm-js';
const PYTHON = process.env.PYTHON || 'python3';
const VERIFY = `
import sys
from ai_economy_sdk import verify_identity_txn
print(verify_identity_txn(sys.argv[1], sys.argv[2]))
`;
const account = algosdk.generateAccount();
const address = account.addr.toString();
const txn = buildIdentityTxn(address, MAINNET.genesisHash);
const header = encodeIdentityHeader(txn.signTxn(account.sk));
console.log(`Account: ${address}`);
console.log(`Header: ${header.slice(0, 40)}... (${header.length} chars)`);
const verified = execFileSync(PYTHON, ['-c', VERIFY, header, MAINNET.genesisHash], { encoding: 'utf-8' }).trim();
console.log(`Verified: ${verified}`);
if (verified !== address) throw new Error(`Address mismatch: expected ${address}, got ${verified}`);
console.log('Identity proof verified.');
```
Source: [examples/localnet/identity.mjs](https://github.com/x402-avm/examples/blob/main/localnet/identity.mjs)
```bash
node localnet/identity.mjs
```
It prints the account address, the start of the encoded header, and the address returned by `verify_identity_txn`.
## Next
- [Pricing and passes](https://x402-avm.github.io/build/pricing): what servers do with the address.
- [Identity reference](https://x402-avm.github.io/reference/python/ai-economy-sdk/verify-identity-txn)
---
# Run a facilitator
> Verify and settle Algorand x402 payments with x402Facilitator, sponsor the network fees, and drive the scheme directly without HTTP.
Use this page when you run the facilitator yourself: as a separate service for several resource servers, or by calling verify and settle directly. If you use `PaymentGate` or the in-process setup on [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api), a facilitator is already running and you can skip this page.
## Verify and settle without HTTP
This script builds a 10,000 microALGO payment with the client scheme, then verifies and settles it with the facilitator scheme, on [LocalNet](https://x402-avm.github.io/production/networks#localnet):
```python
"""The x402 exact-scheme lifecycle on LocalNet with no web framework.
Requirements -> client signs payload -> facilitator verifies -> facilitator settles on-chain.
python localnet/manual_flow.py
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from x402.schemas import PaymentPayload, PaymentRequirements
from x402_algorand import PayerAvmSigner, ServerAvmSigner, caip2_from_genesis_hash
from x402_algorand.exact.client import ExactAvmScheme as ClientScheme
from x402_algorand.exact.facilitator import ExactAvmScheme as FacilitatorScheme
from _localnet import ALGOD, ALGOD_TOKEN, ALGOD_URL, new_funded_account
network = caip2_from_genesis_hash(ALGOD.suggested_params().gh)
server_sk, server_addr = new_funded_account()
client_sk, client_addr = new_funded_account()
print(f"server {server_addr}\nclient {client_addr}\nnetwork {network}")
client_scheme = ClientScheme(PayerAvmSigner.from_private_key(client_sk), algod_url=ALGOD_URL, algod_token=ALGOD_TOKEN)
facilitator = FacilitatorScheme(ServerAvmSigner.from_private_key(server_sk, ALGOD))
requirements = PaymentRequirements(
scheme="exact", network=network, asset="0", amount="10000", pay_to=server_addr,
max_timeout_seconds=300, extra={"feePayer": server_addr},
)
payload = PaymentPayload(
x402_version=2, payload=client_scheme.create_payment_payload(requirements), accepted=requirements
)
verified = facilitator.verify(payload, requirements)
assert verified.is_valid, verified.invalid_reason
print(f"verified payment from {verified.payer}")
settled = facilitator.settle(payload, requirements)
assert settled.success, settled.error_reason
round_ = ALGOD.pending_transaction_info(settled.transaction)["confirmed-round"]
print(f"settled {settled.transaction} in round {round_}")
```
Source: [examples/localnet/manual_flow.py](https://github.com/x402-avm/examples/blob/main/localnet/manual_flow.py)
```bash
python localnet/manual_flow.py
```
It prints both addresses, the network, the verification result, the settled transaction id and the confirmed round.
## Create the facilitator
The facilitator needs a signer that implements [`FacilitatorAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/facilitator-avm-signer): it manages one or more fee payer accounts and talks to algod. [`ServerAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/server-avm-signer) is a ready-made one:
```python
import os
from algosdk.v2client import algod
from x402 import x402Facilitator
from x402_algorand import ALGORAND_MAINNET_CAIP2, ServerAvmSigner
from x402_algorand.exact import register_exact_avm_facilitator
algod_client = algod.AlgodClient("", "https://mainnet-api.algonode.cloud")
signer = ServerAvmSigner.from_mnemonic(os.environ["FEE_PAYER_MNEMONIC"], algod_client)
facilitator = x402Facilitator()
register_exact_avm_facilitator(facilitator, signer, ALGORAND_MAINNET_CAIP2)
```
- Constructors: `from_private_key(key, algod_client=None, *, algod_url=None, algod_token=None)`, `from_mnemonic(...)`, or `ServerAvmSigner([key1, key2], algod_client)` for several fee payers, of which the facilitator picks one at random per request. `ServerAvmSigner` also implements `ClientAvmSigner`.
- With an algod client (or `algod_url=` / `algod_token=`), the first use for a network checks that the node's genesis hash matches it and raises `NetworkMismatchError` otherwise. Without one, the signer uses the algod URL configured for the network in `NETWORK_CONFIGS`: AlgoNode for MainNet and TestNet, or a network added with [`register_network`](https://x402-avm.github.io/production/networks#private-networks).
- `simulate_group` raises `SimulationError` when algod reports that the group would fail; `sign_transaction` / `sign_group` raise `SigningError` for an address the signer does not manage. A malformed key or mnemonic also raises `SigningError`.
- Keys stay in private attributes and are not shown by `repr()`, exception messages or logs. `signer.address` is the first managed address, handy as `pay_to`.
To keep fee payer keys in a KMS or HSM, implement the protocol yourself. `DefaultAvmSigner(private_key, algod_client=...)` from `ai-economy-sdk` also implements it.
`register_exact_avm_facilitator` takes one network id or a list, and also registers the scheme for the x402 v1 names `algorand-mainnet` and `algorand-testnet`. Use the sync `x402FacilitatorSync` with Flask and other WSGI code.
## What verify and settle do
- `facilitator.verify(payload, requirements)` checks the group against the requirement, checks every transaction sent by one of its own addresses (a 0-amount self-payment, no close-out or rekey, fee at most 16,000 microALGO), signs the fee payer transaction and simulates the group on algod. It returns `VerifyResponse(is_valid=True, payer=)`, or `is_valid=False` with `invalid_reason` set to an [error code](https://x402-avm.github.io/reference/errors). Nothing is submitted.
- `facilitator.settle(payload, requirements)` verifies again, signs the fee payer transaction, submits the group, waits up to 4 rounds for confirmation and returns `SettleResponse(success=True, transaction=, network=)`. `transaction` is the ID of the buyer's payment (`paymentGroup[paymentIndex]`), as the specification requires. If submission fails it returns `success=False` with `error_reason="transaction_failed"`.
An invalid payment never raises; `verify()` and `settle()` return a code. The facilitator refuses a payment whose sender is one of its own fee payer addresses (`invalid_exact_avm_payload_fee_payer_transferring_funds`), so the fee payer can never be the buyer. The full order of checks: [AVM exact scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme#verification-steps).
## Next
- [Go to MainNet](https://x402-avm.github.io/production/mainnet#fund-the-fee-payer): fund the fee payer.
- [Security](https://x402-avm.github.io/production/security#abusing-the-fee-payer): what the facilitator refuses to sign.
---
# Networks
> Develop on LocalNet, test on TestNet, run on your own nodes or a private network: CAIP-2 ids, endpoints, funding and network helpers.
Use this page to move a working service from your laptop to a public network. Build on LocalNet, check it against real transactions on TestNet, then follow [Go to MainNet](https://x402-avm.github.io/production/mainnet). The SDKs work the same on all of them; mostly the network name and the endpoints change.
## Networks at a glance
| | MainNet | TestNet | LocalNet |
|---|---|---|---|
| Short name | `mainnet` | `testnet` | `localnet` |
| CAIP-2 id | `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k` | `algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe` | Read from algod |
| Genesis hash | `wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=` | `SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=` | Read from algod |
| Genesis id | `mainnet-v1.0` | `testnet-v1.0` | `dockernet-v1` (AlgoKit) |
| Default algod | `https://mainnet-api.algonode.cloud` | `https://testnet-api.algonode.cloud` | `http://localhost:4001` |
| Default indexer | `https://mainnet-idx.algonode.cloud` | `https://testnet-idx.algonode.cloud` | `http://localhost:8980` |
| USDC asset id | `31566704` | `10458941` | None |
| Constants | Python `MAINNET`, JS `MAINNET` | Python `TESTNET`, JS `TESTNET` | JS `LOCALNET_ENDPOINTS` |
MainNet and TestNet default to the public [AlgoNode](https://algonode.io) endpoints, which need no API key. USDC has 6 decimals: `1000000` base units is 1 USDC. In Python, `MAINNET` and `TESTNET` are the CAIP-2 id strings; in JavaScript they are presets that also carry `genesisHash`, `genesisId`, `algodUrl`, `indexerUrl` and `usdc`.
## Network ids
Wherever an API takes a network, you can pass a short name or a CAIP-2 id. Ids follow the [Algorand CAIP-2 profile](https://github.com/ChainAgnostic/namespaces/blob/main/algorand/caip2.md): `algorand:` plus the first 32 characters of the genesis hash in URL-safe base64 (`+` becomes `-`, `/` becomes `_`, no padding). The official `x402` SDK validates ids against `^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$`, which is why the reference is 32 characters long.
Older releases used the full 44-character genesis hash (`algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=`). These legacy ids are still accepted as input everywhere and converted to the short form; do not write them in new code.
| Input | Resolves to |
|---|---|
| `"mainnet"`, `"algorand-mainnet"`, `"algorand"` | MainNet |
| `"testnet"`, `"algorand-testnet"` | TestNet |
| `"localnet"` (Python also accepts `"algorand-localnet"`, `"dockernet"`, `"sandnet"`) | The network of the LocalNet algod |
| `"algorand:<32 characters>"` | That network |
| `"algorand:<44-character genesis hash>"` | That network, converted to the short id |
These names work in `ai-economy-sdk` and `x402-avm-js`. The lower-level `x402-algorand` functions, such as `normalize_network`, take CAIP-2 ids and the x402 v1 names (`algorand-mainnet`, `algorand-testnet`, `algorand`), not `"mainnet"` or `"localnet"`. In JavaScript, `resolveNetwork("localnet")` throws, because a LocalNet id must be read from a node.
```python
from algosdk.v2client import algod
from ai_economy_sdk import resolve_network, genesis_hash_for, endpoints_for, usdc_asset_id
resolve_network("mainnet") # 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
genesis_hash_for("mainnet") # 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8='
usdc_asset_id("testnet") # 10458941
endpoints_for("testnet").algod_url # 'https://testnet-api.algonode.cloud'
# LocalNet: ask its algod
local = algod.AlgodClient("a" * 64, "http://localhost:4001")
resolve_network("localnet", local) # 'algorand:<32 characters>'
```
```ts
import { MAINNET, algodClient, networkFromAlgod, networkFromGenesisHash, resolveNetwork } from 'x402-avm-js';
resolveNetwork('testnet'); // 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe'
networkFromGenesisHash(MAINNET.genesisHash); // 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
MAINNET.usdc; // 31566704
// LocalNet: ask its algod
const id = await networkFromAlgod(algodClient('localnet'));
```
| JavaScript function | Input | Output |
|---|---|---|
| `resolveNetwork(name)` | A name from the table above (not `"localnet"`), a short id or a legacy id | The short id; throws `UnknownNetworkError` otherwise |
| `networkFromGenesisHash(hash)` | Base64 string or `Uint8Array` | The short id |
| `networkFromAlgod(algod)` | An `Algodv2` client | The id of the node's network (async) |
| `algodClient(network, url?, token?)` | `"mainnet"`, `"testnet"`, `"localnet"`, or any id with a `url` | An `Algodv2` client |
[localnet/networks.py](https://github.com/x402-avm/examples/blob/main/localnet/networks.py) prints this table for all three networks; its LocalNet row differs on your machine.
A payment is bound to its network by the genesis hash in every transaction, and both client and facilitator check it ([details](https://x402-avm.github.io/production/security#payments-from-another-network)).
## LocalNet
LocalNet is a private Algorand network that runs in Docker on your machine, from [AlgoKit](https://github.com/algorandfoundation/algokit-cli). Transactions confirm in seconds, accounts are funded from a built-in dispenser, and nothing costs money. Every example that settles payments runs on it.
```bash
algokit localnet start # start the containers
algokit localnet status # show service status
algokit localnet reset # wipe the chain and start again
algokit localnet stop # stop the containers
```
| Service | URL | Token |
|---|---|---|
| algod | `http://localhost:4001` | 64 × `a` |
| indexer | `http://localhost:8980` | none |
| KMD | `http://localhost:4002` | 64 × `a` |
```bash
curl -s -H "X-Algo-API-Token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
http://localhost:4001/v2/status | grep last-round
```
LocalNet's genesis hash is created with the network, so its id differs on every machine and changes after a reset. Never hard-code it. `PaymentGate`, `AIEconomySDK` and `paid_mcp_session` read it from the signer's (or session's) algod when given `network="localnet"`, and register the network. In JavaScript, `algodClient('localnet')` connects to the defaults in `LOCALNET_ENDPOINTS` (x402-avm-js before 0.4.1 connected to port 80; upgrade), and `payForRequirement` reads the network from the algod you pass.
> **Warning:**
After `algokit localnet reset`, restart your servers and clients. A running server keeps the old network id and rejects payments signed for the new chain with `invalid_exact_avm_payload_genesis_hash_mismatch`. Old accounts and assets are gone; the examples create fresh ones each run.
### Fund test accounts
LocalNet's KMD holds a funded wallet named `unencrypted-default-wallet`. The examples use this helper:
```python
"""LocalNet helper for doc examples: funds test accounts using LocalNet's KMD dispenser."""
from algosdk import account, kmd, transaction
from algosdk.atomic_transaction_composer import AccountTransactionSigner
from algosdk.v2client import algod
ALGOD_URL = "http://localhost:4001"
ALGOD_TOKEN = "a" * 64
KMD_URL = "http://localhost:4002"
KMD_TOKEN = "a" * 64
INDEXER_URL = "http://localhost:8980"
ALGOD = algod.AlgodClient(ALGOD_TOKEN, ALGOD_URL)
def dispenser() -> tuple[str, str]:
"""Retrieve the primary funded account from LocalNet's default unencrypted KMD wallet."""
k = kmd.KMDClient(KMD_TOKEN, KMD_URL)
w = next(x for x in k.list_wallets() if x["name"] == "unencrypted-default-wallet")
h = k.init_wallet_handle(w["id"], "")
addr = max(k.list_keys(h), key=lambda a: ALGOD.account_info(a)["amount"])
return addr, k.export_key(h, "", addr)
def new_funded_account(algos: int = 10) -> tuple[str, str]:
"""Generate a new account and fund it with the specified amount of ALGO from the dispenser."""
sk, addr = account.generate_account()
d_addr, d_sk = dispenser()
sp = ALGOD.suggested_params()
txn = transaction.PaymentTxn(d_addr, sp, addr, algos * 1_000_000)
ALGOD.send_transaction(AccountTransactionSigner(d_sk).sign_transactions([txn], [0])[0])
transaction.wait_for_confirmation(ALGOD, txn.get_txid(), 10)
return sk, addr
```
Source: [examples/localnet/_localnet.py](https://github.com/x402-avm/examples/blob/main/localnet/_localnet.py)
`new_funded_account(algos=10)` returns `(private_key, address)` for a new account holding 10 ALGO. The JavaScript examples do the same with `algosdk.Kmd` in [localnet/_localnet.mjs](https://github.com/x402-avm/examples/blob/main/localnet/_localnet.mjs).
### Assets on LocalNet
LocalNet has no USDC. Price in ALGO (`asset_id=0`) while developing, or create your own ASA. A custom ASA is not one of the client's default assets, so allow it explicitly, and opt both `pay_to` and the buyer in to it:
```python
async with paid_mcp_session(
url, buyer_sk, "localnet",
spend_controls={"allowed_assets": [
{"network": local_network_id, "asset": str(my_asa_id), "max_amount_per_payment": "5000000"}
]},
) as session:
...
```
### Examples that run on LocalNet
From the root of the [examples repository](https://github.com/x402-avm/examples), after `pip install -r requirements.txt` and `npm install`, `bash scripts/run_all_localnet.sh` runs them all in order and starts and stops the servers they need.
| Example | Shown on |
|---|---|
| `localnet/quickstart_server.py`, `quickstart_client.py`, `js_pay.mjs` with `server_for_js.py` | [Quickstart](https://x402-avm.github.io/quickstart) |
| `localnet/paid_mcp_tool/` | [Sell MCP tools](https://x402-avm.github.io/build/sell-mcp-tools) |
| `localnet/pricing.py`, `passes.py` | [Pricing and passes](https://x402-avm.github.io/build/pricing) |
| `localnet/failed_call_not_charged.py` | [How it works](https://x402-avm.github.io/how-it-works#settle-on-success) |
| `localnet/identity.py`, `identity.mjs` | [Identity](https://x402-avm.github.io/build/identity) |
| `localnet/fastapi_paywall.py`, `flask_paywall.py` | [Paywall an HTTP API](https://x402-avm.github.io/build/paywall-http-api) |
| `localnet/httpx_client.py` | [Pay from Python](https://x402-avm.github.io/build/pay-from-python#pay-http-apis) |
| `localnet/browser_paywall/`, `browser_wallet.ts` | [Pay from the browser](https://x402-avm.github.io/build/pay-from-browser) |
| `localnet/manual_flow.py` | [Run a facilitator](https://x402-avm.github.io/build/facilitator) |
## TestNet
TestNet is a public network whose ALGO has no value. Payments are real transactions that anyone can see in an explorer, so it is where you check a deployment before MainNet.
### Create two accounts
A server account (it receives payments and pays the group fees) and a buyer:
```python
from algosdk import account, mnemonic
for role in ("server", "buyer"):
sk, addr = account.generate_account()
print(role, addr)
print(role, "mnemonic:", mnemonic.from_private_key(sk))
```
Keep the mnemonics in a secret store or environment variables. `mnemonic.to_private_key(...)` turns one back into the base64 key the SDKs take.
### Fund them with free TestNet ALGO
Use the dispenser at [lora.algokit.io/testnet/fund](https://lora.algokit.io/testnet/fund). A few ALGO each is plenty: the server pays 2,000 microALGO per settled call (1 ALGO covers 500 calls), and every account keeps a [minimum balance](https://x402-avm.github.io/resources/glossary#mbr) of 0.1 ALGO.
### Run the server
Compared with the Quickstart server, only the network, the algod client and the key source change:
```python
import os
import uvicorn
from algosdk import account, mnemonic
from algosdk.v2client import algod
from fastmcp import FastMCP
from ai_economy_sdk import DefaultAvmSigner, PaymentGate
server_sk = mnemonic.to_private_key(os.environ["SERVER_MNEMONIC"])
server_addr = account.address_from_private_key(server_sk)
algod_client = algod.AlgodClient("", "https://testnet-api.algonode.cloud")
mcp = FastMCP("TestNetServer")
@mcp.tool()
def echo(text: str) -> str:
"""Echo back input text."""
return f"echo: {text}"
gate = PaymentGate(
signer=DefaultAvmSigner(server_sk, algod_client=algod_client),
network="testnet",
pay_to=server_addr,
asset_id=0,
prices={"echo": 5000},
)
uvicorn.run(gate.wrap(mcp, transport="streamable-http"), host="127.0.0.1", port=9201)
```
### Pay from the client
`paid_mcp_session` uses the public TestNet algod when `network="testnet"`:
```python
import asyncio
import os
from algosdk import mnemonic
from ai_economy_sdk import paid_mcp_session
async def main() -> None:
buyer_sk = mnemonic.to_private_key(os.environ["BUYER_MNEMONIC"])
async with paid_mcp_session("http://127.0.0.1:9201/mcp", buyer_sk, "testnet") as session:
result = await session.call_tool("echo", {"text": "hello testnet"})
print(result.content[0].text)
asyncio.run(main())
```
Look up either address in the [Lora explorer](https://lora.algokit.io/testnet) to see the settled group.
These two scripts are the Quickstart scripts with TestNet settings. For a tested TestNet payment, run [`testnet/live_payment.py`](https://github.com/x402-avm/examples/blob/main/testnet/live_payment.py). It makes one real 1,000 microALGO payment with the client and facilitator schemes, with the server account as fee payer, and prints the confirmed transaction id and an explorer link. Without both mnemonics set it prints instructions and exits with status 0.
```bash
export TESTNET_BUYER_MNEMONIC="..." # buyer, funded at lora.algokit.io/testnet/fund
export TESTNET_SERVER_MNEMONIC="..." # receiver and fee payer, also funded
python testnet/live_payment.py
```
To charge TestNet USDC (asset `10458941`), follow [Accept USDC](https://x402-avm.github.io/production/mainnet#accept-usdc) with the TestNet asset id.
### Check payments without funds
You can validate payment groups against live TestNet state with no keys or funds: build the group with a signer that signs nothing, then ask algod to simulate it with empty signatures allowed. These scripts find funded accounts through the public indexer and simulate four cases: ALGO and USDC, each with and without a fee payer. The package test suites run the same kind of checks with `PUBLIC_NETS=1`.
**Python**
```python
"""Public network simulation for x402 Algorand payments on TestNet.
Performs read-only validation against real TestNet ledger without spending funds:
1. Queries the public AlgoNode indexer to identify real funded accounts holding USDC and ALGO.
2. Constructs payment groups for ALGO (asset 0) and USDC (asset 10458941), both with and without fee payers.
3. Evaluates the constructed atomic groups via Algod's simulate endpoint using empty signatures.
4. Confirms that all 4 test cases simulate successfully without on-chain execution.
How to run:
python testnet/simulate.py
What it prints:
Network progress and "ok" for each of the 4 test cases.
"""
import httpx
from algosdk import encoding, transaction
from algosdk.v2client import algod
from algosdk.v2client.models import SimulateRequest, SimulateRequestTransactionGroup
from x402.schemas import PaymentRequirements
from x402_algorand.constants import ALGORAND_TESTNET_CAIP2
from x402_algorand.exact.client import ExactAvmScheme as ExactAvmClient
CONFIG = {
"name": "testnet",
"caip": ALGORAND_TESTNET_CAIP2,
"algod_url": "https://testnet-api.algonode.cloud",
"indexer_url": "https://testnet-idx.algonode.cloud",
"usdc_id": 10458941,
}
class _WatchOnly:
"""Watch-only signer providing an address without private keys.
Generates unsigned transactions for simulate endpoint evaluation.
"""
def __init__(self, address: str):
self.address = address
def sign_transactions(self, txns: list[bytes], indexes: list[int]) -> list[None]:
return [None] * len(txns)
def get_algod(cfg: dict) -> algod.AlgodClient:
return algod.AlgodClient("", cfg["algod_url"])
def find_funded_holders(cfg: dict, n: int = 3) -> list[str]:
"""Find real funded accounts holding ALGO and USDC via public indexer."""
client = get_algod(cfg)
idx_url = cfg["indexer_url"]
usdc_id = cfg["usdc_id"]
resp = httpx.get(
f"{idx_url}/v2/assets/{usdc_id}/balances",
params={"currency-greater-than": 5_000_000, "limit": 40},
timeout=20,
)
balances = resp.json().get("balances", [])
out = []
for b in balances:
try:
info = client.account_info(b["address"])
if info["amount"] - info["min-balance"] > 2_000_000 and not info.get("auth-addr"):
out.append(b["address"])
if len(out) == n:
return out
except Exception:
continue
raise RuntimeError(f"Could not find {n} funded USDC holders on {cfg['name']}")
def simulate_group(client: algod.AlgodClient, group_b64: list[str]) -> str | None:
"""Run transaction group through Algod simulation with empty signatures."""
stx = []
for b in group_b64:
d = encoding.msgpack_decode(b)
stx.append(
d
if isinstance(d, transaction.SignedTransaction)
else transaction.SignedTransaction(d, None)
)
req = SimulateRequest(
txn_groups=[SimulateRequestTransactionGroup(txns=stx)],
allow_empty_signatures=True,
)
res = client.simulate_transactions(req)
return res["txn-groups"][0].get("failure-message")
def main():
net_name = CONFIG["name"]
caip = CONFIG["caip"]
print(f"Testing {net_name} ({caip})...")
holders = find_funded_holders(CONFIG, n=3)
payer, pay_to, fp = holders
client = get_algod(CONFIG)
test_cases = [
("ALGO", "0", True),
("ALGO", "0", False),
("USDC", str(CONFIG["usdc_id"]), True),
("USDC", str(CONFIG["usdc_id"]), False),
]
for asset_name, asset_id, fee_payer in test_cases:
extra = {"feePayer": fp} if fee_payer else {}
req = PaymentRequirements(
scheme="exact",
network=caip,
asset=asset_id,
amount="10000",
pay_to=pay_to,
max_timeout_seconds=300,
extra=extra,
)
avm_client = ExactAvmClient(_WatchOnly(payer), algod_url=CONFIG["algod_url"])
payload = avm_client.create_payment_payload(req)
failure = simulate_group(client, payload["paymentGroup"])
assert failure is None, f"Simulation failed on {net_name} {asset_name} (fee_payer={fee_payer}): {failure}"
print(f" {net_name} {asset_name} (fee_payer={fee_payer}): ok")
print(f"All {net_name} simulations passed successfully.")
if __name__ == "__main__":
main()
```
Source: [examples/testnet/simulate.py](https://github.com/x402-avm/examples/blob/main/testnet/simulate.py)
**JavaScript**
```javascript
/**
* Read-only simulation of ALGO and USDC payments on Algorand TestNet.
*
* Demonstrates:
* 1. Discovering real funded USDC holders via public AlgoNode indexer endpoints.
* 2. Building exact AVM payment groups using a watch-only signer (empty signatures).
* 3. Verifying transaction group validity on live TestNet nodes using algod.simulateTransactions().
* 4. Verifying both native ALGO and ASA USDC transfers, with and without fee payers.
*
* How to run:
* node testnet/simulate.mjs
*
* What it prints:
* Found account addresses on TestNet and "ok" for each simulated payment scenario.
*/
import algosdk from 'algosdk';
import {
TESTNET,
X402AvmError,
algodClient,
payForRequirement,
} from 'x402-avm-js';
// Refuse anything above 10,000 base units (the default cap is 1,000,000).
const SPEND_CONTROLS = { maxAmount: 10_000n };
async function fundedUsdcHolders(net, algod) {
const url = `${net.indexerUrl}/v2/assets/${net.usdc}/balances?currency-greater-than=5000000&limit=40`;
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Indexer query failed with status ${res.status}`);
}
const rows = (await res.json()).balances;
const out = [];
for (const row of rows) {
const info = await algod.accountInformation(row.address).do();
if (info.amount - info.minBalance > 2_000_000n && !info.authAddr) {
out.push(row.address);
}
if (out.length === 3) return out;
}
throw new Error(`Not enough funded USDC holders found on ${net.genesisId}`);
}
async function main() {
const name = 'testnet';
const net = TESTNET;
console.log(`Testing ${name} (${net.caip2})...`);
const algod = algodClient(name);
const [payer, payTo, feePayer] = await fundedUsdcHolders(net, algod);
console.log(`Discovered active accounts:`);
console.log(` Payer: ${payer}`);
console.log(` PayTo: ${payTo}`);
console.log(` Fee payer: ${feePayer}`);
const cases = [
{ asset: 'ALGO', assetId: '0', withFeePayer: true },
{ asset: 'ALGO', assetId: '0', withFeePayer: false },
{ asset: 'USDC', assetId: String(net.usdc), withFeePayer: true },
{ asset: 'USDC', assetId: String(net.usdc), withFeePayer: false },
];
for (const c of cases) {
const requirement = {
scheme: 'exact',
network: net.caip2,
asset: c.assetId,
amount: '10000',
payTo,
maxTimeoutSeconds: 300,
extra: c.withFeePayer ? { feePayer } : {},
};
const emptySigner = async (txns) => txns.map(() => null);
const challenge = {
x402Version: 2,
accepts: [requirement],
};
const paymentSignatureHeader = await payForRequirement(challenge, payer, algod, emptySigner, SPEND_CONTROLS);
const decoded = JSON.parse(new TextDecoder().decode(algosdk.base64ToBytes(paymentSignatureHeader)));
const txns = decoded.payload.paymentGroup.map(
(b64) =>
new algosdk.SignedTransaction({
txn: algosdk.decodeUnsignedTransaction(algosdk.base64ToBytes(b64)),
})
);
const sim = await algod
.simulateTransactions(
new algosdk.modelsv2.SimulateRequest({
txnGroups: [new algosdk.modelsv2.SimulateRequestTransactionGroup({ txns })],
allowEmptySignatures: true,
})
)
.do();
const failure = sim.txnGroups[0].failureMessage ?? null;
if (failure) {
throw new Error(`Simulation failed on ${name} ${c.asset} (withFeePayer=${c.withFeePayer}): ${failure}`);
}
console.log(` ${name} ${c.asset} (fee_payer=${c.withFeePayer}): ok`);
}
console.log(`All ${name} simulations passed successfully.`);
}
main().catch((err) => {
// x402-avm-js errors carry a stable `code`, e.g. SPEND_LIMIT_EXCEEDED.
console.error('TestNet simulation failed:', err instanceof X402AvmError ? `${err.code}: ${err.message}` : err);
process.exit(1);
});
```
Source: [examples/testnet/simulate.mjs](https://github.com/x402-avm/examples/blob/main/testnet/simulate.mjs)
```bash
python testnet/simulate.py
node testnet/simulate.mjs
```
## Use your own nodes
Environment variables replace the default endpoints. Python reads them when `x402_algorand` and `ai_economy_sdk` are imported.
| Variable | Network | Default |
|---|---|---|
| `ALGOD_MAINNET_URL`, `INDEXER_MAINNET_URL` | MainNet | AlgoNode |
| `ALGOD_TESTNET_URL`, `INDEXER_TESTNET_URL` | TestNet | AlgoNode |
| `ALGOD_LOCALNET_URL`, `INDEXER_LOCALNET_URL` | LocalNet (`ai-economy-sdk`) | `http://localhost:4001`, `http://localhost:8980` |
Or pass endpoints directly: `paid_mcp_session(..., algod_url=..., algod_token=...)`, `DefaultAvmSigner(key, algod_client=...)` and `ChainReader(indexer_url)` in Python, `algodClient(network, url, token)` in JavaScript.
## Private networks
Register a private or consortium network once at start-up. Registration needs the full genesis hash, because a 32-character id cannot be turned back into a hash; the simplest way is to read it from the network's algod.
```python
from algosdk.v2client import algod
from ai_economy_sdk import network_from_algod, register_network
# Read the genesis hash from a node, register the network, get its CAIP-2 id
node = algod.AlgodClient(token, "http://node.private.lan:4001")
network_id = network_from_algod(node)
# Or register from the full 44-character genesis hash (bare or as "algorand:")
register_network(
"algorand:mFgazF+2uRS1tMiL9dsj01hJGySEmPN28B/TjjvpVW0=",
genesis_id="my-private-net-v1",
algod_url="http://node.private.lan:4001",
indexer_url="http://indexer.private.lan:8980",
)
```
```python
from x402_algorand import register_network
network_id = register_network(
genesis_hash="mFgazF+2uRS1tMiL9dsj01hJGySEmPN28B/TjjvpVW0=",
genesis_id="privatenet-v1",
algod_url="http://node.internal:4001",
indexer_url="http://node.internal:8980",
)
# 'algorand:mFgazF-2uRS1tMiL9dsj01hJGySEmPN2'
```
`network_from_algod` registers the network with the default LocalNet URLs, and `x402_algorand.register_network` without URLs uses `http://localhost:4001` and `http://localhost:8980`. So pass your node explicitly where the SDK takes one: `DefaultAvmSigner(key, algod_client=node)` on the server, `paid_mcp_session(..., algod_url=..., algod_token=...)` on the client.
In JavaScript nothing needs registering: create a client with `algodClient(networkId, url, token)` and `payForRequirement` reads the network from that node.
### x402-algorand network utilities
All are exported from `x402_algorand` and `x402_algorand.utils`:
```python
import base64
from x402_algorand.utils import caip2_from_genesis_hash, get_genesis_hash, normalize_network
# Genesis hash (base64 string or 32 raw bytes) to CAIP-2 id
caip2_from_genesis_hash("wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=")
caip2_from_genesis_hash(base64.b64decode("wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8="))
# both 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
# x402 v1 names and legacy 44-character ids to short ids; valid short ids pass through
normalize_network("algorand-testnet") # 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe'
normalize_network("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=")
# 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe'
# Full base64 genesis hash of a registered network
get_genesis_hash("algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k")
# 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8='
```
`normalize_network` raises `NetworkError` (a `ValueError`) for anything else, including `"mainnet"` and `"localnet"`. More, such as `get_network_config` and `network_from_genesis_hash`: [x402-algorand reference](https://x402-avm.github.io/reference/python/x402-algorand/index).
## Next
When TestNet works, follow [Go to MainNet](https://x402-avm.github.io/production/mainnet).
---
# Go to MainNet
> A go-live checklist for a paid service on Algorand MainNet: USDC pricing and opt-ins, funding the fee payer, keys, workers, one config for every network, simulation and monitoring.
Work through this page when your service runs on [TestNet](https://x402-avm.github.io/production/networks#testnet) and you are ready to take real money. On MainNet, payments move real ALGO and USDC.
## What changes
| | LocalNet | MainNet | Check |
|---|---|---|---|
| Network id | read from algod | `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k` | The id matches the algod's genesis hash |
| Asset | ALGO (`0`) | USDC (`31566704`) or ALGO | `pay_to` has opted in to USDC |
| algod, indexer | `localhost:4001`, `localhost:8980` | AlgoNode or your own nodes | Latency, rate limits, uptime; the indexer is needed for passes, subscriptions and bulk discounts |
| Keys | KMD dispenser | Secret manager or platform secrets | No keys in source code or images |
| Fee payer | funded from KMD | funded with real ALGO | Low-balance alert |
| Minimum balance | 0.1 ALGO | 0.1 ALGO plus 0.1 ALGO per opted-in asset | `pay_to` and fee payer cover it |
| Replay store | in memory | SQLite (`replay_db`) with several workers | Shared by every worker |
| Clock | any | NTP-synchronized | Identity proofs allow 120 seconds of skew |
## Go-live checklist
### Separate the accounts
Use a receiving account (`pay_to`) where revenue collects, and a separate fee payer account holding only the ALGO needed for fees. In `PaymentGate` the fee payer is the `signer`'s account; `pay_to` can be any address.
### Opt in to USDC
If you price in USDC, opt `pay_to` in to asset `31566704`; every buyer must opt in too. See [Accept USDC](#accept-usdc).
### Fund the fee payer
Enough ALGO for the calls you expect plus its minimum balance, with an alert. See [Fund the fee payer](#fund-the-fee-payer).
### Load keys from a secret store
Never put private keys or mnemonics in source code or images. See [Keys](#keys).
### Share the replay store across workers
With more than one worker process, pass `replay_db="/var/lib//replay.db"`. See [Replay store](https://x402-avm.github.io/production/security#replay-store).
### Use reliable nodes
The public AlgoNode endpoints need no key. For production traffic, consider your own node or a provider with an SLA, and [point the SDKs at it](https://x402-avm.github.io/production/networks#use-your-own-nodes).
### Keep the clock in sync
Run NTP on servers that rely on passes, subscriptions or per-caller prices: identity proofs are accepted only within 120 seconds of the server's clock.
### Simulate before you go live
Check ALGO and USDC payment groups against MainNet without keys or funds. See [Simulate on MainNet](#simulate-on-mainnet).
### Monitor
Fee payer balance, settlement failures, replay rejections. See [Monitor](#monitor).
## Server configuration
```python
import os
from algosdk import mnemonic
from algosdk.v2client import algod
from fastmcp import FastMCP
from ai_economy_sdk import MAINNET, DefaultAvmSigner, PaymentGate, usdc_asset_id
mcp = FastMCP("AnalysisService") # your tools: @mcp.tool() ...
algod_client = algod.AlgodClient(
os.environ.get("ALGOD_TOKEN", ""),
os.environ.get("ALGOD_URL", "https://mainnet-api.algonode.cloud"),
)
fee_payer_sk = mnemonic.to_private_key(os.environ["FEE_PAYER_MNEMONIC"])
gate = PaymentGate(
signer=DefaultAvmSigner(fee_payer_sk, algod_client=algod_client),
network=MAINNET,
pay_to=os.environ["VENDOR_ADDRESS"],
asset_id=usdc_asset_id(MAINNET), # 31566704
prices={"analyze": 100_000}, # 0.10 USDC
replay_db="/var/lib/my-service/replay.db",
)
app = gate.wrap(mcp, transport="streamable-http") # MCP endpoint: POST /mcp
```
Run it with several workers, for example `uvicorn server_mainnet:app --workers 4`.
On the client side, `paid_mcp_session(server_url, buyer_sk, "mainnet")` uses the public MainNet algod unless you pass `algod_url`. Its default [spend controls](https://x402-avm.github.io/build/pay-from-python#spend-controls) allow ALGO and MainNet USDC up to 1,000,000 base units per payment. Keep a buyer's balance small: the cap does not limit how many payments a session makes.
## Accept USDC
| Network | USDC asset id | Decimals |
|---|---|---|
| MainNet | `31566704` (Circle USDC) | 6 |
| TestNet | `10458941` | 6 |
| LocalNet | none: use ALGO or your own ASA | |
`usdc_asset_id(network)` (Python) and `MAINNET.usdc` / `TESTNET.usdc` (JavaScript) return these ids. Prices are integers in base units:
| USDC | Base units |
|---|---|
| 1.00 | `1000000` |
| 0.10 | `100000` |
| 0.01 | `10000` |
| 0.005 | `5000` |
**Opt in.** An Algorand account only holds assets it has opted in to, which stops unwanted assets being sent to it. Both the vendor's `pay_to` account and every buyer need a 0-amount transfer of the asset to themselves:
```python
from algosdk.transaction import AssetTransferTxn, wait_for_confirmation
from algosdk.atomic_transaction_composer import AccountTransactionSigner
def opt_in(algod_client, address: str, private_key: str, asset_id: int) -> None:
sp = algod_client.suggested_params()
txn = AssetTransferTxn(sender=address, sp=sp, receiver=address, amt=0, index=asset_id)
txid = algod_client.send_transaction(AccountTransactionSigner(private_key).sign_transactions([txn], [0])[0])
wait_for_confirmation(algod_client, txid, 4)
```
Each opt-in raises the account's minimum balance by 0.1 ALGO, so the account needs that ALGO first. If either side has not opted in, the facilitator's simulation fails with `transaction_simulation_failed`, and the node's message in `invalid_message` names the account.
**Fees stay in ALGO.** The buyer spends only USDC; the fee payer spends 2,000 microALGO per call ([why](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group)). The [fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor) does not apply to USDC prices.
**For an HTTP API** with `x402-algorand`, put the asset in the route price: `{"amount": "50000", "asset": "31566704"}`.
**Clients** allow MainNet and TestNet USDC by default, up to 1 USDC per payment. Buyers with higher prices raise the cap, for example `spend_controls={"max_amount_per_payment": "$5"}`.
**On TestNet**, use asset `10458941` and get test USDC from Circle's faucet at [faucet.circle.com](https://faucet.circle.com):
```python
from ai_economy_sdk import TESTNET, PaymentGate, usdc_asset_id
gate = PaymentGate(
signer=signer,
network=TESTNET,
pay_to=server_addr,
asset_id=usdc_asset_id(TESTNET), # 10458941
default_price=50_000, # 0.05 USDC per call
)
```
## Fund the fee payer
The fee payer pays 2,000 microALGO per settled call, whatever asset the price is in:
| Settled calls | Fees |
|---|---|
| 500 | 1 ALGO |
| 5,000 | 10 ALGO |
| 50,000 | 100 ALGO |
Add its 0.1 ALGO minimum balance, alert when the balance falls below a threshold (for example 5 ALGO), and top it up from a treasury account. When it runs out, settlement fails and callers get `SettlementError("payment settlement failed: ...")`: they are not charged, but they get no result either.
## Keys
Load keys at start-up from the environment or a secret manager:
```python
import os
from algosdk import mnemonic
if "SERVER_PRIVATE_KEY" in os.environ:
server_key = os.environ["SERVER_PRIVATE_KEY"]
elif "SERVER_MNEMONIC" in os.environ:
server_key = mnemonic.to_private_key(os.environ["SERVER_MNEMONIC"])
else:
raise RuntimeError("missing server credentials")
```
`DefaultAvmSigner` keeps the key in process memory and signs only the fee payer transaction of each group. Since 0.5.0 the key is not in a public attribute and `repr()` shows only the address; `DefaultAvmSigner.private_key` is read-only and deprecated, so keep your own reference if you need the key. Hold only working capital in the fee payer.
## One configuration for every network
[`shared/config.py`](https://github.com/x402-avm/examples/blob/main/shared/config.py) builds the endpoints, network id and payment asset from one `NETWORK` variable (`localnet`, `testnet` or `mainnet`): ALGO on LocalNet, USDC on TestNet and MainNet. It reads `NETWORK`, `ALGOD_URL`, `ALGOD_TOKEN`, `INDEXER_URL` and `INDEXER_TOKEN`.
```python
"""Multi-network configuration manager for Algorand payments.
Switches configuration between LocalNet, TestNet, and MainNet using the
NETWORK environment variable. Selects ALGO for LocalNet development and
USDC for TestNet and MainNet.
Usage:
NETWORK=localnet python shared/config.py
NETWORK=testnet python shared/config.py
NETWORK=mainnet python shared/config.py
Dry run:
python shared/config.py --dry-run
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Literal
from ai_economy_sdk import (
MAINNET,
TESTNET,
endpoints_for,
is_public,
resolve_network,
usdc_asset_id,
)
from algosdk.v2client import algod, indexer
NetworkName = Literal["localnet", "testnet", "mainnet"]
@dataclass(frozen=True)
class NetworkConfig:
"""Resolved runtime configuration for Algorand payments."""
network_name: NetworkName
network_id: str
algod_url: str
algod_token: str
indexer_url: str
indexer_token: str
asset_id: int
asset_name: str
asset_decimals: int
is_public: bool
fee_payer_funded: bool
def get_algod_client(self) -> algod.AlgodClient:
"""Construct AlgodClient with configured endpoint and headers."""
return algod.AlgodClient(self.algod_token, self.algod_url)
def get_indexer_client(self) -> indexer.IndexerClient:
"""Construct IndexerClient with configured endpoint and headers."""
return indexer.IndexerClient(self.indexer_token, self.indexer_url)
def load_network_config(network_name: str | None = None) -> NetworkConfig:
"""Load and validate configuration for the requested or environment network.
Args:
network_name: Target network ('localnet', 'testnet', 'mainnet').
Defaults to the NETWORK environment variable, or 'localnet'.
Returns:
Immutable NetworkConfig dataclass.
"""
raw_name = (network_name or os.environ.get("NETWORK", "localnet")).strip().lower()
if raw_name in ("localnet", "sandbox", "devnet"):
name: NetworkName = "localnet"
algod_url = os.environ.get("ALGOD_URL", "http://localhost:4001")
algod_token = os.environ.get("ALGOD_TOKEN", "a" * 64)
indexer_url = os.environ.get("INDEXER_URL", "http://localhost:8980")
indexer_token = os.environ.get("INDEXER_TOKEN", "a" * 64)
# Retrieve genesis hash from local algod if available
try:
client = algod.AlgodClient(algod_token, algod_url)
network_id = resolve_network("localnet", client)
except Exception:
network_id = "algorand:localnet"
return NetworkConfig(
network_name=name,
network_id=network_id,
algod_url=algod_url,
algod_token=algod_token,
indexer_url=indexer_url,
indexer_token=indexer_token,
asset_id=0, # ALGO native microALGO
asset_name="ALGO",
asset_decimals=6,
is_public=False,
fee_payer_funded=True,
)
if raw_name in ("testnet", "test"):
name = "testnet"
endpoints = endpoints_for(TESTNET)
algod_url = os.environ.get("ALGOD_URL", endpoints.algod_url)
algod_token = os.environ.get("ALGOD_TOKEN", endpoints.algod_token)
indexer_url = os.environ.get("INDEXER_URL", endpoints.indexer_url)
indexer_token = os.environ.get("INDEXER_TOKEN", endpoints.indexer_token)
usdc_id = usdc_asset_id(TESTNET) or 10458941
return NetworkConfig(
network_name=name,
network_id=TESTNET,
algod_url=algod_url,
algod_token=algod_token,
indexer_url=indexer_url,
indexer_token=indexer_token,
asset_id=usdc_id,
asset_name="USDC",
asset_decimals=6,
is_public=True,
fee_payer_funded=False, # Operator must fund fee-payer account with ALGO
)
if raw_name in ("mainnet", "prod", "production"):
name = "mainnet"
endpoints = endpoints_for(MAINNET)
algod_url = os.environ.get("ALGOD_URL", endpoints.algod_url)
algod_token = os.environ.get("ALGOD_TOKEN", endpoints.algod_token)
indexer_url = os.environ.get("INDEXER_URL", endpoints.indexer_url)
indexer_token = os.environ.get("INDEXER_TOKEN", endpoints.indexer_token)
usdc_id = usdc_asset_id(MAINNET) or 31566704
return NetworkConfig(
network_name=name,
network_id=MAINNET,
algod_url=algod_url,
algod_token=algod_token,
indexer_url=indexer_url,
indexer_token=indexer_token,
asset_id=usdc_id,
asset_name="USDC",
asset_decimals=6,
is_public=True,
fee_payer_funded=False, # Operator must fund fee-payer account with ALGO
)
raise ValueError(
f"Unsupported NETWORK value '{raw_name}'. Expected 'localnet', 'testnet', or 'mainnet'."
)
# Default singleton instance resolved from current environment
current_config = load_network_config()
def dry_run() -> None:
"""Print resolved configuration for all three supported networks.
Performs read-only inspection. No transactions or network writes are executed.
"""
targets: list[NetworkName] = ["localnet", "testnet", "mainnet"]
print("=" * 72)
print(" Algorand Payment Network Configuration Matrix (Dry Run)")
print("=" * 72)
for target in targets:
cfg = load_network_config(target)
print(f"\n[Network: {cfg.network_name.upper()}]")
print(f" CAIP-2 Network ID : {cfg.network_id}")
print(f" Algod Endpoint : {cfg.algod_url}")
print(f" Indexer Endpoint : {cfg.indexer_url}")
print(f" Payment Asset : {cfg.asset_name} (Asset ID: {cfg.asset_id})")
print(f" Asset Decimals : {cfg.asset_decimals}")
print(f" Public Network : {cfg.is_public}")
print(f" Fee Payer Model : {'Auto-dispensed (dev)' if not cfg.is_public else 'ALGO funded wallet required'}")
print("\n" + "=" * 72)
print(" Dry run completed successfully. 0 transactions submitted.")
print("=" * 72)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] in ("--dry-run", "dry-run", "all"):
dry_run()
else:
# Default behavior: run dry-run to prove all three network configs
dry_run()
```
Source: [examples/shared/config.py](https://github.com/x402-avm/examples/blob/main/shared/config.py)
`python shared/config.py --dry-run` prints the configuration of all three networks without sending a transaction (it reads LocalNet's genesis hash from its algod):
```text
[Network: LOCALNET]
CAIP-2 Network ID : algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY
Algod Endpoint : http://localhost:4001
Indexer Endpoint : http://localhost:8980
Payment Asset : ALGO (Asset ID: 0)
...
[Network: MAINNET]
CAIP-2 Network ID : algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k
Algod Endpoint : https://mainnet-api.algonode.cloud
Indexer Endpoint : https://mainnet-idx.algonode.cloud
Payment Asset : USDC (Asset ID: 31566704)
...
Dry run completed successfully. 0 transactions submitted.
```
Then set the environment for production. `VENDOR_ADDRESS` and `FEE_PAYER_MNEMONIC` are read by your own server code, as in [Server configuration](#server-configuration):
```bash
export NETWORK=mainnet
export ALGOD_URL=https://mainnet-api.algonode.cloud
export INDEXER_URL=https://mainnet-idx.algonode.cloud
export VENDOR_ADDRESS="YOUR_RECEIVING_ADDRESS"
export FEE_PAYER_MNEMONIC="..." # injected by your secret manager, not typed into a shell history
```
## Simulate on MainNet
[`mainnet/simulate.py`](https://github.com/x402-avm/examples/blob/main/mainnet/simulate.py) and [`mainnet/simulate.mjs`](https://github.com/x402-avm/examples/blob/main/mainnet/simulate.mjs) are the [TestNet simulations](https://x402-avm.github.io/production/networks#check-payments-without-funds) with MainNet settings: they find funded accounts through the public MainNet indexer, build ALGO and USDC (`31566704`) groups with and without a fee payer, and check them with algod's simulate endpoint. Nothing is signed with a funded key and nothing is sent.
```bash
python mainnet/simulate.py
node mainnet/simulate.mjs
```
## Monitor
| Signal | How |
|---|---|
| Fee payer balance | `algod_client.account_info(fee_payer)["amount"]` on a schedule |
| Settlement failures | `SettlementError("payment settlement failed: ...")` returned to callers; `WARNING` records on the `ai_economy_sdk` logger |
| Settlement latency | Time from tool completion to confirmation |
| Replay rejections | `402` with `{"error": "Replay detected"}`: a misbehaving client or an attack |
| Revenue | Payments to `pay_to` on the indexer, or `ChainReader.past_usage` per buyer |
The `ai_economy_sdk` logger records refused calls, settlement failures, expired reservations and failed chain lookups at `WARNING`; `x402_algorand` logs fee payer signing, simulation and settlement failures. Attach a handler, for example `logging.basicConfig(level=logging.WARNING)`, and alert on them.
---
# Security
> The attacks ai-economy-sdk, x402-algorand and x402-avm-js are built to resist, where each protection lives, and how to share the replay store across workers.
Read this page before you take real payments: it lists what the packages protect against, where each check is implemented, and the one thing you must configure yourself, the shared replay store. To report a vulnerability, follow the [security policy](https://github.com/x402-avm/.github/blob/main/SECURITY.md); do not open a public issue.
## Unpaid tool calls
**Threat.** A client reaches a priced tool without paying, over a transport or path the gate does not inspect.
**Protection.** Since ai-economy-sdk 0.5.0 the gate inspects the JSON-RPC body of every HTTP `POST`, whatever its path or transport (Streamable HTTP at `/mcp`, SSE at `/messages/`, or an app mounted under a prefix). It fails closed: `SettleOnSuccessMiddleware` refuses with `PaymentRequiredError` any priced call that did not pass through the gate, or whose reservation has expired. JSON-RPC batches containing `tools/call` get HTTP `400`, and without `SettleOnSuccessMiddleware` the gate refuses priced calls with HTTP `500`.
> **Warning:**
In ai-economy-sdk 0.4.x the gate only inspected `POST` requests whose path ended in `/messages`. A FastMCP Streamable HTTP app wrapped with `PaymentGate.middleware()` (`POST /mcp`), or a gated SSE app mounted under a path prefix, served priced tools without payment. Upgrade to 0.5.0 or later.
**Where.** `_GateASGIMiddleware` and `SettleOnSuccessMiddleware` in [`ai_economy_sdk/gate.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/gate.py).
## Replayed payments
**Threat.** A client or an eavesdropper sends the same signed payment several times to get several calls.
**Protection.** Each payment's hash is reserved before the tool runs and rejected if already reserved or settled ([how](https://x402-avm.github.io/how-it-works#replay-protection)). The chain itself also rejects a group that was already confirmed (a resent settled payment fails verification with `transaction_simulation_failed`), but the replay store stops a duplicate before the tool runs.
**Where.** [`ai_economy_sdk/replay.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/replay.py), [`ai_economy_sdk/gate.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/gate.py).
### Replay store
- **In memory** (`replay_db=None`, the default): a dictionary guarded by a lock. Protects one process only.
- **SQLite** (`replay_db="/path/replay.db"`): a database in WAL mode (`PRAGMA journal_mode=WAL;`). `reserve` is an `INSERT` on the primary key, so two processes can never accept the same payment. Use it whenever more than one process serves the same `pay_to`, for example `uvicorn --workers 4` or several containers sharing a disk.
```python
gate = PaymentGate(
signer=signer,
network="mainnet",
pay_to=server_address,
asset_id=0,
prices={"echo": 5000},
replay_db="/var/data/replay.db", # shared by every worker
)
```
## Payments from another network
**Threat.** A client pays where funds cost nothing (LocalNet, TestNet) and presents the payment to a MainNet service.
**Protection.** The facilitator derives the CAIP-2 id from each transaction's genesis hash and rejects the group if it differs from the requirement's network (`invalid_exact_avm_payload_genesis_hash_mismatch`). The Python client scheme refuses to build a payment when its algod is on another network, for example `NetworkMismatchError: algod is on algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY but the payment is for algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe`; `x402-avm-js` only pays an offer for its algod's network, and refuses one whose `extra.genesisHash` or `extra.genesisId` disagrees with algod.
**Where.** [`x402_algorand/exact/facilitator.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/facilitator.py), [`x402_algorand/exact/client.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/client.py).
## Draining or taking over accounts
**Threat.** A group includes a close-out (`close_remainder_to`, `asset_close_to`) that empties an account, a rekey that hands control to an attacker, or a key registration.
**Protection.** Before signing anything, the facilitator rejects any close-out field (`..._close_to_detected`), any key registration (`..._blocked_transaction_type`), and any rekey that is not a balanced pair returning authority to the sender within the group (`..._rekey_detected`).
**Where.** `validate_no_security_risks` and `validate_rekey_operations` in [`x402_algorand/utils.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py).
## Abusing the fee payer
**Threat.** A crafted group makes the server's fee payer pay large fees, send funds, or act as the buyer.
**Protection.** Every transaction sent by one of the facilitator's addresses must be a `pay` to itself with amount 0, no close-out, no rekey and a fee of at most 16,000 microALGO; the fee payer's transactions are signed only after these checks. The facilitator signs only for addresses it manages and rejects any payment sent from one of them (`..._fee_payer_transferring_funds`). On the business side, `PaymentGate` refuses ALGO prices that do not cover the 2,000 microALGO fee per call, unless `allow_loss=True`.
**Where.** `validate_fee_payer_transaction` in [`x402_algorand/utils.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py); the fee floor in [`ai_economy_sdk/gate.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/gate.py).
## Wrong amount, recipient or asset
**Threat.** A client pays less than the price, pays someone else, or pays in another asset.
**Protection.** The receiver must equal `payTo` (`..._recipient_mismatch`), the amount must equal the required amount exactly (`..._amount_insufficient`), and the asset must match (`..._asset_id_mismatch`). The buyer's authorization is verified (`..._invalid_signature`): an Ed25519 signature by the sender or its auth address (rekeyed account), a k-of-n multisig, or a logic signature, as the exact scheme allows. A signed transaction cannot be altered. Finally the group is simulated on algod, which catches insufficient balances and missing opt-ins.
**Where.** [`x402_algorand/exact/facilitator.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/facilitator.py).
## Charging for failed work
**Threat.** A service takes payment and then fails, leaving the buyer to ask for a refund.
**Protection.** [Settle-on-success](https://x402-avm.github.io/how-it-works#settle-on-success): a failed tool releases the reservation and the signed group is never submitted.
**Where.** `SettleOnSuccessMiddleware` in [`ai_economy_sdk/gate.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/gate.py).
## Overspending clients
**Threat.** A malicious or mispriced server asks a client, often an unattended agent, for more than intended.
**Protection.** Both clients check the offer before anything is signed. The official `x402` Python client allows only known assets (ALGO, and USDC on MainNet and TestNet) up to `$1` per payment by default; `paid_mcp_session` exposes this as [`spend_controls`](https://x402-avm.github.io/build/pay-from-python#spend-controls). Since 0.4.0, `x402-avm-js` refuses any payment above 1,000,000 base units and can restrict assets, networks and recipients ([options](https://x402-avm.github.io/build/pay-from-browser#spend-controls)).
**Where.** `checkSpendControls` in [`x402-avm-js/src/index.ts`](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts).
## Key handling
**Threat.** Private keys leak from a client or server.
**Protection.** Clients send only signed transactions; keys never leave the signer. On the server, `DefaultAvmSigner` (ai-economy-sdk) and `ServerAvmSigner` (x402-algorand) hold the fee payer key in memory and sign only the indexes they are asked to, which the facilitator restricts to validated fee payer transactions. Keys are kept in private attributes and `repr()` shows only the address; `ServerAvmSigner` and `PayerAvmSigner` also keep them out of exception messages and logs. To use a KMS, HSM or wallet, implement the `ClientAvmSigner` / `FacilitatorAvmSigner` protocols. Load keys from the environment or a secret manager and keep the fee payer separate from the revenue account ([Keys](https://x402-avm.github.io/production/mainnet#keys)).
**Where.** [`ai_economy_sdk/signer.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/signer.py), [`x402_algorand/signer.py`](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/signer.py).
## Stolen or replayed identity proofs
**Threat.** An attacker reuses a caller's identity proof to impersonate it, for example to use its pass.
**Protection.** Proofs carry a timestamp and are accepted only within 120 seconds of the server's clock. An `X-Identity-Txn` proof is bound to one network, must be a plain Ed25519-signed 0-amount self-payment with fee 0, no close-out and no rekey, and cannot execute on chain. Proofs from multisig accounts, logic signatures or rekeyed accounts are refused ([rules](https://x402-avm.github.io/build/identity#the-identity-transaction)).
**Where.** `verify_identity_txn` and `verify_identity` in [`ai_economy_sdk/identity.py`](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py).
> **Note:**
Anyone who captures an identity proof can replay it within its 120-second window. Serve paid tools over HTTPS so headers cannot be read in transit.
---
# API reference
> Reference for every public object of ai-economy-sdk, x402-algorand and x402-avm-js, generated from the source.
- [ai-economy-sdk](https://x402-avm.github.io/reference/python/ai-economy-sdk/index.md)
`PaymentGate`, `AIEconomySDK`, `paid_mcp_session`, identity, network helpers. Python.
- [x402-algorand](https://x402-avm.github.io/reference/python/x402-algorand/index.md)
Registration helpers, scheme classes, signer protocols, utilities, constants. Python.
- [x402-avm-js](https://x402-avm.github.io/reference/js/index.md)
Payments, spend controls, identity, networks, types and errors. TypeScript.
## How the reference is generated
| Package | Source | Generator |
|---|---|---|
| `ai-economy-sdk` 0.5.1 | numpy-style docstrings | `scripts/gen_python_reference.py` (griffe, static analysis) |
| `x402-algorand` 0.3.0 | Google-style docstrings | `scripts/gen_python_reference.py` |
| `x402-avm-js` 0.4.1 | TSDoc in `src/index.ts` and `src/errors.ts` | `scripts/gen_js_reference.py` |
Signatures, types and defaults come from the code; descriptions, return values, exceptions and examples come from the documentation comments. Each page links to the source line it was generated from. To regenerate, see the [site's README](https://github.com/x402-avm/x402-avm.github.io#regenerate-the-api-reference).
## Official x402 SDK
`x402-algorand` plugs into the official [`x402`](https://github.com/x402-foundation/x402) Python SDK. The classes you use from it are summarized under **x402 core (upstream)**: [core classes](https://x402-avm.github.io/reference/x402/core), [schemas](https://x402-avm.github.io/reference/x402/schemas) and [HTTP integration](https://x402-avm.github.io/reference/x402/http). The upstream project is the authoritative reference for them.
## Protocol and packages
- [Packages and versions](https://x402-avm.github.io/reference/packages): install commands, compatibility and upgrade notes.
- [AVM exact scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme): wire format, verification steps and settlement.
- [HTTP 402 reference](https://x402-avm.github.io/reference/protocol/http-402): the three headers of a real payment, decoded.
- [Errors and error codes](https://x402-avm.github.io/reference/errors): every failure reason and exception class.
---
# Packages and versions
> Install commands, supported runtimes, dependency ranges and upgrade notes for ai-economy-sdk, x402-algorand and x402-avm-js.
Use this page to install a specific version, check what it runs on, or upgrade from an older release.
| Package | Registry | Version | Licence | Runtime |
|---|---|---|---|---|
| `ai-economy-sdk` | [PyPI](https://pypi.org/project/ai-economy-sdk/) | 0.5.1 | MIT | Python 3.10–3.14 |
| `x402-algorand` | [PyPI](https://pypi.org/project/x402-algorand/) | 0.3.0 | Apache-2.0 (with NOTICE) | Python 3.10–3.14 |
| `x402-avm-js` | [npm](https://www.npmjs.com/package/x402-avm-js) | 0.4.1 | MIT | Node.js 20+, browsers, workers |
`x402-algorand` is derived from GoPlausible's `x402-avm` 2.0.2 and plugs into the official `x402` Python SDK (`x402>=2.28,<3`) maintained by the x402 Foundation.
## Install
```bash
pip install ai-economy-sdk==0.5.1 # sell MCP tools, pay for them from Python
pip install x402-algorand==0.3.0 # only the Algorand scheme for the x402 SDK
```
```bash
uv pip install ai-economy-sdk==0.5.1
uv pip install x402-algorand==0.3.0
```
```bash
npm install x402-avm-js@0.4.1 algosdk
```
```bash
pnpm add x402-avm-js@0.4.1 algosdk
```
```bash
yarn add x402-avm-js@0.4.1 algosdk
```
- `ai-economy-sdk` also installs `x402-algorand`, the official `x402` package, FastMCP, the MCP SDK, `py-algorand-sdk`, httpx, Starlette, FastAPI and uvicorn.
- The official SDK's framework integrations need their extras, for example `pip install "x402[flask]"` for the Flask middleware.
- `x402-avm-js` is an ES module with one runtime dependency, `algosdk` (v3); install it alongside to create clients and sign. It uses only standard web APIs (`Uint8Array`, `TextEncoder`, `TextDecoder`) and no Node built-ins such as `Buffer`, so it runs in browsers, Node.js, workers and edge runtimes without polyfills.
Check the installation:
```bash
python -c '
import x402, x402_algorand, ai_economy_sdk
print("ai-economy-sdk", ai_economy_sdk.__version__)
print("x402-algorand", x402_algorand.__version__)
print("x402", x402.__version__)
'
```
```bash
node --input-type=module -e "import { resolveNetwork } from 'x402-avm-js'; console.log(resolveNetwork('mainnet'))"
```
```text
ai-economy-sdk 0.5.1
x402-algorand 0.3.0
x402 2.28.0
```
The `x402` version is the one pip resolved, 2.28 or later. The Node.js check prints `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k`.
## Compatibility
From each package's `pyproject.toml` / `package.json` and CI matrix:
| Package | Version | Official `x402` (Python) | Python | Node.js | Other dependency ranges |
|---|---|---|---|---|---|
| `ai-economy-sdk` | 0.5.1 | `>=2.28,<3` | `>=3.10`; tested on 3.10–3.14 | | `x402-algorand>=0.2.1`, `fastmcp>=3.4,<4`, `mcp>=1.29,<2`, `py-algorand-sdk>=2.6`, `httpx>=0.27`, `uvicorn>=0.30` |
| `x402-algorand` | 0.3.0 | `>=2.28,<3` | `>=3.10`; tested on 3.10–3.14 | | `py-algorand-sdk>=2.6`, `pynacl>=1.4` |
| `x402-avm-js` | 0.4.1 | | | `>=20`; tested on 20, 22, 24 | `algosdk ^3.9.0` |
`fastmcp` 4.x and `mcp` 2.x are excluded on purpose: the 0.4.1 release notes record upstream `httpx` changes in those majors that affect `x402` compatibility. These docs were checked on Python 3.14 with `x402` 2.28.0, `fastmcp` 3.4.11 and `mcp` 1.30.0, and on Node.js 24 with `algosdk` 3.9.0.
Previous releases: `ai-economy-sdk` 0.4.1 and `x402-algorand` 0.2.1 declared Python 3.10 to 3.13 (`>=3.10`) and the same `x402`, `fastmcp` and `mcp` ranges; `ai-economy-sdk` 0.4.1 required `x402-algorand>=0.2.0`. `x402-avm-js` 0.3.1 declared Node.js `>=18`.
Every release: [Changelog](https://x402-avm.github.io/resources/changelog).
## Upgrade notes
### ai-economy-sdk 0.5
0.5.0 is a security release: in 0.4.x the gate did not cover the Streamable HTTP transport or SSE apps mounted under a path prefix, so priced tools could be called without paying there ([details](https://x402-avm.github.io/production/security#unpaid-tool-calls)). After upgrading:
- Pass `transport=` to `wrap()` explicitly. `"streamable-http"` is recommended; without `transport=`, `wrap()` still serves SSE and emits a `FutureWarning`.
- Point clients at the transport you serve: `paid_mcp_session` uses Streamable HTTP for URLs whose path ends in `/mcp`, and SSE for other URLs (or pass `transport=`).
- Errors have their own classes ([Errors](https://x402-avm.github.io/reference/errors#ai-economy-sdk-exceptions)). Each still subclasses the type raised in 0.4.x, so `except ValueError` / `except RuntimeError` / `except ToolError` handlers keep working.
- A pricing function that accepts neither `(args, sender)` nor `(args)` raises `ConfigurationError` when the tool is registered with `AIEconomySDK.add_tool()`, instead of failing per request.
- `ChainReader` and `PaymentGate` still treat failed indexer and algod lookups as "no usage, subscription or pass", but other exceptions now propagate.
- `DefaultAvmSigner.private_key` is read-only and deprecated; keep your own reference to the key. `sign_identity()` is deprecated in favour of `sign_identity_txn()`.
- 0.5.1: a payment refused by the buyer's spend controls raises `SpendLimitExceededError` instead of an `ExceptionGroup`.
### ai-economy-sdk from 0.3
- Network ids are CAIP-2 short ids (`algorand:` plus 32 characters), for example `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k`. Legacy 44-character ids are still accepted everywhere and converted.
- `x402-algorand` is a plugin for the official `x402` package (2.28 or later) instead of a fork of it.
### x402-algorand 0.3
0.3.0 is backward compatible with code written for 0.2.x. Changes you may notice:
- Hand-written signers can be replaced by `PayerAvmSigner` and `ServerAvmSigner`.
- Unsupported networks, wrong-network algod nodes and undecodable transactions raise `NetworkError`, `NetworkMismatchError` and `TransactionDecodeError` (all still `ValueError`s).
- `settle()` returns the ID of the buyer's payment transaction (`paymentGroup[paymentIndex]`), as the specification requires. With a fee payer, 0.2.x returned the fee payer transaction's ID.
- Payments authorized by a k-of-n multisig, a logic signature, or the auth address of a rekeyed account are accepted. A rekey pair is only accepted when the second rekey returns authority to the sender.
- The V1 facilitator and client wrappers accept the official SDK's `PaymentPayloadV1` / `PaymentRequirementsV1` models, so V1 payments routed through `x402Facilitator` / `x402Client` work.
- `x402_algorand.__version__` and a `py.typed` marker; Python 3.14 is supported.
### x402-algorand from 0.1.x
0.2.0 had two breaking changes:
1. **A plugin, not a fork.** 0.1.x installed its own copy of the top-level `x402` package. 0.2.0 ships only `x402_algorand` and depends on the official `x402` package.
| 0.1.x | 0.2.0 |
|---|---|
| `from x402.mechanisms.avm.exact.client import ExactAvmScheme` | `from x402_algorand.exact.client import ExactAvmScheme` |
| `from x402.mechanisms.avm.exact.register import register_exact_avm_client` | `from x402_algorand.exact.register import register_exact_avm_client` |
| core classes from the fork | `from x402 import x402Client, x402ResourceServer, x402Facilitator` |
2. **Short CAIP-2 ids.** The official SDK validates network ids with `^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$`, so ids use 32 characters of the URL-safe base64 genesis hash. Legacy 44-character ids are still accepted by `normalize_network()` and converted.
### x402-avm-js 0.4
- **Default spend cap.** Payments above 1,000,000 base units are refused. To pay more, pass `{ maxAmount: ... }` as the last argument of `payForRequirement` or `buildExactAvmGroup`.
- **Node.js 20 or later.** Node.js 18 is no longer supported.
- **Validation.** `decodePaymentRequired` validates the decoded shape and throws `InvalidPaymentRequiredError` (0.3 returned whatever JSON it found). `selectRequirement`, `encodePaymentHeader` and `payForRequirement` take `PaymentRequired` instead of `PaymentRequired | any`; `extra` and `extensions` values are `unknown` instead of `any`.
- **Typed errors.** Catch `X402AvmError` subclasses or check `error.code` instead of matching messages.
- 0.4.1: `algodClient('localnet')` connects to port 4001; earlier versions connected to port 80.
### x402-avm-js from 0.2
0.3 uses the Algorand CAIP-2 profile for network ids: `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k` for MainNet and `algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe` for TestNet. Legacy 44-character ids are still accepted by `resolveNetwork` and `selectRequirement`, so existing servers keep working.
---
# AVM exact scheme
> Wire format, atomic group layout, verification steps and settlement of the x402 exact scheme on Algorand.
Use this page when you implement or debug the Algorand `exact` scheme: the wire format, what the facilitator checks and in what order, and how settlement reports back. The scheme pays exactly the requested amount of one asset to one address, in an atomic group, so the payment and the fee sponsorship both happen or neither does. The official specification is [scheme_exact_algo.md](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_algo.md).
## Wire format
### PAYMENT-REQUIRED (server to client)
With HTTP `402`, the server sends a base64-encoded JSON `PaymentRequired` object (x402 version 2). Real captured headers, with every field explained, are on [HTTP 402 response reference](https://x402-avm.github.io/reference/protocol/http-402).
```json
{
"x402Version": 2,
"resource": { "url": "http://127.0.0.1:9211/weather", "description": "Weather data" },
"accepts": [
{
"scheme": "exact",
"network": "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k",
"asset": "0",
"amount": "10000",
"payTo": "YOUR_SERVER_ADDRESS",
"maxTimeoutSeconds": 300,
"extra": {
"decimals": 6,
"feePayer": "SERVER_FEE_PAYER_ADDRESS",
"genesisHash": "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=",
"genesisId": "mainnet-v1.0"
}
}
]
}
```
| Field | Meaning |
|---|---|
| `scheme` | Always `"exact"`. |
| `network` | CAIP-2 id. |
| `asset` | `"0"` for ALGO, otherwise the ASA id as a string (`"31566704"` for USDC on MainNet, `"10458941"` on TestNet). |
| `amount` | Base units as a string (`"10000"` microALGO is 0.01 ALGO). |
| `payTo` | Recipient address (58 characters). |
| `extra.feePayer` | Optional. Address of the account that sponsors the group's fees. |
### PAYMENT-SIGNATURE (client to server)
The client retries with a base64-encoded JSON `PaymentPayload`:
```json
{
"x402Version": 2,
"accepted": { "...": "the PaymentRequirements the client chose" },
"payload": {
"paymentGroup": [
"",
""
],
"paymentIndex": 1
}
}
```
`paymentGroup` holds every transaction of the group in order: the buyer's signed, the fee payer's unsigned. `paymentIndex` points at the buyer's payment.
## Atomic group layout
With `extra.feePayer`, `paymentGroup` is two transactions: the fee payer's 0-amount self-payment with a fee of 2,000 microALGO (2 × the minimum fee) at index 0, signed by the facilitator at settlement, and the buyer's `pay` or `axfer` of the amount with fee 0 at index 1. Without a fee payer it is one buyer payment that pays the network fee (1,000 microALGO minimum). Why, and the full table: [How it works](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group).
## Verification steps
`ExactAvmFacilitatorScheme.verify()` runs these checks in order and stops at the first failure, returning `VerifyResponse(is_valid=False, invalid_reason=)`:
1. **Scheme and network.** Both the accepted requirement and the server's requirement use scheme `exact` (`unsupported_scheme`); the accepted network equals the required one (`network_mismatch`).
2. **Group size.** `paymentGroup` is not empty (`invalid_exact_avm_payload_empty_group`), has at most 16 transactions (`..._group_too_large`), and `paymentIndex` is inside it (`..._payment_index`).
3. **Decode.** Every transaction decodes from base64 msgpack (`..._group_decode_failed`).
4. **Group id.** In a multi-transaction group, every transaction has the same group id (`..._missing_group_id`, `..._group_id_mismatch`).
5. **Network.** Every transaction's genesis hash maps to the required network (`..._genesis_hash_mismatch`).
6. **Security, per transaction.** No `close_remainder_to` or `asset_close_to` (`..._close_to_detected`); no blocked type, which is `keyreg` (`..._blocked_transaction_type`).
7. **Rekeys, per group.** A rekey is allowed only as a balanced pair in which the second rekey returns authority to the sender, within the group (`..._rekey_detected`).
8. **Payment terms.** For ALGO the payment is a `pay` transaction, for an ASA an `axfer` of that asset (`..._asset_id_mismatch`); the receiver is `payTo` (`..._recipient_mismatch`); the amount equals the required amount exactly (`..._amount_insufficient`).
9. **Buyer authorization.** The payment is signed (`..._missing_signature`) and its authorization verifies (`..._invalid_signature`): an Ed25519 signature by the sender or by its auth address (rekeyed account), a k-of-n multisig with at least the threshold of valid subsignatures, or a logic signature (the program itself is evaluated by the simulation).
10. **Fee payer.** The buyer is not one of the facilitator's own addresses (`..._fee_payer_transferring_funds`). If the requirement names a fee payer, the facilitator manages that address (`fee_payer_not_managed_by_facilitator`) and the group contains a transaction from it (`..._missing_fee_payer`). Every transaction sent by one of the facilitator's addresses (not only the first) must be a self-payment of type `pay` (`..._fee_payer_transaction_invalid`) with amount 0 (`..._fee_payer_has_amount`), no close-to (`..._fee_payer_has_close_to`), no rekey (`..._fee_payer_has_rekey_to`) and a fee of at most 16,000 microALGO (`..._fee_payer_transaction_invalid`).
11. **Simulation.** The facilitator signs the fee payer transaction and simulates the group on algod with empty signatures allowed. A failure such as insufficient balance or a missing opt-in returns `transaction_simulation_failed` with the node's message in `invalid_message`.
12. **Success.** `VerifyResponse(is_valid=True, payer=)`.
Codes shown as `..._` start with `invalid_exact_avm_payload`. All codes: [Error codes](https://x402-avm.github.io/reference/errors).
## Settlement
`ExactAvmFacilitatorScheme.settle()`:
1. Runs `verify()` again; on failure returns `SettleResponse(success=False, error_reason=)`.
2. Signs the fee payer transaction, if the requirement names one.
3. Submits the group with the signer's `send_group`.
4. Waits for confirmation with `confirm_transaction` (4 rounds by default).
5. Returns `SettleResponse(success=True, transaction=, network=, payer=)`, where `transaction` is the ID of `paymentGroup[paymentIndex]`, the buyer's payment (since 0.3.0; 0.2.x returned the fee payer transaction's ID). A submission or confirmation error returns `success=False` with `error_reason="transaction_failed"`.
## Run it
[Run a facilitator](https://x402-avm.github.io/build/facilitator#verify-and-settle-without-http) builds a payment with the client scheme and verifies and settles it with the facilitator scheme, without HTTP.
---
# HTTP 402 response reference
> The PAYMENT-REQUIRED, PAYMENT-SIGNATURE and PAYMENT-RESPONSE headers of a real Algorand x402 payment, decoded field by field.
Use this page to read or debug x402 traffic: the three headers of one real payment, captured on LocalNet with `x402-algorand` 0.3.0 and the official `x402` 2.28.0 SDK: a FastAPI route `GET /weather` priced at 10,000 microALGO, protected by `payment_middleware` with an in-process facilitator whose account is both `payTo` and fee payer (the setup on [FastAPI](https://x402-avm.github.io/build/paywall-http-api#fastapi)). The buyer paid with `x402Client` and `PayerAvmSigner`. Addresses, the LocalNet network id and transaction ids differ on every machine and run.
The headers are defined by the x402 [HTTP transport (v2)](https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/http.md), their JSON objects by the [x402 v2 specification](https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md), and the Algorand-specific parts by the [exact scheme on Algorand](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_algo.md).
| Header | Direction | Status | Content |
|---|---|---|---|
| `PAYMENT-REQUIRED` | server to client | `402` | base64 of a JSON `PaymentRequired` |
| `PAYMENT-SIGNATURE` | client to server | (request) | base64 of a JSON `PaymentPayload` |
| `PAYMENT-RESPONSE` | server to client | `200` | base64 of a JSON `SettlementResponse` |
Each header value is standard base64 of UTF-8 JSON. Decode it with `json.loads(base64.b64decode(value))` in Python, `decodePaymentRequired(value)` in x402-avm-js, or `decode_payment_required_header` / `decode_payment_signature_header` / `decode_payment_response_header` from `x402.http`.
## 1. The 402 response
The unpaid request `GET /weather` returned:
```http
HTTP/1.1 402 Payment Required
content-type: application/json
cache-control: no-store
payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIiwicmVzb3VyY2UiOnsidXJsIjoiaHR0cDovLzEyNy4wLjAuMTo5MzAyL3dlYXRoZXIiLCJkZXNjcmlwdGlvbiI6IiIsIm1pbWVUeXBlIjoiIn0sImFjY2VwdHMiOlt7InNjaGVtZSI6ImV4YWN0IiwibmV0d29yayI6ImFsZ29yYW5kOnRnMGN5akV6MTRGWks5QlRwTDJxMFRPeUZiYzBNY3dZIiwiYXNzZXQiOiIwIiwiYW1vdW50IjoiMTAwMDAiLCJwYXlUbyI6IlVRUFgzQUdKRlY2Tk5aVzRXRUpET1ZDSTdUUUZRQjJYWlFQQUVOTTdCUFY0UUNCQ1Y1N0tOTTJRS1UiLCJtYXhUaW1lb3V0U2Vjb25kcyI6MzAwLCJleHRyYSI6eyJkZWNpbWFscyI6NiwiZmVlUGF5ZXIiOiJVUVBYM0FHSkZWNk5OWlc0V0VKRE9WQ0k3VFFGUUIyWFpRUEFFTk03QlBWNFFDQkNWNTdLTk0yUUtVIn19XX0=
{"error":"Payment required"}
```
Decoded `PAYMENT-REQUIRED`:
```json
{
"x402Version": 2,
"error": "Payment required",
"resource": {
"url": "http://127.0.0.1:9302/weather",
"description": "",
"mimeType": ""
},
"accepts": [
{
"scheme": "exact",
"network": "algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY",
"asset": "0",
"amount": "10000",
"payTo": "UQPX3AGJFV6NNZW4WEJDOVCI7TQFQB2XZQPAENM7BPV4QCBCV57KNM2QKU",
"maxTimeoutSeconds": 300,
"extra": {
"decimals": 6,
"feePayer": "UQPX3AGJFV6NNZW4WEJDOVCI7TQFQB2XZQPAENM7BPV4QCBCV57KNM2QKU"
}
}
]
}
```
| Field | Value here | Meaning |
|---|---|---|
| `x402Version` | `2` | Protocol version. Must be 2 for this header format ([spec §5.1](https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md#51-paymentrequired-schema)). |
| `error` | `"Payment required"` | Optional human-readable reason. |
| `resource.url` | the requested URL | The protected resource. |
| `resource.description`, `resource.mimeType` | `""` | Optional; set from the route configuration (`PaymentGate` sets the description to `"Paid MCP tool call"`). |
| `accepts` | one entry | The payment options the server accepts. A server may list several (for example MainNet USDC and TestNet ALGO); clients pick one they can pay. |
| `accepts[].scheme` | `"exact"` | Pay exactly `amount`. |
| `accepts[].network` | `"algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY"` | CAIP-2 id: `algorand:` plus the first 32 characters of the URL-safe base64 genesis hash. This is the default LocalNet id. See [Networks](https://x402-avm.github.io/production/networks). |
| `accepts[].asset` | `"0"` | ASA id as a string. `"0"` (native ALGO, paid with a `pay` transaction) is an extension of `x402-algorand`; the specification defines ASA ids such as USDC `"31566704"`. |
| `accepts[].amount` | `"10000"` | Amount in base units, as a string: 10,000 microALGO = 0.01 ALGO. |
| `accepts[].payTo` | 58-character address | The recipient. |
| `accepts[].maxTimeoutSeconds` | `300` | How long the payment may take to complete. |
| `accepts[].extra.decimals` | `6` | Decimals of the asset, for display. Added by `x402-algorand`'s server scheme. |
| `accepts[].extra.feePayer` | an address of the facilitator | Optional in the specification. When present, the client builds a two-transaction group in which this account pays all fees. Here it equals `payTo` because one account plays both roles. |
### From a PaymentGate MCP server
A `tools/call` posted to a `PaymentGate` server (`POST /mcp`, Streamable HTTP) without payment gets the same kind of `402`. The decoded header captured from a server built like the [Quickstart](https://x402-avm.github.io/quickstart) server (here on port 9303, `echo` at 5,000 microALGO) differs in these fields:
```json
{
"resource": { "url": "http://127.0.0.1:9303/mcp", "description": "Paid MCP tool call", "mimeType": "" },
"accepts": [
{
"amount": "5000",
"extra": {
"decimals": 6,
"feePayer": "",
"genesisHash": "tg0cyjEz14FZK9BTpL2q0TOyFbc0McwYsFJbszmFANk=",
"genesisId": "dockernet-v1"
}
}
]
}
```
`extra.genesisHash` and `extra.genesisId` are optional hints added by `x402-algorand`'s server scheme when the network is registered (as `ai-economy-sdk` does for `"localnet"`, and as MainNet and TestNet always are). x402-avm-js 0.4.0 refuses to pay a requirement whose hints disagree with its algod (`NetworkMismatchError`).
## 2. The paid retry
The client retried `GET /weather` with a `PAYMENT-SIGNATURE` header. Decoded:
```json
{
"x402Version": 2,
"payload": {
"paymentGroup": [
"iqNmZWXNB9CiZnbNBk+jZ2VurGRvY2tlcm5ldC12MaJnaMQgtg0cyjEz14FZK9BTpL2q0TOyFbc0McwYsFJbszmFANmjZ3JwxCCCufmcdC8hsJUS97zRK4wR7ETp1mhBbrxnweg/EerpmaJsds0KN6Rub3RlxCJ4NDAyLWZlZS1wYXllci0xNzk1MDcxODUyODkxNjY5Njc0o3JjdsQgpB99gMktfNbm3LESN1RI/OBYB1fMHgI1nwvryAgir36jc25kxCCkH32AyS181ubcsRI3VEj84FgHV8weAjWfC+vICCKvfqR0eXBlo3BheQ==",
"gqNzaWfEQBGwW+LIuRKcEOqamNuvfwgAFw4SwON2endRckyU+qGecunwgLkiur/A3aW9rgdspsQNBre7IpQqAmSMSfKz/QOjdHhuiqNhbXTNJxCiZnbNBk+jZ2VurGRvY2tlcm5ldC12MaJnaMQgtg0cyjEz14FZK9BTpL2q0TOyFbc0McwYsFJbszmFANmjZ3JwxCCCufmcdC8hsJUS97zRK4wR7ETp1mhBbrxnweg/EerpmaJsds0KN6Rub3RlxCB4NDAyLXBheW1lbnQtMTc5NTA3MTg1Mjg5MTY4MTcyN6NyY3bEIKQffYDJLXzW5tyxEjdUSPzgWAdXzB4CNZ8L68gIIq9+o3NuZMQg7SrCQfscmlZIcOcTNKBlDOHS6X+CkHRfDujoAbl9LqykdHlwZaNwYXk="
],
"paymentIndex": 1
},
"accepted": {
"scheme": "exact",
"network": "algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY",
"asset": "0",
"amount": "10000",
"payTo": "UQPX3AGJFV6NNZW4WEJDOVCI7TQFQB2XZQPAENM7BPV4QCBCV57KNM2QKU",
"maxTimeoutSeconds": 300,
"extra": {
"decimals": 6,
"feePayer": "UQPX3AGJFV6NNZW4WEJDOVCI7TQFQB2XZQPAENM7BPV4QCBCV57KNM2QKU"
}
},
"resource": {
"url": "http://127.0.0.1:9302/weather",
"description": "",
"mimeType": ""
}
}
```
| Field | Meaning |
|---|---|
| `x402Version` | `2`. |
| `accepted` | The `accepts` entry the client chose, copied unchanged. The facilitator rejects the payment if its `scheme` or `network` differs from the server's requirement (`unsupported_scheme`, `network_mismatch`). |
| `resource` | Optional copy of the resource. |
| `payload` | Scheme-specific data ([spec §5.2](https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md#52-paymentpayload-schema)). For Algorand: |
| `payload.paymentGroup` | Every transaction of the atomic group, in order, each base64 msgpack. Signed transactions are encoded as signed transactions; the fee payer's transaction is sent unsigned. At most 16 entries. |
| `payload.paymentIndex` | Index of the transaction that pays the resource server: `1` with a fee payer, `0` without. |
The two transactions, decoded with `algosdk.encoding.msgpack_decode` (msgpack field names):
| Field | Transaction 0 (fee payer, unsigned) | Transaction 1 (buyer, signed) |
|---|---|---|
| `type` | `pay` | `pay` (`axfer` for an ASA) |
| `snd` | fee payer | buyer |
| `rcv` | fee payer (a payment to itself) | `payTo` |
| `amt` | 0 (omitted) | `10000` |
| `fee` | `2000`: twice the 1,000 microALGO minimum, covering both transactions | 0 (omitted) |
| `fv`, `lv` | `1615`, `2615` | `1615`, `2615` (a window of 1,000 rounds) |
| `gen`, `gh` | `dockernet-v1`, the LocalNet genesis hash | same |
| `grp` | the group id | same group id |
| `note` | `x402-fee-payer-` | `x402-payment-` |
| `sig` | none: the facilitator signs it after verification | the buyer's Ed25519 signature |
The notes make each group, and so each payment hash, unique. What the facilitator checks before it signs transaction 0 is listed on [AVM exact scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme#verification-steps).
## 3. The 200 response
The facilitator verified the group, the route ran, and the middleware settled the payment:
```http
HTTP/1.1 200 OK
content-type: application/json
payment-response: eyJzdWNjZXNzIjogdHJ1ZSwgInBheWVyIjogIjVVVk1FUVAzRFNORk1TRFE0NEpUSklERkJUUTVGMkw3UUtJSElYWU81RFVBRE9MNUYyV01UQ0pFQUEiLCAidHJhbnNhY3Rpb24iOiAiNTRNRzYyNFpXTE43WVRLSFBGSE5ZSTRaTTQ1S1M1SDROUVBPRkNCU0VGRlhHVVYySDRXQSIsICJuZXR3b3JrIjogImFsZ29yYW5kOnRnMGN5akV6MTRGWks5QlRwTDJxMFRPeUZiYzBNY3dZIn0=
{"city":"Boston","temperature":68}
```
Decoded `PAYMENT-RESPONSE`:
```json
{
"success": true,
"payer": "5UVMEQP3DSNFMSDQ44JTJIDFBTQ5F2L7QKIHIXYO5DUADOL5F2WMTCJEAA",
"transaction": "54MG624ZWLN7YTKHPFHNYI4ZM45KS5H4NQPOFCBSEFFXGUV2H4WA",
"network": "algorand:tg0cyjEz14FZK9BTpL2q0TOyFbc0McwY"
}
```
| Field | Meaning |
|---|---|
| `success` | `true` when the group was submitted and confirmed. |
| `payer` | The buyer's address. |
| `transaction` | The ID of `paymentGroup[paymentIndex]`, the buyer's payment, as the [Algorand exact scheme](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_algo.md) requires. Here it is transaction 1's ID; x402-algorand 0.2.x returned the fee payer transaction's ID instead. Look it up on algod (`/v2/transactions/pending/`) or an explorer. |
| `network` | CAIP-2 id of the network it settled on. |
| `errorReason` | Only on failure, with one of the [error codes](https://x402-avm.github.io/reference/errors). |
The buyer's balance fell by exactly 10,000 microALGO; the fee payer paid the 2,000 microALGO fee.
### From a PaymentGate MCP server
On Streamable HTTP, the paid `tools/call` returns `200` with `content-type: text/event-stream`, the JSON-RPC result in the body, and a `PAYMENT-RESPONSE` header of the same shape. The header is only sent when the tool succeeded and the payment settled: a failed tool returns an MCP error result and nothing is submitted.
Sending the same `PAYMENT-SIGNATURE` again after it settled returns `402` with `{"error":"transaction_simulation_failed"}`: the group is already on chain, so it fails verification. A duplicate sent while the first use is still in progress gets `402` with `{"error":"Replay detected"}`.
## Reproduce it
Run the [FastAPI paywall](https://x402-avm.github.io/build/paywall-http-api#fastapi) on LocalNet, then:
```python
import base64, json
import httpx
r = httpx.get("http://127.0.0.1:9211/weather")
print(r.status_code, json.dumps(json.loads(base64.b64decode(r.headers["payment-required"])), indent=2))
```
For the paid side, use the [HTTPX client](https://x402-avm.github.io/build/pay-from-python#pay-http-apis) and print `response.headers["payment-response"]` the same way.
---
# Errors and error codes
> Every verification and settlement failure reason of the Algorand exact scheme, and the exception classes of ai-economy-sdk, x402-algorand and x402-avm-js.
Look up an error code or exception here to find out what caused it and how to fix it. For symptoms without a code, see [Troubleshooting](https://x402-avm.github.io/resources/troubleshooting).
## Facilitator error codes
When `ExactAvmFacilitatorScheme.verify()` rejects a payment, it returns `VerifyResponse(is_valid=False)` with `invalid_reason` set to one of these strings; `settle()` returns them in `error_reason`. The constants are defined in `x402_algorand.constants`. The order in which checks run is on [AVM exact scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme#verification-steps).
| Code | Constant | Meaning and typical cause | Fix |
|---|---|---|---|
| `unsupported_scheme` | `ERR_UNSUPPORTED_SCHEME` | The accepted or required scheme is not `exact`. | Use scheme `"exact"`. |
| `network_mismatch` | `ERR_NETWORK_MISMATCH` | The network in the client's `accepted` requirement differs from the server's requirement. | Pay the offer as given; do not rewrite its network. |
| `invalid_exact_avm_payload_empty_group` | `ERR_EMPTY_GROUP` | `paymentGroup` is missing or empty. | Send the whole group in `payload.paymentGroup`. |
| `invalid_exact_avm_payload_group_too_large` | `ERR_GROUP_TOO_LARGE` | More than 16 transactions. | Algorand groups hold at most 16 transactions. |
| `invalid_exact_avm_payload_payment_index` | `ERR_INVALID_PAYMENT_INDEX` | `paymentIndex` is outside the group. | Point `paymentIndex` at the buyer's payment (1 with a fee payer, 0 without). |
| `invalid_exact_avm_payload_group_decode_failed` | `ERR_GROUP_DECODE_FAILED` | A transaction is not valid base64 msgpack. | Encode each transaction with msgpack, then base64. |
| `invalid_exact_avm_payload_missing_group_id` | `ERR_MISSING_GROUP_ID` | A multi-transaction group has a transaction without a group id. | Assign the group id to every transaction before signing. |
| `invalid_exact_avm_payload_group_id_mismatch` | `ERR_INVALID_GROUP_ID` | Transactions carry different group ids. | Compute the group id over the final transactions, then sign. |
| `invalid_exact_avm_payload_genesis_hash_mismatch` | `ERR_GENESIS_HASH_MISMATCH` | A transaction was built for another network than the requirement's. | Use an algod on the requirement's network. |
| `invalid_exact_avm_payload_close_to_detected` | `ERR_CLOSE_TO_DETECTED` | A transaction sets `close_remainder_to` or `asset_close_to`. | Remove close-out fields. |
| `invalid_exact_avm_payload_blocked_transaction_type` | `ERR_BLOCKED_TXN_TYPE` | A transaction is a key registration (`keyreg`). | Remove it from the group. |
| `invalid_exact_avm_payload_rekey_detected` | `ERR_REKEY_DETECTED` | A rekey that is not undone within the group. | Remove `rekey_to`. |
| `invalid_exact_avm_payload_asset_id_mismatch` | `ERR_INVALID_ASSET_ID` | Wrong transaction type for the asset (`pay` for ALGO, `axfer` for an ASA) or wrong ASA. | Pay the asset in `requirements.asset`. |
| `invalid_exact_avm_payload_recipient_mismatch` | `ERR_RECIPIENT_MISMATCH` | The receiver is not `payTo`. | Pay the `payTo` from the challenge. |
| `invalid_exact_avm_payload_amount_insufficient` | `ERR_AMOUNT_INSUFFICIENT` | The amount differs from the required amount (it must be equal). `invalid_message` shows both. | Pay exactly `requirements.amount`. |
| `invalid_exact_avm_payload_missing_signature` | `ERR_MISSING_SIGNATURE` | The buyer's payment is unsigned. | Sign the transaction at `paymentIndex`. |
| `invalid_exact_avm_payload_invalid_signature` | `ERR_INVALID_SIGNATURE` | The Ed25519 signature does not verify, for example a wrong key or a transaction changed after signing. | Sign with the sender's key after the group id is set. |
| `invalid_exact_avm_payload_fee_payer_transferring_funds` | `ERR_FEE_PAYER_TRANSFERRING` | The buyer's payment is sent from one of the facilitator's own addresses. | Use a buyer account different from the fee payer. |
| `fee_payer_not_managed_by_facilitator` | `ERR_FEE_PAYER_NOT_MANAGED` | `extra.feePayer` is not an address this facilitator signs for. | Use the fee payer the server advertised. |
| `invalid_exact_avm_payload_missing_fee_payer` | `ERR_FEE_PAYER_MISSING` | The requirement names a fee payer but no transaction in the group is from it. | Include the fee payer's transaction (index 0). |
| `invalid_exact_avm_payload_fee_payer_transaction_invalid` | `ERR_FEE_PAYER_INVALID_TXN` | The fee payer transaction is not a `pay` from the fee payer to itself, or its fee is above 16,000 microALGO. | Build it as a 0-amount self-payment with the pooled fee. |
| `invalid_exact_avm_payload_fee_payer_has_amount` | `ERR_FEE_PAYER_HAS_AMOUNT` | The fee payer transaction moves ALGO. | Set its amount to 0. |
| `invalid_exact_avm_payload_fee_payer_has_close_to` | `ERR_FEE_PAYER_HAS_CLOSE` | The fee payer transaction sets `close_remainder_to`. | Remove it. |
| `invalid_exact_avm_payload_fee_payer_has_rekey_to` | `ERR_FEE_PAYER_HAS_REKEY` | The fee payer transaction sets `rekey_to`. | Remove it. |
| `transaction_simulation_failed` | `ERR_SIMULATION_FAILED` | algod's simulation rejected the group: insufficient balance, an account below its minimum balance, a missing ASA opt-in, expired rounds. The node's message is in `invalid_message`. | Fund or opt in the account named in the message; rebuild with fresh parameters. |
| `transaction_failed` | `ERR_TRANSACTION_FAILED` | Settlement: submitting or confirming the group failed. | Check algod, the fee payer's balance and the validity rounds; the buyer can pay again. |
Three constants are defined for compatibility but not returned by the facilitator: `invalid_exact_avm_payload` (`ERR_INVALID_PAYLOAD`), `invalid_exact_avm_payload_transaction_decode_failed` (`ERR_TXN_DECODE_FAILED`) and `invalid_exact_avm_payload_transaction_type` (`ERR_INVALID_TXN_TYPE`). A wrong transaction type is reported as `invalid_exact_avm_payload_asset_id_mismatch`.
## ai-economy-sdk exceptions
Since 0.5.0, every exception `ai-economy-sdk` raises on purpose derives from `AIEconomyError` (in `ai_economy_sdk.exceptions`, also exported from `ai_economy_sdk`). Each class also derives from the type raised at the same place in 0.4.x, so existing handlers keep working.
```text
AIEconomyError
├── ConfigurationError (ValueError)
│ ├── UnknownNetworkError
│ └── AlgodClientRequiredError (also RuntimeError)
├── SpendLimitExceededError
├── PaymentVerificationError (RuntimeError)
├── PaymentRequiredError (fastmcp ToolError)
└── SettlementError (fastmcp ToolError)
```
| Exception | Also a | Raised when |
|---|---|---|
| `ConfigurationError` | `ValueError` | Invalid arguments, detected before any payment: a fixed ALGO price in `(0, 2000]` without `allow_loss=True` ([the fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor)); an unsupported `transport=` in `wrap()` or `paid_mcp_session`; a `pricing_func` that is not callable or accepts neither `(args, sender)` nor `(args)`; `subscription_issuer` set with a `chain` whose `has_active_subscription()` has no `issuer` parameter. |
| `UnknownNetworkError` | `ConfigurationError` | A network name or CAIP-2 id cannot be resolved, for example `register_network()` with a 32-character id of an unknown network (pass the full genesis hash or use `network_from_algod`). |
| `AlgodClientRequiredError` | `ConfigurationError`, `RuntimeError` | `DefaultAvmSigner` was created without `algod_client` and is asked to simulate, send or confirm. |
| `SpendLimitExceededError` | | Since 0.5.1. `paid_mcp_session`: the buyer's `spend_controls` refused a payment (price above the cap, asset not allowed). Nothing was signed. The message includes the amount and asset the server asked for; x402's `PaymentError` is the `__cause__`. In 0.5.0 this arrived as an `ExceptionGroup`. |
| `PaymentVerificationError` | `RuntimeError` | `DefaultAvmSigner` simulated a payment group and algod reported a failure. |
| `PaymentRequiredError` | FastMCP `ToolError` | A priced tool call reached the FastMCP server without passing through the gate (for example over a transport the gate does not wrap), or its payment reservation expired. The call is refused, not served unpaid. |
| `SettlementError` | FastMCP `ToolError` | The tool succeeded but the payment could not be settled. The tool output is withheld and the reservation released, so the buyer is not charged. |
Other responses from a gated server:
| What the caller sees | Cause |
|---|---|
| `402` with `{"error": "Replay detected"}` | The same signed payment was presented again while its first use is still reserved. A payment that was already settled fails verification first: resending it returns `402` with `{"error": "transaction_simulation_failed"}`. |
| HTTP `400`, JSON-RPC error `batched tools/call requests are not supported` | A JSON-RPC batch contains a `tools/call`. |
| HTTP `500`, JSON-RPC error `payment gate misconfigured` | A priced call arrived but `SettleOnSuccessMiddleware` was never installed (the app was built without `wrap()` and without `mcp.add_middleware(SettleOnSuccessMiddleware(gate))`). |
| MCP result with `isError=True` | The tool itself failed; the payment was discarded and nothing was submitted. |
Refusals, settlement failures, expired reservations and failed chain lookups are logged at `WARNING` to the `ai_economy_sdk` logger.
## x402-algorand exceptions
Since 0.3.0, the exceptions `x402-algorand` raises derive from `X402AlgorandError` (in `x402_algorand.errors`, also exported from `x402_algorand`). Each also derives from the built-in type raised before 0.3.0.
| Exception | Also a | Raised when |
|---|---|---|
| `NetworkError` | `ValueError` | A network id is malformed, unsupported or not registered, for example a client scheme asked to pay on a network with no configured algod and no `algod_url`. |
| `NetworkMismatchError` | `NetworkError` | algod is on a different network than requested: the client's algod differs from the requirement's network (`algod is on but the payment is for `), or a `ServerAvmSigner`'s algod differs from the network it is used for. |
| `TransactionDecodeError` | `ValueError` | Bytes or base64 text are not a decodable Algorand transaction (`decode_transaction_bytes`, `decode_base64_transaction`). |
| `SigningError` | `ValueError` | `PayerAvmSigner` / `ServerAvmSigner` got a malformed key or mnemonic, or was asked to sign for an address it does not manage. |
| `SimulationError` | `RuntimeError` | `ServerAvmSigner.simulate_group` was told by algod that the group would fail. |
An invalid payment never raises: `verify()` and `settle()` return a response with one of the [facilitator error codes](#facilitator-error-codes) above. The package logs to the `x402_algorand` logger.
## x402 client errors (Python)
| Where | Error | Cause |
|---|---|---|
| `x402Client.create_payment_payload` | `NoMatchingRequirementsError` | No offer passes the spend controls and policies, or none is for a registered network. |
| `wrapHttpxWithPayment` / `x402HttpxClient`, and so `paid_mcp_session` | `x402.http.clients.httpx.PaymentError` (`Failed to handle payment: ...`), caused by the `NoMatchingRequirementsError` | The same refusal, raised by the HTTP client. `paid_mcp_session` converts it to [`SpendLimitExceededError`](#ai-economy-sdk-exceptions) (0.5.1; in 0.5.0 it reached your code inside an `ExceptionGroup`). |
## x402-avm-js errors
Since 0.4.0, every error extends `X402AvmError` and carries a stable `code` string; `name` is the class name.
| Class | `code` | Thrown when |
|---|---|---|
| `SpendLimitExceededError` | `spend_limit_exceeded` | The amount is above the cap (1,000,000 base units by default). Properties `asset`, `amount`, `limit`. Thrown before anything is signed. |
| `PaymentNotAllowedError` | `payment_not_allowed` | The asset, network or recipient is not on an allow list. Properties `field` (`asset`, `network` or `payTo`) and `value`. |
| `InvalidPaymentRequiredError` | `invalid_payment_required` | The `PAYMENT-REQUIRED` header or a requirement is malformed (`decodePaymentRequired`, `parsePaymentRequired`, `buildExactAvmGroup`). |
| `NoSupportedRequirementError` | `no_supported_requirement` | The challenge has no `accepts` entries. |
| `NetworkMismatchError` | `network_mismatch` | No offer is for the wallet's network, or a requirement's `extra.genesisHash` / `extra.genesisId` differs from algod's. Properties `offered`, `expected`. |
| `UnknownNetworkError` | `unknown_network` | A network name or CAIP-2 id is not recognised (`resolveNetwork`, `algodClient` without a URL). For LocalNet use `networkFromAlgod`. |
| `InvalidOptionsError` | `invalid_options` | A spend control is malformed, for example a negative `maxAmount`. |
Errors raised by algod or by your `signTxns` callback propagate unchanged.
---
# ai-economy-sdk reference
> Payment-gated MCP servers and paid MCP client sessions on Algorand.
Every public object of the `ai_economy_sdk` module ([`ai-economy-sdk` on PyPI](https://pypi.org/project/ai-economy-sdk/)), generated from the docstrings in [x402-avm/ai-economy-sdk](https://github.com/x402-avm/ai-economy-sdk).
## Server
| Object | Kind | Summary |
|---|---|---|
| [`PaymentGate`](https://x402-avm.github.io/reference/python/ai-economy-sdk/payment-gate) | class | Payment gate protecting FastMCP server tools with x402 on Algorand. |
| [`AIEconomySDK`](https://x402-avm.github.io/reference/python/ai-economy-sdk/ai-economy-sdk) | class | Payment-gated MCP server SDK. |
| [`DefaultAvmSigner`](https://x402-avm.github.io/reference/python/ai-economy-sdk/default-avm-signer) | class | A default implementation of AvmSigner for convenience. |
| [`ChainReader`](https://x402-avm.github.io/reference/python/ai-economy-sdk/chain-reader) | class | Reader for Algorand blockchain state via an Indexer client. |
| [`SettleOnSuccessMiddleware`](https://x402-avm.github.io/reference/python/ai-economy-sdk/settle-on-success-middleware) | class | FastMCP middleware that settles payments on chain only upon tool success. |
## Client
| Object | Kind | Summary |
|---|---|---|
| [`paid_mcp_session`](https://x402-avm.github.io/reference/python/ai-economy-sdk/paid-mcp-session) | function | Open an MCP session that pays for tool calls with x402 on Algorand. |
## Identity
| Object | Kind | Summary |
|---|---|---|
| [`make_identity_txn`](https://x402-avm.github.io/reference/python/ai-economy-sdk/make-identity-txn) | function | Create an unsigned identity proof payment transaction. |
| [`sign_identity_txn`](https://x402-avm.github.io/reference/python/ai-economy-sdk/sign-identity-txn) | function | Create and sign an identity proof transaction, returning the X-Identity-Txn header. |
| [`verify_identity_txn`](https://x402-avm.github.io/reference/python/ai-economy-sdk/verify-identity-txn) | function | Verify an X-Identity-Txn header value against timestamp skew and Algorand signature. |
| [`sign_identity`](https://x402-avm.github.io/reference/python/ai-economy-sdk/sign-identity) | function | Generate legacy identity verification headers signed with an Algorand private key. |
| [`verify_identity`](https://x402-avm.github.io/reference/python/ai-economy-sdk/verify-identity) | function | Verify identity headers against timestamp skew and Algorand signature. |
## Networks
| Object | Kind | Summary |
|---|---|---|
| [`resolve_network`](https://x402-avm.github.io/reference/python/ai-economy-sdk/resolve-network) | function | Return the CAIP-2 id for a network name or id, and register it with x402. |
| [`genesis_hash_for`](https://x402-avm.github.io/reference/python/ai-economy-sdk/genesis-hash-for) | function | Return the full 44-character base64 genesis hash for a network. |
| [`endpoints_for`](https://x402-avm.github.io/reference/python/ai-economy-sdk/endpoints-for) | function | Default algod/indexer endpoints: AlgoNode for MainNet/TestNet, LocalNet for anything else. |
| [`usdc_asset_id`](https://x402-avm.github.io/reference/python/ai-economy-sdk/usdc-asset-id) | function | Circle USDC's asset id on MainNet/TestNet; None elsewhere. |
| [`is_public`](https://x402-avm.github.io/reference/python/ai-economy-sdk/is-public) | function | Check whether a network identifier represents public MainNet or TestNet. |
| [`register_network`](https://x402-avm.github.io/reference/python/ai-economy-sdk/register-network) | function | Register an Algorand network in x402's network tables (no-op for MainNet/TestNet, which are built in). |
| [`network_from_algod`](https://x402-avm.github.io/reference/python/ai-economy-sdk/network-from-algod) | function | Derive the CAIP-2 network id from an algod client and register it. |
| [`Endpoints`](https://x402-avm.github.io/reference/python/ai-economy-sdk/endpoints) | class | Connection parameters for Algorand node services. |
## Errors
| Object | Kind | Summary |
|---|---|---|
| [`AIEconomyError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/ai-economy-error) | class | Base class for every exception the SDK raises deliberately. |
| [`ConfigurationError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/configuration-error) | class | Invalid arguments or configuration, detected before any payment is attempted. |
| [`UnknownNetworkError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/unknown-network-error) | class | A network name or CAIP-2 identifier could not be resolved. |
| [`AlgodClientRequiredError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/algod-client-required-error) | class | An operation needs an algod connection but the signer was created without one. |
| [`PaymentVerificationError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/payment-verification-error) | class | A payment transaction group failed verification (for example, algod simulation). |
| [`PaymentRequiredError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/payment-required-error) | class | A priced tool was invoked without a verified payment. |
| [`SettlementError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/settlement-error) | class | A verified payment could not be settled on chain after the tool succeeded. |
| [`SpendLimitExceededError`](https://x402-avm.github.io/reference/python/ai-economy-sdk/spend-limit-exceeded-error) | class | The buyer's own spend controls refused a payment, so nothing was signed or sent. |
## Constants
| Object | Kind | Summary |
|---|---|---|
| [`MAINNET, TESTNET, PASS_NOTE_PREFIX, ...`](https://x402-avm.github.io/reference/python/ai-economy-sdk/constants) | constants | Network ids, the pass note prefix and the legacy identity header names exported by ai_economy_sdk. |
---
# 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)
---
# AIEconomySDK
> Payment-gated MCP server SDK.
```python
from ai_economy_sdk import AIEconomySDK
```
```python
class AIEconomySDK(
server_signer: ServerSigner,
network: str,
asset_id: str | int,
pay_to_address: str,
indexer_url: str | None = None,
subscription_asset_id: str | int | None = None,
name: str = 'ai_economy_server',
)
```
Payment-gated MCP server SDK.
High-level framework for building Model Context Protocol servers on Algorand.
Provides decorator-based tool registration, dynamic per-tool pricing callbacks,
subscription checking, and automatic PaymentGate ASGI integration.
## Constructor parameters
- `server_signer` (`ServerSigner`, required):
Signer instance (e.g., `DefaultAvmSigner`) providing private keys and
algod connection to sponsor fees as fee payer.
- `network` (`str`, required):
Network name (`"mainnet"`, `"testnet"`, `"localnet"`) or CAIP-2 identifier.
- `asset_id` (`str | int`, required):
Asset ID accepted for payments (0 for native ALGO in microALGO, or ASA ID).
- `pay_to_address` (`str`, required):
Algorand address where service payments are deposited.
- `indexer_url` (`str | None`, default `None`):
URL of the Algorand Indexer API for checking past usage and subscriptions.
- `subscription_asset_id` (`str | int | None`, default `None`):
ASA ID required for subscription-based free access.
- `name` (`str`, default `'ai_economy_server'`):
Name of the FastMCP server application.
## Attributes
- `mcp` (`FastMCP`):
Underlying FastMCP instance managing registered tools.
- `chain` (`ChainReader or None`):
ChainReader instance if `indexer_url` is provided.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk import AIEconomySDK
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> sdk = AIEconomySDK(server_signer=signer, network="mainnet", asset_id=0, pay_to_address=addr)
>>> @sdk.add_tool(name="calc", description="Run calc", pricing_func=lambda args, sender: 5000)
... def calc(x: int) -> int:
... return x * 2
```
## Methods
### `add_tool`
```python
def add_tool(
name: str,
description: str,
pricing_func: ToolPriceFunction,
) -> Callable[[_F], _F]
```
Decorator — register an MCP tool with dynamic pricing.
**Parameters**
- `name` (`str`, required):
Unique tool name recognized by MCP clients.
- `description` (`str`, required):
Human-readable description of tool behavior.
- `pricing_func` (`ToolPriceFunction`, required):
Pricing function calculating cost in base units. May accept
`(args, sender)` or `(args)`; which one is decided from its signature
when the tool is registered.
**Returns**
- `returns` (`Callable`):
Decorator wrapping the target tool function.
**Raises**
- `ConfigurationError`: If `pricing_func` accepts neither `(args, sender)` nor `(args)`.
**Example**
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk import AIEconomySDK
>>> sk, addr = account.generate_account()
>>> sdk = AIEconomySDK(server_signer=DefaultAvmSigner(sk), network="mainnet", asset_id=0, pay_to_address=addr)
>>> @sdk.add_tool("greet", "Greeting tool", lambda args, sender: 3000)
... def greet(name: str) -> str:
... return f"Hello, {name}"
```
### `build_app`
```python
def build_app(transport: Transport | None = None, **wrap_kwargs: Any = {}) -> Any
```
Build and wrap the FastMCP application with PaymentGate.
Constructs a `PaymentGate` instance wired with registered pricing
functions and wraps the FastMCP application as an ASGI app.
**Parameters**
- `transport` (`Transport | None`, default `None`):
Passed to `PaymentGate.wrap`. When omitted, the legacy SSE transport is
served and a `FutureWarning` is emitted (the default will change to
`"streamable-http"`).
- `wrap_kwargs` (`Any`, default `{}`):
**Returns**
- `returns` (`starlette.applications.Starlette`):
ASGI application ready to serve with uvicorn.
**Example**
```python
# Needs configured server:
# app = sdk.build_app(transport="streamable-http")
# uvicorn.run(app, host="127.0.0.1", port=8000)
```
### `has_active_subscription`
```python
def has_active_subscription(sender_address: str, max_age_days: float = 30.0) -> bool
```
Check if the sender holds the subscription asset and received it recently.
**Parameters**
- `sender_address` (`str`, required):
Algorand address of the sender.
- `max_age_days` (`float`, default `30.0`):
Maximum age in days of the latest subscription token transfer.
**Returns**
- `returns` (`bool`):
True if sender holds the subscription asset and received it within
`max_age_days`, False otherwise.
**Example**
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk import AIEconomySDK
>>> sk, addr = account.generate_account()
>>> sdk = AIEconomySDK(server_signer=DefaultAvmSigner(sk), network="mainnet", asset_id=0, pay_to_address=addr)
>>> sdk.has_active_subscription("")
False
```
### `get_past_usage_amount`
```python
def get_past_usage_amount(sender_address: str, days: int = 30) -> int
```
Calculate how much the sender has paid to this server in the last N days.
**Parameters**
- `sender_address` (`str`, required):
Algorand address of the sender.
- `days` (`int`, default `30`):
Number of days prior to current time to tally.
**Returns**
- `returns` (`int`):
Total spend in base units (microALGO for ALGO, or base ASA units).
**Example**
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk import AIEconomySDK
>>> sk, addr = account.generate_account()
>>> sdk = AIEconomySDK(server_signer=DefaultAvmSigner(sk), network="mainnet", asset_id=0, pay_to_address=addr)
>>> sdk.get_past_usage_amount("")
0
```
## See also
- `PaymentGate`: Middleware powering the x402 payment enforcement.
- `DefaultAvmSigner`: Default signing implementation.
Source: [ai_economy_sdk/__init__.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/__init__.py#L170)
---
# DefaultAvmSigner
> A default implementation of AvmSigner for convenience.
```python
from ai_economy_sdk import DefaultAvmSigner
```
```python
class DefaultAvmSigner(
private_key: str,
algod_client: AlgodClient | None = None,
)
```
A default implementation of AvmSigner for convenience.
Wraps an Algorand account private key and an optional AlgodClient connection
to handle signing and submitting single transactions or atomic transaction groups.
## Constructor parameters
- `private_key` (`str`, required):
Base64-encoded 32-byte Algorand private key.
- `algod_client` (`AlgodClient | None`, default `None`):
Connected algod client used for group simulation, transmission, and confirmation.
Default is None.
## Attributes
- `address` (`str`):
The corresponding Algorand public address.
- `algod_client` (`algosdk.v2client.algod.AlgodClient or None`):
Client used for on-chain interactions.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> signer.address == addr
True
>>> signer.get_addresses() == [addr]
True
```
## Methods
### `get_addresses`
```python
def get_addresses() -> list[str]
```
Return the list of public addresses managed by this signer.
**Returns**
- `returns` (`list of str`):
Single-element list containing `self.address`.
**Example**
```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> signer.get_addresses() == [addr]
True
```
### `sign_transactions`
```python
def sign_transactions(
unsigned_txns: list[bytes],
indexes: list[int],
) -> list[bytes | None]
```
Sign selected transactions in a list.
**Parameters**
- `unsigned_txns` (`list[bytes]`, required):
List of raw msgpack-encoded unsigned transaction bytes.
- `indexes` (`list[int]`, required):
0-based indices in `unsigned_txns` to sign.
**Returns**
- `returns` (`list of bytes or None`):
List of the same length as `unsigned_txns`, containing raw signed
transaction bytes at designated indexes and None elsewhere.
**Example**
```python
>>> import base64, algosdk.encoding
>>> from algosdk import account, transaction
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> sp = transaction.SuggestedParams(1000, 1, 1000, "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=", flat_fee=True)
>>> txn = transaction.PaymentTxn(addr, sp, addr, 0)
>>> raw_bytes = base64.b64decode(algosdk.encoding.msgpack_encode(txn))
>>> signed = signer.sign_transactions([raw_bytes], [0])
>>> len(signed)
1
>>> signed[0] is not None
True
```
### `sign_transaction`
```python
def sign_transaction(txn_bytes: bytes, fee_payer: Any, network: str) -> bytes
```
Sign a single raw transaction.
**Parameters**
- `txn_bytes` (`bytes`, required):
Raw msgpack-encoded unsigned transaction bytes.
- `fee_payer` (`Any`, required):
Whether this signer acts as fee payer for the transaction.
- `network` (`str`, required):
Target network identifier (unused during raw local signing).
**Returns**
- `returns` (`bytes`):
Raw msgpack-encoded signed transaction bytes.
**Example**
```python
>>> import base64, algosdk.encoding
>>> from algosdk import account, transaction
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> sp = transaction.SuggestedParams(1000, 1, 1000, "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=", flat_fee=True)
>>> txn = transaction.PaymentTxn(addr, sp, addr, 0)
>>> raw_bytes = base64.b64decode(algosdk.encoding.msgpack_encode(txn))
>>> stxn = signer.sign_transaction(raw_bytes, False, "mainnet")
>>> len(stxn) > 0
True
```
### `sign_group`
```python
def sign_group(
group_bytes: list[bytes],
fee_payer: Any,
indexes: list[int],
network: str,
) -> list[bytes]
```
Sign specified transactions within an atomic transaction group.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of raw transaction bytes representing the atomic group.
- `fee_payer` (`Any`, required):
Whether this signer acts as fee payer for the group.
- `indexes` (`list[int]`, required):
Indices within `group_bytes` to be signed by this signer.
- `network` (`str`, required):
Target network identifier.
**Returns**
- `returns` (`list of bytes`):
New list where transactions at `indexes` have been replaced with
their signed counterparts.
**Example**
```python
>>> import base64, algosdk.encoding
>>> from algosdk import account, transaction
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> sp = transaction.SuggestedParams(1000, 1, 1000, "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=", flat_fee=True)
>>> txn = transaction.PaymentTxn(addr, sp, addr, 0)
>>> raw = base64.b64decode(algosdk.encoding.msgpack_encode(txn))
>>> group = signer.sign_group([raw], True, [0], "mainnet")
>>> len(group)
1
```
### `simulate_group`
```python
def simulate_group(group_bytes: list[bytes], network: str) -> dict[str, Any]
```
Simulate execution of an atomic transaction group against algod.
Decodes the transactions, constructs a SimulateRequest with
`allow_empty_signatures=True`, and calls `algod_client.simulate_transactions`.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of raw msgpack-encoded transaction bytes in the group.
- `network` (`str`, required):
Target network identifier.
**Returns**
- `returns` (`dict`):
Raw simulation response dictionary from the algod node.
**Raises**
- `AlgodClientRequiredError`: (a `RuntimeError`) If `self.algod_client` is None.
- `PaymentVerificationError`: (a `RuntimeError`) If simulation fails with a failure message from algod.
**Example**
```python
# Needs connected AlgodClient:
# sim_result = signer.simulate_group(group_bytes, "localnet")
```
### `send_group`
```python
def send_group(group_bytes: list[bytes], network: str) -> str
```
Broadcast a signed atomic transaction group to the network.
**Notes**
Broadcasts the atomic transaction group to the Algorand blockchain. Once confirmed,
the on-chain state transition (transfers, fees, note payloads) becomes irreversible.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of signed raw transaction bytes.
- `network` (`str`, required):
Target network identifier.
**Returns**
- `returns` (`str`):
First transaction ID (txid) of the submitted atomic group.
**Raises**
- `AlgodClientRequiredError`: (a `RuntimeError`) If `self.algod_client` is None.
**Example**
```python
# Needs connected AlgodClient:
# txid = signer.send_group(signed_group_bytes, "localnet")
```
### `confirm_transaction`
```python
def confirm_transaction(txid: str, network: str, rounds: int = 4) -> dict[str, Any]
```
Wait for an on-chain transaction to be confirmed by algod.
**Parameters**
- `txid` (`str`, required):
Transaction ID to wait for.
- `network` (`str`, required):
Target network identifier.
- `rounds` (`int`, default `4`):
Number of rounds to wait before raising an error.
**Returns**
- `returns` (`dict`):
Confirmed transaction information dictionary from algod.
**Raises**
- `AlgodClientRequiredError`: (a `RuntimeError`) If `self.algod_client` is None.
**Example**
```python
# Needs connected AlgodClient:
# info = signer.confirm_transaction(txid, "localnet")
```
## See also
- `PaymentGate`: Accepts a signer to sign fee-payer and settlement transactions.
Source: [ai_economy_sdk/signer.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/signer.py#L21)
---
# 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:` 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)
---
# SettleOnSuccessMiddleware
> FastMCP middleware that settles payments on chain only upon tool success.
```python
from ai_economy_sdk import SettleOnSuccessMiddleware
```
```python
class SettleOnSuccessMiddleware(gate: PaymentGate)
```
FastMCP middleware that settles payments on chain only upon tool success.
If the tool raises an exception or returns an error result (`is_error=True`),
the payment reservation in ReplayStore is released and the buyer is not charged.
It also refuses (with `PaymentRequiredError`)
any tool call with a positive price that did not pass through the gate's HTTP
middleware, for example a call made over a transport the gate does not wrap.
## Constructor parameters
- `gate` (`PaymentGate`, required):
## Methods
### `on_call_tool`
```python
async def on_call_tool(context: Any, call_next: Any) -> Any
```
**Parameters**
- `context` (`Any`, required):
- `call_next` (`Any`, required):
Source: [ai_economy_sdk/gate.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/gate.py#L107)
---
# paid_mcp_session
> Open an MCP session that pays for tool calls with x402 on Algorand.
```python
from ai_economy_sdk import paid_mcp_session
```
```python
@contextlib.asynccontextmanager
async def paid_mcp_session(
sse_url: str,
private_key: str,
network: str,
algod_url: str | None = None,
algod_token: str | None = None,
identity: bool = True,
timeout: float = 30.0,
spend_controls: SpendControlsArg = None,
transport: ClientTransport | None = None,
) -> AsyncGenerator[ClientSession, None]
```
Open an MCP session that pays for tool calls with x402 on Algorand.
Connects to a remote Model Context Protocol server over Streamable HTTP or the
legacy SSE transport, initializing a ClientSession configured with an x402-aware
HTTP client. Outgoing requests automatically carry identity headers (if enabled)
and auto-sign 402 payment challenges for exact Algorand scheme payments.
**Notes**
On receiving HTTP 402 with `PAYMENT-REQUIRED`, the client verifies requirements,
constructs an Algorand transaction or 2-txn atomic group (where the server sponsors
transaction fees as fee payer), signs it, and resubmits under `PAYMENT-SIGNATURE`.
Funds are only deducted from the buyer's account if the tool execution succeeds.
## Parameters
- `sse_url` (`str`, required):
URL of the server's MCP endpoint: `"http://localhost:8000/mcp"` for Streamable
HTTP or `"http://localhost:8000/sse"` for SSE. (The parameter keeps its 0.4
name for compatibility; it accepts either kind of URL.)
- `private_key` (`str`, required):
Base64-encoded 32-byte Algorand private key used by the buyer to sign payments
and identity proofs.
- `network` (`str`, required):
Target Algorand network name (`"mainnet"`, `"testnet"`, `"localnet"`),
canonical CAIP-2 identifier (`"algorand:<32-char-prefix>"`), or legacy long ID.
- `algod_url` (`str | None`, default `None`):
Custom URL for the algod node. If None, defaults to the standard endpoint
for the given network (AlgoNode for public networks, localhost for localnet).
- `algod_token` (`str | None`, default `None`):
Custom authentication token header for the algod node. Default is None.
- `identity` (`bool`, default `True`):
Whether to attach cryptographic identity headers (`x-sender-*`) proving
account ownership on every request to enable vendor discounts and passes.
- `timeout` (`float`, default `30.0`):
HTTP request timeout in seconds for normal requests. Stream reads allow up
to 300 seconds.
- `spend_controls` (`SpendControlsArg`, default `None`):
Client-side spending limits enforced by x402Client before payment authorization:
- None (default): official x402 defaults apply — only default assets (native ALGO
and USDC) are allowed, capped at 1,000,000 base atomic units (1 ALGO / 1 USDC) per payment.
- False: disables all spend controls (any asset, unlimited amount).
- dict: custom spend controls following the x402 SpendControls schema, e.g.:
`{"max_amount_per_payment": False}` removes the amount cap while keeping default assets,
`{"allowed_assets": True}` allows any asset while keeping default payment cap, or
`{"allowed_assets": [{"network": network, "asset": "12345", "max_amount_per_payment": "5000000"}]}`
whitelists a specific ASA.
- `transport` (`ClientTransport | None`, default `None`):
MCP transport to use. When omitted, Streamable HTTP is used if the URL path ends
in `/mcp` and SSE otherwise, which keeps 0.4 behaviour for SSE URLs.
## Yields
- `yields` (`mcp.ClientSession`):
Active, initialized MCP client session capable of invoking tools via
`session.call_tool(tool_name, arguments)`.
## Raises
- `ConfigurationError`: If `transport` is not `"streamable-http"` or `"sse"`.
- `SpendLimitExceededError`: If a tool call needs a payment that `spend_controls` forbid (amount above the cap, or an asset that is not allowed). Nothing is signed and no funds move. The x402 error is its `__cause__`. Other errors propagate unchanged.
## Examples
```python
# Needs running paid MCP server:
import asyncio
from ai_economy_sdk import paid_mcp_session
async def run():
async with paid_mcp_session(
"http://localhost:8000/mcp",
private_key=buyer_pk,
network="localnet",
) as session:
result = await session.call_tool("echo", {"text": "hello"})
print(result)
asyncio.run(run())
```
## See also
- `PaymentGate`: Server-side payment middleware.
- `AIEconomySDK`: High-level server framework.
Source: [ai_economy_sdk/client.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/client.py#L100)
---
# make_identity_txn
> Create an unsigned identity proof payment transaction.
```python
from ai_economy_sdk import make_identity_txn
```
```python
def make_identity_txn(
address: str,
genesis_hash_b64: str,
sp: algosdk.transaction.SuggestedParams | None = None,
ts: int | None = None,
) -> algosdk.transaction.PaymentTxn
```
Create an unsigned identity proof payment transaction.
This transaction is never submitted to the network. It proves account ownership
by signing a zero-amount, zero-fee self-payment containing a timestamped identity note.
## Parameters
- `address` (`str`, required):
Algorand public address of the sender/prover.
- `genesis_hash_b64` (`str`, required):
Base64-encoded genesis hash of the target network.
- `sp` (`algosdk.transaction.SuggestedParams | None`, default `None`):
Base suggested transaction parameters. If omitted, default parameters
with fee=0, first=1, last=1000, and flat_fee=True are generated.
- `ts` (`int | None`, default `None`):
Unix timestamp (seconds) embedded in the transaction note. Defaults
to current system time (`int(time.time())`).
## Returns
- `returns` (`algosdk.transaction.PaymentTxn`):
Unsigned PaymentTxn with sender=address, receiver=address, amount=0, fee=0,
and note `x402-identity::`.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.identity import make_identity_txn
>>> _, addr = account.generate_account()
>>> txn = make_identity_txn(addr, "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=", ts=1700000000)
>>> txn.amt
0
>>> txn.fee
0
>>> txn.sender == txn.receiver == addr
True
```
## See also
- `sign_identity_txn`: Create and sign this transaction into an X-Identity-Txn header.
- `verify_identity_txn`: Validate and decode the signed transaction.
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L49)
---
# sign_identity_txn
> Create and sign an identity proof transaction, returning the X-Identity-Txn header.
```python
from ai_economy_sdk import sign_identity_txn
```
```python
def sign_identity_txn(
private_key: str,
genesis_hash_b64: str,
ts: int | None = None,
) -> dict[str, str]
```
Create and sign an identity proof transaction, returning the X-Identity-Txn header.
Constructs a zero-amount self-payment transaction containing the timestamped
identity note and signs it with the provided private key.
## Parameters
- `private_key` (`str`, required):
Base64-encoded Algorand private key of the sender.
- `genesis_hash_b64` (`str`, required):
Base64-encoded genesis hash of the network against which identity is proven.
- `ts` (`int | None`, default `None`):
Unix timestamp (seconds) embedded in the identity note. Defaults to current time.
## Returns
- `returns` (`dict[str, str]`):
Single-entry dictionary `{"X-Identity-Txn": ""}`.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.identity import sign_identity_txn
>>> sk, _ = account.generate_account()
>>> hdrs = sign_identity_txn(sk, "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=")
>>> "X-Identity-Txn" in hdrs
True
```
## See also
- `verify_identity_txn`: Server-side verification function.
- `sign_identity`: Legacy three-header signing mechanism.
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L131)
---
# verify_identity_txn
> Verify an X-Identity-Txn header value against timestamp skew and Algorand signature.
```python
from ai_economy_sdk import verify_identity_txn
```
```python
def verify_identity_txn(
header_value: str,
expected_genesis_hash_b64: str,
max_skew: float | int = 120,
now: float | int | None = None,
) -> str | None
```
Verify an X-Identity-Txn header value against timestamp skew and Algorand signature.
Decodes the signed transaction, checks that it is a self-payment of 0 amount with
0 fee and no rekeying or close-to fields, verifies network genesis hash matching,
validates round validity window <= 1000, checks timestamp within `max_skew` seconds,
and cryptographically verifies the Ed25519 signature against the sender address.
**Notes**
Rejects multisig, logic signatures, and rekeyed accounts. This proof cannot
be executed on chain because fee is 0 and rounds 1..1000 are long past on live nets.
## Parameters
- `header_value` (`str`, required):
Value of the `X-Identity-Txn` HTTP request header (base64 msgpack).
- `expected_genesis_hash_b64` (`str`, required):
Base64-encoded genesis hash of the expected Algorand network.
- `max_skew` (`float | int`, default `120`):
Maximum allowable clock skew in seconds between the timestamp in the
note and `now`.
- `now` (`float | int | None`, default `None`):
Current unix timestamp. If None, defaults to `time.time()`.
## Returns
- `returns` (`str or None`):
The verified Algorand sender address if all security checks pass,
or None if verification fails. Never raises exceptions.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.identity import sign_identity_txn, verify_identity_txn
>>> sk, addr = account.generate_account()
>>> gh = "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8="
>>> hdrs = sign_identity_txn(sk, gh)
>>> verify_identity_txn(hdrs["X-Identity-Txn"], gh) == addr
True
>>> verify_identity_txn(hdrs["X-Identity-Txn"], "wrong_genesis_hash=") is None
True
```
## See also
- `sign_identity_txn`: Client-side proof creation.
- `verify_identity`: High-level verification supporting both proof formats.
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L176)
---
# sign_identity
> Generate legacy identity verification headers signed with an Algorand private key.
```python
from ai_economy_sdk import sign_identity
```
```python
def sign_identity(private_key: str, now: int | None = None) -> dict[str, str]
```
Generate legacy identity verification headers signed with an Algorand private key.
Signs the ASCII message `x402-identity::` using Ed25519
and returns the three legacy headers `x-sender-address`, `x-sender-timestamp`,
and `x-sender-signature`.
**Notes**
.. deprecated:: 0.5.0
Use `sign_identity_txn`, whose proof is bound to one network's genesis
hash. `sign_identity` keeps working and servers keep accepting its headers;
it emits a `DeprecationWarning` and will be removed in a future major release.
## Parameters
- `private_key` (`str`, required):
Base64-encoded 32-byte Algorand private key.
- `now` (`int | None`, default `None`):
Unix timestamp in seconds. If None, defaults to `int(time.time())`.
## Returns
- `returns` (`dict[str, str]`):
Dictionary with keys `x-sender-address`, `x-sender-timestamp`,
and `x-sender-signature` (base64-encoded signature).
## Examples
```python
>>> import warnings
>>> from algosdk import account
>>> from ai_economy_sdk.identity import sign_identity
>>> sk, addr = account.generate_account()
>>> with warnings.catch_warnings():
... warnings.simplefilter("ignore", DeprecationWarning)
... hdrs = sign_identity(sk, now=1700000000)
>>> hdrs["x-sender-address"] == addr
True
>>> hdrs["x-sender-timestamp"]
'1700000000'
>>> bool(hdrs["x-sender-signature"])
True
```
## See also
- `sign_identity_txn`: Preferred modern transaction-based proof.
- `verify_identity`: Validates both modern and legacy identity headers.
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L321)
---
# verify_identity
> Verify identity headers against timestamp skew and Algorand signature.
```python
from ai_economy_sdk import verify_identity
```
```python
def verify_identity(
headers: Mapping[str, Any],
max_skew: int = 120,
now: int | None = None,
genesis_hash_b64: str | None = None,
) -> str | None
```
Verify identity headers against timestamp skew and Algorand signature.
First checks for the presence of the modern `X-Identity-Txn` header (if
`genesis_hash_b64` is provided). If absent or verification fails, falls back
to inspecting the legacy `x-sender-address`, `x-sender-timestamp`, and
`x-sender-signature` headers.
## Parameters
- `headers` (`Mapping[str, Any]`, required):
HTTP request headers mapping (case-insensitive inspection).
- `max_skew` (`int`, default `120`):
Maximum allowable clock skew in seconds between the timestamp and `now`.
- `now` (`int | None`, default `None`):
Current unix timestamp in seconds. Defaults to `int(time.time())`.
- `genesis_hash_b64` (`str | None`, default `None`):
Base64-encoded network genesis hash. Required to verify `X-Identity-Txn`.
## Returns
- `returns` (`str or None`):
The verified Algorand sender address if signature and skew checks pass,
or None if invalid or missing headers. Never raises exceptions.
## Examples
```python
>>> from algosdk import account
>>> from ai_economy_sdk.identity import sign_identity_txn, verify_identity
>>> sk, addr = account.generate_account()
>>> gh = "wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8="
>>> hdrs = sign_identity_txn(sk, gh)
>>> verify_identity(hdrs, genesis_hash_b64=gh) == addr
True
>>> verify_identity({}) is None
True
```
## See also
- `verify_identity_txn`: Specific verification for the X-Identity-Txn format.
- `sign_identity`: Client-side helper for legacy identity headers.
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L391)
---
# resolve_network
> Return the CAIP-2 id for a network name or id, and register it with x402.
```python
from ai_economy_sdk import resolve_network
```
```python
def resolve_network(network: str, algod_client: Any = None) -> str
```
Return the CAIP-2 id for a network name or id, and register it with x402.
Resolves short aliases such as `"mainnet"` or `"testnet"` to canonical
short CAIP-2 identifiers (`"algorand:<32-char-prefix>"`). Normalizes legacy
long IDs (`"algorand:<44-char-hash>"`). When given `"localnet"` or its aliases,
queries the provided `algod_client` (or the default localnet endpoint) to
derive and register the network configuration dynamically.
## Parameters
- `network` (`str`, required):
Network name, alias, canonical short CAIP-2 ID, or legacy long ID.
- `algod_client` (`Any`, default `None`):
Pre-configured `algosdk.v2client.algod.AlgodClient` instance. Used
to query genesis parameters when resolving `"localnet"`.
## Returns
- `returns` (`str`):
Canonical short CAIP-2 network identifier (e.g. `"algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k"`).
## Raises
- `UnknownNetworkError`: (a `ValueError`) If the network name cannot be resolved or is invalid.
## Examples
```python
>>> from ai_economy_sdk.network import resolve_network, MAINNET, TESTNET
>>> resolve_network("mainnet") == MAINNET
True
>>> resolve_network("testnet") == TESTNET
True
>>> resolve_network("algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=") == MAINNET
True
```
## See also
- `endpoints_for`: Resolves connection endpoints for the network.
- `genesis_hash_for`: Returns the full 44-character base64 genesis hash.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L126)
---
# genesis_hash_for
> Return the full 44-character base64 genesis hash for a network.
```python
from ai_economy_sdk import genesis_hash_for
```
```python
def genesis_hash_for(network: str) -> str
```
Return the full 44-character base64 genesis hash for a network.
## Parameters
- `network` (`str`, required):
Network name (`"mainnet"`, `"testnet"`, `"localnet"`), canonical
short CAIP-2 identifier (`"algorand:<32-char-prefix>"`), or legacy long ID.
## Returns
- `returns` (`str`):
Full 44-character base64-encoded genesis hash including trailing `=`.
## Examples
```python
>>> from ai_economy_sdk.network import genesis_hash_for
>>> genesis_hash_for("mainnet")
'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8='
>>> genesis_hash_for("testnet")
'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='
```
## See also
- `resolve_network`: Resolves network names and aliases to short CAIP-2 IDs.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L377)
---
# endpoints_for
> Default algod/indexer endpoints: AlgoNode for MainNet/TestNet, LocalNet for anything else.
```python
from ai_economy_sdk import endpoints_for
```
```python
def endpoints_for(network: str) -> Endpoints
```
Default algod/indexer endpoints: AlgoNode for MainNet/TestNet, LocalNet for anything else.
## Parameters
- `network` (`str`, required):
Network name, alias, canonical short CAIP-2 ID, or legacy long ID.
## Returns
- `returns` (`Endpoints`):
Named tuple containing algod and indexer URL and token strings.
## Examples
```python
>>> from ai_economy_sdk.network import endpoints_for
>>> ep = endpoints_for("mainnet")
>>> "algonode.cloud" in ep.algod_url
True
>>> ep = endpoints_for("localnet")
>>> ep.algod_url
'http://localhost:4001'
```
## See also
- `resolve_network`: Normalizes network identifiers.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L203)
---
# usdc_asset_id
> Circle USDC's asset id on MainNet/TestNet; None elsewhere.
```python
from ai_economy_sdk import usdc_asset_id
```
```python
def usdc_asset_id(network: str) -> int | None
```
Circle USDC's asset id on MainNet/TestNet; None elsewhere.
## Parameters
- `network` (`str`, required):
Network name, alias, canonical short CAIP-2 ID, or legacy long ID.
## Returns
- `returns` (`int or None`):
Circle USDC ASA ID (31566704 on MainNet, 10458941 on TestNet), or None
if the network does not have an official Circle USDC deployment.
## Examples
```python
>>> from ai_economy_sdk.network import usdc_asset_id
>>> usdc_asset_id("mainnet")
31566704
>>> usdc_asset_id("testnet")
10458941
>>> usdc_asset_id("localnet") is None
True
```
## See also
- `resolve_network`: Resolves network aliases to CAIP-2 identifiers.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L333)
---
# is_public
> Check whether a network identifier represents public MainNet or TestNet.
```python
from ai_economy_sdk import is_public
```
```python
def is_public(network: str) -> bool
```
Check whether a network identifier represents public MainNet or TestNet.
## Parameters
- `network` (`str`, required):
Network name, canonical short CAIP-2 identifier, or legacy long ID.
## Returns
- `returns` (`bool`):
True if the network is Algorand MainNet or TestNet, False otherwise.
## Examples
```python
>>> from ai_economy_sdk.network import is_public, MAINNET, TESTNET
>>> is_public(MAINNET)
True
>>> is_public(TESTNET)
True
>>> is_public("localnet")
False
```
## See also
- `resolve_network`: Resolve any alias to a canonical CAIP-2 identifier.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L88)
---
# register_network
> Register an Algorand network in x402's network tables (no-op for MainNet/TestNet, which are built in).
```python
from ai_economy_sdk import register_network
```
```python
def register_network(
network: str,
genesis_id: str = 'dockernet-v1',
algod_url: str | None = None,
indexer_url: str | None = None,
) -> None
```
Register an Algorand network in x402's network tables (no-op for MainNet/TestNet, which are built in).
## Parameters
- `network` (`str`, required):
Network name, bare 44-character genesis hash, legacy long CAIP-2 ID,
or canonical short CAIP-2 ID.
- `genesis_id` (`str`, default `'dockernet-v1'`):
Genesis ID string associated with the network (e.g. "mainnet-v1.0").
- `algod_url` (`str | None`, default `None`):
Custom Algod REST endpoint URL. If omitted, uses default endpoint.
- `indexer_url` (`str | None`, default `None`):
Custom Indexer REST endpoint URL. If omitted, uses default endpoint.
## Raises
- `ConfigurationError`: (a `ValueError`) If `network` is not a string.
- `UnknownNetworkError`: (a `ValueError`) If an unknown short CAIP-2 ID is passed without the full genesis hash; use `network_from_algod` instead.
## Examples
```python
>>> from ai_economy_sdk.network import register_network
>>> register_network("mainnet")
```
## See also
- `network_from_algod`: Discovers and registers network parameters from Algod.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L243)
---
# network_from_algod
> Derive the CAIP-2 network id from an algod client and register it.
```python
from ai_economy_sdk import network_from_algod
```
```python
def network_from_algod(algod_client: Any) -> str
```
Derive the CAIP-2 network id from an algod client and register it.
## Parameters
- `algod_client` (`Any`, required):
Active `algosdk.v2client.algod.AlgodClient` instance.
## Returns
- `returns` (`str`):
Registered canonical short CAIP-2 network identifier.
## Examples
```python
# Requires running Algod node:
from algosdk.v2client import algod
from ai_economy_sdk.network import network_from_algod
client = algod.AlgodClient("a" * 64, "http://localhost:4001")
caip = network_from_algod(client)
print(caip)
```
## See also
- `register_network`: Manually register network parameters.
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L300)
---
# Endpoints
> Connection parameters for Algorand node services.
```python
from ai_economy_sdk.network import Endpoints
```
```python
class Endpoints(
algod_url: str,
algod_token: str,
indexer_url: str,
indexer_token: str,
)
```
Connection parameters for Algorand node services.
## Constructor parameters
- `algod_url` (`str`, required):
URL of the algod daemon endpoint.
- `algod_token` (`str`, required):
Authentication token header value for algod.
- `indexer_url` (`str`, required):
URL of the Algorand indexer service endpoint.
- `indexer_token` (`str`, required):
Authentication token header value for indexer.
## Examples
```python
>>> from ai_economy_sdk.network import Endpoints
>>> ep = Endpoints("http://localhost:4001", "a" * 64, "http://localhost:8980", "")
>>> ep.algod_url
'http://localhost:4001'
```
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L34)
---
# AIEconomyError
> Base class for every exception the SDK raises deliberately.
```python
from ai_economy_sdk import AIEconomyError
```
```python
class AIEconomyError(Exception)
```
Base class for every exception the SDK raises deliberately.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L36)
---
# ConfigurationError
> Invalid arguments or configuration, detected before any payment is attempted.
```python
from ai_economy_sdk import ConfigurationError
```
```python
class ConfigurationError(AIEconomyError, ValueError)
```
Invalid arguments or configuration, detected before any payment is attempted.
Raised, for example, when an ALGO price does not cover the fee-payer cost and
`allow_loss` is False, when a transport name is not supported, or when a
pricing function has an unsupported signature.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L40)
---
# UnknownNetworkError
> A network name or CAIP-2 identifier could not be resolved.
```python
from ai_economy_sdk import UnknownNetworkError
```
```python
class UnknownNetworkError(ConfigurationError)
```
A network name or CAIP-2 identifier could not be resolved.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L49)
---
# AlgodClientRequiredError
> An operation needs an algod connection but the signer was created without one.
```python
from ai_economy_sdk import AlgodClientRequiredError
```
```python
class AlgodClientRequiredError(ConfigurationError, RuntimeError)
```
An operation needs an algod connection but the signer was created without one.
Subclasses `RuntimeError` as well as `ValueError` because 0.4.x raised a plain
`RuntimeError` here.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L53)
---
# PaymentVerificationError
> A payment transaction group failed verification (for example, algod simulation).
```python
from ai_economy_sdk import PaymentVerificationError
```
```python
class PaymentVerificationError(AIEconomyError, RuntimeError)
```
A payment transaction group failed verification (for example, algod simulation).
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L61)
---
# PaymentRequiredError
> A priced tool was invoked without a verified payment.
```python
from ai_economy_sdk import PaymentRequiredError
```
```python
class PaymentRequiredError(AIEconomyError, ToolError)
```
A priced tool was invoked without a verified payment.
Raised by the server-side settlement middleware when a tool call reaches the
FastMCP server without having passed through the payment gate (for example over a
transport the gate does not cover). The call is refused rather than served unpaid.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L65)
---
# SettlementError
> A verified payment could not be settled on chain after the tool succeeded.
```python
from ai_economy_sdk import SettlementError
```
```python
class SettlementError(AIEconomyError, ToolError)
```
A verified payment could not be settled on chain after the tool succeeded.
The tool's output is withheld from the caller and the payment reservation is
released, so the buyer is not charged.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L74)
---
# SpendLimitExceededError
> The buyer's own spend controls refused a payment, so nothing was signed or sent.
```python
from ai_economy_sdk import SpendLimitExceededError
```
```python
class SpendLimitExceededError(AIEconomyError)
```
The buyer's own spend controls refused a payment, so nothing was signed or sent.
Raised by `ai_economy_sdk.paid_mcp_session` when a server asks for more than the
client's `spend_controls` allow (the default caps a payment at 1 ALGO or 1 USDC), or
for an asset they do not allow. No transaction is built and no funds move. The original
x402 error is kept as `__cause__`; the message includes the offered amount and asset
when the server's offers are known.
Source: [ai_economy_sdk/exceptions.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/exceptions.py#L82)
---
# Constants
> Network ids, the pass note prefix and the legacy identity header names exported by ai_economy_sdk.
```python
from ai_economy_sdk import MAINNET, TESTNET, PASS_NOTE_PREFIX, IDENTITY_HEADERS
```
## `MAINNET`
```python
MAINNET = c.ALGORAND_MAINNET_CAIP2 # 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
```
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L84)
## `TESTNET`
```python
TESTNET = c.ALGORAND_TESTNET_CAIP2 # 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe'
```
Source: [ai_economy_sdk/network.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/network.py#L85)
## `PASS_NOTE_PREFIX`
```python
PASS_NOTE_PREFIX = 'x402-pass:'
```
Source: [ai_economy_sdk/chain.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/chain.py#L20)
## `IDENTITY_HEADERS`
```python
IDENTITY_HEADERS = ('x-sender-address', 'x-sender-timestamp', 'x-sender-signature')
```
Source: [ai_economy_sdk/identity.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/identity.py#L32)
---
# x402-algorand reference
> The Algorand (AVM) exact payment scheme as a plugin for the official x402 Python SDK.
Every public object of the `x402_algorand` module ([`x402-algorand` on PyPI](https://pypi.org/project/x402-algorand/)), generated from the docstrings in [x402-avm/x402-algorand](https://github.com/x402-avm/x402-algorand).
## Registration
| Object | Kind | Summary |
|---|---|---|
| [`register_exact_avm_client`](https://x402-avm.github.io/reference/python/x402-algorand/register-exact-avm-client) | function | Register AVM exact payment schemes to x402Client. |
| [`register_exact_avm_server`](https://x402-avm.github.io/reference/python/x402-algorand/register-exact-avm-server) | function | Register AVM exact payment schemes to x402ResourceServer. |
| [`register_exact_avm_facilitator`](https://x402-avm.github.io/reference/python/x402-algorand/register-exact-avm-facilitator) | function | Register AVM exact payment schemes to x402Facilitator. |
## Schemes
| Object | Kind | Summary |
|---|---|---|
| [`ExactAvmClientScheme`](https://x402-avm.github.io/reference/python/x402-algorand/exact-avm-client-scheme) | class | AVM client implementation for the Exact payment scheme (V2). |
| [`ExactAvmServerScheme`](https://x402-avm.github.io/reference/python/x402-algorand/exact-avm-server-scheme) | class | AVM server implementation for the Exact payment scheme (V2). |
| [`ExactAvmFacilitatorScheme`](https://x402-avm.github.io/reference/python/x402-algorand/exact-avm-facilitator-scheme) | class | AVM facilitator implementation for the Exact payment scheme (V2). |
## Signers
| Object | Kind | Summary |
|---|---|---|
| [`PayerAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/payer-avm-signer) | class | Client-side signer (`ClientAvmSigner`) for a single Algorand account. |
| [`ServerAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/server-avm-signer) | class | Facilitator-side signer (`FacilitatorAvmSigner`) backed by private keys and algod. |
## Signer protocols
| Object | Kind | Summary |
|---|---|---|
| [`ClientAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/client-avm-signer) | class | Protocol for AVM client-side signing operations. |
| [`FacilitatorAvmSigner`](https://x402-avm.github.io/reference/python/x402-algorand/facilitator-avm-signer) | class | Protocol for AVM facilitator-side signing operations. |
## Types
| Object | Kind | Summary |
|---|---|---|
| [`ExactAvmPayload`](https://x402-avm.github.io/reference/python/x402-algorand/exact-avm-payload) | class | Exact payment payload for AVM networks. |
| [`DecodedTransactionInfo`](https://x402-avm.github.io/reference/python/x402-algorand/decoded-transaction-info) | class | Information extracted from a decoded Algorand transaction. |
| [`TransactionGroupInfo`](https://x402-avm.github.io/reference/python/x402-algorand/transaction-group-info) | class | Information about a decoded transaction group. |
## Network utilities
| Object | Kind | Summary |
|---|---|---|
| [`caip2_from_genesis_hash`](https://x402-avm.github.io/reference/python/x402-algorand/caip2-from-genesis-hash) | function | Derive CAIP-2 network identifier from an Algorand genesis hash. |
| [`normalize_network`](https://x402-avm.github.io/reference/python/x402-algorand/normalize-network) | function | Normalize network identifier to CAIP-2 format. |
| [`register_network`](https://x402-avm.github.io/reference/python/x402-algorand/register-network) | function | Register a custom Algorand network (e.g. |
| [`get_genesis_hash`](https://x402-avm.github.io/reference/python/x402-algorand/get-genesis-hash) | function | Get the full base64 genesis hash for a network. |
| [`network_from_genesis_hash`](https://x402-avm.github.io/reference/python/x402-algorand/network-from-genesis-hash) | function | Determine CAIP-2 network from genesis hash. |
| [`is_valid_network`](https://x402-avm.github.io/reference/python/x402-algorand/is-valid-network) | function | Check if a network identifier is valid. |
| [`get_network_config`](https://x402-avm.github.io/reference/python/x402-algorand/get-network-config) | function | Get configuration for a network. |
| [`get_usdc_asa_id`](https://x402-avm.github.io/reference/python/x402-algorand/get-usdc-asa-id) | function | Get the USDC ASA ID for a network. |
## Transaction utilities
| Object | Kind | Summary |
|---|---|---|
| [`decode_transaction_bytes`](https://x402-avm.github.io/reference/python/x402-algorand/decode-transaction-bytes) | function | Decode transaction bytes to DecodedTransactionInfo. |
| [`decode_base64_transaction`](https://x402-avm.github.io/reference/python/x402-algorand/decode-base64-transaction) | function | Decode a base64-encoded transaction. |
| [`decode_payment_group`](https://x402-avm.github.io/reference/python/x402-algorand/decode-payment-group) | function | Decode a payment group from base64 strings. |
| [`encode_transaction_group`](https://x402-avm.github.io/reference/python/x402-algorand/encode-transaction-group) | function | Encode a list of transaction bytes to base64 strings. |
| [`validate_no_security_risks`](https://x402-avm.github.io/reference/python/x402-algorand/validate-no-security-risks) | function | Validate that a transaction has no security risks (per-transaction checks). |
| [`validate_fee_payer_transaction`](https://x402-avm.github.io/reference/python/x402-algorand/validate-fee-payer-transaction) | function | Validate a fee payer transaction. |
| [`is_valid_address`](https://x402-avm.github.io/reference/python/x402-algorand/is-valid-address) | function | Validate an Algorand address format. |
## Amount utilities
| Object | Kind | Summary |
|---|---|---|
| [`parse_money_to_decimal`](https://x402-avm.github.io/reference/python/x402-algorand/parse-money-to-decimal) | function | Parse money value to decimal. |
| [`to_atomic_amount`](https://x402-avm.github.io/reference/python/x402-algorand/to-atomic-amount) | function | Convert decimal amount to atomic units. |
| [`from_atomic_amount`](https://x402-avm.github.io/reference/python/x402-algorand/from-atomic-amount) | function | Convert atomic units to decimal amount. |
## Errors
| Object | Kind | Summary |
|---|---|---|
| [`X402AlgorandError`](https://x402-avm.github.io/reference/python/x402-algorand/x402-algorand-error) | class | Base class for all exceptions raised by x402-algorand. |
| [`NetworkError`](https://x402-avm.github.io/reference/python/x402-algorand/network-error) | class | A network identifier is malformed, unsupported, or not registered. |
| [`NetworkMismatchError`](https://x402-avm.github.io/reference/python/x402-algorand/network-mismatch-error) | class | An algod node is connected to a different network than the one requested. |
| [`TransactionDecodeError`](https://x402-avm.github.io/reference/python/x402-algorand/transaction-decode-error) | class | Bytes or base64 text could not be decoded as an Algorand transaction. |
| [`SigningError`](https://x402-avm.github.io/reference/python/x402-algorand/signing-error) | class | A signer could not sign: bad key material or an address it does not manage. |
| [`SimulationError`](https://x402-avm.github.io/reference/python/x402-algorand/simulation-error) | class | An algod `simulate` call reported that the transaction group would fail. |
## Constants
| Object | Kind | Summary |
|---|---|---|
| [`ALGORAND_MAINNET_CAIP2, ALGORAND_TESTNET_CAIP2, MAINNET_GENESIS_HASH, ...`](https://x402-avm.github.io/reference/python/x402-algorand/constants) | constants | Network ids, genesis hashes, USDC asset ids and protocol limits exported by x402_algorand. |
---
# register_exact_avm_client
> Register AVM exact payment schemes to x402Client.
```python
from x402_algorand.exact import register_exact_avm_client
```
```python
def register_exact_avm_client(
client: ClientT,
signer: ClientAvmSigner,
networks: str | list[str] | None = None,
policies: list | None = None,
algod_url: str | None = None,
algod_token: str | None = None,
) -> ClientT
```
Register AVM exact payment schemes to x402Client.
Registers:
- V2: algorand:* wildcard (or specific networks if provided)
- V1: All supported AVM networks
## Parameters
- `client` (`ClientT`, required):
x402Client instance.
- `signer` (`ClientAvmSigner`, required):
AVM signer for payment authorizations.
- `networks` (`str | list[str] | None`, default `None`):
Optional specific network(s) (default: wildcard).
- `policies` (`list | None`, default `None`):
Optional payment policies.
- `algod_url` (`str | None`, default `None`):
Optional custom Algod URL.
- `algod_token` (`str | None`, default `None`):
Optional custom Algod token.
## Returns
- `returns` (`ClientT`):
Client for chaining.
## Examples
```python
import os
from x402 import x402Client
from x402_algorand import PayerAvmSigner
from x402_algorand.exact import register_exact_avm_client
client = x402Client()
register_exact_avm_client(
client,
PayerAvmSigner.from_mnemonic(os.environ["PAYER_MNEMONIC"]),
algod_url="http://localhost:4001", # LocalNet; omit on MainNet / TestNet
algod_token="a" * 64,
)
```
Source: [x402_algorand/exact/register.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/register.py#L28)
---
# register_exact_avm_server
> Register AVM exact payment schemes to x402ResourceServer.
```python
from x402_algorand.exact import register_exact_avm_server
```
```python
def register_exact_avm_server(
server: ServerT,
networks: str | list[str] | None = None,
) -> ServerT
```
Register AVM exact payment schemes to x402ResourceServer.
V2 only (no server-side for V1).
## Parameters
- `server` (`ServerT`, required):
x402ResourceServer instance.
- `networks` (`str | list[str] | None`, default `None`):
Optional specific network(s) (default: wildcard).
## Returns
- `returns` (`ServerT`):
Server for chaining.
## Examples
```python
from x402 import x402Facilitator, x402ResourceServer
from x402_algorand.exact import register_exact_avm_server
facilitator = x402Facilitator() # register the facilitator scheme on it too
server = x402ResourceServer(facilitator)
register_exact_avm_server(server) # all Algorand networks (algorand:*)
```
Source: [x402_algorand/exact/register.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/register.py#L78)
---
# register_exact_avm_facilitator
> Register AVM exact payment schemes to x402Facilitator.
```python
from x402_algorand.exact import register_exact_avm_facilitator
```
```python
def register_exact_avm_facilitator(
facilitator: FacilitatorT,
signer: FacilitatorAvmSigner,
networks: str | list[str],
) -> FacilitatorT
```
Register AVM exact payment schemes to x402Facilitator.
Registers:
- V2: Specified networks
- V1: All supported AVM networks
## Parameters
- `facilitator` (`FacilitatorT`, required):
x402Facilitator instance.
- `signer` (`FacilitatorAvmSigner`, required):
AVM signer for verification/settlement.
- `networks` (`str | list[str]`, required):
Network(s) to register.
## Returns
- `returns` (`FacilitatorT`):
Facilitator for chaining.
## Examples
```python
import os
from algosdk.v2client.algod import AlgodClient
from x402 import x402Facilitator
from x402_algorand import ServerAvmSigner, caip2_from_genesis_hash
from x402_algorand.exact import register_exact_avm_facilitator
algod = AlgodClient("a" * 64, "http://localhost:4001") # LocalNet
network = caip2_from_genesis_hash(algod.suggested_params().gh)
signer = ServerAvmSigner.from_mnemonic(os.environ["FACILITATOR_MNEMONIC"], algod)
facilitator = x402Facilitator()
register_exact_avm_facilitator(facilitator, signer, network)
```
Source: [x402_algorand/exact/register.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/register.py#L108)
---
# ExactAvmClientScheme
> AVM client implementation for the Exact payment scheme (V2).
```python
from x402_algorand.exact import ExactAvmClientScheme # defined as x402_algorand.exact.client.ExactAvmScheme
```
```python
class ExactAvmClientScheme(
signer: ClientAvmSigner,
algod_url: str | None = None,
algod_token: str | None = None,
)
```
AVM client implementation for the Exact payment scheme (V2).
Implements SchemeNetworkClient protocol. Returns the inner payload dict,
which x402Client wraps into a full PaymentPayload.
Creates atomic transaction groups for ASA payments:
- Without fee abstraction: Single ASA transfer transaction
- With fee abstraction: [Fee payer txn (unsigned), ASA transfer (signed)]
## Constructor parameters
- `signer` (`ClientAvmSigner`, required):
- `algod_url` (`str | None`, default `None`):
- `algod_token` (`str | None`, default `None`):
## Attributes
- `scheme` (`Any`):
The scheme identifier ("exact").
## Examples
```python
import os
from x402_algorand import PayerAvmSigner
from x402_algorand.exact import ExactAvmClientScheme
scheme = ExactAvmClientScheme(
PayerAvmSigner.from_mnemonic(os.environ["PAYER_MNEMONIC"]),
algod_url="http://localhost:4001",
algod_token="a" * 64,
)
# Usually registered with register_exact_avm_client(); called directly it returns
# the inner payload {"paymentGroup": [...], "paymentIndex": 1} for a requirement:
# inner = scheme.create_payment_payload(requirements)
```
## Methods
### `create_payment_payload`
```python
def create_payment_payload(requirements: PaymentRequirements) -> dict[str, Any]
```
Create atomic transaction group for payment.
If feePayer in requirements.extra:
- Creates 2-txn group: [fee_payer_txn (unsigned), asa_transfer (signed)]
- Fee payer covers all fees (pooled: minFee * 2)
- Client signs only ASA transfer
**Else**
- Creates single ASA transfer with normal fee
- Client signs the transaction
**Parameters**
- `requirements` (`PaymentRequirements`, required):
Payment requirements from server.
**Returns**
- `returns` (`dict[str, Any]`):
Inner payload dict (paymentGroup, paymentIndex).
x402Client wraps this with x402_version, accepted, resource, extensions.
**Raises**
- `NetworkError`: If the network is unsupported and no `algod_url` was given.
- `NetworkMismatchError`: If algod is connected to a different network than `requirements.network`.
### `find_default_asset`
```python
def find_default_asset(asset: str, network: str) -> dict[str, Any] | None
```
Find default asset info for spend controls.
Returns the shape of official x402 ExactDefaultAssetInfo:
{asset, name, version, decimals, symbol}.
- asset "0" on ANY Algorand network -> Algo (decimals 6)
- USDC (31566704 on MainNet / 10458941 on TestNet) -> USD Coin (decimals 6)
- anything else -> None
**Parameters**
- `asset` (`str`, required):
Asset identifier ("0" for ALGO or ASA ID).
- `network` (`str`, required):
CAIP-2 or legacy V1 network identifier.
**Returns**
- `returns` (`dict[str, Any] | None`):
Matching default asset dict or None.
Source: [x402_algorand/exact/client.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/client.py#L27)
---
# ExactAvmServerScheme
> AVM server implementation for the Exact payment scheme (V2).
```python
from x402_algorand.exact import ExactAvmServerScheme # defined as x402_algorand.exact.server.ExactAvmScheme
```
```python
class ExactAvmServerScheme()
```
AVM server implementation for the Exact payment scheme (V2).
Parses prices and enhances payment requirements with AVM-specific data.
Note: feePayer is OPTIONAL for AVM (unlike SVM which requires it).
If not provided, the client pays their own fees.
## Attributes
- `scheme` (`Any`):
The scheme identifier ("exact").
## Examples
```python
from x402_algorand.exact import ExactAvmServerScheme
scheme = ExactAvmServerScheme()
price = scheme.parse_price({"amount": "10000", "asset": "0"}, "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k")
print(price.amount, price.asset) # 10000 0
```
## Methods
### `register_money_parser`
```python
def register_money_parser(parser: MoneyParser) -> ExactAvmScheme
```
Register custom money parser in the parser chain.
Multiple parsers can be registered - tried in registration order.
If parser returns None, next parser is tried.
**Parameters**
- `parser` (`MoneyParser`, required):
Custom function to convert amount to AssetAmount.
**Returns**
- `returns` (`ExactAvmScheme`):
Self for chaining.
### `parse_price`
```python
def parse_price(price: Price, network: Network) -> AssetAmount
```
Parse price into asset amount.
If price is already AssetAmount, returns it directly.
If price is Money (str|float), parses and tries custom parsers.
Falls back to default USDC conversion.
**Parameters**
- `price` (`Price`, required):
Price to parse (string, number, or AssetAmount dict).
- `network` (`Network`, required):
Network identifier.
**Returns**
- `returns` (`AssetAmount`):
AssetAmount with amount, asset, and extra fields.
### `enhance_payment_requirements`
```python
def enhance_payment_requirements(
requirements: PaymentRequirements,
supported_kind: SupportedKind,
extension_keys: list[str],
) -> PaymentRequirements
```
Add scheme-specific enhancements to payment requirements.
For AVM:
- Adds decimals to extra (required for display)
- Adds feePayer from facilitator if provided (OPTIONAL)
- Adds genesis info if available
**Parameters**
- `requirements` (`PaymentRequirements`, required):
Base payment requirements.
- `supported_kind` (`SupportedKind`, required):
Supported kind from facilitator.
- `extension_keys` (`list[str]`, required):
Extension keys being used.
**Returns**
- `returns` (`PaymentRequirements`):
Enhanced payment requirements.
### `get_asset_info`
```python
def get_asset_info(network: str, asset: str) -> dict[str, Any]
```
Get information about an asset.
**Parameters**
- `network` (`str`, required):
Network identifier.
- `asset` (`str`, required):
ASA ID as string.
**Returns**
- `returns` (`dict[str, Any]`):
Asset info with name, decimals, asa_id.
Source: [x402_algorand/exact/server.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/server.py#L33)
---
# ExactAvmFacilitatorScheme
> AVM facilitator implementation for the Exact payment scheme (V2).
```python
from x402_algorand.exact import ExactAvmFacilitatorScheme # defined as x402_algorand.exact.facilitator.ExactAvmScheme
```
```python
class ExactAvmFacilitatorScheme(signer: FacilitatorAvmSigner)
```
AVM facilitator implementation for the Exact payment scheme (V2).
Verifies and settles ASA payments on Algorand networks.
## Constructor parameters
- `signer` (`FacilitatorAvmSigner`, required):
## Attributes
- `scheme` (`Any`):
The scheme identifier ("exact").
- `caip_family` (`Any`):
The CAIP family pattern ("algorand:*").
## Examples
```python
import os
from x402_algorand import ServerAvmSigner
from x402_algorand.exact import ExactAvmFacilitatorScheme
signer = ServerAvmSigner.from_mnemonic(
os.environ["FACILITATOR_MNEMONIC"], algod_url="http://localhost:4001", algod_token="a" * 64
)
scheme = ExactAvmFacilitatorScheme(signer)
# Usually registered with register_exact_avm_facilitator(). Called directly:
# result = scheme.verify(payload, requirements) # VerifyResponse, never raises for a bad payment
# if result.is_valid:
# settled = scheme.settle(payload, requirements) # settled.transaction = buyer's payment txid
```
## Methods
### `get_extra`
```python
def get_extra(network: Network) -> dict[str, Any] | None
```
Get mechanism-specific extra data for the supported kinds endpoint.
For AVM, this includes a randomly selected fee payer address.
Random selection distributes load across multiple signers.
**Parameters**
- `network` (`Network`, required):
Network identifier (used for validation only).
**Returns**
- `returns` (`dict[str, Any] | None`):
Extra data with feePayer address, or None if no signers.
### `get_signers`
```python
def get_signers(network: Network) -> list[str]
```
Get facilitator wallet addresses.
**Parameters**
- `network` (`Network`, required):
Network identifier.
**Returns**
- `returns` (`list[str]`):
List of facilitator fee payer addresses.
### `verify`
```python
def verify(
payload: PaymentPayload,
requirements: PaymentRequirements,
context: Any = None,
*args: Any = (),
**kwargs: Any = {},
) -> VerifyResponse
```
Verify ASA payment payload.
Validates per Algorand exact scheme spec:
1. Check paymentGroup contains 16 or fewer elements
2. Decode all transactions from the paymentGroup
3. Locate payment transaction (paymentIndex):
- Check aamt (asset amount) == requirements.amount
- Check arcv (asset receiver) matches requirements.payTo
4. If feePayer in requirements:
- Locate fee payer transaction
- Check type is "pay"
- Check close, rekey, amt are omitted/zero
- Check fee is reasonable
- Sign the transaction
5. Simulate group to verify it would succeed
Security checks:
- No unbalanced rekey operations (sandwich rekey+rekey-back allowed)
- No close-to operations allowed
- keyreg transactions blocked
- Facilitator signers cannot transfer their own funds
**Parameters**
- `payload` (`PaymentPayload`, required):
Payment payload from client.
- `requirements` (`PaymentRequirements`, required):
Payment requirements.
- `context` (`Any`, default `None`):
- `args` (`Any`, default `()`):
- `kwargs` (`Any`, default `{}`):
**Returns**
- `returns` (`VerifyResponse`):
VerifyResponse with is_valid and payer.
### `settle`
```python
def settle(
payload: PaymentPayload,
requirements: PaymentRequirements,
context: Any = None,
*args: Any = (),
**kwargs: Any = {},
) -> SettleResponse
```
Settle ASA payment on-chain.
- Re-verifies payment
- Signs fee payer transaction
- Sends transaction group to network
- Waits for confirmation (instant finality)
**Parameters**
- `payload` (`PaymentPayload`, required):
Verified payment payload.
- `requirements` (`PaymentRequirements`, required):
Payment requirements.
- `context` (`Any`, default `None`):
- `args` (`Any`, default `()`):
- `kwargs` (`Any`, default `{}`):
**Returns**
- `returns` (`SettleResponse`):
SettleResponse with success, transaction, and payer.
Source: [x402_algorand/exact/facilitator.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/exact/facilitator.py#L72)
---
# PayerAvmSigner
> Client-side signer (`ClientAvmSigner`) for a single Algorand account.
```python
from x402_algorand import PayerAvmSigner
```
```python
class PayerAvmSigner(private_key: str)
```
Client-side signer (`ClientAvmSigner`) for a single Algorand account.
**Example**
```python
signer = PayerAvmSigner.from_mnemonic(os.environ["PAYER_MNEMONIC"])
register_exact_avm_client(client, signer)
```
## Constructor parameters
- `private_key` (`str`, required):
## Methods
### `from_private_key`
```python
@classmethod
def from_private_key(private_key: str) -> PayerAvmSigner
```
Create a signer from a base64 private key (as returned by `algosdk`).
**Parameters**
- `private_key` (`str`, required):
### `from_mnemonic`
```python
@classmethod
def from_mnemonic(mnemonic_phrase: str) -> PayerAvmSigner
```
Create a signer from a 25-word Algorand mnemonic.
**Parameters**
- `mnemonic_phrase` (`str`, required):
### `sign_transactions`
```python
def sign_transactions(
unsigned_txns: list[bytes],
indexes_to_sign: list[int],
) -> list[bytes | None]
```
Sign the transactions at `indexes_to_sign`; `None` elsewhere.
**Parameters**
- `unsigned_txns` (`list[bytes]`, required):
- `indexes_to_sign` (`list[int]`, required):
**Raises**
- `SigningError`: If a transaction to sign is not sent by this account.
Source: [x402_algorand/signer.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/signer.py#L298)
---
# ServerAvmSigner
> Facilitator-side signer (`FacilitatorAvmSigner`) backed by private keys and algod.
```python
from x402_algorand import ServerAvmSigner
```
```python
class ServerAvmSigner(
private_keys: str | Sequence[str],
algod_client: algod.AlgodClient | None = None,
algod_url: str | None = None,
algod_token: str | None = None,
)
```
Facilitator-side signer (`FacilitatorAvmSigner`) backed by private keys and algod.
Signs fee payer transactions, simulates groups, sends them, and waits for
confirmation. It also implements `ClientAvmSigner` (`address` /
`sign_transactions`), so one object can serve both roles in tests and demos.
algod selection:
- `algod_client` (or `algod_url`/`algod_token`) given: that node is used for
every call. The first call for a network checks that the node's genesis hash
matches it and raises `NetworkMismatchError` otherwise.
- nothing given: the algod URL configured for the network in `NETWORK_CONFIGS`
(MainNet / TestNet defaults, or a network added with `register_network`).
**Example**
```python
signer = ServerAvmSigner.from_mnemonic(
os.environ["FACILITATOR_MNEMONIC"],
algod_url="http://localhost:4001",
algod_token="a" * 64,
)
register_exact_avm_facilitator(facilitator, signer, network)
```
## Constructor parameters
- `private_keys` (`str | Sequence[str]`, required):
- `algod_client` (`algod.AlgodClient | None`, default `None`):
- `algod_url` (`str | None`, default `None`):
- `algod_token` (`str | None`, default `None`):
## Methods
### `from_private_key`
```python
@classmethod
def from_private_key(
private_key: str,
algod_client: algod.AlgodClient | None = None,
algod_url: str | None = None,
algod_token: str | None = None,
) -> ServerAvmSigner
```
Create a signer from one base64 private key.
**Parameters**
- `private_key` (`str`, required):
- `algod_client` (`algod.AlgodClient | None`, default `None`):
- `algod_url` (`str | None`, default `None`):
- `algod_token` (`str | None`, default `None`):
### `from_mnemonic`
```python
@classmethod
def from_mnemonic(
mnemonic_phrase: str,
algod_client: algod.AlgodClient | None = None,
algod_url: str | None = None,
algod_token: str | None = None,
) -> ServerAvmSigner
```
Create a signer from a 25-word Algorand mnemonic.
**Parameters**
- `mnemonic_phrase` (`str`, required):
- `algod_client` (`algod.AlgodClient | None`, default `None`):
- `algod_url` (`str | None`, default `None`):
- `algod_token` (`str | None`, default `None`):
### `sign_transactions`
```python
def sign_transactions(
unsigned_txns: list[bytes],
indexes_to_sign: list[int],
) -> list[bytes | None]
```
Sign the transactions at `indexes_to_sign` with the key of each sender.
**Parameters**
- `unsigned_txns` (`list[bytes]`, required):
- `indexes_to_sign` (`list[int]`, required):
### `get_addresses`
```python
def get_addresses() -> list[str]
```
All managed fee payer addresses.
### `sign_transaction`
```python
def sign_transaction(txn_bytes: bytes, fee_payer: str, network: str) -> bytes
```
Sign one unsigned transaction with `fee_payer`'s key.
**Parameters**
- `txn_bytes` (`bytes`, required):
- `fee_payer` (`str`, required):
- `network` (`str`, required):
**Raises**
- `SigningError`: If `fee_payer` is not managed by this signer.
### `sign_group`
```python
def sign_group(
group_bytes: list[bytes],
fee_payer: str,
indexes_to_sign: list[int],
network: str,
) -> list[bytes]
```
Sign the transactions at `indexes_to_sign` with `fee_payer`'s key.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
- `fee_payer` (`str`, required):
- `indexes_to_sign` (`list[int]`, required):
- `network` (`str`, required):
**Raises**
- `SigningError`: If `fee_payer` is not managed by this signer.
### `simulate_group`
```python
def simulate_group(group_bytes: list[bytes], network: str) -> None
```
Simulate the group with algod (unsigned transactions allowed).
**Parameters**
- `group_bytes` (`list[bytes]`, required):
- `network` (`str`, required):
**Raises**
- `SimulationError`: If algod reports the group would fail.
- `NetworkMismatchError`: If algod is on a different network.
### `send_group`
```python
def send_group(group_bytes: list[bytes], network: str) -> str
```
Submit a fully signed group; returns the ID of its first transaction.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
- `network` (`str`, required):
### `confirm_transaction`
```python
def confirm_transaction(txid: str, network: str, rounds: int = 4) -> None
```
Wait up to `rounds` rounds for `txid` to be in a block.
**Parameters**
- `txid` (`str`, required):
- `network` (`str`, required):
- `rounds` (`int`, default `4`):
**Raises**
- `algosdk.error.ConfirmationTimeoutError`: If not confirmed in time.
- `algosdk.error.TransactionRejectedError`: If the pool rejected it.
### `algod_for`
```python
def algod_for(network: str) -> algod.AlgodClient
```
The algod client used for `network` (CAIP-2 or V1 name).
**Parameters**
- `network` (`str`, required):
**Raises**
- `NetworkError`: If no algod is configured for the network.
- `NetworkMismatchError`: If the configured algod is on another network.
Source: [x402_algorand/signer.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/signer.py#L348)
---
# ClientAvmSigner
> Protocol for AVM client-side signing operations.
```python
from x402_algorand import ClientAvmSigner
```
```python
class ClientAvmSigner(Protocol)
```
Protocol for AVM client-side signing operations.
Used by x402Client to sign transactions for payment payloads.
The client signer is responsible for:
- Providing the sender address
- Signing transactions where the client is the sender
## Methods
### `sign_transactions`
```python
def sign_transactions(
unsigned_txns: list[bytes],
indexes_to_sign: list[int],
) -> list[bytes | None]
```
Sign specified transactions in a group.
Only signs transactions at the specified indexes.
Returns None for transactions that should not be signed by this signer.
**Parameters**
- `unsigned_txns` (`list[bytes]`, required):
List of unsigned transaction bytes (msgpack encoded).
- `indexes_to_sign` (`list[int]`, required):
Indexes of transactions this signer should sign.
**Returns**
- `returns` (`list[bytes | None]`):
List parallel to unsigned_txns, with signed transaction bytes
at indexes_to_sign and None elsewhere.
Source: [x402_algorand/signer.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/signer.py#L45)
---
# FacilitatorAvmSigner
> Protocol for AVM facilitator-side signing operations.
```python
from x402_algorand import FacilitatorAvmSigner
```
```python
class FacilitatorAvmSigner(Protocol)
```
Protocol for AVM facilitator-side signing operations.
Used by x402Facilitator to verify, sign, simulate, and settle transactions.
The facilitator signer is responsible for:
- Providing the fee payer addresses it manages
- Signing fee payer transactions
- Simulating transaction groups
- Sending transaction groups to the network
- Confirming transaction finality
## Methods
### `get_addresses`
```python
def get_addresses() -> list[str]
```
Get all managed fee payer addresses.
**Returns**
- `returns` (`list[str]`):
List of 58-character Algorand addresses that can be used
as fee payers. Enables load distribution across multiple signers.
### `sign_transaction`
```python
def sign_transaction(txn_bytes: bytes, fee_payer: str, network: str) -> bytes
```
Sign a single transaction with the fee payer's key.
**Parameters**
- `txn_bytes` (`bytes`, required):
Unsigned transaction bytes (msgpack encoded).
- `fee_payer` (`str`, required):
Algorand address of the fee payer.
- `network` (`str`, required):
CAIP-2 network identifier.
**Returns**
- `returns` (`bytes`):
Signed transaction bytes (msgpack encoded).
**Raises**
- `ValueError`: If fee_payer is not managed by this signer.
### `sign_group`
```python
def sign_group(
group_bytes: list[bytes],
fee_payer: str,
indexes_to_sign: list[int],
network: str,
) -> list[bytes]
```
Sign specified transactions in a group with the fee payer's key.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of transaction bytes (some signed, some unsigned).
- `fee_payer` (`str`, required):
Algorand address of the fee payer.
- `indexes_to_sign` (`list[int]`, required):
Indexes of transactions the fee payer should sign.
- `network` (`str`, required):
CAIP-2 network identifier.
**Returns**
- `returns` (`list[bytes]`):
List of transaction bytes with fee payer's transactions now signed.
**Raises**
- `ValueError`: If fee_payer is not managed by this signer.
### `simulate_group`
```python
def simulate_group(group_bytes: list[bytes], network: str) -> None
```
Simulate a transaction group to verify it will succeed.
Uses Algorand's simulate endpoint to dry-run the transaction group
without committing it to the network.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of signed/unsigned transaction bytes.
- `network` (`str`, required):
CAIP-2 network identifier.
**Raises**
- `Exception`: If simulation fails (contains error message).
### `send_group`
```python
def send_group(group_bytes: list[bytes], network: str) -> str
```
Send a transaction group to the network.
**Parameters**
- `group_bytes` (`list[bytes]`, required):
List of fully-signed transaction bytes.
- `network` (`str`, required):
CAIP-2 network identifier.
**Returns**
- `returns` (`str`):
Transaction ID of the first transaction in the group.
**Raises**
- `Exception`: If sending fails.
### `confirm_transaction`
```python
def confirm_transaction(txid: str, network: str, rounds: int = 4) -> None
```
Wait for transaction confirmation.
Algorand has instant finality - once a transaction is in a block,
it is final and will never be reverted.
**Parameters**
- `txid` (`str`, required):
Transaction ID to confirm.
- `network` (`str`, required):
CAIP-2 network identifier.
- `rounds` (`int`, default `4`):
Maximum rounds to wait (default 4).
**Raises**
- `Exception`: If confirmation times out or transaction fails.
Source: [x402_algorand/signer.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/signer.py#L85)
---
# ExactAvmPayload
> Exact payment payload for AVM networks.
```python
from x402_algorand import ExactAvmPayload
```
```python
class ExactAvmPayload(payment_group: list[str] = list(), payment_index: int = 0)
```
Exact payment payload for AVM networks.
Contains an atomic group of base64-encoded msgpack transactions.
The paymentIndex identifies which transaction pays the resource server.
## Constructor parameters
- `payment_group` (`list[str]`, default `list()`):
- `payment_index` (`int`, default `0`):
## Attributes
- `payment_group` (`list[str]`):
List of base64-encoded msgpack transactions.
- `payment_index` (`int`):
Index of the payment transaction in the group.
## Methods
### `to_dict`
```python
def to_dict() -> dict[str, Any]
```
Convert to dictionary for JSON serialization.
**Returns**
- `returns` (`dict[str, Any]`):
Dictionary with camelCase keys for JSON.
### `from_dict`
```python
@classmethod
def from_dict(data: dict[str, Any]) -> ExactAvmPayload
```
Create from dictionary.
**Parameters**
- `data` (`dict[str, Any]`, required):
Dictionary with payload data.
**Returns**
- `returns` (`ExactAvmPayload`):
ExactAvmPayload instance.
Source: [x402_algorand/types.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/types.py#L10)
---
# DecodedTransactionInfo
> Information extracted from a decoded Algorand transaction.
```python
from x402_algorand import DecodedTransactionInfo
```
```python
class DecodedTransactionInfo(
type: str,
sender: str,
fee: int,
first_valid: int,
last_valid: int,
genesis_hash: str,
genesis_id: str | None = None,
group: str | None = None,
is_signed: bool = False,
note: bytes | None = None,
lease: bytes | None = None,
receiver: str | None = None,
amount: int | None = None,
close_remainder_to: str | None = None,
asset_index: int | None = None,
asset_receiver: str | None = None,
asset_amount: int | None = None,
asset_close_to: str | None = None,
rekey_to: str | None = None,
)
```
Information extracted from a decoded Algorand transaction.
Provides a unified view of transaction data regardless of whether
the transaction is signed or unsigned.
## Constructor parameters
- `type` (`str`, required):
- `sender` (`str`, required):
- `fee` (`int`, required):
- `first_valid` (`int`, required):
- `last_valid` (`int`, required):
- `genesis_hash` (`str`, required):
- `genesis_id` (`str | None`, default `None`):
- `group` (`str | None`, default `None`):
- `is_signed` (`bool`, default `False`):
- `note` (`bytes | None`, default `None`):
- `lease` (`bytes | None`, default `None`):
- `receiver` (`str | None`, default `None`):
- `amount` (`int | None`, default `None`):
- `close_remainder_to` (`str | None`, default `None`):
- `asset_index` (`int | None`, default `None`):
- `asset_receiver` (`str | None`, default `None`):
- `asset_amount` (`int | None`, default `None`):
- `asset_close_to` (`str | None`, default `None`):
- `rekey_to` (`str | None`, default `None`):
## Attributes
- `type` (`str`):
Transaction type ("pay", "axfer", "keyreg", etc.).
- `sender` (`str`):
Algorand address of the sender.
- `fee` (`int`):
Fee in microALGO.
- `first_valid` (`int`):
First valid round.
- `last_valid` (`int`):
Last valid round.
- `genesis_hash` (`str`):
Base64 encoded genesis hash.
- `genesis_id` (`str | None`):
Genesis ID string (e.g., "mainnet-v1.0").
- `group` (`str | None`):
Base64 encoded group ID or None.
- `is_signed` (`bool`):
Whether the transaction has a signature.
- `note` (`bytes | None`):
Transaction note bytes or None.
- `receiver` (`str | None`):
Payment receiver address or None.
- `amount` (`int | None`):
Payment amount in microALGO or None.
- `close_remainder_to` (`str | None`):
Close-to address or None.
- `asset_index` (`int | None`):
ASA ID or None.
- `asset_receiver` (`str | None`):
Asset receiver address or None.
- `asset_amount` (`int | None`):
Asset amount or None.
- `asset_close_to` (`str | None`):
Asset close-to address or None.
- `lease` (`bytes | None`):
Lease bytes or None.
- `rekey_to` (`str | None`):
Rekey-to address or None (SECURITY: should be None).
Source: [x402_algorand/types.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/types.py#L57)
---
# TransactionGroupInfo
> Information about a decoded transaction group.
```python
from x402_algorand import TransactionGroupInfo
```
```python
class TransactionGroupInfo(
transactions: list[DecodedTransactionInfo],
group_id: str | None = None,
total_fee: int = 0,
has_fee_payer: bool = False,
fee_payer_index: int | None = None,
payment_index: int = 0,
)
```
Information about a decoded transaction group.
Provides summary information about a group of transactions.
## Constructor parameters
- `transactions` (`list[DecodedTransactionInfo]`, required):
- `group_id` (`str | None`, default `None`):
- `total_fee` (`int`, default `0`):
- `has_fee_payer` (`bool`, default `False`):
- `fee_payer_index` (`int | None`, default `None`):
- `payment_index` (`int`, default `0`):
## Attributes
- `transactions` (`list[DecodedTransactionInfo]`):
List of decoded transaction info.
- `group_id` (`str | None`):
Base64 encoded group ID (if present).
- `total_fee` (`int`):
Sum of all transaction fees.
- `has_fee_payer` (`bool`):
Whether a fee payer transaction exists.
- `fee_payer_index` (`int | None`):
Index of the fee payer transaction or None.
- `payment_index` (`int`):
Index of the payment transaction.
Source: [x402_algorand/types.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/types.py#L121)
---
# caip2_from_genesis_hash
> Derive CAIP-2 network identifier from an Algorand genesis hash.
```python
from x402_algorand import caip2_from_genesis_hash
```
```python
def caip2_from_genesis_hash(genesis_hash: str | bytes) -> str
```
Derive CAIP-2 network identifier from an Algorand genesis hash.
Following the Algorand CAIP-2 profile, the reference is the first 32
characters of the URL-safe base64 encoding of the raw 32-byte genesis hash.
## Parameters
- `genesis_hash` (`str | bytes`, required):
32-byte genesis hash (raw bytes or base64-encoded string).
## Returns
- `returns` (`str`):
CAIP-2 network identifier (e.g. "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k").
## Raises
- `TypeError`: If `genesis_hash` is neither `str` nor `bytes`.
- `NetworkError`: If `genesis_hash` is not valid base64.
## Examples
```python
from x402_algorand import caip2_from_genesis_hash
print(caip2_from_genesis_hash("wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8="))
# algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k
```
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L78)
---
# normalize_network
> Normalize network identifier to CAIP-2 format.
```python
from x402_algorand import normalize_network
```
```python
def normalize_network(network: str) -> str
```
Normalize network identifier to CAIP-2 format.
## Parameters
- `network` (`str`, required):
Network identifier (V1 name, legacy long CAIP-2, or short CAIP-2).
## Returns
- `returns` (`str`):
CAIP-2 network identifier.
## Raises
- `NetworkError`: If network is not supported or invalid format (subclass of `ValueError`).
## Examples
```python
from x402_algorand import normalize_network
print(normalize_network("algorand-testnet"))
# algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe
print(normalize_network("algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=")) # legacy id
# algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k
```
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L153)
---
# register_network
> Register a custom Algorand network (e.g.
```python
from x402_algorand import register_network
```
```python
def register_network(
genesis_hash: str | bytes,
genesis_id: str = '',
algod_url: str | None = None,
indexer_url: str | None = None,
) -> str
```
Register a custom Algorand network (e.g. LocalNet or private network).
Computes the CAIP-2 identifier, updates NETWORK_CONFIGS, GENESIS_HASH_TO_NETWORK,
and SUPPORTED_NETWORKS.
## Parameters
- `genesis_hash` (`str | bytes`, required):
32-byte genesis hash (base64 string or raw bytes).
- `genesis_id` (`str`, default `''`):
Genesis ID string (e.g. "dockernet-v1").
- `algod_url` (`str | None`, default `None`):
Algod endpoint URL (defaults to "http://localhost:4001").
- `indexer_url` (`str | None`, default `None`):
Indexer endpoint URL (defaults to "http://localhost:8980").
## Returns
- `returns` (`str`):
The registered CAIP-2 network identifier.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L109)
---
# get_genesis_hash
> Get the full base64 genesis hash for a network.
```python
from x402_algorand import get_genesis_hash
```
```python
def get_genesis_hash(network: str) -> str
```
Get the full base64 genesis hash for a network.
## Parameters
- `network` (`str`, required):
Network identifier (legacy long ID, short CAIP-2 ID, or V1 name).
## Returns
- `returns` (`str`):
Base64-encoded 32-byte genesis hash.
## Raises
- `NetworkError`: If network is unknown or unregistered (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L240)
---
# network_from_genesis_hash
> Determine CAIP-2 network from genesis hash.
```python
from x402_algorand import network_from_genesis_hash
```
```python
def network_from_genesis_hash(genesis_hash: str) -> str | None
```
Determine CAIP-2 network from genesis hash.
## Parameters
- `genesis_hash` (`str`, required):
Base64-encoded genesis hash.
## Returns
- `returns` (`str | None`):
CAIP-2 network identifier or None if unknown.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L267)
---
# is_valid_network
> Check if a network identifier is valid.
```python
from x402_algorand import is_valid_network
```
```python
def is_valid_network(network: str) -> bool
```
Check if a network identifier is valid.
## Parameters
- `network` (`str`, required):
Network identifier.
## Returns
- `returns` (`bool`):
True if network is supported.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L186)
---
# get_network_config
> Get configuration for a network.
```python
from x402_algorand import get_network_config
```
```python
def get_network_config(network: str) -> dict[str, Any]
```
Get configuration for a network.
## Parameters
- `network` (`str`, required):
Network identifier (V1 name or CAIP-2).
## Returns
- `returns` (`dict[str, Any]`):
NetworkConfig dictionary.
## Raises
- `NetworkError`: If network is not supported (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L202)
---
# get_usdc_asa_id
> Get the USDC ASA ID for a network.
```python
from x402_algorand import get_usdc_asa_id
```
```python
def get_usdc_asa_id(network: str) -> int
```
Get the USDC ASA ID for a network.
## Parameters
- `network` (`str`, required):
Network identifier.
## Returns
- `returns` (`int`):
USDC ASA ID.
## Raises
- `NetworkError`: If network is not supported (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L221)
---
# decode_transaction_bytes
> Decode transaction bytes to DecodedTransactionInfo.
```python
from x402_algorand import decode_transaction_bytes
```
```python
def decode_transaction_bytes(txn_bytes: bytes) -> DecodedTransactionInfo
```
Decode transaction bytes to DecodedTransactionInfo.
Handles both signed and unsigned transactions.
## Parameters
- `txn_bytes` (`bytes`, required):
Msgpack-encoded transaction bytes.
## Returns
- `returns` (`DecodedTransactionInfo`):
DecodedTransactionInfo with extracted data.
## Raises
- `TransactionDecodeError`: If decoding fails (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L321)
---
# decode_base64_transaction
> Decode a base64-encoded transaction.
```python
from x402_algorand import decode_base64_transaction
```
```python
def decode_base64_transaction(b64_txn: str) -> DecodedTransactionInfo
```
Decode a base64-encoded transaction.
## Parameters
- `b64_txn` (`str`, required):
Base64-encoded msgpack transaction.
## Returns
- `returns` (`DecodedTransactionInfo`):
DecodedTransactionInfo with extracted data.
## Raises
- `TransactionDecodeError`: If decoding fails (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L421)
---
# decode_payment_group
> Decode a payment group from base64 strings.
```python
from x402_algorand import decode_payment_group
```
```python
def decode_payment_group(
payment_group: list[str],
payment_index: int,
) -> TransactionGroupInfo
```
Decode a payment group from base64 strings.
## Parameters
- `payment_group` (`list[str]`, required):
List of base64-encoded transactions.
- `payment_index` (`int`, required):
Index of the payment transaction.
## Returns
- `returns` (`TransactionGroupInfo`):
TransactionGroupInfo with all decoded transactions.
## Raises
- `TransactionDecodeError`: If decoding fails (subclass of `ValueError`).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L441)
---
# encode_transaction_group
> Encode a list of transaction bytes to base64 strings.
```python
from x402_algorand import encode_transaction_group
```
```python
def encode_transaction_group(txn_bytes_list: list[bytes]) -> list[str]
```
Encode a list of transaction bytes to base64 strings.
## Parameters
- `txn_bytes_list` (`list[bytes]`, required):
List of msgpack-encoded transaction bytes.
## Returns
- `returns` (`list[str]`):
List of base64-encoded strings.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L711)
---
# validate_no_security_risks
> Validate that a transaction has no security risks (per-transaction checks).
```python
from x402_algorand import validate_no_security_risks
```
```python
def validate_no_security_risks(txn_info: DecodedTransactionInfo) -> str | None
```
Validate that a transaction has no security risks (per-transaction checks).
Checks for:
- Close-to operations (draining accounts)
- Blocked transaction types (keyreg)
Note: Rekey operations are validated at group level by validate_rekey_operations()
which allows balanced sandwich patterns (rekey A->B then rekey back to A).
## Parameters
- `txn_info` (`DecodedTransactionInfo`, required):
Decoded transaction info.
## Returns
- `returns` (`str | None`):
Error code string if security risk found, None otherwise.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L503)
---
# validate_fee_payer_transaction
> Validate a fee payer transaction.
```python
from x402_algorand import validate_fee_payer_transaction
```
```python
def validate_fee_payer_transaction(
txn_info: DecodedTransactionInfo,
expected_fee_payer: str,
) -> str | None
```
Validate a fee payer transaction.
Per spec, fee payer transaction must be:
- Type "pay" (payment)
- Sender is the fee payer
- Receiver is the fee payer (self-payment)
- Amount is 0 (no value transfer)
- No close-to field
- No rekey field
- Fee is reasonable (covers pooled fees)
## Parameters
- `txn_info` (`DecodedTransactionInfo`, required):
Decoded transaction info.
- `expected_fee_payer` (`str`, required):
Expected fee payer address.
## Returns
- `returns` (`str | None`):
Error code string if invalid, None otherwise.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L649)
---
# is_valid_address
> Validate an Algorand address format.
```python
from x402_algorand import is_valid_address
```
```python
def is_valid_address(address: str) -> bool
```
Validate an Algorand address format.
## Parameters
- `address` (`str`, required):
String to validate.
## Returns
- `returns` (`bool`):
True if valid Algorand address format.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L51)
---
# parse_money_to_decimal
> Parse money value to decimal.
```python
from x402_algorand import parse_money_to_decimal
```
```python
def parse_money_to_decimal(money: str | float | int) -> float
```
Parse money value to decimal.
## Parameters
- `money` (`str | float | int`, required):
Money value (string, float, or int).
## Returns
- `returns` (`float`):
Decimal amount.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L279)
---
# to_atomic_amount
> Convert decimal amount to atomic units.
```python
from x402_algorand import to_atomic_amount
```
```python
def to_atomic_amount(amount: float, decimals: int = DEFAULT_DECIMALS) -> int
```
Convert decimal amount to atomic units.
## Parameters
- `amount` (`float`, required):
Decimal amount.
- `decimals` (`int`, default `DEFAULT_DECIMALS`):
Number of decimal places.
## Returns
- `returns` (`int`):
Amount in atomic units (smallest unit).
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L295)
---
# from_atomic_amount
> Convert atomic units to decimal amount.
```python
from x402_algorand import from_atomic_amount
```
```python
def from_atomic_amount(amount: int, decimals: int = DEFAULT_DECIMALS) -> float
```
Convert atomic units to decimal amount.
## Parameters
- `amount` (`int`, required):
Amount in atomic units.
- `decimals` (`int`, default `DEFAULT_DECIMALS`):
Number of decimal places.
## Returns
- `returns` (`float`):
Decimal amount.
Source: [x402_algorand/utils.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/utils.py#L308)
---
# X402AlgorandError
> Base class for all exceptions raised by x402-algorand.
```python
from x402_algorand import X402AlgorandError
```
```python
class X402AlgorandError(Exception)
```
Base class for all exceptions raised by x402-algorand.
## Examples
```python
from x402_algorand import X402AlgorandError, normalize_network
try:
normalize_network("ethereum")
except X402AlgorandError as e: # any error raised by x402-algorand
print(type(e).__name__, e) # NetworkError Unsupported network: ethereum
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L27)
---
# NetworkError
> A network identifier is malformed, unsupported, or not registered.
```python
from x402_algorand import NetworkError
```
```python
class NetworkError(X402AlgorandError, ValueError)
```
A network identifier is malformed, unsupported, or not registered.
## Examples
```python
from x402_algorand import NetworkError, get_genesis_hash
try:
get_genesis_hash("algorand:not-a-registered-network")
except NetworkError as e: # also a ValueError
print(e)
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L31)
---
# NetworkMismatchError
> An algod node is connected to a different network than the one requested.
```python
from x402_algorand import NetworkMismatchError
```
```python
class NetworkMismatchError(NetworkError)
```
An algod node is connected to a different network than the one requested.
## Examples
```python
import os
from algosdk.v2client.algod import AlgodClient
from x402_algorand import ALGORAND_MAINNET_CAIP2, NetworkMismatchError, ServerAvmSigner
local = AlgodClient("a" * 64, "http://localhost:4001") # a LocalNet node
signer = ServerAvmSigner.from_mnemonic(os.environ["FACILITATOR_MNEMONIC"], local)
try:
signer.algod_for(ALGORAND_MAINNET_CAIP2) # the node is not on MainNet
except NetworkMismatchError as e:
print(e) # algod is on algorand:... but the request is for algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L35)
---
# TransactionDecodeError
> Bytes or base64 text could not be decoded as an Algorand transaction.
```python
from x402_algorand import TransactionDecodeError
```
```python
class TransactionDecodeError(X402AlgorandError, ValueError)
```
Bytes or base64 text could not be decoded as an Algorand transaction.
## Examples
```python
from x402_algorand import TransactionDecodeError, decode_base64_transaction
try:
decode_base64_transaction("not base64!")
except TransactionDecodeError as e: # also a ValueError
print(e)
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L39)
---
# SigningError
> A signer could not sign: bad key material or an address it does not manage.
```python
from x402_algorand import SigningError
```
```python
class SigningError(X402AlgorandError, ValueError)
```
A signer could not sign: bad key material or an address it does not manage.
## Examples
```python
from x402_algorand import PayerAvmSigner, SigningError
try:
PayerAvmSigner.from_mnemonic("not a valid mnemonic")
except SigningError as e: # also a ValueError; the message never contains key material
print(e) # invalid 25-word Algorand mnemonic
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L43)
---
# SimulationError
> An algod `simulate` call reported that the transaction group would fail.
```python
from x402_algorand import SimulationError
```
```python
class SimulationError(X402AlgorandError, RuntimeError)
```
An algod `simulate` call reported that the transaction group would fail.
## Examples
```python
from x402_algorand import SimulationError
# Raised by ServerAvmSigner.simulate_group() when algod's simulate reports a failure.
# The facilitator catches it and returns invalid_reason="transaction_simulation_failed".
try:
signer.simulate_group(group_bytes, network)
except SimulationError as e: # also a RuntimeError
print("would fail on chain:", e)
```
Source: [x402_algorand/errors.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/errors.py#L47)
---
# Constants
> Network ids, genesis hashes, USDC asset ids and protocol limits exported by x402_algorand.
```python
from x402_algorand import ALGORAND_MAINNET_CAIP2, ALGORAND_TESTNET_CAIP2, MAINNET_GENESIS_HASH, TESTNET_GENESIS_HASH
```
## `ALGORAND_MAINNET_CAIP2`
```python
ALGORAND_MAINNET_CAIP2 = 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L60)
## `ALGORAND_TESTNET_CAIP2`
```python
ALGORAND_TESTNET_CAIP2 = 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe'
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L61)
## `MAINNET_GENESIS_HASH`
```python
MAINNET_GENESIS_HASH = 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8='
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L56)
## `TESTNET_GENESIS_HASH`
```python
TESTNET_GENESIS_HASH = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L57)
## `USDC_MAINNET_ASA_ID`
```python
USDC_MAINNET_ASA_ID = 31566704
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L52)
## `USDC_TESTNET_ASA_ID`
```python
USDC_TESTNET_ASA_ID = 10458941
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L53)
## `SCHEME_EXACT`
```python
SCHEME_EXACT = 'exact'
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L10)
## `DEFAULT_DECIMALS`
```python
DEFAULT_DECIMALS = 6
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L13)
## `MIN_TXN_FEE`
```python
MIN_TXN_FEE = 1000
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L16)
## `MAX_GROUP_SIZE`
```python
MAX_GROUP_SIZE = 16
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L19)
## `SUPPORTED_NETWORKS`
```python
SUPPORTED_NETWORKS = [ALGORAND_MAINNET_CAIP2, ALGORAND_TESTNET_CAIP2]
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L84)
## `V1_NETWORKS`
```python
V1_NETWORKS = ['algorand-mainnet', 'algorand-testnet']
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L78)
## `V1_TO_V2_NETWORK_MAP`
```python
V1_TO_V2_NETWORK_MAP: dict[str, str] = {'algorand-mainnet': ALGORAND_MAINNET_CAIP2, 'algorand-testnet': ALGORAND_TESTNET_CAIP2, 'algorand': ALGORAND_MAINNET_CAIP2}
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L64)
## `DEFAULT_ASSETS`
```python
DEFAULT_ASSETS: dict[str, list[dict[str, Any]]] = ... # see source
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L188)
## `NETWORK_CONFIGS`
```python
NETWORK_CONFIGS: dict[str, NetworkConfig] = ... # see source
```
Source: [x402_algorand/constants.py](https://github.com/x402-avm/x402-algorand/blob/main/x402_algorand/constants.py#L153)
The payload error codes (`ERR_*` in `x402_algorand.constants`) are listed on [Error codes](https://x402-avm.github.io/reference/errors).
---
# Core classes
> x402Client, x402ResourceServer and x402Facilitator from the official x402 Python SDK, as used with x402-algorand.
These classes come from the official [`x402`](https://github.com/x402-foundation/x402) package (`from x402 import ...`), version 2.28 or later. This page summarizes the members used with `x402-algorand`; signatures are taken from `x402` 2.28.0. The upstream project is the authoritative reference.
Each class has a synchronous variant for WSGI and other sync code: `x402ClientSync`, `x402ResourceServerSync`, `x402FacilitatorSync`.
## x402Client
Selects a payment requirement from a `402` challenge, enforces spend controls and policies, and asks the registered scheme to create the payment.
```python
from x402 import x402Client
```
| Member | Signature | Description |
|---|---|---|
| constructor | `x402Client(payment_requirements_selector=None)` | Optional function that picks one requirement from the filtered list. |
| `from_config` | `x402Client.from_config(config: x402ClientConfig)` | Build from `x402ClientConfig(schemes, policies=None, spend_controls=None, payment_requirements_selector=None)`. |
| `register` | `register(network, client)` | Register a scheme for a network or pattern such as `"algorand:*"`. `register_exact_avm_client` calls this. |
| `register_v1` | `register_v1(network, client)` | Register a scheme for an x402 v1 network name. |
| `register_policy` | `register_policy(policy)` | Add a filter `(x402_version, requirements) -> requirements`. If every requirement is filtered out, payment creation raises `NoMatchingRequirementsError`. |
| `set_spend_controls` | `set_spend_controls(controls)` | Replace spend controls; `False` disables them. |
| `create_payment_payload` | `async create_payment_payload(payment_required, resource=None, extensions=None)` | Select a requirement and return a signed `PaymentPayload`. |
Spend controls default to the assets the registered schemes recognize (ALGO and USDC for Algorand) with a cap of `DEFAULT_MAX_AMOUNT_PER_PAYMENT = "$1"`. See [Guardrails](https://x402-avm.github.io/build/pay-from-python#spend-controls).
## x402ResourceServer
Turns route configuration into payment requirements and coordinates verification and settlement with facilitators.
```python
from x402 import x402ResourceServer
```
| Member | Signature | Description |
|---|---|---|
| constructor | `x402ResourceServer(facilitator_clients=None)` | One facilitator client or a list. An in-process `x402Facilitator` can be passed directly. |
| `register` | `register(network, server)` | Register a server scheme. `register_exact_avm_server` calls this with `"algorand:*"`. |
| `initialize` | `initialize()` | Fetch what the facilitators support. |
| `build_payment_requirements` | `build_payment_requirements(config, extensions=None)` | Build the concrete, scheme-enhanced requirements for a route. |
| `find_matching_requirements` | `find_matching_requirements(available, payload)` | Find which requirement a client's payload answers. |
| `verify_payment` | `verify_payment(payload, requirements, ...)` | Verify through the facilitator. |
| `settle_payment` | `settle_payment(payload, requirements, ...)` | Settle through the facilitator. |
## x402Facilitator
Verifies and settles payments with the registered scheme implementations.
```python
from x402 import x402Facilitator
```
| Member | Signature | Description |
|---|---|---|
| constructor | `x402Facilitator()` | |
| `register` | `register(networks, facilitator)` | Register a scheme for a list of networks. `register_exact_avm_facilitator` calls this. |
| `get_supported` | `get_supported()` | Supported schemes and networks, including scheme `extra` such as the Algorand fee payer address. |
| `verify` | `verify(payload, requirements, payload_bytes=None, requirements_bytes=None)` | Returns a `VerifyResponse`. |
| `settle` | `settle(payload, requirements, payload_bytes=None, requirements_bytes=None)` | Returns a `SettleResponse`. |
## Related
- [Schemas](https://x402-avm.github.io/reference/x402/schemas)
- [HTTP integration](https://x402-avm.github.io/reference/x402/http)
- [x402-algorand registration helpers](https://x402-avm.github.io/reference/python/x402-algorand/register-exact-avm-client)
---
# Schemas
> PaymentRequired, PaymentRequirements, PaymentPayload, VerifyResponse and SettleResponse from the official x402 Python SDK.
Pydantic models from `x402.schemas` (official `x402` package, fields as of 2.28.0). In JSON they use the camelCase alias shown; in Python, the snake_case field name.
## PaymentRequired
The object in the `PAYMENT-REQUIRED` header of a `402` response.
| Field (alias) | Type | Description |
|---|---|---|
| `x402_version` (`x402Version`) | `int` | Protocol version, 2. |
| `error` | `str \| None` | Optional reason. |
| `resource` | `ResourceInfo \| None` | The protected resource: `url`, and optionally `description`, `mime_type` (`mimeType`), `service_name`, `tags`, `icon_url`. |
| `accepts` | `list[PaymentRequirements]` | The offers the server accepts. |
| `extensions` | `dict \| None` | Protocol extensions. |
## PaymentRequirements
One offer.
| Field (alias) | Type | Description |
|---|---|---|
| `scheme` | `str` | `"exact"`. |
| `network` | `str` | CAIP-2 id, validated against `^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$`. |
| `asset` | `str` | `"0"` for ALGO, otherwise the ASA id. |
| `amount` | `str` | Base units. |
| `pay_to` (`payTo`) | `str` | Recipient address. |
| `max_timeout_seconds` (`maxTimeoutSeconds`) | `int` | How long the offer is valid. |
| `extra` | `dict` | Scheme data; for Algorand `decimals`, `feePayer`, `genesisHash`, `genesisId`. |
## PaymentPayload
The object in the `PAYMENT-SIGNATURE` header.
| Field (alias) | Type | Description |
|---|---|---|
| `x402_version` (`x402Version`) | `int` | 2. |
| `payload` | `dict` | Scheme payload; for Algorand `paymentGroup` (base64 msgpack transactions) and `paymentIndex`. |
| `accepted` | `PaymentRequirements` | The offer being paid. |
| `resource` | `ResourceInfo \| None` | |
| `extensions` | `dict \| None` | |
## VerifyResponse
Returned by `verify`.
| Field (alias) | Type | Description |
|---|---|---|
| `is_valid` (`isValid`) | `bool` | Whether the payment passed every check. |
| `invalid_reason` (`invalidReason`) | `str \| None` | An [error code](https://x402-avm.github.io/reference/errors). |
| `invalid_message` (`invalidMessage`) | `str \| None` | Details, such as algod's simulation message. |
| `payer` | `str \| None` | Buyer address. |
| `extensions`, `extension_responses`, `extra` | `dict \| None` | Extension data. |
## SettleResponse
Returned by `settle`, and carried in the `PAYMENT-RESPONSE` header.
| Field (alias) | Type | Description |
|---|---|---|
| `success` | `bool` | Whether the group was submitted and confirmed. |
| `transaction` | `str` | Transaction id. |
| `network` | `str` | CAIP-2 id. |
| `payer` | `str \| None` | Buyer address. |
| `error_reason` (`errorReason`) | `str \| None` | For example `transaction_failed`. |
| `error_message` (`errorMessage`) | `str \| None` | Node error message. |
| `amount` | `str \| None` | |
| `extensions`, `extension_responses`, `extra` | `dict \| None` | Extension data. |
| `after_settle_aborted` (`afterSettleAborted`) | `bool` | |
---
# HTTP integration
> Header encoding, HTTP clients and server middleware from the official x402 Python SDK.
From the official `x402` package (signatures as of 2.28.0). The upstream project is the authoritative reference.
## Header encoding
From `x402.http`:
| Function | Signature | Returns |
|---|---|---|
| `decode_payment_required_header` | `(header_value: str)` | `PaymentRequired` |
| `encode_payment_required_header` | `(payment_required)` | `str` |
| `decode_payment_signature_header` | `(header_value: str)` | `PaymentPayload` |
| `encode_payment_signature_header` | `(payload)` | `str` |
| `decode_payment_response_header` | `(header_value: str)` | `SettleResponse` |
| `encode_payment_response_header` | `(settle_response)` | `str` |
Each header is base64-encoded JSON of the corresponding [schema](https://x402-avm.github.io/reference/x402/schemas).
## Clients
| Name | Module | Description |
|---|---|---|
| `wrapHttpxWithPayment(x402_client, **httpx_kwargs)` | `x402.http.clients.httpx` | Returns an `httpx.AsyncClient` whose transport pays `402` responses and retries. |
| `x402HttpxClient(x402_client, **kwargs)` | `x402.http.clients.httpx` | `httpx.AsyncClient` subclass with the payment transport; used by `paid_mcp_session`. |
| `x402AsyncTransport(client, transport=None)` | `x402.http.clients.httpx` | The transport itself; can wrap another transport such as `httpx.ASGITransport`. |
| `wrapRequestsWithPayment(session, client, **adapter_kwargs)` | `x402.http.clients` | Mounts a payment adapter on a `requests.Session`; takes an `x402ClientSync`. |
Example: [HTTPX and requests](https://x402-avm.github.io/build/pay-from-python#pay-http-apis).
## Server middleware
| Name | Module | Signature |
|---|---|---|
| `payment_middleware` (FastAPI) | `x402.http.middleware.fastapi` | `(routes, server, paywall_config=None, paywall_provider=None, sync_facilitator_on_start=True)`; register with `app.middleware("http")(...)`. |
| `payment_middleware` (Flask) | `x402.http.middleware.flask` | `(app, routes, server, paywall_config=None, paywall_provider=None, sync_facilitator_on_start=True)`; `server` is an `x402ResourceServerSync`. Needs `x402[flask]`. |
| `x402HTTPResourceServer` | `x402.http` | Framework-independent route matching and payment processing; `PaymentGate` uses it. |
Examples: [FastAPI](https://x402-avm.github.io/build/paywall-http-api#fastapi), [Flask](https://x402-avm.github.io/build/paywall-http-api#flask).
### Route configuration
```python
routes = {
"GET /weather": {
"accepts": [
{
"scheme": "exact",
"price": {"amount": "10000", "asset": "0"},
"network": "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k",
"pay_to": "YOUR_ALGORAND_ADDRESS",
}
],
"description": "Weather data",
}
}
```
The route key is `" "`; `PaymentGate` uses `"POST /messages*"`. `price` can also be a callable that receives the request context, which is how `PaymentGate` prices each tool call.
---
# x402-avm-js reference
> Every export of x402-avm-js, generated from the TSDoc in src/index.ts and src/errors.ts.
`x402-avm-js` has 32 exports, all named exports of the package root ([`x402-avm-js` on npm](https://www.npmjs.com/package/x402-avm-js)). It is an ES module with one runtime dependency, `algosdk`.
```ts
import { payForRequirement, decodePaymentRequired, SpendLimitExceededError } from 'x402-avm-js';
```
## Payments
| Export | Kind | Summary |
|---|---|---|
| [`payForRequirement`](https://x402-avm.github.io/reference/js/pay-for-requirement) | function | Helper to execute full payment flow for an x402 payment challenge. |
| [`decodePaymentRequired`](https://x402-avm.github.io/reference/js/decode-payment-required) | function | Decode a base64-encoded PAYMENT-REQUIRED header value into a PaymentRequired object. |
| [`parsePaymentRequired`](https://x402-avm.github.io/reference/js/parse-payment-required) | function | Validate untrusted input (for example a decoded PAYMENT-REQUIRED header) and return it as a {@link PaymentRequired}. |
| [`selectRequirement`](https://x402-avm.github.io/reference/js/select-requirement) | function | Select the first acceptable payment requirement matching the payer's network. |
| [`buildExactAvmGroup`](https://x402-avm.github.io/reference/js/build-exact-avm-group) | function | Build atomic transaction group for Exact AVM payment scheme. |
| [`encodePaymentHeader`](https://x402-avm.github.io/reference/js/encode-payment-header) | function | Encode a payment payload into a base64-encoded PAYMENT-SIGNATURE header. |
## Spend controls
| Export | Kind | Summary |
|---|---|---|
| [`checkSpendControls`](https://x402-avm.github.io/reference/js/check-spend-controls) | function | Check a requirement against spend controls. |
| [`SpendControls`](https://x402-avm.github.io/reference/js/spend-controls) | interface | Client-side limits checked before anything is signed. |
| [`AmountLimit`](https://x402-avm.github.io/reference/js/amount-limit) | type | A limit in base units: bigint, a non-negative safe integer, a decimal string, or `Infinity` for no cap. |
| [`DEFAULT_MAX_AMOUNT`](https://x402-avm.github.io/reference/js/default-max-amount) | constant | Default per-payment cap in base units (1 ALGO, or 1 USDC) applied when `maxAmount` is not set. |
## Identity
| Export | Kind | Summary |
|---|---|---|
| [`buildIdentityTxn`](https://x402-avm.github.io/reference/js/build-identity-txn) | function | Build an identity transaction for wallet ownership proof. |
| [`encodeIdentityHeader`](https://x402-avm.github.io/reference/js/encode-identity-header) | function | Encode signed identity transaction bytes to base64 string for the X-Identity-Txn header. |
## Networks
| Export | Kind | Summary |
|---|---|---|
| [`resolveNetwork`](https://x402-avm.github.io/reference/js/resolve-network) | function | Resolve a network name, alias, or legacy ID into a canonical CAIP-2 identifier. |
| [`networkFromGenesisHash`](https://x402-avm.github.io/reference/js/network-from-genesis-hash) | function | Derive the canonical CAIP-2 identifier from a network's genesis hash per the Algorand profile. |
| [`networkFromAlgod`](https://x402-avm.github.io/reference/js/network-from-algod) | function | Query an algod client for its current suggested transaction parameters and return its CAIP-2 identifier. |
| [`algodClient`](https://x402-avm.github.io/reference/js/algod-client) | function | Create an Algodv2 client for a named network or custom endpoint. |
| [`MAINNET`](https://x402-avm.github.io/reference/js/mainnet) | constant | MainNet network constants and public AlgoNode endpoints. |
| [`TESTNET`](https://x402-avm.github.io/reference/js/testnet) | constant | TestNet network constants and public AlgoNode endpoints. |
| [`LOCALNET_ENDPOINTS`](https://x402-avm.github.io/reference/js/localnet-endpoints) | constant | LocalNet endpoints and token. |
## Types
| Export | Kind | Summary |
|---|---|---|
| [`PaymentRequired`](https://x402-avm.github.io/reference/js/payment-required) | interface | Decoded payload of the HTTP 402 PAYMENT-REQUIRED header. |
| [`PaymentRequirements`](https://x402-avm.github.io/reference/js/payment-requirements) | interface | Payment requirements specified by an x402 server. |
| [`ResourceInfo`](https://x402-avm.github.io/reference/js/resource-info) | interface | Metadata about the protected resource in an x402 payment challenge. |
| [`BuildGroupResult`](https://x402-avm.github.io/reference/js/build-group-result) | interface | Result of building an atomic transaction group for the exact AVM payment scheme. |
| [`AlgorandNetwork`](https://x402-avm.github.io/reference/js/algorand-network) | interface | Network configuration and endpoints for an Algorand network. |
## Errors
| Export | Kind | Summary |
|---|---|---|
| [`X402AvmError`](https://x402-avm.github.io/reference/js/x402-avm-error) | class | Typed errors thrown by x402-avm-js. |
| [`SpendLimitExceededError`](https://x402-avm.github.io/reference/js/spend-limit-exceeded-error) | class | The requested amount is above the client's spend cap. |
| [`PaymentNotAllowedError`](https://x402-avm.github.io/reference/js/payment-not-allowed-error) | class | The requirement's asset, network or recipient is not on the caller's allow list. |
| [`InvalidPaymentRequiredError`](https://x402-avm.github.io/reference/js/invalid-payment-required-error) | class | The PAYMENT-REQUIRED header or object is malformed, or a requirement in it is not a valid exact-AVM offer. |
| [`NoSupportedRequirementError`](https://x402-avm.github.io/reference/js/no-supported-requirement-error) | class | The challenge offers nothing this client can pay (`accepts` is empty). |
| [`NetworkMismatchError`](https://x402-avm.github.io/reference/js/network-mismatch-error) | class | None of the offered requirements is for the network the wallet is on, or a requirement's genesis does not match. |
| [`UnknownNetworkError`](https://x402-avm.github.io/reference/js/unknown-network-error) | class | A network name or CAIP-2 identifier is not recognised, or has no default endpoint. |
| [`InvalidOptionsError`](https://x402-avm.github.io/reference/js/invalid-options-error) | class | A spend-control option is malformed (for example a negative or non-integer maxAmount). |
---
# payForRequirement
> Helper to execute full payment flow for an x402 payment challenge.
```ts
import { payForRequirement } from 'x402-avm-js';
```
```ts
export async function payForRequirement(
paymentRequired: PaymentRequired,
payerAddress: string,
algod: algosdk.Algodv2,
signTxns: (txns: Uint8Array[], indexes: number[]) => Promise<(Uint8Array | null)[]>,
controls: SpendControls = {}
): Promise;
```
Helper to execute full payment flow for an x402 payment challenge.
Automates the complete client payment workflow:
1. Fetches current suggested transaction parameters from the algod client.
2. Matches the requirement against the active algod network using `selectRequirement`.
3. Builds the exact AVM atomic transaction group via `buildExactAvmGroup`.
4. Calls `signTxns` for the transaction indexes requiring payer signature.
5. Assembles signed and unsigned transactions and encodes the `PAYMENT-SIGNATURE` header.
## Parameters
- `paymentRequired` (`PaymentRequired`, required):
The PaymentRequired challenge from HTTP 402 response.
- `payerAddress` (`string`, required):
Algorand address of the paying account.
- `algod` (`algosdk.Algodv2`, required):
Algodv2 client instance for the active network.
- `signTxns` (`true`): Promise<(Uint8Array | null)[]>, controls: SpendControls = {}" required>
Callback function that signs unsigned transaction byte arrays for specified indexes.
## Returns
- `returns` (`true`): ">
Promise resolving to the base64-encoded `PAYMENT-SIGNATURE` header string.
## Throws
- `NoSupportedRequirementError`: If `accepts` is empty.
- `NetworkMismatchError`: If no offer is for the algod's network.
- `SpendLimitExceededError`: If the amount is above the cap.
- `PaymentNotAllowedError`: If the asset, network or recipient is not allowed. Errors from algod or from `signTxns` propagate unchanged.
## Example
```ts
const paymentSignature = await payForRequirement(
challenge,
activeAddress,
algod,
async (txns, indexes) => {
return await signTransactions(txns, indexes);
}
);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L732)
---
# decodePaymentRequired
> Decode a base64-encoded PAYMENT-REQUIRED header value into a PaymentRequired object.
```ts
import { decodePaymentRequired } from 'x402-avm-js';
```
```ts
export function decodePaymentRequired(headerB64: string): PaymentRequired;
```
Decode a base64-encoded PAYMENT-REQUIRED header value into a PaymentRequired object.
Parses the base64-encoded JSON payload received in an HTTP 402 response into a typed
PaymentRequired structure without relying on Node.js binary APIs.
## Parameters
- `headerB64` (`string`, required):
Base64-encoded string from the PAYMENT-REQUIRED response header.
## Returns
- `returns` (`PaymentRequired`):
Decoded PaymentRequired object.
## Throws
- `InvalidPaymentRequiredError`: If decoding or JSON parsing fails, or the decoded shape is invalid.
## Example
```ts
const header = response.headers.get('PAYMENT-REQUIRED');
const challenge = decodePaymentRequired(header);
console.log(challenge.x402Version); // 2
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L389)
---
# parsePaymentRequired
> Validate untrusted input (for example a decoded PAYMENT-REQUIRED header) and return it as a {@link PaymentRequired}.
```ts
import { parsePaymentRequired } from 'x402-avm-js';
```
```ts
export function parsePaymentRequired(value: unknown): PaymentRequired;
```
Validate untrusted input (for example a decoded PAYMENT-REQUIRED header) and return it as a
{@link PaymentRequired}. Every `accepts` entry must have string `scheme`, `network`, `asset`,
`amount` (a non-negative integer), `payTo`, and a numeric `maxTimeoutSeconds`.
## Parameters
- `value` (`unknown`, required):
Parsed JSON of unknown shape.
## Returns
- `returns` (`PaymentRequired`):
## Throws
- `InvalidPaymentRequiredError`: If the shape is wrong.
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L411)
---
# selectRequirement
> Select the first acceptable payment requirement matching the payer's network.
```ts
import { selectRequirement } from 'x402-avm-js';
```
```ts
export function selectRequirement(paymentRequired: Pick, network: string): PaymentRequirements;
```
Select the first acceptable payment requirement matching the payer's network.
Searches the `accepts` array of a PaymentRequired challenge for an offer using the "exact"
payment scheme matching the specified network (resolved via `resolveNetwork`).
## Parameters
- `paymentRequired` (`true`): " required>
Parsed PaymentRequired object (anything with an `accepts` array).
- `network` (`string`, required):
Desired network name, alias, or CAIP-2 identifier.
## Returns
- `returns` (`PaymentRequirements`):
The matching PaymentRequirements entry.
## Throws
- `NoSupportedRequirementError`: If `accepts` is empty.
- `NetworkMismatchError`: If no requirement matches the requested network.
## Example
```ts
const req = selectRequirement(paymentRequired, 'mainnet');
console.log(`Pay ${req.amount} microALGO to ${req.payTo}`);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L336)
---
# buildExactAvmGroup
> Build atomic transaction group for Exact AVM payment scheme.
```ts
import { buildExactAvmGroup } from 'x402-avm-js';
```
```ts
export function buildExactAvmGroup(
req: PaymentRequirements,
payerAddress: string,
suggestedParams: algosdk.SuggestedParams,
controls: SpendControls = {}
): BuildGroupResult;
```
Build atomic transaction group for Exact AVM payment scheme.
If `extra.feePayer` is present in the requirement:
Creates a two-transaction atomic group:
1. Transaction [0]: Fee payer self-payment of 0 ALGO with pooled flat fee equal to `2 * minFee` (2,000 microALGO).
2. Transaction [1]: Payer transfer of `amount` with flat fee of 0.
Sets `paymentIndex = 1` and `signIndexes = [1]`.
If `extra.feePayer` is absent:
Creates a single transaction where the payer pays the standard fee:
Sets `paymentIndex = 0` and `signIndexes = [0]`.
Handles both native ALGO (asset ID "0") and Algorand Standard Assets (ASAs).
## Parameters
- `req` (`PaymentRequirements`, required):
Accepted payment requirement from the server.
- `payerAddress` (`string`, required):
Algorand address of the buyer/payer.
- `suggestedParams` (`algosdk.SuggestedParams`, required):
Current suggested transaction parameters from algod.
- `controls` (`SpendControls = {}`, required):
Spend controls checked before anything is built. Without `maxAmount`, amounts above {@link DEFAULT_MAX_AMOUNT} (1,000,000 base units) are refused.
## Returns
- `returns` (`BuildGroupResult`):
Object containing the transaction group, payment transaction index, and indexes requiring signature.
## Throws
- `SpendLimitExceededError`: If the amount is above the cap.
- `PaymentNotAllowedError`: If the asset, network or recipient is not allowed.
- `NetworkMismatchError`: If `extra.genesisHash` or `extra.genesisId` disagrees with `suggestedParams`.
- `InvalidPaymentRequiredError`: If the amount, asset, payTo or feePayer is malformed.
## Example
```ts
const sp = await algod.getTransactionParams().do();
const { txns, paymentIndex, signIndexes } = buildExactAvmGroup(
requirement,
activeAddress,
sp
);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L547)
---
# encodePaymentHeader
> Encode a payment payload into a base64-encoded PAYMENT-SIGNATURE header.
```ts
import { encodePaymentHeader } from 'x402-avm-js';
```
```ts
export function encodePaymentHeader(
paymentRequired: PaymentRequired,
accepted: PaymentRequirements,
groupB64: string[],
paymentIndex: number
): string;
```
Encode a payment payload into a base64-encoded PAYMENT-SIGNATURE header.
Constructs the standard x402 v2 payment response object containing `accepted` requirements,
the base64-encoded transaction group (signed or unsigned), the `paymentIndex`, and any
resource or extensions metadata copied from the original challenge.
## Parameters
- `paymentRequired` (`PaymentRequired`, required):
The original PaymentRequired challenge object.
- `accepted` (`PaymentRequirements`, required):
The selected and fulfilled PaymentRequirements item.
- `groupB64` (`string[]`, required):
Array of base64-encoded transactions (signed bytes or unsigned fallback).
- `paymentIndex` (`number`, required):
0-based index of the payment transaction within the group.
## Returns
- `returns` (`string`):
Base64-encoded string ready to pass in the `PAYMENT-SIGNATURE` HTTP header.
## Example
```ts
const header = encodePaymentHeader(challenge, accepted, groupB64, paymentIndex);
const response = await fetch(url, {
headers: { 'PAYMENT-SIGNATURE': header }
});
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L672)
---
# checkSpendControls
> Check a requirement against spend controls.
```ts
import { checkSpendControls } from 'x402-avm-js';
```
```ts
export function checkSpendControls(req: PaymentRequirements, controls: SpendControls = {}): void;
```
Check a requirement against spend controls. Throws before anything is built or signed.
## Parameters
- `req` (`PaymentRequirements`, required):
- `controls` (`SpendControls = {}`, required):
## Returns
- `returns` (`void`):
## Throws
- `SpendLimitExceededError`: If the amount is above the cap (default {@link DEFAULT_MAX_AMOUNT}).
- `PaymentNotAllowedError`: If the asset, network or recipient is not on an allow list.
- `InvalidOptionsError`: If a control is malformed.
- `InvalidPaymentRequiredError`: If the requirement's amount or asset is not an unsigned integer.
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L491)
---
# SpendControls
> Client-side limits checked before anything is signed.
```ts
import type { SpendControls } from 'x402-avm-js';
```
```ts
export interface SpendControls {
/**
* Maximum amount per payment in base units. A single value applies to every asset; a record maps
* asset ids (`"0"` for ALGO) to limits, with `"*"` as the fallback for assets not listed. Anything
* not covered falls back to {@link DEFAULT_MAX_AMOUNT}. Pass `Infinity` to remove the cap.
*/
maxAmount?: AmountLimit | Record;
/** If set, only these asset ids may be paid. */
allowedAssets?: Array;
/** If set, only these networks (names or CAIP-2 ids) may be paid. */
allowedNetworks?: string[];
/** If set, only these recipient addresses may be paid. */
allowedPayTo?: string[];
}
```
Client-side limits checked before anything is signed.
The server chooses the amount in a 402 challenge, so a hostile or buggy server could ask for any amount.
These controls bound what the client will agree to.
## Properties
- `maxAmount` (`true`): ">
Maximum amount per payment in base units. A single value applies to every asset; a record maps
asset ids (`"0"` for ALGO) to limits, with `"*"` as the fallback for assets not listed. Anything
not covered falls back to {@link DEFAULT_MAX_AMOUNT}. Pass `Infinity` to remove the cap.
- `allowedAssets` (`true`): ">
If set, only these asset ids may be paid.
- `allowedNetworks` (`string[]`):
If set, only these networks (names or CAIP-2 ids) may be paid.
- `allowedPayTo` (`string[]`):
If set, only these recipient addresses may be paid.
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L442)
---
# AmountLimit
> A limit in base units: bigint, a non-negative safe integer, a decimal string, or `Infinity` for no cap.
```ts
import type { AmountLimit } from 'x402-avm-js';
```
```ts
export type AmountLimit = bigint | number | string;
```
A limit in base units: bigint, a non-negative safe integer, a decimal string, or `Infinity` for no cap.
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L434)
---
# DEFAULT_MAX_AMOUNT
> Default per-payment cap in base units (1 ALGO, or 1 USDC) applied when `maxAmount` is not set.
```ts
import { DEFAULT_MAX_AMOUNT } from 'x402-avm-js';
```
```ts
export const DEFAULT_MAX_AMOUNT = 1_000_000n;
```
Default per-payment cap in base units (1 ALGO, or 1 USDC) applied when `maxAmount` is not set.
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L431)
---
# buildIdentityTxn
> Build an identity transaction for wallet ownership proof.
```ts
import { buildIdentityTxn } from 'x402-avm-js';
```
```ts
export function buildIdentityTxn(
address: string,
genesisHashB64: string,
ts?: number
): algosdk.Transaction;
```
Build an identity transaction for wallet ownership proof.
Constructs an unsubmitted zero-amount payment transaction where sender and receiver
are the payer address, flat fee is 0, firstValid is 1, and lastValid is 1000.
The note field contains `x402-identity::`.
Because valid rounds are set to 1-1000 and fee is 0, this transaction cannot be executed
or replayed on chain; it serves purely as an off-chain cryptographic signature proof.
## Parameters
- `address` (`string`, required):
Algorand address proving ownership.
- `genesisHashB64` (`string`, required):
Network genesis hash as a base64-encoded string.
- `ts` (`number`):
Optional Unix timestamp in seconds (defaults to current time).
## Returns
- `returns` (`algosdk.Transaction`):
Algorand Transaction instance ready for signing.
## Example
```ts
const txn = buildIdentityTxn(activeAddress, MAINNET.genesisHash);
const signed = await signTransactions([algosdk.encodeUnsignedTransaction(txn)], [0]);
const header = encodeIdentityHeader(signed[0]!);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L783)
---
# encodeIdentityHeader
> Encode signed identity transaction bytes to base64 string for the X-Identity-Txn header.
```ts
import { encodeIdentityHeader } from 'x402-avm-js';
```
```ts
export function encodeIdentityHeader(signedBytes: Uint8Array): string;
```
Encode signed identity transaction bytes to base64 string for the X-Identity-Txn header.
Encodes the raw bytes of a signed identity transaction into a base64 string for transmission
in HTTP request headers (`X-Identity-Txn`).
## Parameters
- `signedBytes` (`Uint8Array`, required):
Signed transaction byte array.
## Returns
- `returns` (`string`):
Base64-encoded string representation.
## Example
```ts
const signedTxnBytes = account.signTransaction(identityTxn).blob;
const headerValue = encodeIdentityHeader(signedTxnBytes);
// Pass headerValue in 'X-Identity-Txn' header
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L827)
---
# resolveNetwork
> Resolve a network name, alias, or legacy ID into a canonical CAIP-2 identifier.
```ts
import { resolveNetwork } from 'x402-avm-js';
```
```ts
export function resolveNetwork(network: string): string;
```
Resolve a network name, alias, or legacy ID into a canonical CAIP-2 identifier.
Accepts aliases ("mainnet", "testnet", "algorand-mainnet", "algorand-testnet", "algorand"),
canonical CAIP-2 strings ("algorand:<32-char-reference>"), or legacy long CAIP-2 strings
("algorand:").
For LocalNet, query the daemon with `networkFromAlgod(algod)`.
## Parameters
- `network` (`string`, required):
Network name alias or CAIP-2 string.
## Returns
- `returns` (`string`):
Canonical CAIP-2 network string.
## Throws
- `UnknownNetworkError`: If the network name or CAIP-2 string is unrecognized.
## Example
```ts
const caip2 = resolveNetwork('mainnet');
// 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L234)
---
# networkFromGenesisHash
> Derive the canonical CAIP-2 identifier from a network's genesis hash per the Algorand profile.
```ts
import { networkFromGenesisHash } from 'x402-avm-js';
```
```ts
export function networkFromGenesisHash(genesisHash: Uint8Array | string): string;
```
Derive the canonical CAIP-2 identifier from a network's genesis hash per the Algorand profile.
Computes URL-safe base64 of the genesis hash (with + -> -, / -> _, stripped padding)
and truncates to the first 32 characters as the CAIP-2 reference.
## Parameters
- `genesisHash` (`Uint8Array | string`, required):
32-byte genesis hash as a Uint8Array or base64-encoded string.
## Returns
- `returns` (`string`):
Canonical CAIP-2 identifier formatted as "algorand:<32-char-urlsafe-base64>".
## Example
```ts
const caip2 = networkFromGenesisHash('wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=');
// 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k'
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L258)
---
# networkFromAlgod
> Query an algod client for its current suggested transaction parameters and return its CAIP-2 identifier.
```ts
import { networkFromAlgod } from 'x402-avm-js';
```
```ts
export async function networkFromAlgod(algod: algosdk.Algodv2): Promise;
```
Query an algod client for its current suggested transaction parameters and return its CAIP-2 identifier.
Works with any Algorand node, including LocalNet instances and private testnets where the genesis hash
cannot be known in advance.
## Parameters
- `algod` (`algosdk.Algodv2`, required):
Algodv2 client instance.
## Returns
- `returns` (`true`): ">
Promise resolving to the canonical CAIP-2 network identifier.
## Throws
- `X402AvmError`: If the algod node does not return a genesisHash (network errors from algod propagate unchanged).
## Example
```ts
const algod = algodClient('localnet');
const networkId = await networkFromAlgod(algod);
console.log(networkId); // 'algorand:' followed by the genesis hash, e.g. TestNet's CAIP-2 id
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L282)
---
# algodClient
> Create an Algodv2 client for a named network or custom endpoint.
```ts
import { algodClient } from 'x402-avm-js';
```
```ts
export function algodClient(network: string, url?: string, token?: string): algosdk.Algodv2;
```
Create an Algodv2 client for a named network or custom endpoint.
Connects to public AlgoNode endpoints for "mainnet" and "testnet", or default
credentials (port 4001, token of 64 'a's) for "localnet". For private networks,
pass the node's URL explicitly.
## Parameters
- `network` (`string`, required):
Network name ('mainnet', 'testnet', 'localnet', or CAIP-2 string).
- `url` (`string`):
Optional custom algod base URL.
- `token` (`string`):
Optional authentication token or header.
## Returns
- `returns` (`algosdk.Algodv2`):
Configured Algodv2 client.
## Throws
- `UnknownNetworkError`: If network has no default endpoint and url is omitted.
## Example
```ts
const client = algodClient('testnet'); // https://testnet-api.algonode.cloud
const localClient = algodClient('localnet'); // http://localhost:4001
const status = await localClient.status().do();
const privateNode = algodClient('my-private-net', 'http://10.0.0.5:4001', 'my-token');
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L309)
---
# MAINNET
> MainNet network constants and public AlgoNode endpoints.
```ts
import { MAINNET } from 'x402-avm-js';
```
```ts
export const MAINNET: AlgorandNetwork = {
caip2: 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k',
genesisHash: 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=',
genesisId: 'mainnet-v1.0',
algodUrl: 'https://mainnet-api.algonode.cloud',
indexerUrl: 'https://mainnet-idx.algonode.cloud',
usdc: 31566704,
};
```
MainNet network constants and public AlgoNode endpoints.
## Example
```ts
import { MAINNET } from 'x402-avm-js';
console.log(MAINNET.genesisId); // 'mainnet-v1.0'
console.log(MAINNET.usdc); // 31566704
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L158)
---
# TESTNET
> TestNet network constants and public AlgoNode endpoints.
```ts
import { TESTNET } from 'x402-avm-js';
```
```ts
export const TESTNET: AlgorandNetwork = {
caip2: 'algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe',
genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=',
genesisId: 'testnet-v1.0',
algodUrl: 'https://testnet-api.algonode.cloud',
indexerUrl: 'https://testnet-idx.algonode.cloud',
usdc: 10458941,
};
```
TestNet network constants and public AlgoNode endpoints.
## Example
```ts
import { TESTNET } from 'x402-avm-js';
console.log(TESTNET.genesisId); // 'testnet-v1.0'
console.log(TESTNET.usdc); // 10458941
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L177)
---
# LOCALNET_ENDPOINTS
> LocalNet endpoints and token.
```ts
import { LOCALNET_ENDPOINTS } from 'x402-avm-js';
```
```ts
export const LOCALNET_ENDPOINTS = {
algodUrl: 'http://localhost:4001',
algodToken: 'a'.repeat(64),
indexerUrl: 'http://localhost:8980',
} as const;
```
LocalNet endpoints and token.
Because LocalNet genesis hash changes on every sandbox reset,
use `networkFromAlgod()` to retrieve its dynamic CAIP-2 network identifier.
## Example
```ts
import { LOCALNET_ENDPOINTS } from 'x402-avm-js';
console.log(LOCALNET_ENDPOINTS.algodUrl); // 'http://localhost:4001'
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L198)
---
# PaymentRequired
> Decoded payload of the HTTP 402 PAYMENT-REQUIRED header.
```ts
import type { PaymentRequired } from 'x402-avm-js';
```
```ts
export interface PaymentRequired {
x402Version: number;
error?: string | null;
resource?: ResourceInfo | null;
accepts: PaymentRequirements[];
extensions?: Record | null;
}
```
Decoded payload of the HTTP 402 PAYMENT-REQUIRED header.
Contains the x402 protocol version (2), optional error string, protected resource info,
list of acceptable payment requirements, and optional extensions.
## Properties
- `x402Version` (`number`, required):
x402 protocol version (2).
- `error` (`string | null`):
Optional error message from the server.
- `resource` (`ResourceInfo | null`):
The protected resource.
- `accepts` (`PaymentRequirements[]`, required):
The payment offers the server accepts. `selectRequirement` and `payForRequirement` pick the `exact` offer for the wallet's network.
- `extensions` (`true`): | null">
Optional protocol extensions. `encodePaymentHeader` copies them into the payment payload.
## Example
```ts
const challenge: PaymentRequired = {
x402Version: 2,
accepts: [
{
scheme: 'exact',
network: 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k',
asset: '0',
amount: '10000',
payTo: 'RECEIVER_ADDRESS',
maxTimeoutSeconds: 300
}
]
};
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L100)
---
# PaymentRequirements
> Payment requirements specified by an x402 server.
```ts
import type { PaymentRequirements } from 'x402-avm-js';
```
```ts
export interface PaymentRequirements {
scheme: string;
network: string;
asset: string;
amount: string;
payTo: string;
maxTimeoutSeconds: number;
extra?: {
feePayer?: string;
decimals?: number;
genesisHash?: string;
genesisId?: string;
[key: string]: unknown;
};
}
```
Payment requirements specified by an x402 server.
Defines the scheme, CAIP-2 network, asset ID (0 for ALGO), amount in base units,
recipient address, timeout, and optional extra metadata such as fee payer and token decimals.
## Properties
- `scheme` (`string`, required):
Payment scheme identifier. x402-avm-js builds payments for `"exact"`.
- `network` (`string`, required):
CAIP-2 network id, for example `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k` for MainNet.
- `asset` (`string`, required):
Asset id as a string: `"0"` for native ALGO, otherwise the ASA id (for example `"31566704"` for USDC on MainNet).
- `amount` (`string`, required):
Amount in the asset's base units (microALGO for ALGO), as a string.
- `payTo` (`string`, required):
Algorand address (58 characters) that receives the payment.
- `maxTimeoutSeconds` (`number`, required):
Maximum time, in seconds, the server allows for the payment.
- `extra` (`object`):
Optional scheme metadata sent by the server.
- `feePayer` (`string`):
Address of the server account that pays the group's fees. When present, `buildExactAvmGroup` builds the two-transaction group.
- `decimals` (`number`):
Decimals of the asset.
- `genesisHash` (`string`):
Base64 genesis hash of the network.
- `genesisId` (`string`):
Genesis id of the network, for example `mainnet-v1.0`.
- `[key: string]` (`unknown`):
Any other field the server sends.
## Example
```ts
const req: PaymentRequirements = {
scheme: 'exact',
network: 'algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k',
asset: '0',
amount: '5000',
payTo: 'DN74O524ODU54DND7U42G3...LN7L7Y',
maxTimeoutSeconds: 300,
extra: { feePayer: 'FEEPAYER...' }
};
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L43)
---
# ResourceInfo
> Metadata about the protected resource in an x402 payment challenge.
```ts
import type { ResourceInfo } from 'x402-avm-js';
```
```ts
export interface ResourceInfo {
url: string;
description?: string;
mimeType?: string;
}
```
Metadata about the protected resource in an x402 payment challenge.
## Properties
- `url` (`string`, required):
URL of the protected resource.
- `description` (`string`):
Human-readable description of the resource.
- `mimeType` (`string`):
MIME type of the resource's response.
## Example
```ts
const resource: ResourceInfo = {
url: 'https://api.example.com/v1/tools/translate',
description: 'Machine translation service',
mimeType: 'application/json'
};
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L71)
---
# BuildGroupResult
> Result of building an atomic transaction group for the exact AVM payment scheme.
```ts
import type { BuildGroupResult } from 'x402-avm-js';
```
```ts
export interface BuildGroupResult {
txns: algosdk.Transaction[];
paymentIndex: number;
signIndexes: number[];
}
```
Result of building an atomic transaction group for the exact AVM payment scheme.
## Properties
- `txns` (`algosdk.Transaction[]`, required):
Unsigned transactions of the atomic group, in order.
- `paymentIndex` (`number`, required):
Index of the buyer's payment transaction in `txns` (1 with a fee payer, 0 without).
- `signIndexes` (`number[]`, required):
Indexes the buyer must sign (`[1]` with a fee payer, `[0]` without).
## Example
```ts
const { txns, paymentIndex, signIndexes }: BuildGroupResult = buildExactAvmGroup(
requirement,
payerAddress,
suggestedParams
);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L120)
---
# AlgorandNetwork
> Network configuration and endpoints for an Algorand network.
```ts
import type { AlgorandNetwork } from 'x402-avm-js';
```
```ts
export interface AlgorandNetwork {
/** CAIP-2 id, "algorand:" */
caip2: string;
genesisHash: string;
genesisId: string;
algodUrl: string;
indexerUrl: string;
/** Circle USDC asset id, where it exists */
usdc?: number;
}
```
Network configuration and endpoints for an Algorand network.
## Properties
- `caip2` (`string`, required):
CAIP-2 id: `algorand:` followed by the first 32 characters of the URL-safe base64 genesis hash.
- `genesisHash` (`string`, required):
Base64 genesis hash (44 characters).
- `genesisId` (`string`, required):
Genesis id, for example `mainnet-v1.0`.
- `algodUrl` (`string`, required):
Default algod URL (public AlgoNode endpoint).
- `indexerUrl` (`string`, required):
Default indexer URL (public AlgoNode endpoint).
- `usdc` (`number`):
Circle USDC asset id on this network, where it exists.
## Example
```ts
const net: AlgorandNetwork = MAINNET;
console.log(net.caip2, net.algodUrl);
```
Source: [src/index.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/index.ts#L137)
---
# X402AvmError
> Typed errors thrown by x402-avm-js.
```ts
import { X402AvmError } from 'x402-avm-js';
```
```ts
export class X402AvmError extends Error {
/** Stable machine-readable identifier of the error kind. */
readonly code: string;
constructor(message: string, code = 'x402_avm_error', options?: { cause?: unknown }) {
super(message, options);
this.name = new.target.name;
this.code = code;
}
}
```
Typed errors thrown by x402-avm-js. Every error extends {@link X402AvmError}, carries a stable
string `code`, and sets `name` to the class name, so callers can use `instanceof` or `error.code`.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L6)
---
# SpendLimitExceededError
> The requested amount is above the client's spend cap.
```ts
import { SpendLimitExceededError } from 'x402-avm-js';
```
```ts
export class SpendLimitExceededError extends X402AvmError {
readonly asset: string;
readonly amount: bigint;
readonly limit: bigint;
constructor(asset: string, amount: bigint, limit: bigint) {
super(
`Refusing to pay ${amount} base units of asset ${asset}: above the spend limit of ${limit}. ` +
'Raise it explicitly with the maxAmount option if this is intended.',
'spend_limit_exceeded'
);
this.asset = asset;
this.amount = amount;
this.limit = limit;
}
}
```
The requested amount is above the client's spend cap. Thrown before anything is signed.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L54)
---
# PaymentNotAllowedError
> The requirement's asset, network or recipient is not on the caller's allow list.
```ts
import { PaymentNotAllowedError } from 'x402-avm-js';
```
```ts
export class PaymentNotAllowedError extends X402AvmError {
readonly field: 'asset' | 'network' | 'payTo';
readonly value: string;
constructor(field: 'asset' | 'network' | 'payTo', value: string) {
super(`Refusing to pay: ${field} "${value}" is not in the allowed${field === 'payTo' ? 'PayTo' : field[0].toUpperCase() + field.slice(1) + 's'} list`, 'payment_not_allowed');
this.field = field;
this.value = value;
}
}
```
The requirement's asset, network or recipient is not on the caller's allow list. Thrown before anything is signed.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L72)
---
# InvalidPaymentRequiredError
> The PAYMENT-REQUIRED header or object is malformed, or a requirement in it is not a valid exact-AVM offer.
```ts
import { InvalidPaymentRequiredError } from 'x402-avm-js';
```
```ts
export class InvalidPaymentRequiredError extends X402AvmError {
constructor(message: string, options?: { cause?: unknown }) {
super(message, 'invalid_payment_required', options);
}
}
```
The PAYMENT-REQUIRED header or object is malformed, or a requirement in it is not a valid exact-AVM offer.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L18)
---
# NoSupportedRequirementError
> The challenge offers nothing this client can pay (`accepts` is empty).
```ts
import { NoSupportedRequirementError } from 'x402-avm-js';
```
```ts
export class NoSupportedRequirementError extends X402AvmError {
constructor(message = 'No accepted payment requirements found in paymentRequired') {
super(message, 'no_supported_requirement');
}
}
```
The challenge offers nothing this client can pay (`accepts` is empty).
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L35)
---
# NetworkMismatchError
> None of the offered requirements is for the network the wallet is on, or a requirement's genesis does not match.
```ts
import { NetworkMismatchError } from 'x402-avm-js';
```
```ts
export class NetworkMismatchError extends X402AvmError {
readonly offered: string[];
readonly expected: string;
constructor(message: string, offered: string[], expected: string) {
super(message, 'network_mismatch');
this.offered = offered;
this.expected = expected;
}
}
```
None of the offered requirements is for the network the wallet is on, or a requirement's genesis does not match.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L42)
---
# UnknownNetworkError
> A network name or CAIP-2 identifier is not recognised, or has no default endpoint.
```ts
import { UnknownNetworkError } from 'x402-avm-js';
```
```ts
export class UnknownNetworkError extends X402AvmError {
readonly network: string;
constructor(message: string, network: string) {
super(message, 'unknown_network');
this.network = network;
}
}
```
A network name or CAIP-2 identifier is not recognised, or has no default endpoint.
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L25)
---
# InvalidOptionsError
> A spend-control option is malformed (for example a negative or non-integer maxAmount).
```ts
import { InvalidOptionsError } from 'x402-avm-js';
```
```ts
export class InvalidOptionsError extends X402AvmError {
constructor(message: string) {
super(message, 'invalid_options');
}
}
```
A spend-control option is malformed (for example a negative or non-integer maxAmount).
Source: [src/errors.ts](https://github.com/x402-avm/x402-avm-js/blob/main/src/errors.ts#L84)
---
# Troubleshooting
> Fixes for common problems with LocalNet, networks, opt-ins, balances, prices and payments.
Find your error message or symptom in the table, apply the fix, and follow the link if you need the background.
## Quick diagnosis
| Symptom | Likely cause | Fix |
|---|---|---|
| `Connection refused` on port 4001, or `MaxRetryError ... port=4001` | LocalNet is not running | `algokit localnet start` |
| `invalid_exact_avm_payload_genesis_hash_mismatch` | Client and server use different networks, or LocalNet was reset under a running server | Use the same network on both sides; restart servers after `algokit localnet reset` |
| `NetworkMismatchError: algod is on ... but the payment is for ...` | The client's algod is on another network than the offer | Point the client at an algod on the offer's network |
| `transaction_simulation_failed` mentioning an asset | An account has not opted in to the ASA | Opt in both `pay_to` and the buyer |
| `transaction_simulation_failed` mentioning balance, or `below min` | An account would drop below its minimum balance | Add ALGO: 0.1 ALGO base plus 0.1 ALGO per opted-in asset |
| `ConfigurationError: price ... does not cover facilitator fees` | ALGO price in `(0, 2000]` | Raise the price above 2,000 microALGO or pass `allow_loss=True` |
| `NoMatchingRequirementsError`, or `PaymentError: Failed to handle payment: ...` from the httpx client, or `SpendLimitExceededError` from `paid_mcp_session` (0.5.1; an `ExceptionGroup` in 0.5.0) | The price is above the spend cap, the asset is not allowed, or the offer is for another network | Check the offer; adjust `spend_controls` deliberately |
| `SpendLimitExceededError` / `PaymentNotAllowedError` in x402-avm-js | The offer is above `maxAmount` (1,000,000 base units by default) or not on an allow list | Check the offer; raise `maxAmount` deliberately |
| `FutureWarning: PaymentGate.wrap() was called without transport=` | `wrap(mcp)` without `transport=` serves legacy SSE | Pass `transport="streamable-http"` (recommended) or `transport="sse"` |
| `PaymentRequiredError: payment required: tool ... must be called through the payment gate` | A priced tool was reached without passing through the gate, for example over a transport the gate does not wrap | Serve the app built by `gate.wrap(...)`, or install both `gate.middleware()` and `SettleOnSuccessMiddleware` |
| HTTP `500` with `payment gate misconfigured` | The app was built without `SettleOnSuccessMiddleware` | Use `gate.wrap(...)` or `mcp.add_middleware(SettleOnSuccessMiddleware(gate))` |
| The MCP client cannot connect, or gets `404` / `405` | Client and server use different transports | Use `.../mcp` for `transport="streamable-http"` and `.../sse` for `transport="sse"` |
| `SettlementError: payment settlement failed: ...` | Submission failed: expired rounds, fee payer out of ALGO, node error | Check the fee payer's balance and algod; the buyer was not charged |
| `402` with `Replay detected`, or `transaction_simulation_failed` on a resent payment | The same signed payment was sent twice | Build a new payment for each call |
| `invalid_exact_avm_payload_recipient_mismatch` | The payment goes to another address than `payTo` | Use the `payTo` from the challenge |
| `invalid_exact_avm_payload_invalid_signature` | Wrong key, or the transaction changed after signing | Sign with the sender's key after the group id is set |
All facilitator codes are explained on [Error codes](https://x402-avm.github.io/reference/errors).
## LocalNet not reachable
```text
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4001): Max retries exceeded with url: /v2/status
```
1. Start LocalNet: `algokit localnet start`.
2. Check algod:
```bash
curl -H "X-Algo-API-Token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" http://localhost:4001/v2/status
```
3. Check the endpoints and tokens: algod `http://localhost:4001` and KMD `http://localhost:4002` use 64 × `a`; the indexer at `http://localhost:8980` needs no token.
## Asset not opted in
An account must opt in to an ASA, such as USDC, before it can receive it, and both the vendor's `pay_to` account and the buyer need it. The opt-in code is in [Accept USDC](https://x402-avm.github.io/production/mainnet#accept-usdc).
## Balance below the minimum
Every account must keep 100,000 microALGO (0.1 ALGO), plus 100,000 microALGO for each asset it has opted in to (applications add more). An account cannot spend below this, so a payment that would cross it fails simulation. Top the account up with ALGO.
## The client keeps getting 402 after paying
The server rejected the payment and answered with the challenge again. Look at the server's logs, or decode the response, for the failure reason. Common causes:
- The transactions expired (their last valid round passed) between building and sending.
- The group was modified after signing, so the group id or signature no longer matches.
- The buyer cannot cover the amount.
- The client is on a different network from the server.
The official `x402` httpx client does not loop: after a bounded number of paid retries it returns the server's answer, so a `402` after paying reaches your code.
## Prices below the fee floor
```text
ai_economy_sdk.exceptions.ConfigurationError: price 1000 for tool 'summarize' does not cover facilitator fees (2000 microalgos); raise it or pass allow_loss=True
```
Charge more than 2,000 microALGO, or pass `allow_loss=True` to subsidize calls on purpose. See [the fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor).
## LocalNet was reset
A reset creates a new genesis hash, so the LocalNet network id changes. Restart servers and clients so they read the new id; see [LocalNet](https://x402-avm.github.io/production/networks#localnet).
## Still stuck
Search the [examples](https://github.com/x402-avm/examples) for a working configuration close to yours, and open an issue in the relevant repository with the error, the package versions and the network.
---
# FAQ
> Short answers to common questions about x402 on Algorand and the x402-avm packages, with links to the full explanation.
### What is x402?
An open protocol that sells a resource per request with HTTP status `402 Payment Required`: the server states the price, the client retries with a signed payment, the server settles. See [How it works](https://x402-avm.github.io/how-it-works).
### What is the exact scheme on Algorand?
The x402 scheme in which the client pays exactly the requested amount of one asset to one address, as an Algorand atomic group. See [AVM exact scheme](https://x402-avm.github.io/reference/protocol/avm-exact-scheme).
### Why does the payment group have two transactions, and who pays the fees?
Transaction 0 is the server's fee payer covering the fees of both; transaction 1 is the buyer's payment with fee 0. The server pays 2,000 microALGO per settled call, so the buyer pays exactly the price. See [the atomic group](https://x402-avm.github.io/how-it-works#the-two-transaction-atomic-group).
### What is the lowest price I can charge in ALGO?
More than 2,000 microALGO; 3,000 is a sensible minimum. `PaymentGate` refuses lower fixed ALGO prices unless you pass `allow_loss=True`. The floor does not apply to USDC. See [the fee floor](https://x402-avm.github.io/build/pricing#the-fee-floor).
### How can buyers pay in USDC if fees are in ALGO?
The fee payer pays the ALGO fees in the same group, so the buyer needs no ALGO beyond its minimum balance. Both sides must opt in to USDC first. See [Accept USDC](https://x402-avm.github.io/production/mainnet#accept-usdc).
### What is the minimum balance requirement?
Every Algorand account must hold 0.1 ALGO, plus 0.1 ALGO per opted-in asset (applications add more), and cannot spend below it.
### When is a payment settled, and what if the tool fails?
After the tool succeeds. If it fails, the signed payment is discarded and the buyer is not charged. See [Settle-on-success](https://x402-avm.github.io/how-it-works#settle-on-success).
### How does replay protection work with several workers?
Pass `replay_db="/path/replay.db"` so every worker shares one SQLite store. See [Replay store](https://x402-avm.github.io/production/security#replay-store).
### How is a pass different from a per-call payment?
A pass is one payment with the note `x402-pass:` that makes calls in that scope free for a period (30 days by default). See [Passes](https://x402-avm.github.io/how-it-works#passes).
### Can an identity proof move my funds?
No. It is a 0-amount payment to yourself with fee 0 and an expired validity window, so the network will never accept it. See [Identity](https://x402-avm.github.io/build/identity).
### Which wallets work with x402-avm-js?
Any wallet that signs Algorand transactions given the encoded transactions and the indexes to sign, for example through `@txnlab/use-wallet-react` (Pera, Defly, Lute, KMD and others), or a local key in Node. See [Connect a wallet](https://x402-avm.github.io/build/pay-from-browser#connect-a-wallet).
### How long does a payment take?
The server returns the result after the group is confirmed in a block, usually a few seconds. Algorand blocks are final once confirmed, with no forks to wait out.
### Can an AI agent pay for tools safely?
Within limits you set: a dedicated wallet with a small balance, and spend controls that cap each payment. See [AI agents](https://x402-avm.github.io/build/ai-agents#set-limits).
### How do I move from LocalNet to MainNet?
Follow [Networks](https://x402-avm.github.io/production/networks) to TestNet, then the [go-live checklist](https://x402-avm.github.io/production/mainnet#go-live-checklist).
---
# Glossary
> Terms used across the x402-avm documentation.
Look up a term used in these docs; each entry links to the page that explains it in full.
## x402
An open payment protocol that uses HTTP status `402 Payment Required` to sell a resource per request. The server describes the price in a `PAYMENT-REQUIRED` header, the client answers with a signed payment in `PAYMENT-SIGNATURE`, and the server reports settlement in `PAYMENT-RESPONSE`. See [x402.org](https://www.x402.org).
## Exact scheme
The x402 payment scheme where the client pays exactly the requested amount of one asset to one address. `x402-algorand` implements it for Algorand; the facilitator rejects any amount that differs from the requirement.
## CAIP-2
A chain-agnostic format for network ids, `namespace:reference`. Under the Algorand profile the reference is the first 32 characters of the URL-safe base64 genesis hash, for example `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k` for MainNet. See [Networks](https://x402-avm.github.io/production/networks#network-ids).
## Resource server
The service that sells something: an MCP server wrapped with `PaymentGate`, or an HTTP API protected by the `x402` middleware. It turns a request into payment requirements and delegates verification and settlement to a facilitator.
## Facilitator
The component that verifies a payment (structure, signature, simulation) and settles it (signs the fee payer transaction, submits the group, waits for confirmation). `PaymentGate` runs one in process.
## Fee payer
An account run by the service that pays the network fees for the payment group, so the buyer pays only the price. Its transaction is a 0-amount payment to itself with a fee that covers the whole group.
## Atomic group
Up to 16 Algorand transactions submitted together with a shared group id. Either all of them are committed or none is.
## ASA
Algorand Standard Asset: a token on Algorand, such as USDC. An account must opt in to an ASA before it can hold it.
## microALGO
The smallest unit of ALGO. 1 ALGO is 1,000,000 microALGO. ALGO prices are given in microALGO.
## Base units
The integer unit an asset's amounts are expressed in: microALGO for ALGO, and 10-6 USDC for USDC (6 decimals). Prices and `amount` fields are always in base units.
## Genesis hash
The 32-byte hash of a network's genesis block. Every transaction carries it, so a transaction signed for one network is invalid on another.
## MBR
Minimum balance requirement. Every Algorand account must keep 0.1 ALGO, plus 0.1 ALGO for each asset it has opted in to.
## MCP
[Model Context Protocol](https://modelcontextprotocol.io): an open protocol through which AI applications discover and call tools. `ai-economy-sdk` gates MCP tool calls served over Streamable HTTP (recommended) or the legacy SSE transport.
## Identity proof
A signature that proves which address a caller controls, without paying. Either an `X-Identity-Txn` header (a zero-fee self-payment that can never execute) or the legacy `x-sender-*` headers. See [Identity](https://x402-avm.github.io/build/identity).
## Pass
A prepaid on-chain payment to a vendor with the note `x402-pass:`. While it is valid (30 days by default), the vendor's gate charges the holder 0 for tools in that scope. See [Passes](https://x402-avm.github.io/build/pricing#passes).
## Settle-on-success
`PaymentGate` submits the payment only after the tool succeeds. A failed tool call is never charged.
## Settlement
Submitting the signed group to the network and waiting for confirmation.
## Simulate
An algod feature (`/v2/transactions/simulate`) that evaluates a group against the current ledger without committing it. The facilitator simulates every group during verification, with empty signatures allowed.
## Spend controls
Client-side limits in the official `x402` client: which assets may be paid and the maximum amount per payment. By default only ALGO and USDC are allowed, up to 1,000,000 base units per payment. See [Guardrails](https://x402-avm.github.io/build/ai-agents#set-limits).
---
# Changelog
> Notable changes to ai-economy-sdk, x402-algorand and x402-avm-js, newest first.
This page combines the changelogs of the three packages: [ai-economy-sdk](https://github.com/x402-avm/ai-economy-sdk/blob/main/CHANGELOG.md), [x402-algorand](https://github.com/x402-avm/x402-algorand/blob/main/CHANGELOG.md) and [x402-avm-js](https://github.com/x402-avm/x402-avm-js/blob/main/CHANGELOG.md).
## 2026-11-19 (ai-economy-sdk 0.5.1, x402-avm-js 0.4.1) (ai-economy-sdk 0.5.1, x402-avm-js 0.4.1)
## ai-economy-sdk 0.5.1
**Fixed**
- When the buyer's own spend controls refused a payment inside `paid_mcp_session`, the caller got an `ExceptionGroup` wrapping x402's `PaymentError` (cause `NoMatchingRequirementsError`), so `except AIEconomyError` missed it. The refusal now surfaces as `SpendLimitExceededError`, with the x402 error as `__cause__`. Other errors, and groups that contain anything besides the refusal, propagate unchanged.
**Added**
- `SpendLimitExceededError(AIEconomyError)`, exported from the package and documented in `ai_economy_sdk.exceptions`. Its message includes the amount and asset the server asked for.
## x402-avm-js 0.4.1
**Fixed**
- `algodClient('localnet')` connected to port 80 instead of 4001: the empty-string port passed to `algosdk.Algodv2` made algosdk 3.x override the port in the URL. The port is now omitted so the URL's own port (or the scheme default for MainNet and TestNet) is used. Affected every release since the first.
## 2026-11-19 (minor releases) (ai-economy-sdk 0.5.0, x402-algorand 0.3.0, x402-avm-js 0.4.0)
> **Warning:**
**Security: upgrade ai-economy-sdk to 0.5.0.** In 0.4.x the payment gate only inspected `POST` requests whose path ended in `/messages`. A FastMCP Streamable HTTP app wrapped with `PaymentGate.middleware()` (`POST /mcp`), or a gated SSE app mounted under a path prefix, passed priced `tools/call` requests to the server **without a payment**.
## Security
**ai-economy-sdk 0.5.0**
- The gate inspects the JSON-RPC body of every HTTP `POST`, whatever its path or transport, and its route table matches every path.
- Fails closed: `SettleOnSuccessMiddleware` refuses (with `PaymentRequiredError`) any priced tool call that did not pass through the HTTP gate. A gated call whose payment reservation has expired is refused instead of being served without settlement. JSON-RPC batches containing `tools/call` are rejected with HTTP 400, and the HTTP middleware refuses priced calls with HTTP 500 if `SettleOnSuccessMiddleware` was never installed.
- `subscription_issuer` can no longer be silently ignored: the issuer is always passed to `chain.has_active_subscription()`, and `PaymentGate` raises `ConfigurationError` at construction if that method has no `issuer` parameter.
- `DefaultAvmSigner` no longer stores the key in a public attribute, and its `repr()` shows only the address.
**x402-avm-js 0.4.0**
- Client-side spend limits protect against a server requesting an unexpectedly large amount (see Breaking below).
## Breaking and changed
**x402-avm-js 0.4.0**
- **Default spend cap.** `payForRequirement` and `buildExactAvmGroup` refuse any payment above 1,000,000 base units (1 ALGO, or 1 USDC) with a `SpendLimitExceededError`, before anything is signed. To pay more, pass the new options argument, for example `payForRequirement(challenge, address, algod, signer, { maxAmount: 5_000_000n })`; `maxAmount: Infinity` removes the cap.
- Node.js 18 is no longer supported; the package requires Node.js 20 or later.
- Types: `extra` and `extensions` values are `unknown` instead of `any`; `selectRequirement`, `encodePaymentHeader` and `payForRequirement` take `PaymentRequired` instead of `PaymentRequired | any`.
- `decodePaymentRequired` validates the decoded shape and throws `InvalidPaymentRequiredError` (it used to return whatever JSON it found).
- `src/` is published in the package, so source maps and go-to-definition resolve.
**ai-economy-sdk 0.5.0**
- `PaymentGate.wrap()` without `transport=` still serves SSE but emits a `FutureWarning`; the default will change to `"streamable-http"` in a future release.
- The SSE compatibility patch (stateless MCP sessions, so raw JSON-RPC clients can call tools without the `initialize` handshake) is applied only for the SSE transport. Correction to the 0.4.0 entry "Removed monkeypatches": this FastMCP patch was still present in 0.4.0 and 0.4.1.
- **Potentially breaking:** `AIEconomySDK.add_tool()` decides once, from the pricing function's signature, whether to call it as `(args, sender)` or `(args)`; a function accepting neither raises `ConfigurationError` at registration (0.4.x failed per request).
- **Potentially breaking:** `ChainReader` and `PaymentGate` catch only lookup errors (algod/indexer HTTP errors, connection errors, malformed responses), log them and report no usage, subscription or pass, as before. Other exceptions now propagate.
- **Potentially breaking:** `DefaultAvmSigner.private_key` is a read-only property; assigning to it raises `AttributeError`.
- On the SSE transport the `POST` response is the server's own response plus settlement headers.
- Signing uses `AccountTransactionSigner` instead of the deprecated `Transaction.sign()`.
- Requires `x402-algorand>=0.2.1`.
**x402-algorand 0.3.0**
- Errors for unsupported or unregistered networks are `NetworkError`, for an algod on the wrong network `NetworkMismatchError`, and for undecodable transactions `TransactionDecodeError`. All are subclasses of `ValueError`, as before.
- The facilitator checks every transaction sent by one of its own addresses (not only the first), and signs all of the advertised `feePayer`'s transactions, as the specification requires.
- Fee payer signing, simulation and settlement failures are also logged to the `x402_algorand` logger; the returned `invalid_reason` / `error_reason` codes are unchanged.
- `settle()` returns the ID of `paymentGroup[paymentIndex]` as the transaction, as required by the specification; with a fee payer it previously returned the ID of the fee payer transaction.
- The V1 facilitator and client wrappers accept the official SDK's `PaymentPayloadV1` / `PaymentRequirementsV1` models and return `VerifyResponse` / `SettleResponse`, so V1 payments routed through `x402Facilitator` / `x402Client` work. Requirements without `extra` no longer fail validation.
- Ed25519 signature verification of a payment from a rekeyed account uses the auth address. A rekey pair is only accepted when the second rekey returns authority to the sender.
- `pynacl` is a declared dependency (it was already required through `py-algorand-sdk`).
## Added
**ai-economy-sdk 0.5.0**
- Streamable HTTP support: `PaymentGate.wrap(mcp, transport="streamable-http")` (alias `"http"`) serves the MCP Streamable HTTP transport at `POST /mcp`, stateless by default (`stateless_http=False` enables MCP sessions). `wrap()` also accepts `path=` and other `FastMCP.http_app()` keyword arguments. `AIEconomySDK.build_app(transport=...)` forwards to it.
- `paid_mcp_session(..., transport=...)` connects over Streamable HTTP or SSE. Without `transport=`, URLs whose path ends in `/mcp` use Streamable HTTP and all others use SSE.
- Exception hierarchy, exported from the package: `AIEconomyError`, `ConfigurationError` (a `ValueError`), `UnknownNetworkError`, `AlgodClientRequiredError` (also a `RuntimeError`), `PaymentVerificationError` (a `RuntimeError`), `PaymentRequiredError` and `SettlementError` (FastMCP `ToolError`s). Each also subclasses the type raised at the same place in 0.4.x. See [Errors and error codes](https://x402-avm.github.io/reference/errors#ai-economy-sdk-exceptions).
- Typing module `ai_economy_sdk.types` (`ServerSigner`, `ChainLookup`, `Prices`, `GatePriceFunction`, `ToolPriceFunction`, `SpendControlsArg`, `Transport`), and a `py.typed` marker.
- `ai_economy_sdk.__version__`.
- `SettleOnSuccessMiddleware` is exported for apps that build the FastMCP HTTP app themselves.
- Logging to the `ai_economy_sdk` logger: refused calls, settlement failures, expired reservations and failed chain lookups at `WARNING`.
- Python 3.14 support.
**x402-algorand 0.3.0**
- Ready-made signers: `PayerAvmSigner` (client side) and `ServerAvmSigner` (facilitator side: fee payer signing, simulate, send, confirm; also usable as a client signer), built with `from_private_key(...)` or `from_mnemonic(...)`. `ServerAvmSigner` accepts several keys, an `algod_client` or `algod_url`/`algod_token`, and checks that algod is on the requested network. Keys are never included in `repr()`, error messages or logs.
- Exception hierarchy in `x402_algorand.errors`, exported from `x402_algorand`: `X402AlgorandError`, `NetworkError`, `NetworkMismatchError`, `TransactionDecodeError`, `SigningError`, `SimulationError`.
- Payments authorized by a k-of-n multisig, a logic signature, or the auth address of a rekeyed account are accepted, as allowed by the exact scheme specification.
- `x402_algorand.__version__`, a `py.typed` marker, and Python 3.14 support.
**x402-avm-js 0.4.0**
- Spend controls: `maxAmount` (per payment, or per asset), `allowedAssets`, `allowedNetworks`, `allowedPayTo`; exported `SpendControls`, `DEFAULT_MAX_AMOUNT`, `checkSpendControls`. See [Guardrails](https://x402-avm.github.io/build/pay-from-browser#spend-controls).
- Typed errors, all extending `X402AvmError` with a stable `code`: `SpendLimitExceededError`, `PaymentNotAllowedError`, `InvalidPaymentRequiredError`, `NoSupportedRequirementError`, `NetworkMismatchError`, `UnknownNetworkError`, `InvalidOptionsError`.
- `parsePaymentRequired(value: unknown)` for validating untrusted input.
- `buildExactAvmGroup` rejects requirements whose `extra.genesisHash` or `extra.genesisId` disagrees with the algod parameters, and malformed `payTo`, `feePayer`, `amount` and `asset` values.
## Deprecated
**ai-economy-sdk 0.5.0**
- `sign_identity()` (legacy `x-sender-*` headers): use `sign_identity_txn()`, which binds the proof to one network. It still works and emits a `DeprecationWarning`; servers keep accepting legacy headers, and `paid_mcp_session` still sends them.
- Reading `DefaultAvmSigner.private_key` emits a `DeprecationWarning`. Keep your own reference to the key.
## Fixed
**ai-economy-sdk 0.5.0**
- A `TypeError` raised inside a two-argument pricing function was caught and the function was called again with one argument.
## 2026-11-19 (patch releases) (ai-economy-sdk 0.4.1, x402-algorand 0.2.1, x402-avm-js 0.3.1)
## ai-economy-sdk 0.4.1
- Project URLs (`Homepage`, `Documentation`, `Repository`, `Issues`, `Changelog`) and PyPI classifiers in `pyproject.toml`.
- Dependency ranges kept at `fastmcp>=3.4,<4` and `mcp>=1.29,<2`: `mcp` 2.x and `fastmcp` 4.x are excluded because of upstream `httpx` changes that affect `x402` compatibility.
## x402-algorand 0.2.1
- Project URLs (`Homepage`, `Documentation`, `Issues`, `Changelog`) and classifiers (Python 3.10–3.13, `Typing :: Typed`, `Development Status :: 4 - Beta`) in `pyproject.toml`.
## x402-avm-js 0.3.1
- Package metadata: repository, homepage, bugs URL, keywords and author.
- The timestamp helper `getNs()` reads `globalThis.process` safely, so it works in browser, edge and Node.js environments.
## 2026-11-18 (ai-economy-sdk 0.4.0, x402-algorand 0.2.0, x402-avm-js 0.3.0, and earlier 0.2/0.3 releases)
## x402-algorand 0.2.0
**Changed**
- x402-algorand is now a plugin for the official `x402` Python SDK (`x402>=2.28,<3`, github.com/x402-foundation/x402). It ships only the Algorand exact scheme, under the import name `x402_algorand` (was `x402.mechanisms.avm` inside a fork of the whole SDK).
- Network ids follow the Algorand CAIP-2 profile: `algorand:` plus the first 32 characters of the URL-safe base64 genesis hash (MainNet `algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k`, TestNet `algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe`). Legacy long ids are accepted and converted.
- The facilitator checks the network by the id derived from each transaction's genesis hash, so LocalNet and private networks need no registry entry.
**Added**
- `caip2_from_genesis_hash`, `register_network` and `get_genesis_hash` helpers.
- The client scheme implements `find_default_asset`, so the official `x402Client` spend controls pay ALGO and USDC by default (capped at 1,000,000 base units per payment); other assets are allowed with `x402Client.set_spend_controls(...)`.
- The client refuses to build a payment when its algod is on a different network than the requirement.
**Removed**
- The bundled copy of the x402 core SDK (`x402/`); install the official `x402` package instead.
## ai-economy-sdk 0.4.0
**Added**
- Integration with the official `x402>=2.28` framework and the `x402-algorand>=0.2.0` plugin.
- `spend_controls` parameter of `paid_mcp_session` (`dict | Literal[False] | None = None`), to enforce per-payment caps or allow custom ASAs before signing.
- NumPy-style docstrings across the public API (`PaymentGate`, `paid_mcp_session`, `ChainReader`, `DefaultAvmSigner`).
**Changed**
- Monkeypatches removed in favour of the native `find_default_asset` and spend control filtering provided by `x402-algorand`.
- Network ids follow the Algorand CAIP-2 profile (first 32 characters of the URL-safe base64 genesis hash).
## x402-avm-js 0.3.0
**Added**
- CAIP-2 short network ids (`algorand:` plus 32 characters), with fallback for legacy 44-character ids.
- Compatibility with the official `x402` 2.28 protocol and the `x402_algorand` plugin.
- Native ALGO (asset 0) and ASAs, including Circle USDC.
- Fee sponsorship through `feePayer` two-transaction atomic groups.
- Identity proofs with `buildIdentityTxn` and `encodeIdentityHeader` (`X-Identity-Txn`).
- A self-contained test suite that funds LocalNet accounts from the KMD dispenser and creates its own test ASAs.
Migration notes: [x402-algorand from 0.1.x](https://x402-avm.github.io/reference/packages#x402-algorand-from-0-1-x), [ai-economy-sdk from 0.3](https://x402-avm.github.io/reference/packages#ai-economy-sdk-from-0-3), [x402-avm-js from 0.2](https://x402-avm.github.io/reference/packages#x402-avm-js-from-0-2).
## ai-economy-sdk 0.3.1
- Added vendor passes: `ChainReader.active_passes()`, `ChainReader.has_pass()` and `PaymentGate(pass_scopes=..., pass_days=...)`.
- The MIT `LICENSE` file ships in the package.
- Requires `x402-algorand>=0.1.4`.
## ai-economy-sdk 0.3.0
- Multi-network resolution: `PaymentGate`, `AIEconomySDK` and `paid_mcp_session` accept `"mainnet"`, `"testnet"`, `"localnet"` and CAIP-2 ids.
- New network utilities: `resolve_network`, `endpoints_for`, `is_public` and `usdc_asset_id`.
- Identity proofs for browser wallets: `make_identity_txn`, `sign_identity_txn` and `verify_identity_txn`, producing zero-fee `X-Identity-Txn` proofs.
- Subscription issuer enforcement: `PaymentGate(subscription_issuer=...)` and `has_active_subscription(issuer=...)`.
- `paid_mcp_session` resolves algod endpoints from the network (AlgoNode for MainNet and TestNet).
- The 2,000 microALGO fee floor applies only to native ALGO prices.
## x402-algorand 0.1.4
- Licensed Apache-2.0 like the projects it derives from (GoPlausible/x402-avm, coinbase/x402). Ships `LICENSE` and `NOTICE`, and each file changed from x402-avm 2.0.2 says so. Releases 0.1.0 to 0.1.3 were labelled MIT by mistake.
## x402-algorand 0.1.3
- Package metadata update (README as the PyPI description). Network ids were still the long form `algorand:`.
## x402-avm-js 0.2.1
- The MIT `LICENSE` file is included in the published npm package.
## x402-avm-js 0.2.0
- No Node `Buffer` dependency: runs in browsers, workers and edge runtimes without polyfills.
- Network presets and helpers: `MAINNET`, `TESTNET`, `LOCALNET_ENDPOINTS`, `resolveNetwork`, `networkFromAlgod`, `networkFromGenesisHash`, `algodClient` and `selectRequirement`.
- `payForRequirement` checks that the algod's network matches the server's offers and throws when none matches.
- Read-only `PUBLIC_NETS=1` tests on MainNet and TestNet.
- Published package manifest with an `exports` map, types, and build and tests in `prepublishOnly`.
## 2026-11-17 (ai-economy-sdk 0.2.0, x402-avm-js 0.1.0)
## ai-economy-sdk 0.2.0
- Settle-on-success: `PaymentGate` verifies payments before the tool runs and settles only after the tool succeeds.
- Replay protection: `ReplayStore`, in memory or SQLite in WAL mode for several processes.
- Fee floor: ALGO prices at or below 2,000 microALGO are rejected at start-up unless `allow_loss=True`.
- Caller identity: `sign_identity` and `verify_identity`.
## x402-avm-js 0.1.0
- First implementation of the Algorand exact-scheme client: parse `PAYMENT-REQUIRED`, build the transaction group, sign through a wallet callback and encode `PAYMENT-SIGNATURE`.
## x402-algorand 0.1.0 to 0.1.2 (Earlier releases)
- A fork of GoPlausible/x402-avm 2.0.2 (Python, the whole x402 SDK): native ALGO payments (asset 0), an algod token parameter, any `algorand:` network (LocalNet or private), and facilitator fixes for sync facilitators and streaming (SSE) responses.
---
# Docs for AI tools
> llms.txt, llms-full.txt and Markdown versions of every page for coding assistants, and the AGENTS.md file in each x402-avm repository.
Give these to a coding assistant, an agent or a chat model so it answers from the current documentation and follows each repository's rules.
## Files for models
| URL | Contents | Use it when |
|---|---|---|
| [`/llms.txt`](https://x402-avm.github.io/llms.txt) | An index of every page: title, one-line description, link to its Markdown version, grouped as in the navigation. | The tool can follow links and fetch only what it needs. |
| [`/llms-full.txt`](https://x402-avm.github.io/llms-full.txt) | The full text of every page in navigation order, as Markdown. | You want to paste or attach everything at once. |
| `/.md` | One page as Markdown, for example [`/quickstart.md`](https://x402-avm.github.io/quickstart.md) or [`/reference/python/ai-economy-sdk/paid-mcp-session.md`](https://x402-avm.github.io/reference/python/ai-economy-sdk/paid-mcp-session.md). | The tool needs one topic. |
The files follow the [llms.txt convention](https://llmstxt.org) and are rebuilt from the page sources on every deploy. The menu next to each page title also has **Copy page** (Markdown), **View as Markdown**, **Open in ChatGPT** and **Open in Claude**.
The API reference is generated from the Python docstrings and the TSDoc of `x402-avm-js`, so a model reading it sees the same signatures and parameter descriptions as the source. Each reference page links to the exact source line.
```text
Read https://x402-avm.github.io/llms-full.txt. Then add a paid MCP tool to my FastMCP server
with ai-economy-sdk, priced at 5,000 microALGO per call on LocalNet.
```
```text
Read https://x402-avm.github.io/build/ai-agents.md and configure paid_mcp_session for my agent
with a $0.05 per-payment cap on TestNet.
```
## AGENTS.md files
[AGENTS.md](https://agents.md) is a Markdown file at the root of a repository that tells coding agents how to work on it: setup, tests, conventions, and what never to do. Every repository in the [x402-avm organization](https://github.com/x402-avm) has one. An agent should read the file of the repository it works on first; it takes precedence over the organization-wide one.
| Repository | Use its AGENTS.md for |
|---|---|
| [x402-avm](https://github.com/x402-avm/x402-avm/blob/main/AGENTS.md) (hub) | Choosing the repository for a task, the three test modes, organization-wide conventions |
| [ai-economy-sdk](https://github.com/x402-avm/ai-economy-sdk/blob/main/AGENTS.md) | Changing the MCP payment gate and client |
| [x402-algorand](https://github.com/x402-avm/x402-algorand/blob/main/AGENTS.md) | Changing the Algorand scheme plugin |
| [x402-avm-js](https://github.com/x402-avm/x402-avm-js/blob/main/AGENTS.md) | Changing the TypeScript client |
| [examples](https://github.com/x402-avm/examples/blob/main/AGENTS.md) | Adding or running examples |
| [marketplace-demo](https://github.com/x402-avm/marketplace-demo/blob/main/AGENTS.md) | Running the LocalNet demonstration marketplace |
| [x402-avm.github.io](https://github.com/x402-avm/x402-avm.github.io/blob/main/AGENTS.md) | Editing this site, regenerating the API reference, refreshing inlined examples |
The hub file maps tasks to repositories (sell MCP tools: `ai-economy-sdk`; add Algorand to an x402 SDK server or client: `x402-algorand`; pay from a browser or Node: `x402-avm-js`). It also has a [hub llms.txt](https://github.com/x402-avm/x402-avm/blob/main/llms.txt).
### Test modes
All packages use the same three tiers; each package's README and AGENTS.md say which it supports.
| Mode | Python | JavaScript | Needs |
|---|---|---|---|
| Offline | `python -m pytest tests -q` | `npm test` | Nothing |
| `LOCALNET=1` | `LOCALNET=1 python -m pytest tests -q` | `LOCALNET=1 npm test` | AlgoKit LocalNet running; settles real payments |
| `PUBLIC_NETS=1` | `PUBLIC_NETS=1 python -m pytest tests -q -m public` | `PUBLIC_NETS=1 npm test` | Internet access; builds TestNet and MainNet payments and simulates them, no keys or funds |
### Conventions every agent follows
- Use CAIP-2 network ids (`algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k`, `algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe`); do not hand-write the 44-character form in new code.
- Amounts are integers in base units; USDC has 6 decimals (MainNet 31566704, TestNet 10458941).
- Never commit private keys, mnemonics or tokens; read them from the environment.
- Never send a MainNet transaction from a test. Settle on LocalNet; use `PUBLIC_NETS=1` simulation for public networks.
- Tests must not depend on local paths or pre-existing accounts; LocalNet tests fund fresh accounts from the KMD dispenser.
- Documentation uses plain, precise language, without marketing terms or emojis.