# Multi-Wallet Strategy
Source: https://developers.fd.xyz/agent-wallet/advanced/multi-agent
Isolate funds by purpose with separate wallets — per-role budgets, clear audit trails, and independent control.
When a single wallet handles everything — research payments, trading, and merchant settlements — you lose visibility into what's spending what, and a bug in one function can drain funds meant for another. The solution: assign a **separate wallet to each role**.
Each wallet is its own District Pass account, running in its own agent instance. One user orchestrates them all, but each wallet is isolated on-chain.
## Why Separate Wallets?
1. **Blast radius containment** — a misbehaving role can only burn its own wallet, not others
2. **Clear audit trail** — every transaction is attributed to a specific wallet address and role
3. **Per-role budgets** — fund each wallet according to its purpose and risk
4. **Independent control** — pause, drain, or shut down one wallet without touching the rest
A shared wallet makes it impossible to attribute spending, enforce budgets, or contain damage.
## Architecture Patterns
### By Role
Different wallets for different purposes. Each wallet is funded and monitored independently.
```
Research role → Wallet A ($50) — buys data, pays APIs
Trading role → Wallet B ($500) — executes swaps
Payments role → Wallet C ($200) — settles merchant invoices
```
**Best for:** An agent (or set of agents) that handles multiple financial functions with different risk profiles.
### By Responsibility
One workflow, multiple wallets scoped by what each part of the workflow needs to do.
```
Analyst wallet → read-only (balance checks, no funds needed)
Executor wallet → $1,000 (swaps and transfers)
Reporter wallet → read-only (no funds needed)
```
**Best for:** Complex workflows where different steps need different financial capabilities.
### By Scale
Many identical instances doing the same task in parallel, each with its own wallet.
```
Worker 1 → Wallet ($50)
Worker 2 → Wallet ($50)
Worker 3 → Wallet ($50)
...
Worker N → Wallet ($50)
```
**Best for:** Parallel processing where each instance independently buys data, pays for API access, or executes trades.
## Setting Up Multiple Wallets
Each wallet requires its own **District Pass account**. A single CLI or MCP session authenticates one account at a time, so each wallet runs in a **separate instance** — a separate container, process, or machine.
### MCP Configuration
Every instance uses the same MCP server URL but authenticates with its own District Pass via OAuth PKCE:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
Each instance maintains its own OAuth session. Wallets are fully isolated — one instance cannot access another's funds.
You cannot sign into multiple District Pass accounts within a single CLI or MCP session. Each wallet must run in its own process or environment.
## Budget Management
Apply the [pocket money philosophy](/agent-wallet/concepts/trust) per wallet:
| Wallet Role | Suggested Funding | Refill Strategy |
| - | - | - |
| Research / data buying | \$10–50 | Per session |
| API access payment | \$50–200 | Weekly |
| Active trading | \$500–2,000 | Based on performance |
| Payment processing | Task-appropriate | Per batch |
**Fund individually.** Each wallet gets only what its role needs.
**Refill rather than pre-fund.** Keep balances low and refill when needed. Each refill is a checkpoint to review activity.
**Monitor on-chain.** Check each wallet address on a block explorer to review spending patterns.
## Monitoring
Each wallet has its own on-chain address, making monitoring straightforward:
* **Per-wallet activity** — look up each address on the relevant block explorer
* **Balance tracking** — check balances via MCP, CLI, or block explorer
* **Spending patterns** — review transaction history to verify each role is operating within expectations
For scaled deployments, script balance checks across all wallets:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
#!/bin/bash
WALLETS=("wallet-research" "wallet-trading" "wallet-payments")
for wallet in "${WALLETS[@]}"; do
echo "=== $wallet ==="
fdx wallet getWalletOverview --chainKey ethereum
done
```
## Scaling Considerations
**Start small.** Set up one or two wallets, validate the workflow, then add more.
**Same code, different credentials.** For scaled patterns, each instance runs identical code — the only difference is the District Pass it authenticates with.
**Graceful shutdown.** Before decommissioning a wallet, withdraw remaining funds. The wallet and its on-chain history remain accessible even after the instance stops.
# Agent Frameworks
Source: https://developers.fd.xyz/agent-wallet/ai-integration/agent-frameworks
Add real crypto wallet capabilities to LangChain, CrewAI, AutoGen, and more — no MCP client required.
If your framework supports MCP, connect directly to the Agent Wallet MCP server. If not, wrap the [FDX CLI](/agent-wallet/ai-integration/cli) as a shell tool. Both approaches give the same wallet capabilities.
## Integration Approaches
| Framework | MCP Support | Recommended Approach |
| - | - | - |
| LangChain | Via MCP adapter | MCP native |
| CrewAI | Via MCP adapter or shell tools | FDX CLI wrapping |
| AutoGen | Via MCP adapter | MCP native |
| Semantic Kernel | Via adapter | MCP native |
| Custom | Depends on implementation | MCP SDK or FDX CLI |
**MCP-native** is preferred when available — it gives the agent direct access to wallet tools through the standard MCP tool-calling interface. **FDX CLI wrapping** works with any framework that can execute shell commands, which covers essentially every agent framework.
## LangChain
### MCP Integration (Recommended)
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_anthropic import ChatAnthropic
# Connect to Agent Wallet MCP server
async with MultiServerMCPClient(
{
"finance-district": {
"url": "https://wallet-mcp.fd.xyz",
"transport": "streamable-http",
}
}
) as client:
tools = client.get_tools()
agent = create_react_agent(
ChatAnthropic(model="claude-sonnet-4-20250514"),
tools
)
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Check my wallet balance"}]}
)
```
### FDX CLI Tool Wrapper
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import subprocess
import json
from langchain.tools import tool
@tool
def wallet(method: str) -> str:
"""Execute an FDX wallet command. Pass an MCP method name and arguments.
Example: 'getWalletOverview --chainKey ethereum'
Run 'fdx wallet' for available methods."""
result = subprocess.run(
["fdx", "wallet"] + method.split(),
capture_output=True, text=True
)
return result.stdout
# Use in an agent
agent = create_react_agent(llm, [wallet])
```
## CrewAI
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from crewai import Agent, Task, Crew
from crewai.tools import tool
import subprocess
import json
@tool("Agent Wallet")
def wallet(method: str) -> str:
"""Manage crypto wallet via FDX. Pass an MCP method name and arguments.
Example: 'getWalletOverview --chainKey ethereum' or 'transferTokens --chainKey ethereum --toAddress 0x... --amount 5 --asset USDC'"""
result = subprocess.run(
["fdx", "wallet"] + method.split(),
capture_output=True, text=True
)
return result.stdout
financial_agent = Agent(
role="Financial Agent",
goal="Manage wallet operations and execute transactions",
tools=[wallet],
verbose=True
)
task = Task(
description="Check the wallet balance and swap 10 USDC for ETH if balance allows",
agent=financial_agent
)
crew = Crew(agents=[financial_agent], tasks=[task])
result = crew.kickoff()
```
## AutoGen
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from autogen import ConversableAgent
import subprocess
import json
def wallet_command(method: str) -> str:
result = subprocess.run(
["fdx", "wallet"] + method.split(),
capture_output=True, text=True
)
return result.stdout
assistant = ConversableAgent(
name="financial_assistant",
llm_config={"model": "claude-sonnet-4-20250514"},
)
# Register wallet as a callable function
assistant.register_for_llm(
name="wallet",
description="Execute FDX wallet commands. Pass MCP method name and arguments."
)(wallet_command)
```
## Custom MCP Client
For frameworks with direct MCP support or when building your own agent:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
async function createMcpClient() {
const transport = new StreamableHTTPClientTransport(
new URL("https://wallet-mcp.fd.xyz"),
);
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);
return client;
}
// Use in your agent logic
const client = await createMcpClient();
// Check balance
const result = await client.callTool({
name: "getWalletOverview",
arguments: {},
});
// Transfer
const transfer = await client.callTool({
name: "transferTokens",
arguments: {
to: "0x1234...5678",
amount: "5",
token: "USDC",
},
});
```
See the [MCP SDK documentation](https://modelcontextprotocol.io/docs) for full client implementation details.
## Best Practices
**Use MCP when possible.** The MCP approach gives your agent richer context — tool descriptions, parameter schemas, and error details that help the LLM make better decisions.
**FDX output is always JSON.** All `fdx wallet` / `fdx prism` output is structured JSON, making it straightforward for agents to parse.
**Write clear tool descriptions.** The LLM uses your tool description to decide when and how to call the tool. Be specific about what each command does.
**Start with small amounts.** Validate your agent's behavior with a small balance before scaling up funding.
**Handle errors gracefully.** Agents should check for insufficient balance, failed transactions, and network errors — and communicate these clearly rather than retrying blindly.
# Finance District CLI Skills
Source: https://developers.fd.xyz/agent-wallet/ai-integration/agent-skills
Give any AI agent crypto wallet and merchant payment capabilities — one skill install, zero code.
The Finance District skill follows the [Agent Skills specification](https://agentskills.io/specification) and works with OpenClaw, Claude Code, GitHub Copilot, and 40+ other agentic platforms. Once installed, the skill teaches your agent how to use the [Finance District CLI](/agent-wallet/ai-integration/cli) — giving it wallet management, token transfers, DEX swaps, DeFi yield, x402 payments, and Prism merchant operations through natural language.
## Why a Skill?
The skill bridges the gap between the CLI and your agent. Without it, the agent would need to figure out which `fdx` commands exist, what parameters they take, and how to chain them together. The skill provides:
* **Tool discovery** — the agent knows which `fdx` commands are available and uses `--help` to learn parameters on demand
* **Workflow guidance** — authentication flows, pre-operation checklists, safety confirmations before irreversible operations
* **Protocol knowledge** — the full [x402 payment flow](/agent-wallet/concepts/x402-payments), including when to use `authorizePayment` vs `getX402Content`
* **Two service areas** — both **Wallet** (`fdx wallet`) and **Prism** (`fdx prism`) operations in a single skill
The skill is a single `SKILL.md` file with reference documents. It doesn't add runtime dependencies — it teaches the agent how to use the CLI you've already installed.
## Installation
**Step 1:** Install the CLI:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install -g @financedistrict/fdx
```
**Step 2:** Install the skill:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npx skills add financedistrict-platform/fd-cli-skills
```
That's it. The skill is automatically detected when your agent encounters a relevant task.
## What the Agent Can Do
Once the skill is installed, your agent handles all of this through natural language:
**Wallet operations:**
> "Set up my wallet" — authentication via email OTP
> "Show my balance on Base" — balances across all chains
> "Send 10 USDC to 0x1234...abcd on Arbitrum" — token transfers with safety confirmations
> "Swap 5 USDC for ETH" — DEX swaps with quote-first flow
> "Find yield strategies for my USDC" — DeFi discovery, deposit, and withdrawal
> "Access the premium API at [https://api.example.com/data](https://api.example.com/data)" — x402 payments
**Prism merchant operations:**
> "Set up my merchant account" — onboarding and configuration
> "Create a new Project" — payment acceptance setup
> "Show my payment history" — earnings and settlement details
The skill guides the agent to confirm with you before any irreversible operation (transfers, swaps, deposits) and to check balances before executing.
## How It Works
The skill is not a wrapper or abstraction layer. It's a set of instructions that teach the agent:
1. **Check prerequisites** — is `fdx` installed? Is the user authenticated?
2. **Use `--help` liberally** — discover tool parameters dynamically rather than hardcoding them
3. **Follow safety patterns** — check balances, confirm with the human, verify chain matches recipient
4. **Handle authentication** — autonomous path (with email inbox access) or human-assisted path
5. **Consult reference docs** — deeper guidance on specific topics (x402 flow, chain capabilities, troubleshooting) loaded only when needed
The agent runs `fdx` commands via bash and parses structured JSON output. All wallet operations use `fdx wallet `, all Prism operations use `fdx prism `.
## Skill vs MCP
The skill and the [MCP server](/agent-wallet/ai-integration/mcp-server) provide access to the same underlying capabilities. Choose based on your agent's environment:
| Approach | How it works | Best for |
| - | - | - |
| **Skill** | Agent runs `fdx` CLI commands via bash | Agents with shell access — Claude Code, OpenClaw, autonomous agents |
| **MCP** | Agent connects to `https://wallet-mcp.fd.xyz` via MCP protocol | MCP-native clients — Claude Code, Cursor, Windsurf |
Both can be used together. An agent with both the skill and MCP access has maximum flexibility.
Full CLI documentation and configuration
Source code and contributing guidelines
# Finance District AI Assistant
Source: https://developers.fd.xyz/agent-wallet/ai-integration/ai-assistant
Manage your crypto by just talking to it — Finance District's AI-powered conversational wallet assistant.
The AI Assistant is Finance District's conversational web interface for managing your wallet. Log in, chat in natural language, and your wallet does what you ask — no MCP configuration, no CLI installation, no technical setup.
## Getting Started
1. Go to [apps.fd.xyz](https://apps.fd.xyz) and log in with your District Pass (or sign up if you don't have an account)
2. Navigate to the AI Assistant
3. Start chatting
That's it. The AI Assistant connects to the same wallet and capabilities as MCP and CLI — just through a chat interface.
See the AI Assistant in action at
[01:35](https://youtu.be/JObnfc-jW78?t=95) in the Agent Wallet setup tutorial —
looking up wallet addresses and checking balances after a deposit.
## What You Can Do
The AI Assistant supports the same wallet capabilities available through MCP and CLI:
**Check your wallet:**
> "What's my balance?"
> "What's my wallet address on Base?"
> "Show my recent transactions"
**Transfer tokens:**
> "Send 5 USDC to 0x1234...5678"
> "Transfer 0.01 ETH to alice.eth on Ethereum"
**Swap tokens:**
> "Swap 10 USDC for ETH"
> "How much ETH would I get for 50 USDC?"
**Explore yield:**
> "What yield opportunities are available for USDC?"
> "Put 100 USDC into the best yield option"
**Pay merchants:**
> "Pay 2 USDC to merchant 0xABC...123"
The assistant understands context and can handle multi-step requests:
> "Check if I have at least 20 USDC, and if so, swap half of it for ETH"
## Who It's For
The AI Assistant serves two audiences:
**Developers exploring Agent Wallet** — use it to test wallet capabilities before integrating via MCP or CLI. It's the fastest way to see what the wallet can do without writing configuration.
**Non-technical users** — manage your wallet through conversation without needing to understand MCP, command lines, or blockchain details.
## AI Assistant vs. MCP vs. CLI
| Feature | AI Assistant | MCP Server | CLI |
| - | - | - | - |
| Setup required | None — just log in | MCP client config | npm install + auth |
| Primary user | Humans | AI agents | Developers, automated agents |
| Automation | No — interactive only | Yes | Yes |
| Programmable | No | Yes — tool calling | Yes — scriptable |
| Best for | Exploration, simple tasks, non-technical users | Primary agent integration | Scripts, agent frameworks, terminal workflows |
## Limitations
The AI Assistant is an interactive web interface, not a programmable endpoint:
* **Not automatable** — you can't script it or call it from code
* **Not for agent integration** — use [MCP Server](/agent-wallet/ai-integration/mcp-server) or [CLI](/agent-wallet/ai-integration/cli) for that
* **Session-based** — requires you to be logged in and chatting actively
For autonomous agent operations, the MCP Server and CLI are the right tools.
# Finance District CLI
Source: https://developers.fd.xyz/agent-wallet/ai-integration/cli
Run your AI agent's wallet from the terminal — hold, send, swap, and earn yield across chains. Works with OpenClaw, GitHub Copilot, and 40+ agentic platforms.
FDX is a command-line interface to the Finance District MCP wallet server. It gives AI agents crypto wallet capabilities — hold, send, swap, and earn yield on assets across multiple chains — without managing private keys.
FDX is built for advanced users and environments where agents have access to CLI tooling and bash — Docker containers, CI pipelines, remote servers, and scripted automation. Agents invoke `fdx wallet ` or `fdx prism ` from the command line and parse JSON output. FDX also powers the [Agent Wallet CLI Skills](/agent-wallet/ai-integration/agent-skills), which plug it directly into OpenClaw, GitHub Copilot, and 40+ other agentic platforms.
* **No Key Management** — Email OTP authentication. No seed phrases. No private key files.
* **Agent-Native** — Structured JSON input/output designed for tool-calling agents.
* **Multi-Chain** — Ethereum, BSC, Arbitrum, Base, Solana, Bitcoin, Sui. One wallet, all chains.
* **DeFi Enabled** — Transfer, swap, and earn yield through integrated DeFi protocols.
For full documentation, architecture details, and development instructions,
see the [FDX GitHub
repository](https://github.com/financedistrict-platform/fd-agent-wallet-cli).
## Quick Start
Install globally:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install -g @financedistrict/fdx
```
Register a new account:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx register --email you@example.com
```
Enter the 8-digit OTP sent to your email:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx verify --code 12345678
```
Check that authentication succeeded:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx status
```
For subsequent sessions, sign in with:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx login --email you@example.com
fdx verify --code 12345678
```
To remove stored credentials:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx logout
```
Watch this install and login flow at
[09:20](https://youtu.be/JObnfc-jW78?t=560) in the Agent Wallet setup tutorial.
## Authentication
FDX uses email one-time passcode (OTP) authentication via Microsoft Entra External ID. No browser is required — the entire flow runs headlessly, making it ideal for autonomous agents, Docker containers, CI pipelines, and remote servers.
### Register (first time)
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx register --email you@example.com
# Check your inbox for an 8-digit OTP
fdx verify --code 12345678
```
### Login (returning users)
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx login --email you@example.com
# Check your inbox for an 8-digit OTP
fdx verify --code 12345678
```
### Token storage
Tokens are stored in the OS credential store where available:
| Platform | Backend |
| - | - |
| macOS | Keychain (`security` CLI) |
| Linux | libsecret (`secret-tool` CLI) |
| Windows | DPAPI (encrypted file in `~/.fdx/`) |
If no credential store is available (e.g. a minimal container), tokens fall back to plaintext in `~/.fdx/auth.json` with a `SecurityWarning` emitted. Tokens are refreshed automatically using the stored refresh token.
### Logging out
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx logout
```
Removes stored tokens from the OS credential store and clears `~/.fdx/auth.json`.
## Usage
Wallet tools use the `fdx wallet` subcommand and Prism tools use `fdx prism`:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Check wallet overview
fdx wallet getWalletOverview --chainKey ethereum
# Send tokens
fdx wallet transferTokens --chainKey ethereum --toAddress 0xABC... --amount 0.1 --asset USDC
# Discover yield strategies
fdx wallet discoverYieldStrategies --chainKey base
# List Prism payments
fdx prism listPayments
```
All output is JSON, making it easy for agents to parse:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet getMyInfo | jq '.email'
```
Run `fdx wallet` without arguments to see all available wallet methods. Run `fdx services` to see all available services.
`fdx call ` was deprecated in v0.4.0 and now exits with an error. Use `fdx wallet ` for wallet tools or `fdx prism ` for Prism tools.
## Services
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# List all available MCP services and their URLs
fdx services
```
Two services are available:
| Service | Subcommand | URL | Description |
| - | - | - | - |
| `wallet` | `fdx wallet` | `https://wallet-mcp.fd.xyz` | Wallet tools (DeFi, transfers, X402) |
| `prism` | `fdx prism` | `https://prism-mcp.fd.xyz` | Prism tools (payments, settlements) |
## Configuration
FDX reads configuration from three sources, in order of precedence:
1. **Environment variables** (highest priority — see `fdx --help` for the full list)
2. **Persistent config file** at `~/.fdx/config.json`
3. **Built-in defaults** (lowest priority)
### Inspect current config
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx config
```
Prints the resolved values for Entra auth, MCP service URLs, and storage/log paths. Each value is labeled with its source — `(env)`, `(config)`, or `(default)`.
### Persist a value
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx config set
```
Writes the value to `~/.fdx/config.json`. Useful when you don't want to set an environment variable for every session — for example, pointing a long-running agent at a custom gateway URL.
### Read or remove a persisted value
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx config get
fdx config unset
```
### Supported keys
| Key | Description |
| - | - |
| `authority` | Entra External ID authority URL |
| `client_id` | Entra application (client) ID |
| `scopes` | OAuth scopes requested at sign-in |
| `wallet_mcp_url` | Wallet MCP service URL (default: `https://wallet-mcp.fd.xyz`) |
| `prism_mcp_url` | Prism MCP service URL (default: `https://prism-mcp.fd.xyz`) |
| `store_path` | Token store path (default: `~/.fdx/auth.json`) |
| `log_path` | Log file path (default: `~/.fdx/fdx.log`) |
| `log_level` | Log verbosity — `debug\|info\|warn\|error\|off` (default: `info`) |
## Using FDX with Agent Frameworks
FDX is designed to work with agent frameworks where the agent can execute shell commands.
### Tool-calling agents
Most agent frameworks let you define custom tools. Wrap FDX as a shell tool:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import subprocess
import json
def wallet_command(method: str, **kwargs) -> dict:
"""Execute an FDX wallet command and return JSON result."""
args = ["fdx", "wallet", method]
for key, value in kwargs.items():
args.extend([f"--{key}", str(value)])
result = subprocess.run(args, capture_output=True, text=True)
return json.loads(result.stdout)
# Check wallet overview
overview = wallet_command("getWalletOverview", chainKey="ethereum")
# Transfer tokens
wallet_command("transferTokens", chainKey="ethereum", toAddress="0x1234...5678", amount="5", asset="USDC")
```
### Script-based automation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
#!/bin/bash
BALANCE=$(fdx wallet getWalletOverview --chainKey base | jq -r '.balances[0].amount')
echo "Current balance: $BALANCE"
```
For deeper integration patterns with specific frameworks, see [Agent Frameworks](/agent-wallet/ai-integration/agent-frameworks).
## FDX vs. MCP Server
FDX and MCP server connect to the same backend and offer the same capabilities:
| Aspect | MCP Server | FDX CLI |
| - | - | - |
| Interface | MCP protocol (tool calls) | Terminal commands (`fdx wallet` / `fdx prism`) |
| Connection | MCP client → server | FDX → MCP client → server |
| Best for | AI agents in MCP clients | Scripts, automation, agent frameworks with shell access |
| Login | Config file in MCP client | `npm install -g` + `fdx login` |
| Auth | OAuth PKCE | Email OTP (Microsoft Entra External ID) |
| Output | MCP tool responses | JSON |
Choose MCP when your agent or AI client supports MCP natively. Choose FDX when you need terminal access or are integrating with a framework that runs shell commands.
# MCP Compatible Clients
Source: https://developers.fd.xyz/agent-wallet/ai-integration/mcp-clients
Give Claude, Cursor, and your favorite AI tools real crypto wallet capabilities in under 5 minutes.
The Agent Wallet MCP server works with any MCP-compatible client. Pick your tool below and you'll be connected in under five minutes.
**Server details for all clients:**
| Property | Value |
| - | - |
| URL | `https://wallet-mcp.fd.xyz` |
| Transport | Streamable HTTP |
| Auth | OAuth PKCE (browser-based authorization) |
## Claude Desktop
Claude Desktop (and Claude.ai web) currently have client-side restrictions that limit Agent Wallet MCP functionality. For the full Agent Wallet experience without restrictions, we recommend [Claude Code](#claude-code), Cursor, or any other MCP-compatible client. The configuration below is documented for completeness, but capabilities may be reduced.
Edit your Claude Desktop config file:
* **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
* **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
Restart Claude Desktop. On first connection, your browser opens for OAuth authorization. Sign in with your [District Pass](/overview/district-pass) (if you aren't already) and authorize the client to access your Finance District account. Once authorized, the connection persists across sessions.
**Verify:** Ask Claude "What Finance District tools do you have?"
## Cursor
Open Cursor Settings → MCP Servers → Add new server:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
Restart Cursor after saving. The browser-based OAuth flow will trigger on first connection.
**Verify:** In Cursor's AI chat, ask "What Finance District wallet tools are available?"
## Windsurf
Open Windsurf Settings → MCP Configuration:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
## Claude Code
Claude Code supports MCP servers directly from the command line:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude mcp add finance-district --transport http https://wallet-mcp.fd.xyz
```
This only registers the server — it does **not** authenticate. `claude mcp list` will show `finance-district` as `! Needs authentication`. To complete authorization, either:
* Run `/mcp` inside Claude Code, select **finance-district**, and choose **Authenticate**, or
* Ask the agent to use a wallet tool — the browser OAuth flow triggers on first use.
After you authorize, the status flips to `✔ Connected` and Claude Code can use wallet tools in your coding sessions.
## n8n
n8n supports MCP servers as tools for AI Agent nodes:
1. Open your n8n workflow
2. Add or configure an **AI Agent** node
3. In the agent's tool configuration, add an MCP server
4. Set the server URL to `https://wallet-mcp.fd.xyz` with Streamable HTTP transport
5. Configure OAuth authorization — sign in with your District Pass when prompted
The agent node can then use wallet capabilities as tools within your n8n workflows.
## Custom MCP Client
For developers building their own MCP client or integrating into a custom agent framework, you'll need to handle both the OAuth PKCE authentication flow and **client registration** with the Agent Wallet MCP server.
### Client Registration
Before an MCP client can authenticate, it must be registered with the authorization server. The Agent Wallet MCP server supports two registration methods:
CIMD lets your client publish its metadata (name, redirect URIs, grant types) as a JSON document at a publicly accessible URL. The authorization server fetches this document to verify your client's identity during the OAuth flow.
**How it works:**
1. You host a JSON metadata document at a URL you control (e.g., `https://your-app.com/.well-known/oauth-client`)
2. Your client uses that URL as its `client_id` in the OAuth flow
3. The authorization server fetches the document to validate the client
This is the **recommended approach** — no registration step is needed on our side, and you maintain full control of your client metadata.
See the [MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for the full metadata document schema.
DCR ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) allows clients to register programmatically by posting their metadata to a registration endpoint. The server responds with a `client_id` that the client uses for subsequent OAuth flows.
DCR on the Agent Wallet MCP server is **restricted to whitelisted clients**. If you need DCR access for your custom client, [reach out to us on Discord](https://discord.gg/fdxyz) to request whitelisting.
Popular MCP clients — Claude Desktop, Cursor, Windsurf, Claude Code, and n8n —
are already registered and work out of the box. Client registration only
applies when you're building a custom MCP client or integrating the Agent
Wallet MCP server into your own agent framework.
### Code Example
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const transport = new StreamableHTTPClientTransport(
new URL("https://wallet-mcp.fd.xyz"),
);
const client = new Client({
name: "my-agent",
version: "1.0.0",
});
await client.connect(transport);
// Discover available tools
const { tools } = await client.listTools();
console.log(
"Available tools:",
tools.map((t) => t.name),
);
// Call a tool
const result = await client.callTool({
name: "getWalletOverview",
arguments: {},
});
```
The MCP SDK's Streamable HTTP transport handles the OAuth PKCE flow natively. See the [MCP SDK documentation](https://modelcontextprotocol.io/docs) for full implementation details.
## Troubleshooting
**Browser window doesn't open for authentication**
* Ensure your MCP client supports OAuth PKCE with Streamable HTTP transport
* Some older MCP client versions may not support remote server authentication — update to the latest version
**Connection drops after a while**
* OAuth tokens refresh automatically. If the refresh fails, restart your client to trigger a new authentication flow
**Tools aren't showing up**
* Verify the server URL is exactly `https://wallet-mcp.fd.xyz`
* Verify the transport type is set to `streamable-http` (not `sse` or `stdio`)
* Restart your MCP client after adding the configuration
# Finance District MCP Server
Source: https://developers.fd.xyz/agent-wallet/ai-integration/mcp-server
The fastest way to give any AI agent a production-ready crypto wallet — plug in via MCP and go.
The Agent Wallet MCP server is the primary integration point for AI agents. It exposes wallet capabilities as tools that any MCP-compatible client can discover and use — Claude Code, Cursor, Windsurf, n8n, or your own custom agent.
The server is **remote and hosted** at `https://wallet-mcp.fd.xyz`. There's nothing to install, no local processes to run, and no infrastructure to manage.
## What is MCP?
[MCP (Model Context Protocol)](https://modelcontextprotocol.io/) is an open standard by Anthropic for connecting AI assistants to external tools and data sources. Think of it as a universal adapter — any MCP-compatible client can connect to any MCP server and discover what it can do.
Agent Wallet publishes wallet operations as MCP tools. When your AI agent connects, it automatically discovers all available capabilities and can use them through natural language.
## Connection Details
| Property | Value |
| - | - |
| Server URL | `https://wallet-mcp.fd.xyz` |
| Transport | Streamable HTTP |
| Authentication | OAuth Authorization Code Flow with PKCE |
No API keys or bearer tokens to manage. When your MCP client connects for the first time, it triggers an OAuth authorization flow that opens a browser — sign in with your [District Pass](/overview/district-pass) (if you aren't already) and authorize the client to access your Finance District account.
## Connect
Add the MCP server to your client and authorize it through the District Pass OAuth flow. Setup instructions for Claude Code, Cursor, Windsurf, n8n, and custom clients are in [MCP Compatible Clients](/agent-wallet/ai-integration/mcp-clients).
## Verify the Connection
After configuring your client, verify the agent can reach the wallet:
> "What Finance District tools do you have?"
The agent should list the available wallet capabilities. Then try:
> "What's my wallet balance?"
If you see your balance (even if it's zero), the connection is working.
Watch this connector setup and verification step by step at
[05:56](https://youtu.be/JObnfc-jW78?t=356) in the Agent Wallet setup tutorial.
## Tools Reference
The Finance District Wallet MCP server exposes **16 tools** across three categories. MCP clients discover all tool parameters automatically; CLI users can run `fdx wallet --help`.
**Wallet Operations (12)**
1. `getWalletOverview` — balances across the Agent Wallet and Smart Accounts
2. `getAccountActivity` — transaction history for one account on one chain
3. `getTokenPrice` — USD price + 24h change for a token
4. `transferTokens` — transfer tokens across EVM, Solana, Bitcoin, and Sui
5. `swapTokens` — quote or execute a token swap (quote-only by default)
6. `discoverYieldStrategies` — discover DeFi yield strategies (**EVM chains only**)
7. `getYieldPositions` — list active yield positions for an account on a chain
8. `depositForYield` — deposit into a yield strategy
9. `withdrawFromYield` — withdraw from a yield position by vault token address
10. `getRedemptionRequests` — track async vault-withdrawal status (Pending / Finalized / Rejected)
11. `resolveNameService` — resolve ENS (.eth), SNS (.sol), Unstoppable Domains
12. `signMessage` — EIP-191 personal\_sign or EIP-712 typed-data signing (EVM)
**Payments (2)**
13. `authorizePayment` — build an x402 payment authorization from a 402 response
14. `getX402Content` — fetch from an x402 API and auto-pay on HTTP 402
**Support (2)**
15. `getMyInfo` — authenticated user profile + all wallet addresses (EVM, Solana, Bitcoin, Sui)
16. `reportIssue` — file a bug report (creates a GitHub issue)
**Sui: transfers only.** Swap, yield, signing, and Smart Account tools are not supported on Sui.
***
## Authentication
Authentication uses **OAuth Authorization Code Flow with PKCE** — the same standard used by major web applications:
1. Your MCP client connects to `https://wallet-mcp.fd.xyz`
2. The server responds with an OAuth authorization URL
3. Your client opens a browser window
4. You sign in with your District Pass (if not already) and authorize the client to access your Finance District account
5. The OAuth flow completes and your client receives a token
6. Subsequent requests use this token automatically
**Token refresh** is handled automatically by the OAuth flow. You shouldn't need to re-authenticate unless you explicitly revoke access.
**Revoking access** — if you want to disconnect a specific MCP client, you can revoke its OAuth token through the Signer Service web interface.
**Client registration** — popular MCP clients (Claude Desktop, Cursor, Windsurf, Claude Code, n8n) are pre-registered and work out of the box. If you're building a custom MCP client, see [Client Registration](/agent-wallet/ai-integration/mcp-clients#client-registration) for supported registration methods.
## Error Handling
Common scenarios your agent may encounter:
| Error | Meaning | Resolution |
| - | - | - |
| Authentication failed | OAuth token expired or revoked | Re-authenticate through browser flow |
| Insufficient balance | Wallet doesn't have enough tokens for the operation | Fund the wallet with more tokens |
| Transaction failed | On-chain error (gas, nonce, network issue) | Retry — transient errors resolve on retry |
| Unsupported chain/token | Requested operation on an unsupported chain or token | Check [Supported Networks](/agent-wallet/supported-networks) |
All tool responses follow a consistent shape:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Success
{ "success": true, "data": { ... } }
// Failure
{ "success": false, "error": { "code": "...", "message": "...", "retryable": true, "details": {} } }
```
If `retryable` is `true`, the client may retry the same request once. Otherwise, inputs or state must change before retrying.
MCP clients typically display tool errors in the conversation. The agent can often explain what went wrong and suggest a fix.
# Commerce Payments
Source: https://developers.fd.xyz/agent-wallet/concepts/commerce
Agent Wallet handles the payment layer for UCP and x402 commerce. Declare support in your profile, and the wallet signs when it's time to pay.
Agent Wallet plugs into two commerce patterns. In both, the wallet's role is the same: sign the payment when asked.
| Pattern | Trigger | What the wallet does |
| - | - | - |
| **x402 Paywall** | Agent hits a paid API | Detects the 402, signs, retries automatically |
| **UCP Checkout** | Agent shops at a merchant | Signs the x402 authorization when the agent requests it during checkout |
Everything else (discovering merchants, browsing catalogs, creating checkout sessions, submitting the credential) is handled by the agent or its platform. This page covers only the parts where Agent Wallet enters.
## Declare the Handler
For UCP merchants to know your agent can pay via Prism, your platform's UCP profile must include the `xyz.fd.prism_payment` handler.
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"ucp": {
"version": "2026-08-25",
"payment_handlers": {
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"spec": "https://prism-gw.fd.xyz/ucp/prism.md",
"schema": "https://prism-gw.fd.xyz/ucp/schema.json",
"available_instruments": [{ "type": "x402" }],
"config": {}
}
]
}
}
}
```
This tells merchants: "this agent can pay with Prism-settled stablecoins." The `spec` and `schema` point to the handler definition so the merchant can validate compatibility.
## Authorize the Payment
During a UCP checkout, the merchant returns payment requirements inside the handler's `config`: which chains, tokens, and amounts are accepted. Your agent passes this to the Agent Wallet MCP server, and the wallet:
1. Checks that the agent has sufficient balance on a supported chain
2. Selects a chain/token pair from the merchant's accepted options
3. Signs an ERC-3009 `transferWithAuthorization` inside the TEE
4. Returns the signed credential
Before submitting, the agent adds `type: "x402"` to the credential. The instrument uses `handler_id: "xyz.fd.prism_payment"` and `type: "x402"`.
The agent never sees private keys. The output is a self-contained x402 payment object that the agent submits back to the merchant to complete the checkout.
## x402 Paywall
When your agent requests a Prism-protected resource, the server responds with HTTP `402 Payment Required`. The wallet handles this automatically: it reads the payment requirements, signs, and retries with proof of payment. No extra work from the agent.
For more detail on the x402 protocol, see [x402 Payments](/agent-wallet/concepts/x402-payments).
## What the Wallet Handles
Across both patterns, the Agent Wallet MCP server is responsible for:
* **Payment signing** inside the TEE (private keys never leave the enclave)
* **Chain and token selection** from the merchant's accepted options
* **Balance validation** before signing
* **ERC-3009 authorization** (the x402 payment primitive)
Your agent handles the merchant interaction. The wallet handles the money.
Connect your agent to the wallet
The merchant side of this flow
Full UCP checkout flow (protocol-level detail)
Both sides of a complete purchase
# Security Model
Source: https://developers.fd.xyz/agent-wallet/concepts/security
Your keys never leave a secure enclave — enterprise-grade, non-custodial security built for autonomous agents.
Agent Wallet uses a non-custodial architecture with private keys secured inside AWS Nitro Enclaves. Finance District is an infrastructure provider — we don't hold custody of your wallet or keys. This is by design and architecture. You have full control over your wallet at all times.
## The Problem with Typical Approaches
If your AI agent needs a wallet today, you're probably doing one of these:
**Environment variables.** Generate a private key, store it in `.env`, use it in your agent code. This is the most common pattern in agent ecosystems — and the most dangerous. One compromised server, one leaked log, one misconfired deploy, and the key is gone. This isn't theoretical — credential leaks and key exposure are already being documented across agent platforms.
**Application config.** Private key in a JSON config, YAML file, or secrets manager that the application reads at startup. Better than `.env`, but still accessible to anything with file or process access on the host.
**Agent-managed keys.** The agent generates and manages its own key material, typically held in memory or the agent's storage. If the agent is compromised — or if the orchestrator framework has a vulnerability — the key goes with it.
All of these patterns share one fundamental flaw: the key exists somewhere the host system can reach it.
## Trusted Execution Environment (TEE)
Agent Wallet uses [AWS Nitro Enclaves](https://aws.amazon.com/ec2/nitro/nitro-enclaves/) for key management. Nitro Enclaves are isolated compute environments that run on dedicated, hardened hardware — separate from the host instance's CPU, memory, and storage.
**How it works:**
1. Your private key is **generated inside** the Nitro Enclave
2. The key **never leaves** the enclave
3. All transaction **signing happens inside** the enclave
4. The host operating system **cannot access** the enclave's memory or storage
5. Even Finance District infrastructure operators **cannot extract** key material
The enclave receives signing requests, performs the cryptographic operation internally, and returns the signed transaction. At no point is the raw private key exposed to any external process, API, or human.
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
flowchart LR
A[Agent] -->|Signing Request| S
subgraph enclave["AWS Nitro Enclave"]
K["Private Key\n(generated here, never leaves)"] --> S[Sign Transaction]
end
S -->|Signed Transaction| A
```
### Comparison
| Approach | Where Keys Live | Who Can Access | Risk |
| - | - | - | - |
| Environment variables | Host memory / disk | Anyone with server access | High — one breach exposes keys |
| Application config | Config files | App + anyone with file access | High |
| Agent-managed | Agent memory / storage | Agent + orchestrator | Medium — agent compromise = key compromise |
| **TEE (Agent Wallet)** | **Nitro Enclave** | **Nobody — signing happens inside** | **Low — hardware isolation** |
## Non-Custodial Architecture
Finance District is an infrastructure provider, not a custodian. The architecture is non-custodial by design:
* **We don't hold your keys.** Keys exist inside Nitro Enclaves. There is no mechanism for Finance District to extract, copy, or use your private keys.
* **You have full control.** You can withdraw funds, export your keys, and manage your wallet at any time.
* **You can export your keys.** Through the Signer Service web interface, you can request a full key export and back up your private keys independently. This means you are never locked into Finance District infrastructure.
This is the same non-custodial model used by other non-custodial infrastructure providers — the platform secures and manages keys on your behalf, but you retain ownership and can take your keys elsewhere at any time.
Key export means you can always self-custody. Agent Wallet is infrastructure
you choose to use, not a walled garden you're locked into.
## What We Don't Do
To be explicit about the security boundaries:
* **We don't store keys in environment variables** — keys live in Nitro Enclaves, not on the host
* **We don't trust the host environment** — the enclave is isolated from the host OS, memory, and storage
* **We don't hold custody** — no Finance District employee or system can access your private keys
* **We don't let agents manage key material** — agents call signing operations; they never touch the key itself
* **We don't expose raw private keys through any interface** — MCP, CLI, AI Assistant, and Web App all interact with signing as a service, not with keys directly
## Audit Trail
Every on-chain transaction your wallet makes is recorded on the blockchain and visible through any block explorer. Agent Wallet does not maintain a separate proprietary logging layer — the blockchain itself is your audit trail.
To review your wallet's activity:
* Look up your wallet address on the relevant chain's block explorer (Etherscan, Basescan, Solscan, etc.)
* Every transaction includes sender, recipient, amount, token, timestamp, and transaction hash
* On-chain history is immutable and independently verifiable
This means your audit trail doesn't depend on Finance District — it's public, permanent, and cryptographically guaranteed by the blockchain.
## Redundancy and Key Safety
The system has built-in redundancy and backup procedures. Simple hardware failures do not result in key loss — the infrastructure is designed to survive individual component failures without interrupting service.
If you want additional peace of mind:
* **Export your keys** at any time through the Signer Service web interface
* **Back up exported keys** using your own secure storage (hardware wallet, encrypted backup, etc.)
* **Self-custody as fallback** — exported keys work with any standard wallet software
## Your Controls
You — the wallet owner — have full control at all times:
* **View activity** — check your transaction history on-chain via block explorers
* **Withdraw funds** — move your funds out of the wallet whenever you want
* **Export keys** — request a full key export through the Signer Service interface
* **Fund conservatively** — the [pocket money approach](/agent-wallet/concepts/trust) is your primary risk control
The non-custodial architecture means these controls are inherent to the design, not features that can be revoked. Your wallet is yours.
# Trust & Constraints
Source: https://developers.fd.xyz/agent-wallet/concepts/trust
The 'pocket money' philosophy — sensible constraints for AI agent financial autonomy.
How much financial autonomy should you give an AI agent? The answer is simpler than most people think.
## The Pocket Money Philosophy
Think of funding an agent wallet like giving pocket money. You put in what's appropriate for the task — not your entire portfolio. The agent operates autonomously within that scope. If something goes wrong, you lose the pocket money, not everything.
This is deliberately simpler than:
* **Complex policy engines** that require extensive configuration before your agent can do anything
* **Role-based permission systems** that add integration overhead and maintenance burden
* **Multi-approval workflows** that defeat the purpose of autonomous operation
The constraint **is** the balance. If you fund a wallet with \$50, the worst case is losing \$50. No policy engine needed. No configuration. The constraint is immediate, obvious, and enforced by the blockchain itself.
Don't give an agent more than you'd be comfortable losing. This one rule
handles 90% of trust decisions.
## How to Think About Funding
**Start small.** Always. Fund what you need for the immediate task, see how the agent performs, and increase as you gain confidence.
**Match funding to the task.** A research agent that buys API access needs \$10–50. A trading agent running a strategy might need \$500. An enterprise payment agent might need more. Let the task dictate the amount.
**Refill rather than pre-fund.** It's better to add \$100 five times than to deposit \$500 upfront. Each refill is a checkpoint — a moment to review what the agent did with the previous funds.
## Setting Constraints
### Balance Is the Primary Constraint
The amount in the wallet is the most powerful constraint you have. It's:
* **Enforced by the blockchain** — the agent literally cannot spend more than what's in the wallet
* **Immediately effective** — no configuration, no policy language, no deployment
* **Transparent** — you can check the balance at any time via any block explorer
* **Universal** — works the same regardless of which interface the agent uses
### Progressive Trust
1. **Small real funds** — Fund with \$10–50. Verify the agent does what you expect.
2. **Working amount** — Once you trust the behavior, fund what the use case actually needs.
3. **Scale up** — Increase funding as the agent proves itself over time.
Each step is a conscious decision. There's no automation that escalates trust — you decide when to increase the balance.
## Trust Patterns by Use Case
| Use Case | Suggested Funding | Constraints | Wallet Level |
| - | - | - | - |
| Testing and exploration | Test tokens (free) | None — let it experiment | EOA |
| Agent buying API access | \$10–50 | Fund per session | EOA |
| Bot making small purchases | \$100–500 | Refill periodically | EOA |
| Agent with recurring tasks | \$500–2,000 | Review activity weekly | EOA |
| Multi-agent deployment | Per-agent budgets | Individual funding per agent | EOA |
| Higher-value production | Task-appropriate | Consider Smart Account for added controls | Smart Account |
| Enterprise with approval needs | Custom | Granular permissions, multi-party control | Delegated |
Most entries in this table are EOA — because most agent use cases work perfectly with just sensible balance management.
## When Simple Constraints Aren't Enough
The pocket money approach works for the vast majority of use cases. But some scenarios call for more:
**You need batch transactions or gas abstraction** → [Smart Account](/agent-wallet/wallet-architecture#level-2-smart-account) adds programmable on-chain logic, session keys, and gas sponsorship.
**You need on-chain spending limits** → [Delegated wallet](/agent-wallet/wallet-architecture#level-3-delegated-wallet) adds granular spending controls enforced by the smart contract itself.
**You need multi-party approval** → Delegated wallets support approval workflows for high-value operations.
The key principle: don't over-engineer trust controls before you need them. Start with sensible funding. Upgrade only when the use case genuinely demands it.
## Common Mistakes
**Over-funding early.** Developers deposit large amounts "to avoid having to refill." This removes the natural safety net. Fund small, refill often.
**Over-engineering controls.** Building complex permission systems before you've validated the agent's behavior. Start with pocket money. Add controls when you have real data on what the agent does.
**Under-monitoring.** The pocket money approach doesn't mean "fund and forget." Check your wallet's on-chain activity periodically. Block explorers make this trivial.
**Treating all agents the same.** A research agent and a trading agent have very different risk profiles. Fund each according to its purpose, not with a blanket amount.
# X402 Payments
Source: https://developers.fd.xyz/agent-wallet/concepts/x402-payments
Multi-chain, multi-asset x402 payments — Agent Wallet's implementation of the x402 protocol for autonomous agent commerce.
Agent Wallet implements [x402 specification v2](https://www.x402.org/) — the open protocol for machine-to-machine stablecoin payments over HTTP. This page covers what Agent Wallet provides and how it differs from other x402 implementations. For a full protocol explainer, see the [x402 official documentation](https://www.x402.org/).
## What Agent Wallet Provides
Most x402 implementations support a single stablecoin on a single chain (typically USDC on Base). Agent Wallet supports **multiple assets across multiple chains**:
| Stablecoin | Supported Chains |
| - | - |
| **USDC** | Base |
| **FDUSD** | BSC, Arbitrum, Ethereum |
**Coming soon:** FDUSD support on SUI.
Your agent's wallet needs to hold the required stablecoin on the chain the merchant accepts. When a merchant supports multiple options, the wallet selects the best match from what's available in your balance.
## x402 Tools
Agent Wallet provides two tools for x402 payments, available through both the [CLI](/agent-wallet/ai-integration/cli) and the [MCP server](/agent-wallet/ai-integration/mcp-server). Which one to use depends on the agent's environment and capabilities.
### authorizePayment (Recommended)
Signs the payment authorization only — the agent handles the HTTP communication with the resource server itself.
**How it works:**
1. Agent calls the resource server and receives HTTP `402 Payment Required` with payment requirements (`accepts[]` array with chain, token, amount, recipient)
2. Agent passes the requirements to `authorizePayment` — the wallet selects the best payment option from the agent's balance and signs an [EIP-3009](https://eips.ethereum.org/EIPS/eip-3009) `transferWithAuthorization`
3. Agent retries the original request with the signed `PaymentPayload` attached
4. The resource server's facilitator verifies and settles the payment on-chain
This gives the agent **maximum autonomy**. The agent understands what's happening at each step, makes its own decisions about whether to pay, and handles the HTTP communication directly. The wallet's role is limited to what it should be: signing the payment authorization.
EIP-3009 means the payment is **gasless for the payer** — the facilitator executes the on-chain transfer, not the agent's wallet.
When using the [Finance District CLI Skills](/agent-wallet/ai-integration/agent-skills), the skill teaches the agent the full x402 protocol flow and guides it to use `authorizePayment` at the right step.
### getX402Content (Fallback)
Bundles the entire x402 flow — initial HTTP request, authorization signing, and retry — into a single call. The agent provides the resource URL, and the wallet handles everything internally.
Use this when the agent **cannot make HTTP requests directly** (e.g. web-based AI assistants like Claude Desktop or Cursor that have MCP access but cannot execute shell commands or make outbound HTTP calls).
### Choosing the Right Tool
| Tool | Agent handles HTTP | Best for |
| - | - | - |
| **authorizePayment** | Yes | Agents with HTTP access — Claude Code, OpenClaw, autonomous agents, agent frameworks |
| **getX402Content** | No | Agents without HTTP access — Claude Desktop, Cursor, web-based assistants |
## Try It Out
**With `authorizePayment`:**
> "Access the premium data API at [https://api.example.com/market-data](https://api.example.com/market-data)"
The agent handles the 402 response, requests payment signing from the wallet, and retries with proof.
**With `getX402Content`:**
> "Pay for the API at [https://api.example.com/market-data](https://api.example.com/market-data)"
The wallet handles the full flow and returns the content.
**Direct payment:**
> "Pay 2 USDC to 0xABC...123 on Base"
The agent can also make explicit payments to known addresses without encountering a 402 flow.
## Agent Wallet + Prism
X402 is where the two Finance District products meet:
* **Agent Wallet** is the buyer side — your agent has funds and wants to pay for services
* **[Prism](/prism/overview)** is the seller side — merchants accept stablecoin payments from AI agents
When an Agent Wallet pays a Prism merchant via x402, the transaction stays within one ecosystem. The agent pays, Prism verifies, the merchant gets their funds.
Learn how merchants accept agent payments
How Prism implements x402 on the merchant side
Install the skills that teach agents x402
Official x402 protocol specification
# Overview
Source: https://developers.fd.xyz/agent-wallet/overview
Agent Wallet — AI-native wallet infrastructure. Give your AI agents genuine financial autonomy.
Agent Wallet is AI-native wallet infrastructure that gives AI agents their own wallets — not borrowed access to a human's. Every user gets EVM, Solana, Bitcoin, and Sui wallets provisioned automatically at signup, with full capabilities out of the box: transfers, swaps, yield generation, and commerce protocol payments. Private keys are secured in a Trusted Execution Environment (TEE), and the architecture is non-custodial — operators maintain ultimate control at all times.
Unlike connecting an AI to an existing human wallet, Agent Wallet is built for agents from day one. It's optimized for agentic workflows, assisted conversations, and autonomous financial operations — so the experience is smooth whether an agent is executing a multi-step trade or a user is chatting with an AI assistant.
## Why AI-Native Matters
Today, if your AI agent needs to handle money, you have three options:
| Approach | How It Works | Limitation |
| - | - | - |
| **Human wallet + AI wrapper** | Agent connects to a user's MetaMask or Coinbase via API | No true autonomy — the human remains the wallet owner |
| **DIY wallet** | A few lines of code to create an address, keys in env vars | Insecure, limited to basic transfers, no production path |
| **AI-native (Agent Wallet)** | Agent gets its own wallet, operates within defined constraints | Genuine autonomy with production-grade security |
The DIY approach gets you basic transfers, but swaps, yield, commerce payments, and secure key management aren't included — each one is a significant engineering effort.
Agent Wallet provides all of this out of the box, with [TEE-secured key management](/agent-wallet/concepts/security), so you can focus on what your agent does rather than building financial infrastructure.
## Four Interfaces, One Wallet
Agent Wallet is infrastructure — a core service exposed through multiple interfaces. All four connect to the same underlying wallet and capabilities.
| Interface | Primary User | Best For |
| - | - | - |
| **[MCP Server](/agent-wallet/ai-integration/mcp-server)** | AI agents and assistants | Any MCP-compatible client — Claude, Cursor, n8n, custom agents |
| **[CLI](/agent-wallet/ai-integration/cli)** | Developers and autonomous agents | Terminal-based workflows, scripting, server-side automation |
| **[AI Assistant](/agent-wallet/ai-integration/ai-assistant)** | Humans (non-technical) | Conversational web interface for wallet management |
| **Web App** | Operators | Traditional wallet UI — manage wallets and view balances |
The MCP Server is the primary integration point for AI agents. The CLI is a lightweight wrapper around an MCP client — same capabilities, accessible from the command line. The AI Assistant and Web App serve humans who need to manage or monitor wallets directly.
## Core Capabilities
When you sign up, EVM, Solana, Bitcoin, and Sui wallets are provisioned for you automatically — no extra steps required. From there, your agent (or you) can:
* **Send & Receive** — Transfer tokens to any address on supported chains
* **Check Balances** — View holdings across all provisioned wallets
* **Swap** — Exchange between token pairs with best-rate routing
* **Earn Yield** — Explore yield opportunities and deploy funds to vaults
* **Commerce Payments** — Pay Prism-enabled merchants via x402 and other commerce protocols
All capabilities are available through MCP, CLI, and AI Assistant. The Web App provides additional management features like wallet configuration.
Agent Wallet supports EVM chains (Ethereum, Base, Polygon, Arbitrum, Optimism, BSC, Avalanche, Linea), Solana, Bitcoin, and Sui. Wallets for all are created by default for every user.
## Get Started
Create your first agent wallet and connect via MCP
Connect your AI agent to the hosted MCP server
Install the CLI for terminal-based agent workflows
TEE key management and non-custodial architecture
# Quick Start
Source: https://developers.fd.xyz/agent-wallet/quickstart
Get a non-custodial agent wallet in under 2 minutes. No blockchain knowledge required.
Sign up with your email, and EVM, Solana, Bitcoin, and Sui wallets are provisioned automatically — no seed phrases to manage. This guide connects that wallet to your AI client so your agent can start transacting.
The video starts from scratch — it also covers [creating a District
Pass](/overview/district-pass) and funding the wallet from an external wallet,
which this page assumes you've already done. Jump to
[05:56](https://youtu.be/JObnfc-jW78?t=356) for the MCP and CLI setup below.
## Connect Your AI Agent
Add the Finance District MCP server to your AI client. Works with Claude Desktop, Claude Code, Hermes Agent, Cursor, and any MCP-compatible client.
Opens Claude Desktop's connector settings
Or add manually:
In Claude Desktop, go to **Settings → Customize → Connectors**, click **+** and select **Add custom connector**.
* **Name:** `Finance District`
* **Remote MCP server URL:** `https://wallet-mcp.fd.xyz`
Sign in with your **District Pass** when prompted and authorize access.
Connect your Finance District Agent Wallet to **Claude Code** so the agent can check balances, transfer tokens, swap, earn yield, and make x402 payments — directly from your terminal or IDE sessions.
### Prerequisites
1. **Install Claude Code** — follow the [official guide](https://docs.anthropic.com/en/docs/claude-code/overview) and confirm it works:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude --version
```
2. **Create a District Pass account** — sign up at [apps.fd.xyz](https://apps.fd.xyz/). You'll use it to authorize the wallet connection.
### How to add
Run the command in your **terminal** (PowerShell, bash, or zsh):
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude mcp add finance-district --transport http https://wallet-mcp.fd.xyz
```
To make the wallet available across **all** your projects, add the user scope:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude mcp add --transport http --scope user finance-district https://wallet-mcp.fd.xyz
```
Verify the server is registered:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude mcp list
```
`finance-district` will appear as `! Needs authentication`. This is expected — registering only adds the server; it does **not** sign you in yet.
### What to do after adding
1. **Authenticate** — start Claude Code (`claude`), then either:
* Run `/mcp` inside the session, select **finance-district**, and choose **Authenticate**, or
* Simply ask the agent to use a wallet tool — the browser OAuth flow triggers on first use.
2. **Authorize with District Pass** — your browser opens for OAuth authorization. Sign in and authorize access. The status flips to `✔ Connected` and the session persists across restarts.
3. **Test it** — ask the agent:
> What Finance District wallet tools do you have? Call `getMyInfo` to show my account.
You should see the wallet tools listed and your account details returned.
Add Finance District MCP to your Hermes Agent config file (`~/.hermes/config.yaml`):
```yaml theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
mcp_servers:
finance_district:
url: "https://wallet-mcp.fd.xyz"
auth: oauth
```
Inside Hermes Agent, run `/reload-mcp`.
Choose which Finance District wallet tools to enable from the checklist and confirm.
Open **Cursor Settings → MCP Servers → Add new server** and paste:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
Restart Cursor.
For any MCP-compatible client (Windsurf, n8n, custom agents), add this configuration:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district": {
"type": "streamable-http",
"url": "https://wallet-mcp.fd.xyz"
}
}
}
```
See [MCP Compatible Clients](/agent-wallet/ai-integration/mcp-clients) for client-specific config file paths, Windsurf and n8n setup, and custom MCP client integration (CIMD / DCR).
On first connection, your browser opens for OAuth authorization. Sign in with your [District Pass](/overview/district-pass) (if you aren't already) and authorize the client to access your Finance District account. Once authorized, the connection persists across sessions.
For client-specific setup instructions, see [MCP Compatible Clients](/agent-wallet/ai-integration/mcp-clients).
## Verify
Ask your agent:
> "Connect to Finance District MCP and show me my wallet information."
The agent should return your wallet addresses across all supported chains. Then try:
> "What's my wallet balance?"
If you see your balances (even if zero), you're fully connected.
For the best agent experience, optionally add the [Agent Wallet Skills](/agent-wallet/ai-integration/agent-skills) to your client. Skills give the agent curated prompt templates and pre-built workflows for common wallet operations — transfers, swaps, yield, and more.
## Try It Out
Once set up, your agent can:
* **Check balances** across Ethereum, Base, Arbitrum, BSC, Solana, Bitcoin, and Sui
* **Send tokens** to any address on any supported chain
* **Swap tokens** via decentralized exchanges
* **Earn yield** through integrated DeFi protocols
* **Pay for services** via the [x402 payment protocol](/agent-wallet/concepts/x402-payments)
Start with a small amount to experiment and verify your agent's behavior before scaling up.
## What's Next?
Full CLI reference and agent framework integration
Drop-in skills for 40+ agentic platforms
Full MCP server documentation and capabilities
Let your agent pay for services automatically
Ethereum, Base, Arbitrum, BSC, Solana, Bitcoin, Sui
Non-custodial architecture with TEE key protection
# Example Prompts
Source: https://developers.fd.xyz/agent-wallet/resources/example-prompts
Ready-to-use prompts for Agent Wallet — copy, paste, go.
Copy-paste prompts for MCP-connected agents and the AI Assistant. [FDX CLI](/agent-wallet/ai-integration/cli) equivalents included where applicable.
## Wallet Basics
**Check balance:**
> "What's my wallet balance?"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet getWalletOverview --chainKey ethereum
```
**Check specific token:**
> "How much USDC do I have?"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet getWalletOverview --chainKey base
```
**Get wallet address:**
> "What's my wallet address on Base?"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet getMyInfo
```
**View supported chains:**
> "What chains does my wallet support?"
## Transfers
**Send tokens:**
> "Send 5 USDC to 0x1234...5678"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet transferTokens --chainKey ethereum --toAddress 0x1234...5678 --amount 5 --asset USDC
```
**Send on a specific chain:**
> "Send 10 USDC to 0x1234...5678 on Base"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet transferTokens --chainKey base --toAddress 0x1234...5678 --amount 10 --asset USDC
```
**Transfer with confirmation:**
> "Send 50 USDC to 0xABC...DEF — confirm before executing"
## Swaps
**Simple swap:**
> "Swap 10 USDC for ETH"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet swapTokens --chainKey ethereum --tokenIn USDC --tokenOut ETH --amount 10
```
**Check quote first:**
> "How much ETH would I get for 50 USDC?"
**Swap with conditions:**
> "Swap 100 USDC for ETH, but only if the rate is better than 0.0003 ETH per USDC"
## Yield
**Explore opportunities:**
> "What yield opportunities are available for my USDC?"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet discoverYieldStrategies --chainKey base
```
**Deploy to yield:**
> "Put 100 USDC into the best yield opportunity"
**Check yield status:**
> "How are my yield positions performing?"
## Commerce Payments
**Pay a merchant:**
> "Pay 2 USDC to the merchant at 0xABC...123 on Base"
**Access a paid API:**
> "Access the premium data API at [https://api.example.com/market-data](https://api.example.com/market-data)"
The agent handles the x402 payment flow automatically — it encounters the 402 response, pays, and retrieves the data.
## Transaction History
**Recent transactions:**
> "Show my last 5 transactions"
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
fdx wallet getAccountActivity --accountAddress 0x1234...5678 --chainKey ethereum
```
**Spending summary:**
> "How much have I spent this week?"
**Filter by type:**
> "Show all my swaps from the last 7 days"
## Multi-Step Operations
These prompts ask the agent to reason and execute multiple steps:
**Conditional transfer:**
> "If I have more than 100 USDC, send 50 to 0x1234...5678"
**Research and swap:**
> "Check the current ETH price. If it's below \$2,500, swap 50 USDC for ETH."
**Portfolio check:**
> "Show me my complete portfolio — balances across all chains and tokens"
**Multi-chain overview:**
> "What's my total USDC balance across all chains?"
## Tips for Effective Prompts
**Be specific about tokens and amounts.** "Send 5 USDC" is better than "send some money."
**Specify chains when it matters.** "Send USDC on Base" avoids ambiguity when you hold USDC on multiple chains.
**Ask for confirmation on large amounts.** "Swap 500 USDC for ETH — confirm before executing" gives you a chance to review.
**Use natural language.** The agent understands context. "Check my balance and swap half my USDC for ETH" works fine.
# Supported Networks
Source: https://developers.fd.xyz/agent-wallet/supported-networks
26 chains across EVM, Solana, Bitcoin, and Sui — each on a named endpoint.
Agent Wallet supports 26 chains across four ecosystems. When you create a District Pass, wallets for every ecosystem are provisioned automatically — one identity, every chain below.
The list is explicit. A chain that is not on it is refused up front with `INVALID_CHAIN`, rather than accepted and failed at the point of signing.
## How chains are served
Every chain resolves to exactly one endpoint, and endpoints come in two tiers.
| Tier | What it means |
| - | - |
| **Dedicated** | A paid, authenticated node reserved for Finance District. Consistent latency and throughput, and the tier we recommend for production volume. |
| **Best-effort** | The chain's own public endpoint, operated by the team that runs the chain — Optimism's `mainnet.optimism.io`, Avalanche's `api.avax.network`, and so on. Correct and current, but rate-limited and offered without an availability guarantee. |
A chain never silently moves between tiers. If its endpoint is unavailable the call fails and says so, rather than quietly falling back to an unknown node.
## Mainnet
| `chainKey` | Network | Ecosystem | Tier |
| - | - | - | - |
| `1` | Ethereum | EVM | Dedicated |
| `137` | Polygon | EVM | Dedicated |
| `56` | BNB Smart Chain | EVM | Dedicated |
| `8453` | Base | EVM | Dedicated |
| `42161` | Arbitrum One | EVM | Dedicated |
| `4663` | Robinhood Chain | EVM | Dedicated |
| `10` | OP Mainnet | EVM | Best-effort |
| `43114` | Avalanche C-Chain | EVM | Best-effort |
| `130` | Unichain | EVM | Best-effort |
| `143` | Monad | EVM | Best-effort |
| `solana` | Solana | Solana | Dedicated |
| `bitcoin` | Bitcoin | Bitcoin | Dedicated |
| `sui` | Sui | Sui | Dedicated |
## Testnet
| `chainKey` | Network | Ecosystem | Tier |
| - | - | - | - |
| `11155111` | Ethereum Sepolia | EVM | Dedicated |
| `80002` | Polygon Amoy | EVM | Dedicated |
| `97` | BNB Smart Chain Testnet | EVM | Dedicated |
| `84532` | Base Sepolia | EVM | Dedicated |
| `421614` | Arbitrum Sepolia | EVM | Best-effort |
| `11155420` | OP Sepolia | EVM | Best-effort |
| `43113` | Avalanche Fuji | EVM | Best-effort |
| `1301` | Unichain Sepolia | EVM | Best-effort |
| `46630` | Robinhood Chain Testnet | EVM | Best-effort |
| `10143` | Monad Testnet | EVM | Best-effort |
| `solana-devnet` | Solana Devnet | Solana | Best-effort |
| `bitcoin-testnet4` | Bitcoin Testnet4 | Bitcoin | Dedicated |
| `sui-testnet` | Sui Testnet | Sui | Dedicated |
**Monad Testnet: no transaction history.** `getAccountActivity` returns an empty list on
`10143`; the indexer behind it covers Monad mainnet only. Balances, transfers, pricing and
swaps behave normally on both Monad networks.
## Naming a chain
`chainKey` accepts any of these, case-insensitively:
`8453`, `137`, `42161`
`eip155:8453`, `eip155:137`
`Base`, `base`, `eth`, `arb1`, `pol`, `avax`, `btc`
`arb`, `op`, `matic`, `sol`, `fuji`
Aliases recognised for each chain:
| Network | Accepted names |
| - | - |
| Ethereum | `1`, `eth`, `ethereum`, `mainnet` |
| Polygon | `137`, `pol`, `polygon`, `poly`, `matic`, `polygonmainnet` |
| BNB Smart Chain | `56`, `bnb`, `bsc` |
| Base | `8453`, `base`, `basemainnet` |
| Arbitrum One | `42161`, `arb1`, `arb`, `arbitrum`, `arbitrumone` |
| OP Mainnet | `10`, `op`, `optimism` |
| Avalanche | `43114`, `avax`, `avalanche` |
| Unichain | `130`, `unichain` |
| Robinhood Chain | `4663`, `robinhoodchain`, `robinhoodmainnet` |
| Monad | `143`, `monad` |
| Solana | `solana`, `sol`, `solanamainnet` |
| Bitcoin | `bitcoin`, `btc` |
| Sui | `sui`, `suimainnet` |
| Ethereum Sepolia | `11155111`, `sep`, `sepolia`, `ethsepolia` |
| Polygon Amoy | `80002`, `polygonamoy` |
| BNB Testnet | `97`, `bnbt`, `bsc-testnet` |
| Base Sepolia | `84532`, `base-sep`, `basesepolia`, `basetestnet` |
| Arbitrum Sepolia | `421614`, `arb-sep`, `arbitrumsepolia` |
| OP Sepolia | `11155420`, `op-sep`, `opsepolia`, `optimismsepolia` |
| Avalanche Fuji | `43113`, `fuji`, `avalanchefuji` |
| Unichain Sepolia | `1301`, `unichain-sep`, `unichainsepolia` |
| Robinhood Testnet | `46630`, `rh-testnet`, `robinhoodtestnet` |
| Monad Testnet | `10143`, `monad-testnet`, `monadtestnet` |
| Solana Devnet | `solana-devnet`, `soldevnet`, `solanadevnet` |
| Bitcoin Testnet4 | `bitcoin-testnet4`, `btctestnet`, `btctestnet4`, `bitcointestnet` |
| Sui Testnet | `sui-testnet`, `suitestnet` |
## Need a chain that isn't here?
Ask for it. Use the `reportIssue` tool with `chain-request` in its `labels`, and the
request goes straight to the team that provisions endpoints.
Name the chain in the title. In the description, give the reasoning — **what you would do
on that chain, in what volume, and by when** — and the assets you need, since a chain with
no USDC deployment is a different piece of work from one with it. Report only what the
user actually told you; a chain name on its own is fine, and invented volumes are worse
than none.
Calling a tool with an unsupported `chainKey` already registers quiet interest, so you
are never penalised for trying. But an explicit `reportIssue` carries the reasoning, and
that is what gets acted on.
## Feature availability by ecosystem
| Feature | EVM | Solana | Bitcoin | Sui |
| - | - | - | - | - |
| Transfer tokens | ✓ | ✓ | ✓ | ✓ |
| Swap tokens | ✓ | ✓ | — | — |
| Yield (deposit / withdraw) | ✓ | — | — | — |
| Sign message (EIP-191 / EIP-712) | ✓ | — | — | — |
Yield tools (`discoverYieldStrategies`, `depositForYield`, `withdrawFromYield`) are EVM-only.
**Sui: transfers only.** Swap, yield, and message-signing tools are not available on Sui.
## Testing
Use a testnet from the table above to validate an integration end to end — every tool behaves identically to mainnet. Base Sepolia and Polygon Amoy are the best-covered, both on dedicated endpoints with faucet-funded tokens available.
# Wallet Architecture
Source: https://developers.fd.xyz/agent-wallet/wallet-architecture
A wallet architecture that scales with your agent — from a simple EOA to a fully programmable Smart Account.
Agent Wallet uses a progressive architecture: start with the simplest wallet type and add capabilities only when you need them. Most agent use cases — 90% or more — work perfectly with a basic EOA wallet. Smart Accounts and Delegated wallets exist for advanced scenarios, but you shouldn't reach for them until your use case demands it.
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
flowchart LR
L1["**Level 1: EOA Wallet**
Standard wallet
Hold, send, receive,
swap, yield, pay
_Default · EVM + Solana + Bitcoin + Sui_"] --> L2["**Level 2: Smart Account**
ERC-4337 smart contract
owned by your EOA
Batch tx, gas abstraction,
session keys
_Deploy when needed · EVM only_"] --> L3["**Level 3: Delegated**
Smart Account +
granular spending
controls and delegation
_Advanced use cases · EVM only_"]
```
## Level 1: EOA Wallet
Every user gets EOA (Externally Owned Account) wallets automatically when they create a District Pass — one for EVM-compatible chains, one for Solana, one for Bitcoin, and one for Sui. No deployment, no gas cost, no extra steps.
An EOA is a standard blockchain wallet controlled by a private key. In Agent Wallet, that key is generated and stored inside a TEE (Trusted Execution Environment) — never exposed to the host system, never stored in environment variables.
**Capabilities:**
* Hold tokens across all supported EVM chains, Solana, Bitcoin, and Sui
* Send and receive transfers
* Swap between token pairs
* Explore and deploy to yield vaults
* Pay Prism merchants via commerce protocols
* Full access through MCP, CLI, AI Assistant, and Web App
**Best for:** The vast majority of agent use cases. Testing, prototyping, production agents with moderate transaction volumes, personal wallets.
**Limitations:** Single signer (the TEE-held key), gas must be paid individually per transaction, no programmable on-chain rules.
The EOA wallet is your starting point and remains functional even after you
deploy a Smart Account. It becomes the **owner** of the Smart Account
contract.
## Level 2: Smart Account
A Smart Account is a lightweight ERC-4337 compatible smart contract account deployed on-chain, owned by your EOA wallet. It's based on Alchemy's widely-used and audited [LightAccount](https://github.com/alchemyplatform/light-account) contract.
The key distinction: your EOA wallet doesn't go away. It continues to function as before. The Smart Account is an **additional** on-chain account that your EOA controls as its owner.
**What this unlocks:**
* **Batch transactions** — execute multiple operations in a single atomic transaction
* **Gas abstraction** — sponsor gas fees or pay gas in tokens other than the chain's native token
* **Session keys** — grant time-limited, scoped access to specific operations
* **Programmable rules** — on-chain logic that governs what the account can do
* **ERC-4337 compatibility** — works with any platform or DeFi protocol that supports account abstraction
**Deployment:**
* Self-service — deploy via MCP Server, AI Assistant, or Web App
* You choose which chain(s) to deploy on (usually one or two chains where you need Smart Account features)
* Your EOA wallet must hold enough native tokens (ETH, MATIC, etc.) on that chain to pay for the contract deployment gas
* EVM only — Solana is not supported for Smart Accounts
**Best for:** Production agents that benefit from batched operations, gas abstraction, or session keys. Multi-step workflows where atomicity matters.
Smart Accounts are currently available to **select pilot users** only. If
you're interested in early access, [contact us](/overview/resources/support).
## Level 3: Delegated Wallet
A Delegated wallet is the same Smart Account contract with additional capabilities for granular spending control. Think of it as Level 2 with fine-grained permissions layered on top.
**What delegation adds:**
* **Spending limits** — cap how much an agent can spend per transaction, per day, or per time window
* **Token restrictions** — limit which tokens the account can interact with
* **Operation scoping** — restrict the types of operations allowed
* **Multi-party control** — require multiple approvals for high-value operations
**Best for:** High-value deployments, enterprise scenarios, and situations where you need precise control over what an agent is allowed to do on-chain.
Delegated wallets are currently available to **select pilot users** only.
## Choosing the Right Level
| Use Case | Recommended | Why |
| - | - | - |
| Testing and prototyping | EOA | Zero setup, works immediately |
| Single agent, standard operations | EOA | More than sufficient — most agents live here |
| Agent doing swaps, transfers, yield | EOA | All capabilities are available at Level 1 |
| Batched multi-step operations | Smart Account | Atomic execution, gas savings |
| Gas sponsorship for agents | Smart Account | Pay gas in stablecoins or sponsor from another account |
| Time-limited agent access | Smart Account | Session keys scope what the agent can do and when |
| Controlled spending budgets | Delegated | On-chain spending limits beyond the "pocket money" approach |
| Enterprise with approval workflows | Delegated | Multi-party control, granular permissions |
**The general guidance:** start with EOA. If you find yourself needing batch transactions, gas abstraction, or session keys, consider a Smart Account. If you need on-chain spending controls or multi-party approval, look at Delegated.
## How Upgrade Works
Upgrading doesn't replace your EOA — it adds a Smart Account alongside it:
1. Your **EOA wallet stays as-is** — same address, same balances, same functionality
2. You **deploy a Smart Account** on your chosen chain(s) via MCP, AI Assistant, or Web App
3. Your EOA becomes the **owner** of the Smart Account contract
4. You now have **two accounts**: your original EOA and the new Smart Account
5. Assets on the EOA remain on the EOA — you move what you need to the Smart Account
The Smart Account has its own address on each chain where it's deployed. You fund it by transferring from your EOA or from external sources.
Moving from Smart Account to Delegated is a configuration change on the same contract — no redeployment needed.
# Agent Wallet
Source: https://developers.fd.xyz/changelog/agent-wallet
Agent Wallet changelog — new features, improvements, and updates.
## June 30, 2026
### Payments (x402)
* `authorizePayment` now accepts `preferredAsset` and `preferredNetwork` — choose the settlement token and chain when a merchant offers several
* Hardened x402 authorization: the payment header is built from the server's 402 challenge rather than the request URL, and token metadata is now optional
### Security
* EVM transactions are now signed directly inside the secure enclave, removing an external signing dependency
* Expanded the signing audit trail (the original message and encoding are recorded), and signing requests now carry the end-user's IP and user-agent for stronger attribution
## June 9, 2026
### Yield
* New yield provider: **IXS** — APY sourced off-chain and refreshed on a schedule; a multi-provider architecture lets new strategies plug in, and `discoverYieldStrategies` now surfaces IXS alongside the existing on-chain options
* Vault-based strategies settle withdrawals asynchronously — the new `getRedemptionRequests` tool lets an agent track pending redemptions and their status
## June 5, 2026
### MCP Server
* Strengthened the server instructions and tool descriptions — including a trust-model summary — so agents call wallet tools more reliably
* Corrected read-only annotations on the tools that don't move funds
## May 26, 2026
### Networks
* **Sui support** (mainnet and testnet) — transfers, balances, and transaction history on Sui. Sui joins the EVM chains, Solana, and Bitcoin.
### Wallet
* Token resolution now resolves symbols from your own wallet balances and internal token sources — including Sui coin types — so you can refer to tokens by symbol instead of pasting a contract address
## March 31, 2026
### CLI v0.4.2
* Minimized npm package surface with `files` whitelist
## March 30, 2026
### CLI v0.4.1
* Persistent configuration via `~/.fdx/config.json`
* New `fdx config set|get|unset ` subcommands for managing CLI settings
* Config source labels in `fdx config` output: `(env)`, `(config)`, `(default)`
## March 16, 2026
### CLI v0.4.0
**Breaking changes** — see migration guide below.
* New `fdx wallet ` subcommand for Wallet MCP tools (transfers, swaps, yield, x402 payments)
* New `fdx prism ` subcommand for Prism MCP tools (payments, settlements, accounts)
* New `fdx services` command — list available services and their URLs
* Multi-service routing — CLI routes tool calls to Wallet or Prism based on subcommand
* Dynamic tool discovery — available methods are fetched from each MCP server at runtime
* New environment variables: `FDX_WALLET_MCP_URL` / `FDX_PRISM_MCP_URL` for per-service URL overrides
**Breaking changes:**
* `fdx call ` is deprecated — use `fdx wallet ` or `fdx prism ` instead
* `WalletClient` renamed to `FdxClient` in SDK exports (no backward-compat alias)
* `FDX_MCP_SERVER` env var deprecated — use `FDX_WALLET_MCP_URL` / `FDX_PRISM_MCP_URL`
**Migration:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Before (v0.3.x)
fdx call getWalletOverview --chainKey ethereum
# After (v0.4.0+)
fdx wallet getWalletOverview --chainKey ethereum
fdx prism listPayments # Prism tools
fdx services # list available services
```
***
## February 28, 2026
### CLI
* Replaced Device Authorization Grant with email OTP — authentication is now fully headless, no browser required
* New auth commands: `fdx register --email `, `fdx login --email `, `fdx verify --code `
* Pending verification state is persisted to the OS credential store and survives between CLI invocations
* Expired access tokens are now refreshed automatically using the stored refresh token
* Windows PowerShell rendering fixed — spinner and checkmarks now use ASCII characters and display correctly
## February 24, 2026
### CLI
* `fdx login` introduced as the primary authentication command (`fdx setup` remains a hidden backward-compatible alias)
* `fdx call --help` now shows required and optional parameters, types, descriptions, and a usage example for each tool
* "Did you mean?" fuzzy matching for mistyped or partially typed method names
* `fdx call` groups tools into categories: Wallet, Transfer, Swap, Yield, Payment, Account, Support
* CLI arguments are automatically coerced to the correct type (numbers, integers) based on the tool schema
* New `getTokenPrice` tool — look up the current USD price and 24h change for any token
* New `resolveNameService` tool — resolve ENS (`.eth`), SNS (`.sol`), and Unstoppable Domain names to addresses and vice versa
* Updated tool parameter signatures for `transferTokens`, `depositForYield`, `withdrawFromYield`, `authorizePayment`, `getAccountActivity`, and `discoverYieldStrategies`
* Removed `deploySmartAccount` and `manageSmartAccountOwnership` tools
## February 19, 2026
### CLI
* Switched authentication to Device Authorization Grant (RFC 8628) — `fdx setup` no longer opens a browser; authentication happens via device code
* Added HTTPS validation for all discovered OAuth endpoints
* Improved error handling for expired OS credential store sessions and missing refresh tokens
* Fixed a bug where `null` client ID was sent as a literal string `"null"` during token refresh
## February 17, 2026
### Documentation Launch
* Full Agent Wallet documentation published in the Developer Hub
* [Wallet Architecture](/agent-wallet/wallet-architecture) — Progressive EOA → Smart Account → Delegated architecture
* [Security Model](/agent-wallet/concepts/security) — TEE key management with AWS Nitro Enclaves
* [Trust & Risk](/agent-wallet/concepts/trust) — Pocket money philosophy and progressive trust
### MCP Server
* MCP Server documentation for connecting AI agents via Model Context Protocol
* Client setup guides for Claude Desktop, Cursor, Windsurf, and custom clients
* [Agent Skills](/agent-wallet/ai-integration/agent-skills) reference covering all wallet capabilities
### Interfaces
* [CLI](/agent-wallet/ai-integration/cli) documentation with full command reference
* [AI Assistant](/agent-wallet/ai-integration/ai-assistant) guide for the conversational wallet interface
* [Example Prompts](/agent-wallet/resources/example-prompts) — ready-to-use prompts for common tasks
### Advanced
* [Multi-Wallet Strategy](/agent-wallet/advanced/multi-agent) patterns for multi-wallet deployments
# Changelog
Source: https://developers.fd.xyz/changelog/overview
Product updates, new features, and improvements across Finance District.
Stay up to date with the latest changes across Finance District products. Select a product from the sidebar to see its changelog.
Updates to AI-native wallet infrastructure, MCP server, and interfaces.
Updates to the payment gateway, SDKs, commerce protocols, and API.
# Prism
Source: https://developers.fd.xyz/changelog/prism
Prism changelog — new features, improvements, and updates.
## October 2026
### UCP version in the path
* New public route `GET /ucp/{ucpVersion}/handlers` needs no API key and returns the `2026-10-07` handler for UCP `2026-01-23`, `2026-04-08` and `2026-08-25`
* New route `POST /api/v2/merchant/payment-requirements` returns the raw x402 PaymentRequired object with no protocol wrapper. It needs the API key and does not depend on the UCP version. The merchant builds the UCP checkout entry `{id, version, config}` from the handlers declaration and this object
* ACP merchants use the same `POST /api/v2/merchant/payment-requirements` and compose the handler from `GET /api/v2/merchant/acp/handlers` (needs the API key). The handler JSON in checkout sessions is unchanged
* An unsupported UCP version returns `422 version_unsupported`
* See [Prism contract selection](/prism/integrations/ucp/supported-versions#prism-contract-selection)
***
## July 2026
### E-commerce Platform Integrations
* Official open-source plugins that make your store agent-payable: **Saleor**, **Medusa**, **Shopware**, **PrestaShop**, and **WooCommerce**
* Each makes your store discoverable and purchasable by AI agents over UCP (and ACP where supported), settling on-chain via the `xyz.fd.prism_payment` handler
* New docs: [E-commerce Platforms](/prism/platforms) and [Custom Integrations](/prism/platforms/custom)
***
## May 2026
### ACP Support
* [ACP integration](/prism/integrations/acp) live with the `xyz.fd.prism_payment` payment handler
* Gateway endpoints for the ACP payment-requirements flow and handler schema
* [Merchant](/prism/integrations/acp/merchants) and [agent](/prism/integrations/acp/agents) integration guides, plus an [end-to-end flow](/prism/integrations/acp/flows)
***
## March 2026
### UCP Support
* [UCP integration](/prism/integrations/ucp) live with payment handler `xyz.fd.prism_payment`
* [Merchant endpoints](/prism/api-reference/endpoints#merchant) for payment profile discovery and checkout preparation
* [Gateway endpoints](/prism/api-reference/endpoints#gateway) serving public UCP handler schema and spec
***
## February 17, 2026
### Documentation Launch
* Full Prism documentation published in the Developer Hub
* [How It Works](/prism/concepts/how-it-works) — Two-layer architecture (Prism orchestration + Spectrum settlement)
* [Commerce Protocols](/prism/concepts/commerce-protocols) — the x402, UCP, and ACP landscape and how Prism abstracts them
### x402 Protocol
* [x402 Documentation](/prism/integrations/x402) — Complete protocol flow, payment requirements, pricing models
* HTTP 402 machine-to-machine stablecoin payments live on all supported chains
### SDK Integration
* Server-side SDK guides for TypeScript ([Express](/prism/sdk/typescript/express), [NestJS](/prism/sdk/typescript/nestjs), [Next.js](/prism/sdk/typescript/nextjs), [Fastify](/prism/sdk/typescript/fastify)), Python ([FastAPI](/prism/sdk/python/fastapi), [Flask](/prism/sdk/python/flask), [Django](/prism/sdk/python/django)), and Java ([Spring Boot](/prism/sdk/java/servlet))
* `@1stdigital/prism-express` package documented with middleware configuration
### API Reference
* [Prism Gateway API](/prism/api-reference/introduction) documented at `prism-gw.fd.xyz`
* [Endpoints](/prism/api-reference/endpoints) — x402 settlement, merchant checkout, and gateway reference
### Production
* [Prism Console](/prism/production/console) guide for merchant dashboard at `apps.fd.xyz/prism/`
* [Network Support](/prism/production/network-support) — Ethereum, Base, BSC, Arbitrum
# AI Tools
Source: https://developers.fd.xyz/overview/developer-tools/ai-tools
Give your coding assistant full context on Prism, Agent Wallet, and x402 while you build.
Every page in this Developer Hub is available in machine-readable formats. Point your AI tool at the right endpoint and it can answer questions about SDK integration, payment flows, and wallet architecture without you leaving your editor.
## llms.txt
The Developer Hub publishes [llms.txt](https://llmstxt.org/) files — a standard format for giving LLMs structured knowledge about a site.
| File | Description |
| - | - |
| [`/llms.txt`](https://developers.fd.xyz/llms.txt) | Index of all pages with titles and descriptions |
| [`/llms-full.txt`](https://developers.fd.xyz/llms-full.txt) | Full content of every page in a single file |
### How to use
**In a system prompt or custom instruction:**
```
Reference the Finance District developer documentation at:
https://developers.fd.xyz/llms-full.txt
```
**In Claude Code or Claude Projects:**
Add the llms-full.txt URL as a project knowledge source. Claude will then have complete context about all Finance District APIs, SDKs, and integration patterns.
**In ChatGPT or any LLM:**
Paste the URL or the contents of `llms-full.txt` into the conversation when asking for integration help.
## Docs MCP Server
Every page in the Developer Hub is also available through an MCP server. This lets AI tools query the documentation dynamically rather than loading all of it up front.
### Cursor
In Cursor Settings → MCP Servers, add:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district-docs": {
"url": "https://developers.fd.xyz/mcp"
}
}
}
```
Cursor will be able to search and retrieve relevant documentation pages on demand as you work.
### Claude Code
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
claude mcp add fd-docs --transport http https://developers.fd.xyz/mcp
```
### VS Code (GitHub Copilot)
In your VS Code MCP configuration (`.vscode/mcp.json`):
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"servers": {
"finance-district-docs": {
"type": "http",
"url": "https://developers.fd.xyz/mcp"
}
}
}
```
### Windsurf
In Windsurf Settings → MCP Configuration:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"finance-district-docs": {
"url": "https://developers.fd.xyz/mcp"
}
}
}
```
## Per-Page Contextual Actions
Every page in the Developer Hub has contextual actions in the top-right corner. Use these to quickly pipe content to your preferred AI tool:
* **Copy as Markdown** — Copy the page content in a format LLMs understand well
* **Open in ChatGPT / Claude / Perplexity** — Opens a new conversation pre-loaded with the page content
* **Open in Cursor / VS Code** — Adds the page as context in your editor's AI chat
* **Connect via MCP** — Get the MCP server configuration for your tool
These are the fastest way to get a single page into your AI tool's context.
## Tips for AI-Assisted Development
* **Start with llms-full.txt** for broad context — it's a single file with everything. Use the MCP server when you want your tool to search docs dynamically.
* **Include your SDK package** (`@1stdigital/prism-express`, `@1stdigital/prism-nestjs`, etc.) in the AI tool's context alongside the docs. The type definitions contain detailed documentation.
* **Reference the [x402 specification](https://www.x402.org/)** alongside FD docs for protocol-aware code generation.
* **Ask for test generation** — an AI tool with full docs context can generate test cases covering the 402 response → payment → verification flow.
Looking to connect your AI agent to Agent Wallet capabilities (wallets,
balances, transactions)? That's a different MCP server. See [MCP Compatible
Clients](/agent-wallet/ai-integration/mcp-clients) for Agent Wallet MCP setup.
# Testnet Faucet
Source: https://developers.fd.xyz/overview/developer-tools/faucet
Get free testnet stablecoins to build and test without spending real money.
The [First Digital Labs Testnet Faucet](https://www.firstdigitallabs.com/testnet-faucet) dispenses test FDUSD and other tokens on supported testnets. Use them to test Prism integrations and Agent Wallet transactions end to end.
Get test FDUSD and other stablecoins on supported testnet chains
## Getting Test Tokens
1. Visit the [First Digital Labs Testnet Faucet](https://www.firstdigitallabs.com/testnet-faucet)
2. Enter your wallet address (your Agent Wallet address or any testnet address)
3. Select the token and testnet chain
4. Request tokens
Tokens typically arrive within a few seconds on testnet chains.
## Using Test Tokens
**Testing Prism integrations:**
* Set up your SDK middleware with testnet chain IDs (e.g., Base Sepolia: `84532`)
* Use test stablecoins to simulate the full x402 payment flow
* Webhooks fire normally on testnet — test your full payment pipeline
**Testing Agent Wallet:**
* Fund your agent wallet with test stablecoins
* Test transfers, swaps, and commerce payments without risk
## Testnet Chains
| Testnet | Chain ID | Mainnet Equivalent |
| - | - | - |
| Ethereum Sepolia | 11155111 | Ethereum |
| Base Sepolia | 84532 | Base |
| BSC Testnet | 97 | BSC |
| Arbitrum Sepolia | 421614 | Arbitrum |
For native gas tokens (testnet ETH, etc.), use the respective chain faucets (e.g., [Base Sepolia Faucet](https://www.coinbase.com/faucets/base-ethereum-goerli-faucet)).
## Other Faucets
Beyond test FDUSD, you'll likely need native gas tokens and other test tokens. These directories list faucets across chains:
| Resource | Description |
| - | - |
| [Alchemy Faucets](https://www.alchemy.com/faucets) | Faucets for Ethereum Sepolia, Base Sepolia, Arbitrum Sepolia, and more |
| [Chainlink Faucets](https://faucets.chain.link/) | Multi-chain faucet — testnet ETH, LINK, and native gas tokens |
| [QuickNode Faucets](https://faucet.quicknode.com/) | Aggregated faucets for major testnets |
| [Coinbase Base Faucet](https://www.coinbase.com/faucets/base-ethereum-goerli-faucet) | Base Sepolia ETH |
| [BNB Chain Faucet](https://www.bnbchain.org/en/testnet-faucet) | BSC Testnet BNB |
# District Pass
Source: https://developers.fd.xyz/overview/district-pass
One account for everything in Finance District. Sign up with just an email.
District Pass is your single identity across Agent Wallet, Prism, and the rest of the ecosystem. No KYC, no wallet connection, no complex onboarding.
## Sign Up
There are two ways to create a District Pass, depending on whether you're a human developer or an autonomous agent.
### For Humans
Use the web app for interactive, browser-based signup.
Visit [apps.fd.xyz](https://apps.fd.xyz/) or
[apps.fd.xyz/district-pass](https://apps.fd.xyz/district-pass/) to create
your District Pass.
Provide your email address. A confirmation code will be sent to your inbox.
Enter the confirmation code. Your District Pass is now active.
EVM, Solana, Bitcoin, and Sui wallets are created for you automatically — no extra steps
required.
That's it. You now have a District Pass with wallets ready to use across Agent Wallet and Prism.
Prefer to watch? See this signup flow at
[00:00](https://youtu.be/JObnfc-jW78) in the Agent Wallet setup tutorial.
### For Autonomous Agents
Agents operating headlessly — in Docker containers, CI pipelines, or remote servers — register using the [Agent Wallet CLI](/agent-wallet/ai-integration/cli). No browser required. The entire flow runs via email OTP from the command line.
`bash npm install -g @financedistrict/fdx `
`bash fdx register --email you@example.com `
Enter the 8-digit code sent to your inbox: `bash fdx verify --code
12345678 `
`bash fdx status ` Wallets are provisioned automatically upon successful
registration.
## Authentication
District Pass can be used for secure authentication across all interfaces:
* **MCP clients** (Claude Code, Cursor, etc.) — When connecting to the Agent Wallet MCP server, you'll be prompted to authenticate via browser. The MCP client handles the flow automatically.
* **FDX CLI** — Run `fdx login --email ` followed by `fdx verify --code ` to authenticate via email OTP. Tokens are stored securely in the OS credential store.
* **Web App & AI Assistant** — Standard email-based login at [apps.fd.xyz](https://apps.fd.xyz).
* **Prism Console** — Log in at [apps.fd.xyz/prism](https://apps.fd.xyz/prism/) with your District Pass credentials.
Tokens are managed automatically by each interface — you don't need to handle authentication details directly.
## Identity Philosophy
Every wallet, every transaction, and every permission in Finance District traces back to an identity — someone who can be held accountable. This is the foundation of the trust model.
District Pass authenticates using **email OTP** (for CLI and headless agents) or **browser-based OAuth** (for MCP clients and web apps), interactive flows that establish user context. This is a deliberate choice. The alternative — **client credentials** — authenticates a service, not a person. It tells us that *some machine* is calling, but not *who* it represents. That's machine-to-machine authentication: useful for backend integrations, but it produces anonymous activity. There is no one on the other end to trust, to audit, or to hold accountable.
We don't want machines as users. We want identities as users.
Today, identity means a human. A District Pass account is a person — and every agent wallet, balance, and action under that account belongs to that person. This is what makes the system auditable: key custody has an owner, spending has a source, and trust has a name behind it.
But identity won't always mean human. As agentic platforms mature, autonomous agents will authenticate, navigate the web, and act with increasing independence. When an agent can establish its own identity — provable, persistent, and accountable — it becomes a user in the same sense a human is. Not a machine executing instructions, but an entity with an identity that the system and other participants can verify and trust.
Finance District is built for that future. The identity model doesn't change — it extends. Whether the user behind a District Pass is a person today or an autonomous agent tomorrow, the principle is the same: every action traces back to an accountable identity.
## What's Next?
Create your first agent wallet and connect via MCP
Set up Prism and accept your first AI agent payment
# FAQ
Source: https://developers.fd.xyz/overview/faq
Frequently asked questions about Agent Wallet, Prism, and the Finance District ecosystem.
## Getting Started
**Get started at:** [https://apps.fd.xyz/](https://apps.fd.xyz/)
1. Sign up → get your District Pass
2. Choose your integration method
3. Connect your agent or start using the CLI
4. Get your agent wallet address and transfer funds from your regular crypto wallet (MetaMask, Coinbase, etc.)
💡 **Start small with Agent Wallet** — \$10–50 for testing. Your agent can only spend funds you deposit. Scale as trust grows.
**District Pass** is the Web3 identity layer for Finance District. Verify once — move securely across wallets, payments, and apps.
**What it does:**
* 🔑 **Universal access** — One login for all Finance District products
* 🔗 **Persistent wallet** — Your identity linked to your wallet(s)
* 🤖 **Agent identity** — Links your agents to you
**Do I need separate accounts for each product?**
No. One District Pass = access to all Finance District solutions.
**Is it secure?**
Yes. Built on OAuth 2.0 + OpenID Connect. Short-lived tokens, not passwords.
**Get yours:** [https://apps.fd.xyz/](https://apps.fd.xyz/)
| Product | What It Does | Get Started |
| - | - | - |
| **Agent Wallet** | Wallet for your AI agents | [apps.fd.xyz](https://apps.fd.xyz/) |
| **CLI** | Terminal-based wallet access | [CLI Docs](/agent-wallet/ai-integration/cli) |
| **MCP Server** | Connect MCP-compatible agents | [MCP Server Docs](/agent-wallet/ai-integration/mcp-server) |
| **Prism** | Accept payments from agents | [Prism Overview](/prism/overview) |
**Estimated setup times:**
* CLI: 5 min
* MCP Server: 5 min
* Agent Wallet (Web): Instant
* Prism: 15–30 min
## Agent Wallet
Agent Wallet is AI-native wallet infrastructure that gives your AI agents **their own wallets** — not borrowed access to yours.
**Key features:**
* AI-Autonomous Transactions
* MCP-Native (works with Claude, GPT-4, etc.)
* CLI with 15+ MCP tools
* TEE-Secured keys
* x402 Payments
* EVM + Solana wallets auto-provisioned
**Four interfaces, one wallet:**
| Interface | Best For |
| - | - |
| MCP Server | AI agents |
| CLI | Developers & automation |
| AI Assistant | Non-technical users |
| Web App | Operators |
| Feature | Regular Crypto Wallet | DIY | Agent Wallet |
| - | - | - | - |
| Autonomy | Borrowed | Basic | Genuine |
| 24/7 Operation | ❌ Human needed | ⚠️ Insecure | ✅ Secure |
| MCP | Build adapter | Manual | Built-in |
| Key security | Human keys | Env vars | TEE enclave |
| Commerce protocols | ❌ | Build it | x402, ACP, UCP |
| Setup | Complex | Days/weeks | 5 minutes |
* **Regular crypto wallets** — great for humans, but require approval popups for every transaction
* **DIY** — insecure; one leaked env var and funds are gone
* **Agent Wallet** — genuine autonomy, production-ready from day one
Agent Wallet supports **3 wallet types** — choose based on your needs:
| Type | Description | Best For |
| - | - | - |
| **EOA Wallet** | Standard externally-owned account | Most use cases, simple setup, low cost |
| **Smart Account** | Contract-based with programmable logic | Batch transactions, custom rules, automation |
| **Delegated Wallet** | Fine-grained access control | Enterprise, multi-sig, team permissions |
**Recommendation:** Start with an EOA Wallet — it covers most use cases. Move to Smart Account or Delegated Wallet when you need advanced features.
**Core operations:**
* 💰 **Hold & Manage** — Multi-chain assets, portfolio view
* 📤 **Transfer** — Send/receive tokens
* 🔄 **Swap** — Exchange token pairs
* 📈 **Earn Yield** — Discover & deploy strategies
* 🛒 **Pay Merchants** — x402, ACP, UCP protocols
**Available MCP tools:**
`getWalletOverview` · `transferTokens` · `swapTokens` · `discoverYieldStrategies` · `depositForYield` · `withdrawFromYield` · `authorizePayment` · `getX402Content` · `getTokenPrice` · `getAccountActivity` · `resolveNameService` · `signMessage` · `getMyInfo` · `reportIssue`
**Yes.** That's the core difference.
**Regular crypto wallet at 3 AM:**
Agent finds opportunity → popup appears → you're asleep → opportunity expires ❌
**Agent Wallet at 3 AM:**
Agent finds opportunity → checks parameters → executes → you wake up to a summary ✅
Your agent has its own wallet and operates within boundaries you set — no per-transaction approval needed.
**Supported assets:**
* ✅ EVM tokens (FDUSD, USDC, DAI, ERC-20s)
* ✅ Solana tokens (SPL)
* ✅ Bitcoin (BTC)
* ✅ Sui tokens (SUI, Move)
All wallets are auto-provisioned at signup across EVM, Solana, Bitcoin, and Sui networks.
The CLI provides command-line access to all wallet capabilities.
**What you can do:**
* Execute payments & transfers
* Manage wallets programmatically
* Script automated workflows
* Server-side automation
The CLI provides access to **15+ MCP tools** across wallet and Prism services. Use `fdx wallet ` for wallet operations and `fdx prism ` for payment operations.
**Get started:** [CLI Docs](/agent-wallet/ai-integration/cli)
## AI & MCP
**MCP (Model Context Protocol)** is a standardized way for AI models to communicate with external tools.
**Why it matters:**
* Zero integration code needed
* LLMs understand MCP natively
* Agents auto-discover wallet capabilities
* Works with Claude, GPT-4, LangChain, CrewAI, and more
* One setup works for all your agents
**Without MCP:** Hundreds of lines of middleware code
**With MCP:** Point your agent at a URL. Done.
Learn more: [MCP Server](/agent-wallet/ai-integration/mcp-server)
The AI Assistant uses models that have regional restrictions in some areas.
**If you're blocked, use these globally available alternatives:**
| Interface | Availability |
| - | - |
| CLI | ✅ Global |
| MCP Server | ✅ Global |
| Web App | ✅ Global |
| AI Assistant | ⚠️ Regional restrictions |
**Recommended:** Use the CLI for full functionality worldwide.
[CLI Docs](/agent-wallet/ai-integration/cli)
## Payments & Protocols
**Agent Wallet** is the buyer-side product (your agent's wallet). **Prism** is the seller-side payment gateway for merchants.
| Product | Role |
| - | - |
| Agent Wallet | Agents that spend |
| Prism | Merchants that receive |
**Together:** Agent Wallet shops → Prism accepts payment.
**Independently:** Each works with other wallets and merchants.
Learn more: [Prism Overview](/prism/overview)
**x402** is an HTTP-native payment protocol for machine-to-machine commerce.
**Use cases:**
* Pay-per-use API access
* Agent-to-agent service payments
* Micropayments for data, compute, or content
* Automated subscription & recurring payments
* Real-time settlement between services
**How it works:**
1. Agent requests a paid resource or service
2. Server returns HTTP 402 + payment requirements
3. Agent wallet pays instantly (on-chain)
4. Server delivers the resource
5. Settlement confirmed ✅
**Why x402 matters:**
* Micropayments down to fractions of a cent
* No subscriptions required — pay exactly what you use
* Instant, verifiable settlement
* Zero chargebacks or disputes
* Fully autonomous — no human approval needed
Learn more: [x402 Protocol](/agent-wallet/concepts/x402-payments)
## Setup & Integration
**Agent Wallet** gives your AI agents their own wallets.
1. Register with **District Pass** at [apps.fd.xyz](https://apps.fd.xyz/)
2. Choose your integration:
* **MCP Server** → For Claude Code, Cursor, and MCP-compatible agents
* **CLI** → For terminal, scripting, and automation
3. Connect to **Agent Skills** for expanded capabilities
**Resources:**
* [MCP Server Docs](/agent-wallet/ai-integration/mcp-server)
* [CLI Docs](/agent-wallet/ai-integration/cli)
**Prism** lets you accept payments from AI agents (merchant/seller side).
1. Register with **District Pass** at [apps.fd.xyz](https://apps.fd.xyz/)
2. Go to the **Prism Console**
3. Get your **Project Identify Tokens**
4. Integrate using the **Prism SDK or API**
**Resources:**
* [Prism Overview](/prism/overview)
* [API Reference](/prism/api-reference/introduction)
Accept payments from AI agents with instant settlement and zero chargebacks.
| Method | Setup Time | Best For |
| - | - | - |
| MCP Server | 5 min | Claude Code, Cursor, MCP agents |
| CLI | 5 min | Terminal, scripting, automation |
| REST API | 30 min | Custom apps, non-MCP |
| Python SDK | 15 min | Python projects |
| JS/TS SDK | 15 min | Node.js/TypeScript |
**Recommendation:**
* MCP-compatible agent? → MCP Server
* Terminal workflows? → CLI
* Custom agent? → SDK
* Full control? → REST API
Use the production environment with small amounts. The API, MCP, and SDK work identically regardless of transaction size. This lets you validate the full end-to-end flow — including real on-chain settlement.
## Security & Safety
**Yes — keys are protected by a TEE (Trusted Execution Environment):**
* Keys are generated **inside** a hardware enclave
* Keys **never leave** the TEE — not to memory, disk, or logs
* Signing happens **inside** the TEE
* Even Finance District cannot access your keys
Agent Wallet is **non-custodial** — you control access, and hardware protects the keys.
| Scenario | DIY (env vars) | Agent Wallet |
| - | - | - |
| Log leak | Keys exposed 💀 | Keys safe ✅ |
| Key recovery | Funds gone | Rotate API key |
**No.** Agent Wallet follows a "pocket money" philosophy.
Your agent only has access to funds you explicitly transfer to its wallet — not your main holdings.
| Use Case | Suggested Budget |
| - | - |
| Testing | \$10–50 |
| Personal agent | \$100–500/mo |
| Business agent | \$1K–10K/mo |
| Enterprise | Custom |
You control what you transfer. The agent can only spend those funds. Scale as trust grows.
## 🔗 Resources
* **Get Started:** [https://apps.fd.xyz/](https://apps.fd.xyz/)
* **Finance District Website:** [https://fd.xyz](https://fd.xyz)
* **Agent Wallet:** [https://fd.xyz/fd-agentwallet](https://fd.xyz/fd-agentwallet)
* **CLI Docs:** [https://developers.fd.xyz/agent-wallet/ai-integration/cli](https://developers.fd.xyz/agent-wallet/ai-integration/cli)
* **Discord:** [https://discord.gg/fdxyz](https://discord.gg/fdxyz)
* **X/Twitter:** [https://x.com/FD\_XYZ](https://x.com/FD_XYZ)
# Introduction
Source: https://developers.fd.xyz/overview/introduction
Financial access for everyone. Financial autonomy for AI.
Finance District is an open ecosystem for digital financial infrastructure. It brings together products, protocols, and developer tools that work independently but become more powerful together.
## Our Flagship Solutions
Today, the ecosystem has two flagship solutions:
AI-native wallet infrastructure giving agents their own wallets —
non-custodial, MCP-native, production-ready. Hold, send, swap, earn yield,
and make payments.
The payment gateway purpose-built for agentic commerce — enabling merchants
and platforms to accept payments from AI shopping agents with instant
stablecoin settlement and zero chargebacks.
**[Agent Wallet](/agent-wallet/overview)** is buyer-side infrastructure. It gives AI agents their own wallets with secure key management inside hardware enclaves. Agents can hold stablecoins, make transfers, swap tokens, deploy to yield vaults, and pay merchants — all through MCP, CLI, or a conversational AI assistant.
**[Prism](/prism/overview)** is the seller-side payment gateway. It enables e-commerce platforms and merchants to accept payments from AI shopping agents through a single integration that supports emerging commerce protocols (x402 and UCP live today, ACP coming soon), with instant stablecoin settlement and zero chargebacks. Think of Prism as Stripe for agentic commerce.
Together, they form the foundation of the Finance District ecosystem — but each is a standalone product. Agent Wallet works with any merchant or protocol. Prism accepts payments from any Web3 wallet, not just Agent Wallet.
## Build on Finance District
Finance District is designed as an ecosystem others can build on. Whether you're building AI agents that need financial capabilities, platforms that want to accept agent payments, or entirely new financial products — the infrastructure is here.
## Quick Paths
| I want to... | Start here |
| - | - |
| Give my AI agent a wallet | [Agent Wallet Quick Start](/agent-wallet/quickstart) |
| Accept payments from AI agents | [Prism Quick Start](/prism/quickstart) |
| Connect an agent via MCP | [MCP Server](/agent-wallet/ai-integration/mcp-server) |
| Integrate a server-side SDK | [SDK Overview](/prism/sdk/overview) |
| Manage Prism via MCP | [Prism MCP Server](/prism/integrations/mcp-server) |
| Understand x402 payments | [x402 Protocol](/prism/integrations/x402) |
| Test with small amounts | [Getting Started](/prism/quickstart) |
## Prerequisites
To use any Finance District product, you need a [District Pass](/overview/district-pass) — a single identity across the entire ecosystem. Signup takes seconds: just an email address and a confirmation code.
# Support & Community
Source: https://developers.fd.xyz/overview/resources/support
Stuck? Our developer community and team are here to help you ship.
## Get Help
| Channel | Best For | Link |
| - | - | - |
| Discord | Community questions, real-time chat | [discord.gg/fdxyz](https://discord.gg/fdxyz) |
| GitHub | Bug reports, feature requests | [github.com/financedistrict-platform](https://github.com/financedistrict-platform) |
| X (Twitter) | Announcements and updates | [@FD\_XYZ](https://x.com/FD_XYZ) |
## Discord
The [Finance District Discord](https://discord.gg/fdxyz) is the primary community hub for developers. Join to ask questions, share what you're building, and get help from the team and community.
## Report a Bug
File bug reports on [GitHub Issues](https://github.com/financedistrict-platform). Include:
* Which product (Agent Wallet or Prism)
* Steps to reproduce
* Expected vs. actual behavior
* SDK version, chain, and token involved (if applicable)
* Error messages or logs
## Feature Requests
Submit feature requests via GitHub Issues or discuss them in Discord. The team prioritizes based on community demand and ecosystem impact.
## Useful Links
* **Website:** [fd.xyz](https://fd.xyz)
* **Prism Console:** [apps.fd.xyz/prism](https://apps.fd.xyz/prism/)
* **Agent Wallet App:** [apps.fd.xyz](https://apps.fd.xyz)
* **Agent Wallet MCP Server:** `https://wallet-mcp.fd.xyz`
* **Prism MCP Server:** `https://prism-mcp.fd.xyz`
* **Prism Gateway:** `https://prism-gw.fd.xyz`
* **Discord:** [discord.gg/fdxyz](https://discord.gg/fdxyz)
* **GitHub:** [github.com/financedistrict-platform](https://github.com/financedistrict-platform)
* **X:** [@FD\_XYZ](https://x.com/FD_XYZ)
# Endpoints
Source: https://developers.fd.xyz/prism/api-reference/endpoints
Prism Gateway API endpoint reference for payment preparation, merchant checkout, and UCP gateway.
Reference for each Prism Gateway API endpoint. See [Introduction](/prism/api-reference/introduction) for base URLs, authentication, and error handling.
All authenticated endpoints require the `X-API-Key` header. Request and response bodies are JSON.
***
## x402 Settlement
Facilitator endpoints for the x402 payment flow. The [server-side SDKs](/prism/sdk/overview) call these automatically. Use them directly for custom integrations.
### Get Payment Requirements
Generate x402 payment requirements for a resource. Returns the accepted payment methods, token amounts, and settlement addresses.
```
POST /api/v2/payment/requirements
```
**Request Body**
| Field | Type | Required | Description |
| - | - | - | - |
| `resourceUrl` | string | Yes | URL of the protected resource |
| `requestedAmount` | number | Yes | Amount to charge (in the resource's currency) |
| `description` | string | No | Human-readable description of the resource |
| `mimeType` | string | No | MIME type of the resource content |
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl -X POST https://prism-gw.fd.xyz/api/v2/payment/requirements \
-H "X-API-Key: your-project-identify-token" \
-H "Content-Type: application/json" \
-d '{
"resourceUrl": "https://api.example.com/premium/data",
"requestedAmount": 0.50,
"description": "Premium API access"
}'
```
**Response** (`PaymentRequiredResponse`)
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": {
"url": "https://api.example.com/premium/data",
"description": "Premium API access"
},
"accepts": [
{
"scheme": "exact",
"network": "base",
"amount": "500000",
"payTo": "0x1234...abcd",
"maxTimeoutSeconds": 300,
"asset": "0xUSDC...addr",
"extra": null,
"protocolVersion": 2
}
],
"protocolVersion": 2
}
```
The `accepts` array contains one entry per token/chain combination the merchant supports. Clients pick one and construct a signed authorization against it.
***
### Verify Payment
Verify a signed x402 payment authorization without settling it on-chain.
```
POST /api/v2/payment/verify
```
**Request Body** (`PaymentSubmissionRequest2`)
| Field | Type | Required | Description |
| - | - | - | - |
| `paymentPayload` | object | Yes | Signed payment authorization (see below) |
| `paymentRequirements` | object | Yes | The accepted payment requirement this authorization targets |
| Field | Type | Required | Description |
| - | - | - | - |
| `x402Version` | integer | Yes | Protocol version (2) |
| `accepted` | object | Yes | The `accepts` entry the payer selected |
| `payload` | object | Yes | Signed authorization data (scheme-specific) |
| `resource` | object | No | Resource metadata |
| `extensions` | object | No | Protocol extensions |
| Field | Type | Required | Description |
| - | - | - | - |
| `scheme` | string | Yes | Payment scheme (e.g. `"exact"`) |
| `network` | string | Yes | Chain identifier (e.g. `"base"`) |
| `amount` | string | Yes | Token amount in smallest unit |
| `payTo` | string | Yes | Merchant settlement address |
| `maxTimeoutSeconds` | integer | Yes | Max time before authorization expires |
| `asset` | string | Yes | Token contract address |
**Response** (`VerifyResponse2`)
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"isValid": true,
"payer": "0xPayerAddress...1234"
}
```
| Field | Type | Description |
| - | - | - |
| `isValid` | boolean | Whether the authorization is valid |
| `payer` | string | Payer wallet address (if valid) |
| `invalidReason` | string | Reason for rejection (if invalid) |
***
### Settle Payment
Settle a verified payment on-chain. Executes the `transferWithAuthorization` (ERC-3009) call to move tokens from the payer to the merchant.
```
POST /api/v2/payment/settle
```
**Request Body** (`PaymentSubmissionRequest2`)
Same structure as [Verify Payment](#verify-payment).
**Response** (`SettleResponse`)
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"success": true,
"payer": "0xPayerAddress...1234",
"transaction": "0xTransactionHash...abcd",
"network": "base"
}
```
| Field | Type | Description |
| - | - | - |
| `success` | boolean | Whether settlement succeeded |
| `payer` | string | Payer wallet address |
| `transaction` | string | On-chain transaction hash |
| `network` | string | Chain the settlement executed on |
| `errorReason` | string | Reason for failure (if unsuccessful) |
Returns `502 Bad Gateway` with a [ProblemDetails](/prism/api-reference/introduction#error-format) body if the on-chain transaction fails.
***
## Merchant
Endpoints for UCP and ACP merchants. The UCP flow has two calls: fetch the handlers declaration for your UCP version, and call Payment Requirements at checkout. ACP merchants use the same Payment Requirements call and fetch the declaration from `/api/v2/merchant/acp/handlers`, which needs the API key.
### Get Handlers
Returns the `xyz.fd.prism_payment` handler declaration for a UCP version. Put it in your storefront's UCP profile. Cache it. This route is public and needs no API key.
```
GET /ucp/{ucpVersion}/handlers
```
It returns the `2026-10-07` handler for UCP `2026-01-23`, `2026-04-08` and `2026-08-25`. See [Prism contract selection](/prism/integrations/ucp/supported-versions#prism-contract-selection).
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl https://prism-gw.fd.xyz/ucp/2026-08-25/handlers
```
An unsupported version returns `422 version_unsupported`.
The unversioned `GET /api/v2/merchant/ucp/handlers` stays as a legacy route for older plugins. The versioned `/api/v2/merchant/ucp/{ucpVersion}/handlers` form was removed. Use the route above.
**Response** (`UcpHandlersResponse`)
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"spec": "https://prism-gw.fd.xyz/ucp/prism.md",
"schema": "https://prism-gw.fd.xyz/ucp/schema.json",
"available_instruments": [{ "type": "x402" }],
"config": {}
}
]
}
```
**Unsupported version** (`422`)
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{"title":"version_unsupported","detail":"Version 2099-01-01 is not supported. Enabled versions: 2026-01-23, 2026-04-08, 2026-08-25."}
```
***
### Payment Requirements
Convert a fiat amount into the raw x402 PaymentRequired object. Call it at checkout, when a buyer selects items. The response has no protocol wrapper and does not depend on the UCP version. Requires the API key.
```
POST /api/v2/merchant/payment-requirements
```
**Request Body**
| Field | Type | Required | Description |
| - | - | - | - |
| `amount` | string | Yes | Fiat amount (e.g. `"10.00"`) |
| `currency` | string | Yes | Fiat currency code (e.g. `"USD"`) |
| `resource` | object | Yes | Resource being purchased |
| `resource.url` | string | Yes | URL identifying the resource |
| `resource.description` | string | No | Human-readable description |
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl -X POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements -H "X-API-Key: your-project-identify-token" -H "Content-Type: application/json" -d '{"amount":"10.00","currency":"USD","resource":{"url":"https://shop.example/checkout/1"}}'
```
**Response**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": { "url": "https://shop.example/checkout/1" },
"accepts": [
{
"scheme": "exact",
"network": "base",
"payTo": "0xMerchant...addr",
"maxTimeoutSeconds": 300,
"asset": "0xUSDC...addr",
"amount": "10000000"
}
]
}
```
The response has one `accepts` entry per token and chain the merchant supports, with `amount` resolved from the fiat price. It may also include `promotions`.
Returns `404` if the merchant is not configured in Prism Console.
Build the UCP checkout entry from the handlers declaration for your UCP version and this object:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"xyz.fd.prism_payment": [
{ "id": "", "version": "", "config": { "x402Version": 2, "resource": {}, "accepts": [] } }
]
}
```
***
## Gateway
Public endpoints serving the UCP handler reference. No authentication required.
### Handler Schema
Returns the JSON schema for the `xyz.fd.prism_payment` handler. The handler config schema is the entry `schema`. The instrument schema is linked at `$defs["xyz.fd.prism_payment"].instrument`.
```
GET /ucp/schema.json
```
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl https://prism-gw.fd.xyz/ucp/schema.json
```
***
### Handler Specification
Returns the human-readable specification for the `xyz.fd.prism_payment` handler in Markdown format.
```
GET /ucp/prism.md
```
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl https://prism-gw.fd.xyz/ucp/prism.md
```
```
```
# Introduction
Source: https://developers.fd.xyz/prism/api-reference/introduction
Prism Gateway REST API for x402 payment settlement, UCP checkout preparation, and merchant profile management.
The Prism Gateway API handles payment settlement, payment requirement generation, and merchant profile management. For most x402 integrations, the [server-side SDKs](/prism/sdk/overview) wrap these endpoints automatically. Use the API directly for custom integrations or when building on top of UCP.
## Base URLs
| Environment | URL |
| - | - |
| Production | `https://prism-gw.fd.xyz` |
## Authentication
Authenticate by including your Project Identify Token in the `X-API-Key` header:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl -X POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements \
-H "X-API-Key: your-project-identify-token" \
-H "Content-Type: application/json" \
-d '{"amount":"10.00","currency":"USD","resource":{"url":"https://shop.example/checkout/1"}}'
```
Get your Project Identify Token from the [Prism Console](https://apps.fd.xyz/prism/) under **Project Identify Tokens**.
Keep your Project Identify Token secret. Never expose it in client-side code, browser
requests, or public repositories.
## Endpoint Groups
The API is organized into three groups:
| Group | Auth | Purpose |
| - | - | - |
| **x402 Settlement** | `X-API-Key` | Generate payment requirements, verify authorizations, settle payments |
| **Merchant** | `X-API-Key` (handlers route is public) | UCP checkout helpers: get the versioned handlers declaration, convert fiat amounts to raw x402 payment requirements |
| **Gateway** | Public | UCP handler reference files: JSON schema and handler spec |
### x402 Settlement
Facilitator endpoints for the x402 payment flow. The SDKs call these under the hood.
| Method | Endpoint | Description |
| - | - | - |
| `POST` | `/api/v2/payment/requirements` | Generate x402 payment requirements for a resource |
| `POST` | `/api/v2/payment/verify` | Verify a signed x402 payment authorization |
| `POST` | `/api/v2/payment/settle` | Settle a verified payment on-chain |
### Merchant
For UCP and ACP merchants. Call these from your server to build your discovery profile and prepare checkout sessions. Both protocols share one payment-requirements endpoint. Each has its own handlers endpoint.
| Method | Endpoint | Description |
| - | - | - |
| `POST` | `/api/v2/merchant/payment-requirements` | Convert a fiat amount into the raw x402 PaymentRequired object, with no protocol wrapper. Used by UCP and ACP |
| `GET` | `/api/v2/merchant/acp/handlers` | Get the ACP handler declaration. Needs the API key |
### Gateway
Public endpoints serving the UCP handler reference. No authentication required.
| Method | Endpoint | Description |
| - | - | - |
| `GET` | `/ucp/schema.json` | UCP handler JSON schema |
| `GET` | `/ucp/prism.md` | UCP handler specification |
| `GET` | `/ucp/{ucpVersion}/handlers` | Handler declaration for a UCP version |
See [Endpoints](/prism/api-reference/endpoints) for full request/response documentation.
## Request Format
* Content-Type: `application/json`
* All request bodies are JSON
* Standard HTTP methods: `GET`, `POST`
## Error Format
Errors follow the [RFC 7807](https://tools.ietf.org/html/rfc7807) Problem Details format:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"type": "https://tools.ietf.org/html/rfc7807",
"title": "Bad Request",
"status": 400,
"detail": "Amount is required"
}
```
| HTTP Status | Meaning |
| - | - |
| 400 | Bad Request (invalid input) |
| 401 | Unauthorized (missing or invalid Project Identify Token) |
| 404 | Not Found (merchant not configured) |
| 502 | Bad Gateway (upstream settlement failure) |
When rate limited, the API returns **429 Too Many Requests**. Back off and retry after the reset time.
## SDKs
For most integrations, use a server-side SDK instead of calling the API directly. The SDKs handle authentication, x402 protocol flow, payment verification, and type safety:
Express, NestJS, Next.js, Fastify, and more
FastAPI, Flask, Django
Servlet-based applications
# Overview
Source: https://developers.fd.xyz/prism/architecture/overview
How Prism is built: one orchestration layer that speaks every commerce protocol, settling on-chain through Spectrum.
Prism is designed as **two layers with a clean separation of concerns**: an off-chain **orchestration layer** (Prism) that speaks the agent-commerce protocols and handles everything a merchant integrates against, and an on-chain **settlement layer** (Spectrum) that moves the money. You build against Prism; Spectrum settles underneath, and you never touch a smart contract directly.
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
flowchart TB
subgraph prism["Prism — Orchestration (off-chain)"]
direction TB
P1["Protocol implementations · x402 · UCP · ACP"]
P2["Merchant management & onboarding"]
P3["Charge creation & transaction routing"]
P4["Webhooks & analytics"]
P5["API: prism-gw.fd.xyz · Console: apps.fd.xyz/prism/"]
end
subgraph spectrum["Spectrum — Settlement (on-chain)"]
direction TB
S1["Smart-contract execution · ERC-3009"]
S2["Stablecoin transfer · FDUSD · USDC"]
S3["Multi-chain · Base · Arbitrum · BSC · Ethereum"]
S4["Verification & finality"]
end
prism -->|"payment credential"| spectrum
spectrum -->|"on-chain confirmation"| prism
```
## Prism — the orchestration layer
Prism is everything the merchant interacts with. It is protocol-aware, off-chain, and stateless with respect to funds — it never holds money. Prism handles:
* **Protocol implementations** — a single integration that speaks x402, UCP, and ACP. Prism translates each protocol's checkout and payment semantics into one internal settlement model, so you're covered whichever protocol a buyer's agent uses.
* **Merchant management** — Project Identify Tokens, accepted chains and tokens, settlement address, onboarding.
* **Charge creation & routing** — turning an order into concrete on-chain payment requirements (amount, token, chain, recipient).
* **Webhooks & analytics** — delivering settlement events and transaction history to your systems.
When you call the Prism Gateway API or drop in a Prism SDK, you're talking to this layer.
## Spectrum — the settlement layer
**Spectrum** is Finance District's on-chain settlement layer — the part that actually moves stablecoins. It's the piece the rest of the docs reference whenever a payment is "settled on-chain."
* **Executes the transfer.** The buyer's wallet signs a payment off-chain using [ERC-3009](https://eips.ethereum.org/EIPS/eip-3009) (`transferWithAuthorization`). Spectrum submits that signed authorization on-chain, moving stablecoins **directly from the buyer's wallet to the merchant's wallet**. No intermediary custodies the funds at any point.
* **Verifies and finalizes.** Spectrum confirms the on-chain transfer — correct amount, token, recipient, and a valid signature — and returns the transaction hash. Once confirmed on-chain, the payment is final: no chargebacks, no clawbacks.
* **Runs multi-chain.** Spectrum settles on EVM-compatible chains — Base, Arbitrum, BSC, and Ethereum today — in the stablecoins merchants enable (FDUSD, USDC). See [Network Support](/prism/production/network-support) for the current matrix.
Because the `payTo` address in every x402 payment requirement is a Spectrum settlement contract, the buyer's signed credential is bound to the on-chain settlement path from the moment it's created.
## One integration, every protocol
The reason the layers are split this way: **protocols evolve, settlement shouldn't.** Prism can add a new commerce protocol or change its merchant-facing business logic without touching the on-chain settlement infrastructure — and Spectrum can stay minimal, auditable, and stable. A merchant integrates once and inherits every protocol Prism supports.
How Prism implements the Universal Commerce Protocol as a payment handler.
How Prism acts as the x402 facilitator — enforce, verify, settle.
How Prism plugs into the Agentic Commerce Protocol for settlement.
The step-by-step behavior of a single payment, request to settlement.
Why settlement is on-chain, and what that gives you: finality, no chargebacks.
# Commerce Protocols
Source: https://developers.fd.xyz/prism/concepts/commerce-protocols
x402, ACP, UCP — the emerging protocols enabling AI agents to shop, and how Prism abstracts them.
Multiple companies are building protocols for AI agent commerce — each covering a different part of the journey from product discovery to payment. Prism is protocol-agnostic: you integrate once, and Prism handles protocol translation behind the scenes. When a new protocol gains traction, Prism adds support without changing your integration.
## The Protocol Landscape
| Layer | Protocol | Created By | Status |
| - | - | - | - |
| Settlement (payment) | x402 | Coinbase (open standard) | **Live** — Prism uses this today |
| Checkout (transaction) | ACP | OpenAI | **Live** — Prism supports this today |
| Full Commerce Journey | UCP | Google | **Live** — Prism supports this today |
These protocols are complementary, not competing. x402 handles the settlement layer — the actual movement of money. ACP and UCP handle the commerce layer — product discovery, cart management, checkout flow. An agent might use ACP to find and select a product, then x402 (via Prism) to pay for it.
## x402 — Settlement Protocol
x402 implements the HTTP 402 "Payment Required" status code for machine-to-machine stablecoin payments. It's Prism's primary protocol today.
**How it works:** Agent requests a resource → server responds 402 with payment requirements → agent pays on-chain → server grants access.
**Best for:** API monetization, data feeds, premium content, pay-per-request services — any endpoint where access requires payment.
**Status:** Live. This is what you integrate with today.
[Full x402 documentation →](/prism/integrations/x402)
## ACP — Agent Commerce Protocol
Created by OpenAI for structured AI agent commerce. ACP covers the full commerce journey: product discovery, cart management, checkout, payment, and order lifecycle. It's designed for scenarios where an agent needs to browse a catalog, select products, and complete a purchase.
**How Prism integrates:** ACP handles the commerce flow (what the agent is buying). Prism handles the settlement (how the agent pays) via the `xyz.fd.prism_payment` handler. Merchants get:
* AI agents that can browse their product catalog programmatically
* Structured checkout with stablecoin settlement via Prism
* The same instant settlement and zero chargebacks as x402
**Best for:** E-commerce product purchases, multi-item orders, any scenario with a traditional checkout flow.
**Status:** Live. Prism supports ACP via the `xyz.fd.prism_payment` handler today.
[Full ACP integration guide →](/prism/integrations/acp)
## UCP — Universal Commerce Protocol
Created by Google for the full commerce journey — from discovery to post-purchase. UCP is more comprehensive than ACP, covering the entire lifecycle: discovery, selection, purchase, fulfillment, returns, and support.
**How Prism integrates:** Prism serves as the settlement and payment verification layer within the UCP flow.
**Best for:** Complex multi-step purchases, scenarios requiring fulfillment tracking, subscription-like flows.
**Status:** Live. Prism supports UCP via the `xyz.fd.prism_payment` handler today.
[Full UCP integration guide →](/prism/integrations/ucp)
## How Prism Abstracts Protocol Complexity
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
flowchart LR
X402[x402] --> P["Prism\n(Gateway)"]
ACP[ACP] --> P
UCP[UCP] --> P
P --> App["Your Application\n(single SDK / API)"]
```
The key insight: **you integrate Prism once**. Prism handles protocol translation on the inbound side. Whether an agent pays via x402, initiates checkout via ACP, or goes through a full UCP commerce journey — your SDK integration and webhook handling stay the same.
This protects your investment. As the protocol landscape evolves, you don't need to re-integrate. Prism adapts; your code doesn't change.
## What Should I Use Today?
x402 is live and supported today. Ideal for API monetization and
pay-per-request models.
Integrate x402 payment protection in minutes with the Prism SDK.
If you're building an e-commerce platform, integrate Prism now with x402, UCP, or ACP (all live today). They use the same `xyz.fd.prism_payment` handler and settle via the same Prism API.
# How Prism Works
Source: https://developers.fd.xyz/prism/concepts/how-it-works
Under the hood: how Prism turns any API endpoint into a paid, permissionless service for AI agents.
Prism uses a two-layer architecture that separates business logic from on-chain settlement. You integrate at the orchestration layer — familiar APIs and SDKs. Settlement happens transparently on-chain through the Spectrum layer. Merchants never need to touch smart contracts directly.
## Two-layer architecture
Prism is the off-chain **orchestration layer** you integrate against; **Spectrum** is the on-chain **settlement layer** that moves the stablecoins. Merchants never touch a smart contract directly. For how the two layers fit together — and how Prism implements each protocol — see the Architecture section.
The orchestration and settlement layers, and Prism as the layer that speaks every protocol.
## Transaction Lifecycle
Here's what happens during a payment, step by step:
An AI agent makes an HTTP request to the merchant's protected endpoint
(e.g., `GET /api/premium/data`).
The Prism SDK middleware intercepts the request and returns **HTTP 402
Payment Required**. The response includes payment requirements: amount,
token, chain, recipient address, and a deadline.
The agent's wallet reads the 402 response, constructs a stablecoin payment,
and submits it on-chain.
The agent retries the original request, this time including the payment
proof (transaction signature) in the `X-PAYMENT` header.
Prism forwards the payment proof to Spectrum, which verifies the on-chain
transaction — correct amount, correct token, correct recipient, transaction
confirmed.
Once verified, settlement is complete. The stablecoins are in the merchant's
wallet. Prism confirms the payment to the SDK middleware.
The middleware allows the original request to proceed. The agent receives
the requested resource.
**Timing:** End-to-end settlement takes a few seconds, depending on the chain. Base transactions typically settle in \~2 seconds, while Ethereum takes \~12 seconds.
After the request completes, Prism delivers a webhook notification to the merchant's configured endpoint with the full transaction details.
## Protocol support
Prism is protocol-agnostic — one integration covers x402, UCP, and ACP, so your setup stays the same regardless of which protocol a buyer's agent speaks. For what each protocol is, see the [protocol landscape overview](/prism/concepts/commerce-protocols); for how Prism implements each, see [Architecture](/prism/architecture/overview).
## Settlement
All settlements happen in stablecoins. Merchants choose which tokens and chains to accept in the [Prism console](/prism/production/console). The transaction is final once confirmed on the blockchain. No chargebacks, no disputes, no clawbacks.
Settlement flows directly from the agent's wallet to the merchant's wallet. No intermediary holds the funds. The merchant can hold stablecoins or transfer them to another wallet.
| Chain | Settlement Time | Gas Cost |
| - | - | - |
| Base | \~2 seconds | Very low |
| Arbitrum | \~2 seconds | Very low |
| BSC | \~3 seconds | Low |
| Ethereum | \~12 seconds | Higher |
[Settlement deep dive →](/prism/concepts/settlement)
# Stablecoin Settlement
Source: https://developers.fd.xyz/prism/concepts/settlement
How Prism settles payments in stablecoins — instant, final, no chargebacks.
All Prism payments settle in stablecoins on-chain. This is a deliberate design choice: stablecoins give you instant finality, zero chargebacks, and global reach — properties that card rails can't match, and properties that AI agents need to transact autonomously.
## Why Stablecoins?
| | Traditional (Card Rails) | Prism (Stablecoin Rails) |
| - | - | - |
| **Settlement speed** | 2–5 business days | Seconds |
| **Chargebacks** | Possible for months | Transactions are final |
| **Fees** | 2.9% + \$0.30 typical | Competitive settlement fees |
| **Currency** | Fiat, with FX conversion | USD-denominated stablecoins |
| **Merchant setup** | Merchant account required | Wallet address is sufficient |
| **Machine-native** | Requires card numbers, PII | Wallet-to-wallet, no PII |
The last point matters most for agentic commerce: AI agents can hold and transact with stablecoins directly. No credit card numbers, no bank accounts, no personally identifiable information. An agent wallet plus stablecoins is the native payment method for machine-to-machine commerce.
## Supported Tokens
Prism settles using any ERC-20 token that implements `transferWithAuthorization` ([ERC-3009](https://eips.ethereum.org/EIPS/eip-3009)). This is the standard that lets the wallet sign a payment off-chain and have Prism execute it on-chain.
Tokens currently enabled:
| Token | Symbol | Peg | Issuer | Chains |
| - | - | - | - | - |
| First Digital USD | FDUSD | USD | First Digital | Ethereum, BSC |
| USD Coin | USDC | USD | Circle | Ethereum, Base, BSC, Arbitrum |
In x402 payment requirements, the `asset` field is the token's **ERC-20 contract address** — not the symbol shown above. See the [API Reference](/prism/api-reference/endpoints) for example values.
**FDUSD** is the native stablecoin of the Finance District ecosystem. Merchants settling in FDUSD benefit from tighter integration with FD infrastructure and priority support.
If you need a token that supports ERC-3009 but isn't listed, [contact us](/overview/resources/support). Adding new tokens is straightforward.
See [Network Support](/prism/production/network-support) for the full chain and token compatibility matrix.
## How Settlement Works
An AI agent's wallet holds stablecoins. The agent initiates a payment via
a commerce protocol (x402, UCP) by submitting a signed payment
with the request.
The Spectrum settlement layer executes the stablecoin transfer from the
agent's wallet to the merchant's wallet on-chain.
Spectrum verifies the on-chain transaction: correct amount, correct token,
correct recipient, transaction confirmed on the blockchain.
Prism confirms the payment to the SDK middleware, which allows the original
request to proceed.
Prism delivers a webhook to the merchant's configured endpoint with full
transaction details — amount, token, chain, transaction hash, and timestamp.
Settlement is **direct wallet-to-wallet**. No intermediary holds the funds, no escrow by default. Once confirmed on-chain, the stablecoins are in the merchant's wallet — available immediately.
## Settlement on Different Chains
Settlement happens on the chain specified in the payment requirements. Merchants configure their preferred chain(s) in the [Prism Console](https://apps.fd.xyz/prism/), and the payment response tells the agent which chain to pay on. Prism can settle on any EVM-compatible chain. Adding a new network is a contract deployment on our side.
Enabled chains:
| Chain | Settlement Time | Gas Cost |
| - | - | - |
| Base | \~2 seconds | Very low |
| Arbitrum | \~2 seconds | Very low |
| BSC | \~3 seconds | Low |
| Ethereum | \~12 seconds | Higher |
Need a chain that isn't listed? [Let us know](/overview/resources/support).
**Chain selection guidance:**
* Accept payments on multiple chains for maximum compatibility with different agent wallets
* Consider your agents' chain preferences — settlement is simplest when both sides use the same chain
* L2 chains generally offer faster settlement and lower gas costs
Test your integration on production with small amounts. The settlement flow
works identically regardless of transaction size.
## Merchant Payouts
Once stablecoins settle to the merchant's wallet, they're yours. Options include:
* **Hold stablecoins** — Keep the USD-denominated balance as-is
* **Transfer** — Move funds to another wallet or treasury address
* **Re-invest** — Use stablecoins in DeFi or other on-chain activity
The [Prism Console](https://apps.fd.xyz/prism/) shows settlement history, balances by chain, and transaction details for reconciliation.
# Overview
Source: https://developers.fd.xyz/prism/integrations/acp
Let AI agents buy from your store via ACP and pay with stablecoins, powered by Prism and x402.
Agentic Commerce Protocol (ACP) is an open standard by OpenAI that gives AI agents a shared way to discover merchants, browse catalogs, manage carts, and complete purchases. Prism handles the payment side: it returns the handler declaration, generates x402 payment requirements for each order, and settles the signed payment on-chain.
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
sequenceDiagram
participant A as Agent
participant M as Merchant
participant Pr as Prism
A->>M: GET /.well-known/acp.json
M-->>A: Discovery (services, versions)
A->>M: POST /checkout_sessions
M->>Pr: GET /api/v2/merchant/acp/handlers (cached)
M->>Pr: POST /api/v2/merchant/payment-requirements
Pr-->>M: x402 payment requirements
M-->>A: Session with composed payment handler
Note over A: Agent Wallet signs x402 authorization
A->>M: POST /checkout_sessions/{id}/complete
M->>Pr: POST /api/v2/payment/settle
Pr-->>M: { success: true, transaction: "0x..." }
M-->>A: Order confirmed with txHash
```
## What Prism Does
1. **Handler**. Prism returns the `xyz.fd.prism_payment` handler declaration. Merchants add the x402 payment requirements as its `config` and include the result in their checkout session responses. Chains, tokens, and settlement addresses are configured in the Prism Console.
2. **Payment requirements**. At checkout, Prism returns x402 payment requirements with the correct token amounts and contract addresses already resolved.
3. **Settlement**. The merchant forwards the agent's signed credential to Prism. Prism verifies it, executes the on-chain transfer, and returns the transaction hash.
Add the Prism handler, prepare checkout sessions, and settle agent payments
Discover ACP merchants, sign x402 payments, and complete checkout
Follow one complete purchase from discovery to on-chain settlement
# Agent Integration
Source: https://developers.fd.xyz/prism/integrations/acp/agents
Discover an ACP merchant, sign an x402 payment, and complete checkout.
When your agent finds an ACP merchant that supports `xyz.fd.prism_payment`, it can pay with any x402-capable wallet. This page covers the full flow: discover, browse, checkout, sign, and complete.
## Prerequisites
* An x402-capable wallet funded on a supported chain
* An ACP client that can call merchant REST endpoints
If your platform uses the Finance District Agent Wallet, x402 signing is handled automatically by the MCP server. See [Agent Wallet MCP Server](/agent-wallet/ai-integration/mcp-server).
## Payment Flow
### Step 1: Discover the Merchant
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://merchant.example/.well-known/acp.json
```
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"protocol": {
"name": "acp",
"version": "2026-04-17",
"supported_versions": ["2026-04-17"]
},
"api_base_url": "https://merchant.example/acp/api",
"transports": ["rest"],
"capabilities": {
"services": ["checkout", "product_feed", "orders"],
"extensions": [],
"supported_currencies": ["usd"],
"supported_locales": ["en-US"]
}
}
```
Discovery does not include payment handlers. The agent won't know if the merchant accepts `xyz.fd.prism_payment` until the checkout session is created.
### Step 2: Browse the Product Feed
Fetch the merchant's product feed (`GET /product_feed`) to find items. Each product has variants with IDs you'll use at checkout.
### Step 3: Create a Checkout Session
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/acp/api/checkout_sessions
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_create_sku_red_m_1
Content-Type: application/json
{
"line_items": [
{
"product_id": "prod_classic_tee",
"variant_id": "sku_red_m",
"quantity": 1
}
]
}
```
The response contains `capabilities.payment.handlers`. Look for a handler with `name: "xyz.fd.prism_payment"`.
If `status` is `"collecting_information"`, check `required_fields` for what's missing and update the session.
### Step 4: Update the Session
Provide the required fields:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PUT https://merchant.example/acp/api/checkout_sessions/cs_001
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_001_update_1
Content-Type: application/json
{
"buyer": {
"name": "Jane Doe",
"email": "jane@email.com"
},
"shipping_address": {
"line1": "123 Main St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
"country": "US"
}
}
```
The response returns updated totals and an updated `config` in the payment handler. Continue until `status` is `"ready_for_payment"`.
### Step 5: Authorize with Your Wallet
Extract the `config` object from the Prism handler in the session response. Pass it directly to your x402-capable wallet as the input:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
wallet_authorize_payment({
...config from the handler
})
```
The wallet selects a network from `accepts`, signs an ERC-3009 authorization, and returns the complete signed payment object. The private key never leaves the wallet.
The Finance District Agent Wallet handles this via its x402 authorization tool. Pass the `config` directly and it returns the signed object ready for submission.
### Step 6: Complete the Checkout
Submit the wallet output as the credential. Set both `instrument.type` and `credential.type` to `"default"` (required by the ACP schema for this handler). The wallet output is spread into the credential object.
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/acp/api/checkout_sessions/cs_001/complete
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_001_complete_1
Content-Type: application/json
{
"payment_data": {
"handler_id": "x402",
"instrument": {
"type": "default",
"credential": {
"type": "default",
...wallet_authorize_payment output
}
}
}
}
```
A successful response returns a confirmed order with an on-chain transaction hash:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_001",
"status": "completed",
"order": {
"id": "ord_001",
"checkout_session_id": "cs_001",
"permalink_url": "https://merchant.example/orders/ord_001",
"confirmation": {
"confirmation_number": "0x7a3b...0f1a",
"receipt_url": "https://basescan.org/tx/0x7a3b...0f1a"
}
}
}
```
No `authentication_required` response occurs with this handler. The x402 cryptographic signature serves as authentication. If the signature is invalid or the balance insufficient, the merchant returns a payment failure directly.
### Step 7: Track the Order
Use the `permalink_url` or order endpoints to track fulfillment.
How Agent Wallet handles the payment signing
Connect your agent to the Finance District wallet via MCP
See the full purchase cycle with both sides visible
# End-to-End Flow
Source: https://developers.fd.xyz/prism/integrations/acp/flows
Watch one complete purchase play out: an AI agent buys socks via ACP from discovery to on-chain settlement.
An AI agent buys one pair of "Classic Crew Socks - Black / M" (\$12.99) from an ACP merchant, paying in USDC on Base Sepolia. Each step shows what the agent sends, what the merchant does behind the scenes, and what Prism returns.
***
## 1. Discovery
The agent checks if the merchant supports ACP.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://merchant.example/.well-known/acp.json
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"protocol": {
"name": "acp",
"version": "2026-04-17",
"supported_versions": ["2026-04-17"]
},
"api_base_url": "https://merchant.example/acp/api",
"transports": ["rest"],
"capabilities": {
"services": ["checkout", "product_feed", "orders"],
"extensions": [],
"supported_currencies": ["usd"],
"supported_locales": ["en-US"]
}
}
```
The agent confirms ACP is supported, extracts `api_base_url`, and proceeds.
***
## 2. Product Feed
The agent fetches the merchant's product feed and finds the item.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://merchant.example/acp/api/product_feed
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"products": [
{
"id": "prod_socks_001",
"title": "Classic Crew Socks",
"description": "Comfortable cotton crew socks",
"variants": [
{
"id": "var_socks_blk_m",
"title": "Black / M",
"price": { "amount": 1299, "currency": "usd" },
"available": true,
"options": { "color": "Black", "size": "M" }
}
]
}
]
}
```
The agent selects `var_socks_blk_m` and proceeds to checkout.
***
## 3. Create Checkout Session
The agent sends the item. The merchant calls Prism to get x402 payment requirements, builds the handler from its cached declaration (`GET /api/v2/merchant/acp/handlers`, needs the API key), and returns it in the session.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/acp/api/checkout_sessions
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_create_socks_1
Content-Type: application/json
{
"line_items": [
{
"product_id": "prod_socks_001",
"variant_id": "var_socks_blk_m",
"quantity": 1
}
]
}
```
**Merchant → Prism** (background)
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements
X-API-Key: prism_live_...
Content-Type: application/json
{
"amount": "12.99",
"currency": "usd",
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
}
}
```
Prism returns the raw x402 PaymentRequired object:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "12990000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
```
The merchant sets this object as `config` on the cached handler declaration and returns the composed handler.
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_001",
"status": "collecting_information",
"currency": "usd",
"capabilities": {
"payment": {
"handlers": [
{
"id": "x402",
"name": "xyz.fd.prism_payment",
"version": "2026-01-15",
"spec": "https://prism-gw.fd.xyz/acp/spec.md",
"requires_delegate_payment": false,
"requires_pci_compliance": false,
"psp": "prism",
"config_schema": "https://prism-gw.fd.xyz/acp/config_schema.json",
"instrument_schemas": [
"https://prism-gw.fd.xyz/acp/instrument_schema.json"
],
"config": {
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "12990000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
}
]
},
"interventions": {
"supported": [],
"required": [],
"enforcement": "conditional"
},
"extensions": []
},
"line_items": [
{
"product_id": "prod_socks_001",
"variant_id": "var_socks_blk_m",
"title": "Classic Crew Socks - Black / M",
"quantity": 1,
"unit_price": { "amount": 1299, "currency": "usd" }
}
],
"totals": {
"subtotal": 1299,
"tax": 0,
"shipping": 0,
"total": 1299
},
"required_fields": ["buyer.name", "buyer.email", "shipping_address"]
}
```
The agent reads `status: "collecting_information"` and `required_fields`. Buyer info and a shipping address are needed.
***
## 4. Session Update
The agent provides buyer info and the shipping address. The merchant recalculates totals and calls Prism payment requirements again with updated amounts.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PUT https://merchant.example/acp/api/checkout_sessions/cs_001
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_001_update_1
Content-Type: application/json
{
"buyer": {
"name": "Alice Smith",
"email": "alice@example.com"
},
"shipping_address": {
"line1": "123 Main St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
"country": "US"
}
}
```
**Merchant → Prism** (background, with updated total)
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements
X-API-Key: prism_live_...
Content-Type: application/json
{
"amount": "20.02",
"currency": "usd",
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
}
}
```
Prism returns the raw x402 PaymentRequired object:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "20020000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
```
The merchant sets this object as `config` on the cached handler declaration and returns the composed handler.
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_001",
"status": "ready_for_payment",
"currency": "usd",
"capabilities": {
"payment": {
"handlers": [
{
"id": "x402",
"name": "xyz.fd.prism_payment",
"version": "2026-01-15",
"config": {
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "20020000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
}
]
}
},
"line_items": [
{
"product_id": "prod_socks_001",
"variant_id": "var_socks_blk_m",
"title": "Classic Crew Socks - Black / M",
"quantity": 1,
"unit_price": { "amount": 1299, "currency": "usd" }
}
],
"totals": {
"subtotal": 1299,
"tax": 104,
"shipping": 599,
"total": 2002
}
}
```
Status is now `ready_for_payment`. Total: \$20.02. The `config.accepts` amount has been updated to `"20020000"` (20.02 USDC).
***
## 5. Payment Authorization
The agent extracts `config` from the handler and passes it to the wallet. No HTTP request goes out; everything happens locally in the wallet.
```
Wallet receives: config — x402 paymentRequirements with accepts[]
Wallet selects: eip155:84532 (Base Sepolia), USDC — sufficient balance
Wallet signs: ERC-3009 transferWithAuthorization inside the secure enclave
Wallet returns: complete signed x402 payment object
```
The wallet output contains:
* `paymentPayload.accepted`: the option the wallet chose (USDC on Base Sepolia)
* `paymentPayload.payload.signature`: EIP-712 signature over the authorization
* `paymentPayload.payload.authorization`: EIP-3009 params (exact value, exact recipient, time-limited)
* `paymentRequirements`: echo of the chosen `accepts[]` item
The private key never leaves the enclave. Only the signed authorization exits.
***
## 6. Complete Checkout
The agent submits the signed wallet output as the credential, adding `type: "default"` discriminators.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/acp/api/checkout_sessions/cs_001/complete
Authorization: Bearer
API-Version: 2026-04-17
Idempotency-Key: cs_001_complete_1
Content-Type: application/json
{
"payment_data": {
"handler_id": "x402",
"instrument": {
"type": "default",
"credential": {
"type": "default",
"x402Version": 2,
"paymentPayload": {
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store",
"mimeType": null
},
"accepted": {
"scheme": "exact",
"network": "eip155:84532",
"amount": "20020000",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"asset": "0x036c...cf7e",
"extra": { "name": "USDC", "version": "2" }
},
"payload": {
"signature": "0xef55...a71c",
"authorization": {
"from": "0xC565...0573",
"to": "0x40a0...C4fD",
"value": "20020000",
"validAfter": "1776664729",
"validBefore": "1776665029",
"nonce": "0xf1c1...1b55"
}
},
"extensions": null
},
"paymentRequirements": {
"scheme": "exact",
"network": "eip155:84532",
"amount": "20020000",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"asset": "0x036c...cf7e",
"extra": { "name": "USDC", "version": "2" }
}
}
}
}
}
```
**Merchant → Prism** (background)
The merchant extracts `paymentPayload` and `paymentRequirements` from the credential (stripping the ACP `type` fields) and forwards them to Prism:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/payment/settle
X-API-Key: prism_live_...
Content-Type: application/json
{
"paymentPayload": { "...signed authorization..." },
"paymentRequirements": { "...chosen accepts[] item..." }
}
```
Prism executes the ERC-3009 `transferWithAuthorization` on Base Sepolia, verifies the transfer, and returns:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"success": true,
"payer": "0xC565...0573",
"transaction": "0x7a3b...1a2b",
"network": "eip155:84532"
}
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_001",
"status": "completed",
"order": {
"id": "ord_001",
"checkout_session_id": "cs_001",
"order_number": "#1001",
"permalink_url": "https://merchant.example/orders/ord_001",
"status": "confirmed",
"confirmation": {
"confirmation_number": "0x7a3b...1a2b",
"receipt_url": "https://sepolia.basescan.org/tx/0x7a3b...1a2b",
"confirmation_email_sent": true
},
"line_items": [
{
"product_id": "prod_socks_001",
"variant_id": "var_socks_blk_m",
"title": "Classic Crew Socks - Black / M",
"quantity": 1,
"unit_price": { "amount": 1299, "currency": "usd" }
}
],
"totals": {
"subtotal": 1299,
"tax": 104,
"shipping": 599,
"total": 2002
}
}
}
```
The socks are ordered. 20.02 USDC has settled on-chain to the merchant's wallet on Base Sepolia.
***
## Testing
Use the Prism gateway with your own account and small amounts to validate the full flow end-to-end against real on-chain settlement.
Step-by-step implementation for the merchant server
Step-by-step implementation for the agent
# Merchant Integration
Source: https://developers.fd.xyz/prism/integrations/acp/merchants
Accept AI agent purchases via ACP: advertise the handler, prepare checkout, settle on-chain.
Your merchant server needs to implement ACP's commerce endpoints (discovery, checkout sessions, orders) and integrate Prism for the payment handler. Prism handles token math, chain selection, and x402 formatting.
## Prerequisites
* A [District Pass](/overview/district-pass) account
* A Prism Project Identify Token from the [Prism Console](https://apps.fd.xyz/prism/)
* An ACP-compatible commerce server exposing `/.well-known/acp.json`, `/checkout_sessions`, `/product_feed`, and order endpoints
## Step 1: Host Discovery
ACP agents discover your store by fetching `GET /.well-known/acp.json`. This is a static file declaring your capabilities:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"protocol": {
"name": "acp",
"version": "2026-04-17",
"supported_versions": ["2026-04-17"]
},
"api_base_url": "https://merchant.example/acp/api",
"transports": ["rest"],
"capabilities": {
"services": ["checkout", "product_feed", "orders"],
"extensions": [],
"supported_currencies": ["usd"],
"supported_locales": ["en-US"]
}
}
```
No payment handler information is included at discovery time. Handlers are returned in the checkout session response.
## Step 2: Build the Handler for Checkout Sessions
When an agent creates a checkout session (`POST /checkout_sessions`), you build the Prism handler from two Prism calls: the handler declaration and the payment requirements.
### Fetch the Handler Declaration
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://prism-gw.fd.xyz/api/v2/merchant/acp/handlers
X-API-Key: {YOUR_PRISM_IDENTIFY_TOKEN}
```
Unlike the UCP handlers route, this one needs the API key. Cache the declaration; it rarely changes. It is the handler with an empty `config`:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "x402",
"name": "xyz.fd.prism_payment",
"version": "2026-01-15",
"spec": "https://prism-gw.fd.xyz/acp/spec.md",
"requires_delegate_payment": false,
"requires_pci_compliance": false,
"psp": "prism",
"config_schema": "https://prism-gw.fd.xyz/acp/config_schema.json",
"instrument_schemas": [
"https://prism-gw.fd.xyz/acp/instrument_schema.json"
],
"config": {}
}
```
### Get Payment Requirements
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements
X-API-Key: {YOUR_PRISM_IDENTIFY_TOKEN}
Content-Type: application/json
{
"amount": "19.99",
"currency": "usd",
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
}
}
```
Prism returns the raw x402 PaymentRequired object, with no wrapper. The call is the same for UCP and ACP:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "19990000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
```
### Include in Session Response
Build the handler yourself: copy the cached declaration and set `config` to the x402 object above (`{ ...declaration, config }`). Do not change any other field. Add the result to `capabilities.payment.handlers[]` in your checkout session response:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_001",
"status": "collecting_information",
"currency": "usd",
"capabilities": {
"payment": {
"handlers": [
{
"id": "x402",
"name": "xyz.fd.prism_payment",
"version": "2026-01-15",
"spec": "https://prism-gw.fd.xyz/acp/spec.md",
"requires_delegate_payment": false,
"requires_pci_compliance": false,
"psp": "prism",
"config_schema": "https://prism-gw.fd.xyz/acp/config_schema.json",
"instrument_schemas": [
"https://prism-gw.fd.xyz/acp/instrument_schema.json"
],
"config": {
"x402Version": 2,
"resource": {
"url": "https://merchant.example/acp/api/checkout_sessions/cs_001",
"description": "Purchase from Example Store"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:56",
"amount": "19990000000000000000",
"asset": "0xaB27...b9d9",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "First Digital USD", "version": "1" }
},
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "19990000",
"asset": "0x036c...cf7e",
"payTo": "0x40a0...C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
}
]
},
"interventions": {
"supported": [],
"required": [],
"enforcement": "conditional"
},
"extensions": []
},
"line_items": [
{
"product_id": "prod_classic_tee",
"variant_id": "sku_red_m",
"title": "Classic Tee - Red / Medium",
"quantity": 1,
"unit_price": { "amount": 1999, "currency": "usd" }
}
],
"totals": {
"subtotal": 1999,
"tax": 0,
"shipping": 0,
"total": 1999
},
"required_fields": ["buyer.name", "buyer.email", "shipping_address"]
}
```
**Request and response amounts use different units.** You send `amount` as a fiat **major-unit decimal string** (`"19.99"` — max decimals must match the currency's exponent). Prism returns the `accepts[].amount` values in **token base units**. The tokens that appear in `accepts` depend on what you have enabled in your Prism Console:
| Token | Decimals | Example for \$19.99 |
| - | - | - |
| USDC | 6 | `"19990000"` |
| FDUSD | 18 | `"19990000000000000000"` |
The `config` must be refreshed on every session update that changes the total (e.g., after adding a shipping address or applying a discount). Re-call Prism's payment-requirements endpoint with the updated amount, set the new object as `config` on the cached declaration, and return the handler in your response.
## Step 3: Handle Session Updates
Sessions change as the agent provides information. When the agent updates the session (`PUT /checkout_sessions/{id}`) with buyer info or a shipping address, recalculate your totals and call Prism payment requirements again with the updated amount.
Return the updated session with:
* New `totals` (including tax, shipping)
* Updated `config` in the payment handler (with amounts reflecting the new total)
* `status: "ready_for_payment"` when all required fields are present
## Step 4: Settle via Prism
When the agent completes checkout (`POST /checkout_sessions/{id}/complete`), extract `paymentPayload` and `paymentRequirements` from `payment_data.instrument.credential` (ignore the `type` fields) and forward them to Prism:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/payment/settle
X-API-Key: {YOUR_PRISM_IDENTIFY_TOKEN}
Content-Type: application/json
{
"paymentPayload": { "..." },
"paymentRequirements": { "..." }
}
```
Prism settles on-chain and returns:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"success": true,
"transaction": "0x7a3b...0f1a",
"network": "eip155:8453"
}
```
Create the order and return it with `status: "completed"`. Use the transaction hash as payment proof:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "cs_x402_001",
"status": "completed",
"order": {
"id": "ord_x402_789",
"checkout_session_id": "cs_x402_001",
"permalink_url": "https://merchant.example/orders/ord_x402_789",
"confirmation": {
"confirmation_number": "0x7a3b...0f1a",
"receipt_url": "https://basescan.org/tx/0x7a3b...0f1a"
}
}
}
```
Do not call the settle endpoint more than once per checkout session. If a
complete request arrives for an already-settled session, return the previous
order without re-submitting to Prism.
## Why Prism is Simpler
| Aspect | Prism (`xyz.fd.prism_payment`) |
| - | - |
| Delegate payment | Not needed. The wallet holds spending authority from the moment it's created. There's nothing to delegate. |
| PCI compliance | Not needed. No card numbers, no sensitive data touches your server. |
| Authentication (3DS) | Not needed. The x402 cryptographic signature is the authentication. |
| Settlement | Immediate settlement, no reversals. |
Configure your chains, tokens, and settlement address
See a complete request/response trace for the full purchase cycle
# MCP Server
Source: https://developers.fd.xyz/prism/integrations/mcp-server
Manage your Prism integration from any AI agent — tools for payments, settlement, wallets, extensions, Project Identify Tokens, staff, and more.
The Prism MCP Server exposes your payment platform as tools that any MCP-compatible AI agent can discover and use. It targets providers managing their Prism integration programmatically — querying payments, configuring Projects, managing wallets, and monitoring earnings — all from within an AI assistant.
| Property | Value |
| - | - |
| Server URL | `https://prism-mcp.fd.xyz` |
| Transport | Streamable HTTP |
| Authentication | OAuth Authorization Code Flow with PKCE |
## Account Model
Each authenticated caller is a **Provider** (tenant) identified by their account. Providers own one or more **Projects** — the core unit representing a payment integration. Most tools operate within a Project context.
* If `projectId` is omitted, tools automatically default to the provider's first active Project.
* IDs are GUIDs throughout (e.g., `projectId`, `walletId`, `paymentId`, `projectIdentifyTokenId`).
## Connection Setup
Add the Prism MCP server to your MCP client using the server URL above. Authentication uses OAuth Authorization Code Flow — the first connection opens a browser for you to sign in with your [District Pass](/overview/district-pass).
Add to your `claude_desktop_config.json`:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"mcpServers": {
"prism": {
"type": "http",
"url": "https://prism-mcp.fd.xyz"
}
}
}
```
Add the server URL `https://prism-mcp.fd.xyz` in your editor's MCP settings panel. The OAuth flow triggers automatically on first use.
Connect using any MCP client library. The server implements standard Streamable HTTP transport with OAuth 2.0 PKCE authentication.
```
MCP Server: https://prism-mcp.fd.xyz
Transport: Streamable HTTP
Auth: OAuth 2.0 Authorization Code + PKCE
```
After connecting, verify the integration:
> "What Prism tools do you have available?"
The agent should list the available tools (see the reference below). Then try:
> "Show me my Projects."
## Tool Reference
All tools return JSON. Errors use `{ "error": "CODE", "message": "description" }`.
**MCP clients** discover all tool parameters automatically on connection. **CLI users** can run `fdx prism --help` to see full parameter details. No need to memorize — the tooling tells you what it needs.
### Provider
| Tool | Description |
| - | - |
| `getProviderInfo` | Get provider profile, available blockchain chains, supported tokens, and (optionally) the country catalog |
| `updateProviderAccountType` | Set the provider account type to `Personal` or `Business` |
### Projects
A Project is the top-level entity representing one payment integration. Most tools operate within a Project context — if `projectId` is omitted, your default active Project is used.
| Tool | Description |
| - | - |
| `listProjects` | List all Projects owned by the authenticated provider |
| `getProjectDetails` | Get full details for a Project including configuration, assets, networks, and wallets |
| `createProject` | Create a fully configured Project in one call — storefront, networks, currencies, and wallet source together — and activate it |
| `updateProjectDetails` | Update a Project's display name, storefront URL, platform, country, or environment |
| `activateProject` | Activate a Project so it can accept payments |
| `deactivateProject` | Deactivate a Project so it stops accepting new payments |
| `listMissingProjectSettings` | List the settings a Project still has to fill in before it is complete |
### Dashboard
| Tool | Description |
| - | - |
| `getProjectOverview` | Recommended entry point for a Project's status — revenue, settlement counts, storefront reachability, API key status, recent transactions, and onboarding state |
| `getEarnings` | Earnings summary (total gross earnings) for a Project within a time range |
| `getRecentPayments` | Recent payment summaries for dashboard views |
| `getSettlementMetrics` | Settlement performance — completed count, average amount, and average broadcast-to-block time |
| `getPaymentsSummary` | Payment counts and totals for a Project, with FIQL filtering |
### Settlement Configuration
| Tool | Description |
| - | - |
| `getSettlementSettings` | Get the full settlement configuration for a Project in one call — networks, currencies, and FX settings |
| `updateSettlementNetworks` | Replace the accepted settlement networks for a Project |
| `updateSettlementCurrencies` | Replace the accepted settlement currencies for a Project |
| `updateSettlementFx` | Update FX and cross-currency payment settings for a Project |
| `resetSettlementDefaults` | Reset networks, currencies, or wallet source back to platform defaults |
### Wallets
| Tool | Description |
| - | - |
| `getWalletSettings` | Read where a Project receives settlements — the authoritative settlement destination |
| `updateWalletSettings` | Change where a Project receives settlements (`fd-agent` or `own`) |
### Project Identify Tokens
Manage Project Identify Tokens that authenticate your application against the Prism Gateway.
| Tool | Description |
| - | - |
| `listProjectIdentifyTokens` | List Project Identify Tokens for a Project (secret values are never returned) |
| `manageProjectIdentifyToken` | Create, disable, or delete a Project Identify Token. Secret returned only on creation; `create` accepts an `expiration` of `30d`, `180d`, `365d`, or `none` (never expires) |
### Staff
Manage staff access to Projects. Staff members are invited by email and must accept via a browser OAuth flow. Only the tenant owner can manage staff.
| Tool | Description |
| - | - |
| `listStaff` | List staff members for the provider, optionally scoped to a Project, with FIQL filtering and sorting |
| `manageStaff` | Invite a staff member to a Project by email, or revoke an existing staff member's access |
| `resendStaffInvitation` | Regenerate and resend an invitation email for a Pending staff member |
### Payments
| Tool | Description |
| - | - |
| `listPayments` | List payments with blockchain transaction details, asset info, and status |
| `getPaymentDetails` | Get full details for a single payment including settlement breakdown and fees |
### Extensions
| Tool | Description |
| - | - |
| `listExtensions` | List the extensions available for a Project, including their enabled state |
| `setExtensionEnabled` | Enable or disable an extension for a Project |
### Cashback
| Tool | Description |
| - | - |
| `acceptCashbackCampaign` | Accept a cashback campaign for a Project |
| `setCashbackEnabled` | Enable or disable a cashback campaign for a Project |
| `setupCustomCashback` | Set up a custom cashback campaign for a Project |
For the full parameter list and annotations for every tool, see the generated manifest (`docs/mcp-tools.json` in `fd-prism-services`).
### Renamed and removed in 2026-09
The tool set was reworked and then renamed so that every tool name describes what it does rather than which screen it came from. Update any saved workflows that reference an old name:
| Old tool | Replacement |
| - | - |
| `listWallets` | `getWalletSettings` |
| `manageWallet` | `updateWalletSettings` |
| `configureProject` | `getSettlementSettings` / `updateSettlementNetworks` / `updateSettlementCurrencies` / `updateSettlementFx` / `resetSettlementDefaults` |
| `updateProject` | `updateProjectDetails` + `activateProject` + `deactivateProject` |
| `createProjectFromWizard` | `createProject` |
| `getHomeSummary` | `getProjectOverview` |
| `getTransactionsSummary` | `getPaymentsSummary` |
| `getRequiredUpdates` | `listMissingProjectSettings` |
| `updateAccountType` | `updateProviderAccountType` |
| `updateProjectAccount` | `updateProjectDetails` |
`createProject` existed before the rework with a different signature (a `configurationJson` blob, no activation). The name is now reused for the one-call create-and-activate tool. A call using the old shape is rejected by validation rather than silently misconfiguring a Project.
## Example Interactions
Once connected, you can ask your AI agent questions like:
```
"List my active Projects."
"Show me all payments from the last 30 days."
"What are my total earnings this month?"
"Create a new identify token named 'production-v2' for my default Project."
"Add a USDC wallet on Base (chain ID 8453) with address 0xABC... to my Project."
"Disable Project Identify Token ."
"Get the full details for payment ."
```
## Error Handling
All tools return structured errors:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{ "error": "ERROR_CODE", "message": "Human-readable description" }
```
Common errors:
| Error Code | Meaning |
| - | - |
| `MISSING_PROJECT_ID` | `projectId` required but omitted (e.g., for activate action) |
| `INVALID_PAYMENT_ID` | `paymentId` is not a valid GUID |
| `MISSING_NAME` | Name parameter required but not provided |
| `INVALID_ACTION` | Unknown action value passed to an action-discriminated tool |
| `INVALID_ACCOUNT_TYPE` | Account type must be `Personal` or `Business` |
| `MISSING_PROJECT_IDENTIFY_TOKEN_ID` | `projectIdentifyTokenId` required but not provided or not a valid GUID |
# Overview
Source: https://developers.fd.xyz/prism/integrations/ucp
Let AI agents buy from your store and pay with stablecoins, powered by Prism and x402.
Universal Commerce Protocol (UCP) is an open standard that gives AI agents a shared way to discover merchants, browse catalogs, build carts, and pay. Prism handles the payment side: it exposes a ready-to-use handler, generates x402 payment requirements for each order, and settles the signed payment on-chain.
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
sequenceDiagram
participant P as Platform (Agent)
participant M as Merchant
participant Pr as Prism
P->>M: GET /.well-known/ucp
M->>Pr: GET /ucp/{ucpVersion}/handlers
Pr-->>M: xyz.fd.prism_payment handler declaration
M-->>P: UCP profile with payment handler
P->>M: POST /checkout-sessions
M->>Pr: POST /api/v2/merchant/payment-requirements
Pr-->>M: raw x402 PaymentRequired (per chain/token)
M-->>P: Session with handler entry (declaration id/version + x402 config)
Note over P: Agent Wallet signs x402 authorization
P->>M: POST /checkout-sessions/{id}/complete
M->>Pr: POST /api/v2/payment/settle
Pr-->>M: { success: true, transaction: "0x..." }
M-->>P: Order confirmed with txHash
```
## What Prism Does
1. **Advertise**. Prism gives merchants a `xyz.fd.prism_payment` handler to drop into their UCP profile. Chains, tokens, and settlement settings live in the Prism Console.
2. **Prepare**. At checkout, Prism returns the x402 payment requirements for the order, with the correct token amounts and contract addresses already resolved.
3. **Settle**. The merchant forwards the agent's signed credential to Prism. Prism verifies it, executes the on-chain transfer, and returns the transaction hash.
Add the Prism handler, prepare checkout sessions, and settle agent payments
Discover UCP merchants, sign x402 payments, and complete checkout cleanly
Follow one complete purchase from discovery to on-chain settlement
# Agent Integration
Source: https://developers.fd.xyz/prism/integrations/ucp/agents
Discover a merchant, sign an x402 payment, and complete checkout in four steps.
When your agent finds a UCP merchant that supports `xyz.fd.prism_payment`, it can pay with any x402-capable wallet. This page covers the four steps: discover, checkout, sign, and complete.
## Prerequisites
* An x402-capable wallet funded on a supported chain
* A UCP profile your agent can reference (e.g., `https://platform.example/ucp/profile`)
* A way to [authenticate](#authentication): request signing with a key in your profile, or an API key from the merchant when the store requires one
If your platform uses the Finance District Agent Wallet, x402 signing is handled automatically by the MCP server. See [Agent Wallet MCP Server](/agent-wallet/ai-integration/mcp-server).
## Advertise the Handler in Your Profile
Include `xyz.fd.prism_payment` in your platform's `payment_handlers` registry. Use the same entry Prism publishes, with an empty `config`. This tells the merchant your platform can fulfill this payment method.
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"ucp": {
"version": "2026-08-25",
"payment_handlers": {
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"spec": "https://prism-gw.fd.xyz/ucp/prism.md",
"schema": "https://prism-gw.fd.xyz/ucp/schema.json",
"available_instruments": [{ "type": "x402" }],
"config": {}
}
]
}
}
}
```
The entry `schema` is the handler config schema. The instrument schema is linked from that document at `$defs["xyz.fd.prism_payment"].instrument`.
## Authentication
Discovery (`GET /.well-known/ucp`), catalog search, and catalog lookup need no credentials. Every other request carries `UCP-Agent: profile="https://..."` with the https URL of your platform profile. Depending on the store, you also prove that profile in one of two ways:
* **Signed requests.** Sign each request with RFC 9421 HTTP message signatures. Publish the public key in the `keys[]` of the profile named in `UCP-Agent`. The store verifies the signature against that profile.
* **API key.** Ask the merchant for an API key registered for your profile URL. Send it in the `X-API-Key` header together with `UCP-Agent`. The key only works for the profile URL the merchant registered it for.
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/checkout-sessions
Content-Type: application/json
UCP-Agent: profile="https://platform.example/ucp/profile"
X-API-Key: {KEY_ISSUED_BY_THE_MERCHANT}
```
What a store requires depends on its access mode:
| Store mode | Without a credential | With a credential |
| - | - | - |
| **Open** (default) | Served, unless your profile is registered at the store. A registered profile gets `401 signature_missing`. | Always checked. A wrong key gets `401 key_not_found`. |
| **Authenticated** | `401 signature_missing` | Must be a valid signature or a registered key. |
| **Registered only** | `403 profile_not_trusted` if your profile is not registered. A registered profile gets `401 signature_missing`. | Must be a registered key, or a signature from a registered profile. |
In Open mode a platform that sends no credential is identified only by the profile URL it claims, and platforms that claim the same URL share the same carts, checkout sessions, and orders. Ask the merchant for a key to get a private space. Once the merchant registers your profile, send the key on every request.
The verified profile URL identifies your platform. On WooCommerce, checkout sessions, carts, and orders belong to the platform that created them. A request for a session, cart, or order that belongs to another platform answers `404` with the route's own not-found code, for example `order_not_found`. Orders are addressed by an opaque id such as `wc_order_...`, and there is no endpoint that lists orders. On Saleor, a sent `X-API-Key` must equal the store's ACP key, orders require the `UCP-Session-Secret` header returned when the checkout session is created, and checkout sessions are protected by their id.
| Status | Code | Meaning |
| - | - | - |
| 400 | `invalid_profile_url` | `UCP-Agent` is missing or does not carry an https profile URL of at most 180 characters |
| 401 | `signature_missing` | The request has neither a signature nor an `X-API-Key`, and the store requires one: the store is in Authenticated mode, or your profile is registered at the store |
| 401 | `key_not_found` | The `X-API-Key` is not registered, is disabled, or does not equal the store key, or the signing key id is not in the profile `keys[]` |
| 401 | `signature_invalid` | The signature does not verify, its required components are missing, or only one of `Signature` and `Signature-Input` is sent |
| 403 | `profile_not_trusted` | The `X-API-Key` is registered for a different profile than the one in `UCP-Agent`, the merchant disabled your platform, or the store accepts registered platforms only and yours is not registered |
| 424 | `profile_unreachable` | The store could not fetch your profile to verify the signature |
## Payment Flow
### Step 1: Discover the Handler
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://merchant.example/.well-known/ucp
```
Confirm `xyz.fd.prism_payment` appears in `payment_handlers`. If present, the merchant accepts Prism payments and the flow can proceed.
### Step 2: Create a Checkout Session
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/checkout-sessions
Content-Type: application/json
UCP-Agent: profile="https://platform.example/ucp/profile"
X-API-Key: {KEY_ISSUED_BY_THE_MERCHANT}
{
"line_items": [
{ "item": { "id": "ticket_vip_01" }, "quantity": 1 }
]
}
```
The response contains `payment_handlers["xyz.fd.prism_payment"][0].config` — the x402 payment requirements populated by Prism. Extract this object; it is the direct input for wallet authorization.
### Step 3: Authorize with Your Wallet
Pass the `config` object to your x402-capable wallet as `paymentRequirements`. The wallet selects a network from `accepts`, signs an ERC-3009 authorization inside the secure enclave, and returns the complete signed payment object.
The Finance District Agent Wallet handles this via its x402 authorization tool. Pass the `config` directly and it returns the signed object ready for submission — no additional formatting required.
### Step 4: Complete the Checkout
Submit the wallet output as the credential. Both `instrument.type` and `credential.type` must be `"x402"`. The credential is the wallet output plus that one `type` field. Set `handler_id` to `xyz.fd.prism_payment` and give the instrument an `id`.
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://merchant.example/checkout-sessions/{id}/complete
Content-Type: application/json
UCP-Agent: profile="https://platform.example/ucp/profile"
X-API-Key: {KEY_ISSUED_BY_THE_MERCHANT}
{
"payment": {
"instruments": [
{
"id": "your_instrument_id",
"handler_id": "xyz.fd.prism_payment",
"type": "x402",
"credential": {
"type": "x402",
"x402Version": 2,
"paymentPayload": { "...": "signed ERC-3009 authorization" },
"paymentRequirements": { "...": "config from Step 2" }
}
}
]
}
}
```
A successful response returns a confirmed order with an on-chain transaction hash:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"order": {
"id": "ord_abc123",
"status": "confirmed",
"payment": {
"handler_id": "xyz.fd.prism_payment",
"status": "settled",
"transaction": "0xe80c...674b"
}
}
}
```
How Agent Wallet handles the payment signing
Connect your agent to the Finance District wallet via MCP
See the full purchase cycle with both sides visible
# End-to-End Flow
Source: https://developers.fd.xyz/prism/integrations/ucp/flows
Watch one complete purchase play out: an AI agent buys a concert ticket from discovery to on-chain settlement.
An AI agent buys one "Coldplay World Tour - Floor Standing GA" ticket (\$120.00), paying in FDUSD on BSC. Each step shows what the agent sends, what the merchant does behind the scenes, and what Prism returns.
***
## 1. Discovery
The agent checks the merchant's UCP profile. The merchant fetches the handler declaration for its UCP version from Prism and returns it. The merchant caches this declaration.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET /.well-known/ucp
UCP-Agent: profile="https://platform.example/ucp/profile"
```
**Merchant → Prism** (background)
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://prism-gw.fd.xyz/ucp/2026-08-25/handlers
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"ucp": {
"version": "2026-08-25",
"payment_handlers": {
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"spec": "https://prism-gw.fd.xyz/ucp/prism.md",
"schema": "https://prism-gw.fd.xyz/ucp/schema.json",
"available_instruments": [{ "type": "x402" }],
"config": {}
}
]
}
}
}
```
Discovery needs no credentials. The agent confirms `xyz.fd.prism_payment` is present and proceeds to checkout. From here on, every request carries `UCP-Agent`, and a credential when the store requires one: an `X-API-Key` the merchant issued for the agent's profile, or an RFC 9421 signature. See [Authentication](/prism/integrations/ucp/agents#authentication).
***
## 2. Checkout Session
The agent sends their cart. The merchant calls Prism to get the raw x402 payment requirements. It builds the handler entry from the cached declaration `id` and `version`, with the x402 object as `config`, and returns it in the session.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST /checkout-sessions
Content-Type: application/json
UCP-Agent: profile="https://platform.example/ucp/profile"
X-API-Key: {KEY_ISSUED_BY_THE_MERCHANT}
{
"line_items": [
{ "item": { "id": "ticket_floor_ga" }, "quantity": 1 }
]
}
```
**Merchant → Prism** (background)
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements
X-API-Key: prism_live_...
Content-Type: application/json
{
"amount": "120.00",
"currency": "USD",
"resource": {
"url": "https://merchant.example/checkout-sessions/sess_abc123",
"description": "Coldplay World Tour - Floor Standing GA"
}
}
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"session_id": "sess_abc123",
"payment_handlers": {
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"config": {
"x402Version": 2,
"resource": {
"url": "https://merchant.example/checkout-sessions/sess_abc123",
"description": "Coldplay World Tour - Floor Standing GA"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:56",
"amount": "120000000000000000000",
"asset": "0xaB27f55DB008704Ed8098f0dfBCf5e1aA387b9d9",
"payTo": "0x40a01003f7543a3a3ee64fFB05504173BDb1C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "First Digital USD", "version": "1" }
},
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "120000000",
"asset": "0x036cbd53842c5426634e7929541ec2318f3dcf7e",
"payTo": "0x40a01003f7543a3a3ee64fFB05504173BDb1C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
}
]
}
}
```
The agent extracts `config` and passes it to the wallet.
***
## 3. Payment Authorization
The agent's wallet receives the `config` as `paymentRequirements`. No HTTP request goes out at this step — everything happens locally inside the TEE.
```
Wallet receives: config.accepts — two options (BSC FDUSD, Base USDC)
Wallet selects: eip155:56 (BSC), FDUSD — sufficient balance available
Wallet signs: ERC-3009 transferWithAuthorization inside the secure enclave
Wallet returns: complete signed x402 payment object
```
The private key never leaves the enclave. Only the signed authorization exits.
***
## 4. Complete Checkout
The agent submits the signed wallet output as the credential, plus one field: `type: "x402"`. The instrument also has `type: "x402"` and `handler_id: "xyz.fd.prism_payment"`.
**Agent → Merchant**
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST /checkout-sessions/sess_abc123/complete
Content-Type: application/json
UCP-Agent: profile="https://platform.example/ucp/profile"
X-API-Key: {KEY_ISSUED_BY_THE_MERCHANT}
{
"payment": {
"instruments": [
{
"id": "wallet_bsc_fdusd",
"handler_id": "xyz.fd.prism_payment",
"type": "x402",
"credential": {
"type": "x402",
"x402Version": 2,
"paymentPayload": {
"signature": "0x...",
"authorization": {
"from": "0xAgentWalletAddress",
"to": "0x40a01003f7543a3a3ee64fFB05504173BDb1C4fD",
"value": "120000000000000000000",
"validAfter": "0",
"validBefore": "1760000000",
"nonce": "0x..."
}
},
"paymentRequirements": { "...": "config from step 2" }
}
}
]
}
}
```
**Merchant → Prism** (background)
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/payment/settle
X-API-Key: prism_live_...
Content-Type: application/json
{ ...credential object verbatim... }
```
Prism executes the ERC-3009 `transferWithAuthorization` on BSC, verifies the transfer, and returns:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"success": true,
"transaction": "0xe80c...674b",
"network": "eip155:56"
}
```
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"order": {
"id": "wc_order_aB3dE5fG7hJ9kL",
"status": "confirmed",
"payment": {
"handler_id": "xyz.fd.prism_payment",
"status": "settled",
"transaction": "0xe80c...674b",
"network": "eip155:56"
}
}
}
```
The ticket is reserved. 120 FDUSD has settled on-chain to the merchant's wallet.
The order `id` is opaque. Orders are fetched by this id, and only the platform that created the order can read it. There is no endpoint that lists orders.
***
## 5. Payment Held for Review
A merchant can hold a settled payment for manual review. The request still succeeds with HTTP `200`. The checkout is not completed, so the agent sends the buyer to `continue_url`.
**Agent receives:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"session_id": "sess_abc123",
"status": "requires_escalation",
"continue_url": "https://merchant.example/checkout/order-received/...",
"messages": [
{
"type": "error",
"code": "payment_on_hold",
"severity": "requires_buyer_review",
"content": "Payment received but held for merchant review"
}
]
}
```
The payment has been received and the merchant keeps the order on hold until the review ends.
A `GET` of the same checkout session returns the same `status`, `continue_url`, and message. Sending the complete request again answers `409 session_requires_escalation`.
***
## Testing
Use the production Prism gateway (`https://prism-gw.fd.xyz`) with your own account and small amounts to validate the full flow end-to-end against real on-chain settlement.
Step-by-step implementation for the merchant server
Step-by-step implementation for the agent platform
# Merchant Integration
Source: https://developers.fd.xyz/prism/integrations/ucp/merchants
Three steps to accept AI agent purchases: advertise the handler, get payment requirements, settle on-chain.
Your merchant server needs three things to accept UCP payments through Prism: a discovery endpoint, a checkout call, and a settle call. Everything else (token math, chain selection, x402 formatting) is handled by Prism.
## Prerequisites
* A [District Pass](/overview/district-pass) account
* A Prism Project Identify Token from the [Prism Console](https://apps.fd.xyz/prism/)
* A UCP-compatible commerce server exposing `/.well-known/ucp`, `/checkout-sessions`, and order endpoints
## Step 1: Advertise the Handler
When a UCP agent calls `GET /.well-known/ucp`, fetch the handler declaration for your UCP version from Prism and include it in your response. The route is public and needs no API key. Cache the declaration; it rarely changes.
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET https://prism-gw.fd.xyz/ucp/2026-08-25/handlers
```
Merge the result into your UCP profile's `payment_handlers` before responding to the agent. Add the entry as Prism returns it; do not change its fields:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"ucp": {
"version": "2026-08-25",
"payment_handlers": {
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"spec": "https://prism-gw.fd.xyz/ucp/prism.md",
"schema": "https://prism-gw.fd.xyz/ucp/schema.json",
"available_instruments": [{ "type": "x402" }],
"config": {}
}
]
}
}
}
```
## Step 2: Get Payment Requirements from Prism
When a platform creates a checkout session (`POST /checkout-sessions`), call Prism to get the x402 payment requirements for that order. This call does not depend on the UCP version:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/merchant/payment-requirements
X-API-Key: {YOUR_PRISM_IDENTIFY_TOKEN}
Content-Type: application/json
{
"amount": "120.00",
"currency": "USD",
"resource": {
"url": "https://merchant.example/checkout-sessions/sess_abc123",
"description": "Coldplay World Tour - Floor Standing GA"
}
}
```
Prism returns the raw x402 PaymentRequired object, with no wrapper:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"resource": {
"url": "https://merchant.example/checkout-sessions/sess_abc123",
"description": "Coldplay World Tour - Floor Standing GA"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:56",
"amount": "120000000000000000000",
"asset": "0xaB27f55DB008704Ed8098f0dfBCf5e1aA387b9d9",
"payTo": "0x40a01003f7543a3a3ee64fFB05504173BDb1C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "First Digital USD", "version": "1" }
},
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "120000000",
"asset": "0x036cbd53842c5426634e7929541ec2318f3dcf7e",
"payTo": "0x40a01003f7543a3a3ee64fFB05504173BDb1C4fD",
"maxTimeoutSeconds": 300,
"extra": { "name": "USDC", "version": "2" }
}
]
}
```
Build the checkout entry yourself. Take `id` and `version` from the cached handlers declaration. Set `config` to the object above. Put the entry in `payment_handlers` of your checkout session response:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"xyz.fd.prism_payment": [
{
"id": "xyz.fd.prism_payment",
"version": "2026-10-07",
"config": {
"x402Version": 2,
"resource": { "url": "https://merchant.example/checkout-sessions/sess_abc123" },
"accepts": ["..."]
}
}
]
}
```
**Request and response amounts use different units.** You send `amount` as a fiat **major-unit decimal string** (`"120.00"` for \$120.00 — max decimals must match the currency's exponent, so USD allows 2). Prism converts it and returns the `accepts[].amount` values in **token base units**. The tokens that appear in `accepts` depend on what you have enabled in your Prism Console:
| Token | Decimals | Example for \$120.00 |
| - | - | - |
| USDC | 6 | `"120000000"` |
| FDUSD | 18 | `"120000000000000000000"` |
UCP requires payments to be bound to the specific product or service being
purchased. Set `resource.url` to the unique checkout session URL. The agent
wallet includes this URL in the signed authorization, tying the credential to
that session.
## Step 3: Settle via Prism
When the platform completes checkout (`POST /checkout-sessions/{id}/complete`), extract the credential from `payment.instruments[0].credential` and forward it to Prism's settlement endpoint:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
POST https://prism-gw.fd.xyz/api/v2/payment/settle
X-API-Key: {YOUR_PRISM_IDENTIFY_TOKEN}
Content-Type: application/json
{ ...entire credential object from the platform... }
```
Prism settles on-chain and returns:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"success": true,
"transaction": "0xe80c...674b",
"network": "eip155:56"
}
```
Before you settle, check that the instrument has `handler_id` `xyz.fd.prism_payment`, `type` `x402`, and `credential.type` `x402`. Reject any other value with a UCP error and do not create an order. The extra `type` field in the credential is safe to forward; Prism ignores it.
Return the confirmed order to the platform with `payment.status: "settled"` and `payment.transaction` set to the returned txHash.
Do not call the settle endpoint more than once per checkout session. If a
complete request arrives for an already-settled session, return the previous
order without re-submitting to Prism.
## Authenticate Platforms
Discovery, catalog search, and catalog lookup are public in every mode. Every other route identifies the calling platform by the profile URL in `UCP-Agent`. A platform proves that profile with an RFC 9421 signature that verifies against the `keys[]` of the profile, or with an API key you registered for the profile.
One store key per merchant. ACP presents it as Authorization: Bearer. UCP presents it as X-API-Key.
### WooCommerce
Open **WooCommerce > Settings > Advanced > UCP versions**. The **Platform access** block has a mode selector and the list of registered platforms.
| Mode | Behavior |
| - | - |
| **Open** (default) | Any platform can shop. A platform registered in the list must send its key or sign, otherwise it gets `401 signature_missing`. A platform that is not registered and sends no credential is served as unverified. |
| **Authenticated** | Every platform must sign its requests or send a registered key. A request with no credential gets `401 signature_missing`. |
| **Registered only** | Only platforms with an enabled entry in the list are served, signed or with their key. Any other platform gets `403 profile_not_trusted`. |
In every mode a presented credential is always checked. A wrong or unknown `X-API-Key` gets `401 key_not_found`. A request that carries a `Signature` or `Signature-Input` header is checked as a signed request and rejected if the signature fails. Neither falls through to unverified.
Open does not protect carts, checkout sessions, or orders of platforms that
send no key. Those callers share ownership per claimed profile URL: anyone who
claims the same profile URL reaches the same records. Only the unguessable
ids and the `Idempotency-Key` the client chooses keep them apart. Someone who
claims the same URL and knows an `Idempotency-Key` and the same create body
gets the existing session back, and a different body gets
`409 idempotency_key_conflict`. Near-identical URLs (other path case,
percent-encoding, a trailing dot in the host, a query string) map to separate
unverified spaces. Turn on **Authenticated** or **Registered only** if the
store holds sensitive buyer data. Register a platform to give it a private
space that only its key can reach.
#### Register a platform
1. Enter the platform's https profile URL (at most 180 characters) and a label, then save.
2. Copy the API key shown in the notice after saving.
3. Give the key to the platform operator. The platform sends it as `X-API-Key` next to its `UCP-Agent` header. For the Finance District MCP server, the operator sets it as `Merchants::ApiKey`.
A key grants the identity of the profile URL it is registered for, so register only profile URLs you have confirmed belong to the platform you are onboarding. A key presented with a different profile URL answers `403 profile_not_trusted`.
Registering a platform that used to shop without a key starts a new private space. What it created before registering is no longer reachable by it.
#### Show a key again
Tick **Show** on the platform's row and save. The key appears once in the notice after saving. It is not printed in the page, in logs, or in REST responses.
* The store keeps the key hash for verification and an encrypted copy so it can be shown again.
* Only users with the `manage_woocommerce` capability can reveal a key. Each reveal is written to **WooCommerce > Status > Logs** (source `fd-ucp`) with the platform profile and user id, never the key.
* A key that cannot be shown must be re-issued: register the profile again to get a new key, then disable the old one. This applies to keys issued before the Show option existed and to keys whose encrypted copy can no longer be read, for example after the WordPress salts change. The old key keeps working until you disable it.
* Anyone who holds a database dump together with `wp-config.php` can decrypt the stored copies. Rotate the key if either leaks.
#### Disable or revoke a platform
You can disable or delete a platform at any time. To revoke a platform, disable all of its entries. The store then refuses that platform with `403 profile_not_trusted` on both the signed and the API key path. A platform with at least one enabled entry is not blocked, so you can rotate a key by adding a new one and disabling the old one. Deleting the entries removes the block.
In **Open** mode a revoked or unregistered platform can still come back as unverified under a different or near-identical profile URL. Use **Authenticated** or **Registered only** when this matters.
Carts, checkout sessions, and orders belong to the platform that created them. Another platform that asks for them gets `404` with the route's own not-found code, for example `order_not_found`.
### Saleor
UCP routes stay open when no `X-API-Key` is sent. A request that sends `X-API-Key` must send the store's ACP key, otherwise it gets `401 key_not_found`, including when the store has no ACP key set. The integration does not check request signatures. Orders require the `UCP-Session-Secret` header returned when the checkout session is created. Checkout sessions are protected only by their id, not by the platform profile.
See [Agent Integration](/prism/integrations/ucp/agents#authentication) for every error code.
Configure your chains, tokens, and settlement address
See a complete request/response trace for the full purchase cycle
# Supported UCP Versions
Source: https://developers.fd.xyz/prism/integrations/ucp/supported-versions
Which UCP versions the Finance District store plugins and Prism serve, how a version is chosen per request, and how to configure it.
The Finance District store plugins serve three UCP versions side by side: **2026-08-25** (default), **2026-04-08** and **2026-01-23**. Each request is answered in the version the agent declares. Existing plugin releases keep working against Prism without any change.
## Two separate versions
Two version numbers appear in a UCP integration with Prism. They change independently.
| Version | Example | Where it appears | Who sets it |
| - | - | - | - |
| UCP protocol version | `2026-08-25` | `ucp.version` in the store profile and in every UCP response | The store, per request |
| Prism handler contract | `2026-10-07` | `version` inside the `xyz.fd.prism_payment` handler entry | Prism |
A store on UCP 2026-01-23 and a store on UCP 2026-08-25 both advertise the same Prism handler contract `2026-10-07`.
## Plugin releases
| Plugin | Release | Default UCP version | Also available |
| - | - | - | - |
| WooCommerce (core 0.3.1, Prism payment 0.3.0) | 0.3.1 | 2026-08-25 | 2026-04-08, 2026-01-23 |
| PrestaShop (`fdpsucp` 0.7.1, `fdpsprism` 0.7.0) | 0.7.1 | 2026-08-25 | 2026-04-08, 2026-01-23 |
| Medusa (`medusa-plugin-agentic-commerce` + `medusa-plugin-prism-payment`) | 1.1.0 | 2026-08-25 | 2026-04-08, 2026-01-23 |
| Saleor core | 1.1.0 | 2026-08-25 | 2026-04-08, 2026-01-23 |
| Saleor Next.js, Prism payment, dummy payment | 2.1.0 | 2026-08-25 | 2026-04-08, 2026-01-23 |
| Shopware Prism handler | 0.7.0 | Follows SwagAgenticCommerce | See [Shopware](#shopware) |
All plugin updates are minor releases. No config key, route, export or response field was removed or renamed.
The default is the latest UCP version, currently 2026-08-25. Fresh installs and upgrades start there. Agents that declare a version in their profile are served that version regardless of the default. Stores that never update the plugin are unaffected.
* **WooCommerce, PrestaShop**: to stay on an older version, set it under UCP versions in the plugin settings. A version already saved there is kept on update.
* **Medusa, Saleor**: an omitted version option means the latest version. To pin, set `ucp_version` (Medusa) or `ucpVersion` (Saleor) to `"2026-04-08"`.
## Discovery
`GET /.well-known/ucp` returns the profile in the store's current version. It lists every other enabled version under `ucp.supported_versions`, each pointing to a leaf profile:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"ucp": {
"version": "2026-08-25",
"supported_versions": {
"2026-04-08": "https://shop.example/.well-known/ucp/2026-04-08",
"2026-01-23": "https://shop.example/.well-known/ucp/2026-01-23"
}
}
}
```
`GET /.well-known/ucp/{version}` returns the profile for one enabled version. A version that is not enabled returns `404 version_unsupported`. Leaf profiles never contain `supported_versions`.
UCP 2026-01-23 has no cart or catalog capability. In that version, cart and catalog routes return `404`.
## Configuration
Every plugin has the same three settings. On Medusa and Saleor the current-version setting already existed and keeps its name. On WooCommerce and PrestaShop all three settings are new in 0.3.0 and 0.7.0.
| Setting | WooCommerce option | PrestaShop key | Medusa option | Saleor option |
| - | - | - | - | - |
| Current version | `fd_ucp_version` | `FDPSUCP_UCP_VERSION` | `ucp_version` | `ucpVersion` |
| Also supported versions | `fd_ucp_supported_versions` | `FDPSUCP_UCP_SUPPORTED_VERSIONS` | `ucp_supported_versions` | `ucpSupportedVersions` |
| Version negotiation | `fd_ucp_version_negotiation` | `FDPSUCP_UCP_NEGOTIATION` | `ucp_version_negotiation` | `ucpVersionNegotiation` |
| Setting | Default | Meaning |
| - | - | - |
| Current version | Latest (`2026-08-25`) | Served at `/.well-known/ucp` and to agents that do not declare a version |
| Also supported versions | Every other known version (`2026-04-08`, `2026-01-23`) | Extra versions an agent may pick. The current version is removed from this list. |
| Version negotiation | `lenient` | `lenient` or `strict`. Decides what happens when the agent profile cannot be used. |
Where to set them:
* **WooCommerce**: WooCommerce > Settings > Advanced > UCP versions.
* **PrestaShop**: Modules > Finance District UCP > Configure > UCP versions.
* **Medusa**: options of the `agenticCommerce` module in `medusa-config.ts`.
* **Saleor**: `createAgenticCommerce({ ucpVersion, ucpSupportedVersions, ucpVersionNegotiation })`. Wire the `discoveryVersion` route at `src/app/.well-known/ucp/[version]/route.ts`. The Next.js integration needs the Node.js runtime.
On Medusa and Saleor, leaving the supported list unset enables every known version other than the current one, so `ucpVersion: "2026-04-08"` alone keeps 2026-08-25 and 2026-01-23 available. On WooCommerce and PrestaShop, the settings page saves both values together.
An unknown version or negotiation value is rejected:
* **Medusa, Saleor**: the store fails at boot.
* **WooCommerce, PrestaShop**: saving the setting fails. If an unknown value is stored anyway, every UCP route answers `500 configuration_invalid` and the admin shows a notice. The rest of the shop keeps running.
## How a request gets its version
The agent names its profile in the `UCP-Agent` header (`profile="https://..."`). The store fetches that profile and reads `ucp.version`.
`UCP-Agent` is required on every route except catalog search and catalog lookup. The same profile identifies the platform for authentication. See [Authentication](/prism/integrations/ucp/agents#authentication).
The profile fetch is restricted: HTTPS only, public addresses only, no redirects, 3 second timeout, 64 KiB limit. Results, including failures, are cached for 10 minutes.
| Agent profile | `lenient` (default) | `strict` |
| - | - | - |
| No `profile` in `UCP-Agent` (catalog routes only; other routes answer `400 invalid_profile_url`) | Current version, as in earlier releases | Same |
| Unreachable, not HTTPS, private host, too large, timeout | Current version + warning | `424 agent_profile_unavailable` |
| No or malformed `ucp.version` | Current version + warning | `422 version_unsupported` |
| Unknown version date | Current version + warning | `422 version_unsupported` |
| Known version, disabled by the store | `422 version_unsupported` | `422 version_unsupported` |
| Enabled version | That version | That version |
The warning is one structured log line with the key `ucp_profile_resolution` and the outcome (`unreachable`, `undeclared` or `unknown`).
The `422 version_unsupported` message lists what the store serves, for example: `Version 2026-07-01 is not supported. This business implements versions 2026-08-25, 2026-04-08, 2026-01-23.`
**Lenient mode deviates from the UCP spec on purpose.** The spec says a business must reject an agent whose profile it cannot read or whose version it does not know. Lenient mode serves the current version instead, so agents built before version negotiation keep working. A version the store disabled is always rejected. Choose `strict` to follow the spec exactly.
### Session pinning
A checkout session (and a cart, where the plugin has one) keeps the version its agent declared when it was created.
| Later request on the same session | Result |
| - | - |
| Agent declares the same version | Served in that version |
| Agent declares a different enabled version | `422 version_unsupported` |
| Agent profile cannot be read, has no version, or names an unknown version (lenient) | Served in the session's version + warning |
A session is pinned only when the agent profile declared a version the store serves. Sessions created on a fallback, and sessions created by an earlier release, are not pinned.
## Payment instruments and the Prism handler entry
Upgraded plugins accept both Prism handler entry shapes:
* the current entry: `id` `xyz.fd.prism_payment`, `version` `2026-10-07`, `spec`, `schema`, `config`, `config_schema`, `instrument_schemas` and, except for 2026-01-23, `available_instruments`;
* the original entry: `id` `x402` (or `xyz.fd.prism_payment`), `config_schema`, `instrument_schemas`, `config`.
Either way, the store advertises the current entry with `id` `xyz.fd.prism_payment`.
Instruments sent by agents written for earlier releases still complete:
* `handler_id`: `xyz.fd.prism_payment`, `x402` or missing
* `type`: `x402`, `tokenized`, `default` or missing
* `credential.type`: `x402` or missing
The Prism quote binding and Prism settlement still apply: the signed amount must match the checkout's Prism quote.
## Prism contract selection
The UCP version is part of the path. Prism picks the handler contract from the route, not from the caller.
| Route | Handler contract |
| - | - |
| `GET /ucp/{ucpVersion}/handlers` | `2026-10-07` for UCP `2026-01-23`, `2026-04-08`, `2026-08-25`. Other values return `422 version_unsupported`. |
The versioned handlers route is public and needs no API key.
Payment requirements do not depend on the UCP version. `POST /api/v2/merchant/payment-requirements` needs the API key and returns the raw x402 PaymentRequired object. The merchant builds the UCP checkout entry `{id, version, config}`: `id` and `version` come from the handlers declaration for its UCP version, `config` is that object.
Prism sends the handlers response with:
```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
Cache-Control: private, max-age=3600
```
### Handler documents
| URL | Content |
| - | - |
| `https://prism-gw.fd.xyz/ucp/{version}/schema.json` | Handler config schema for UCP `{version}` |
| `https://prism-gw.fd.xyz/ucp/{version}/instrument_schema.json` | Instrument and credential schema for UCP `{version}` |
| `https://prism-gw.fd.xyz/ucp/{version}/prism.md` | Handler spec for UCP `{version}` |
| `https://prism-gw.fd.xyz/ucp/schema.json`, `/ucp/instrument_schema.json`, `/ucp/prism.md` | Unchanged. Still served for the original contract. |
A versioned URL for a version Prism does not serve returns `404`.
## Shopware
On Shopware, SwagAgenticCommerce (SAG) serves UCP, and the Prism handler follows the version SAG serves.
| SwagAgenticCommerce | UCP served | Plugins |
| - | - | - |
| 1.2.x | 2026-04-08 | Prism handler 0.7.0 |
| 1.3.x | 2026-08-25 | Prism handler 0.7.0 |
Prism handler 0.7.0 requires `shopware/agentic-commerce` `>=1.0.0 <2.0.0`.
Shopware serves one UCP version per SAG release. A store that upgrades SAG from 1.2 to 1.3 moves from 2026-04-08 to 2026-08-25, and agents that only speak 2026-04-08 get `422 version_unsupported` from SAG. Stores that stay on SAG 1.2 keep 2026-04-08.
# Overview
Source: https://developers.fd.xyz/prism/integrations/x402
Finance District covers both sides of x402: the wallet signs, Prism settles.
x402 is an open payment protocol built on HTTP 402. A client requests a resource, the server returns payment requirements, the client pays on-chain, and the server delivers. No shared secrets, no OAuth.
Finance District participates in x402 from both sides:
* **Agent Wallet** acts as the **buyer** — signing ERC-3009 `transferWithAuthorization` calls inside a secure enclave and submitting the signed payment to the merchant.
* **Prism** acts as the **facilitator** — middleware that enforces payment on merchant endpoints, verifies on-chain transfers via Spectrum, and settles to the merchant's wallet.
How the Agent Wallet selects a network, signs, and submits x402 payments
How Prism middleware enforces x402 on merchant endpoints
# Prism (Facilitator)
Source: https://developers.fd.xyz/prism/integrations/x402/facilitator
How Prism enforces x402 on merchant endpoints — the 402 response format, payment verification, and pricing models.
Prism acts as the x402 facilitator — it adds payment enforcement to your HTTP endpoints without you implementing the protocol directly. You configure prices; Prism handles the 402 response, payment verification, and on-chain settlement.
This page covers x402 from the **merchant/facilitator** perspective. For the
**buyer/agent** side, see [Agent Wallet (Buyer Side)](/prism/integrations/x402/wallet).
## How It Works
```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
sequenceDiagram
participant A as Agent
participant M as Merchant (Prism SDK)
participant B as Blockchain
A->>M: GET /api/data
M-->>A: 402 Payment Required
Note over M: x402Version: 2
network: "eip155:8453"
asset: "0x833589fC..."
amount: "10000"
payTo: "0xSpectrum..."
A->>B: On-chain stablecoin payment
A->>M: GET /api/data
X-PAYMENT: { signed payment }
M->>B: Verify via Spectrum
B-->>M: Confirmed
M-->>A: 200 OK
X-PAYMENT-RESPONSE: 0xTxHash
Body: { requested data }
```
1. A request arrives without a valid payment header
2. Middleware returns **402 Payment Required** with `x402Version`, `accepts`, and `resource` fields
3. The agent's wallet pays on-chain and retries with an `X-PAYMENT` header
4. Prism's Spectrum layer verifies the on-chain transfer
5. If valid, the request proceeds and the transaction hash returns in `X-PAYMENT-RESPONSE`
Your application code only runs after payment is confirmed.
## Integration
You don't implement the x402 protocol directly — the Prism SDK middleware handles it. You configure what to charge, and the middleware handles the 402 response, payment verification, and settlement automatically. It's available for TypeScript, Python, and Java frameworks:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { prismPaymentMiddleware } from "@1stdigital/prism-express";
app.use(
prismPaymentMiddleware(
{
identifyToken: process.env.PRISM_IDENTIFY_TOKEN,
baseUrl: "https://prism-gw.fd.xyz",
},
{
"/api/premium": { price: "$0.01", description: "Premium API access" },
"/api/ai/generate": { price: "$0.50", description: "AI content generation" },
},
),
);
```
See the [Quick Start](/prism/quickstart) for a complete example, or the [SDK Overview](/prism/sdk/overview) for framework-specific guides.
## Payment Requirements (402 Response)
When the middleware returns 402, the response body contains:
| Field | Type | Description |
| - | - | - |
| `x402Version` | integer | Protocol version (currently `2`) |
| `error` | string | Human-readable reason, e.g. `"Payment required to access this resource"` |
| `resource` | object | Describes the gated resource (see below) |
| `accepts` | array | List of accepted payment options — one entry per chain/token combination |
| `extensions` | object | Reserved for future protocol extensions; currently `null` |
The `resource` object contains:
| Field | Type | Description |
| - | - | - |
| `url` | string | Full URL of the resource being protected |
| `description` | string | Human-readable description of what's being purchased (nullable) |
| `mimeType` | string | MIME type of the response once payment is settled (nullable) |
Each entry in `accepts` contains:
| Field | Type | Description |
| - | - | - |
| `scheme` | string | Payment scheme. Prism emits `"exact"` (EIP-3009 `transferWithAuthorization`) |
| `network` | string | CAIP-2 chain identifier — e.g. `"eip155:8453"` (Base mainnet), `"eip155:84532"` (Base Sepolia) |
| `asset` | string | ERC-20 contract address of the settlement token (not a symbol) |
| `payTo` | string | Spectrum settlement contract address — the `to` field in the EIP-3009 authorization |
| `amount` | string | Amount in atomic token units (nullable). Example: `"10000"` = \$0.01 USDC at 6 decimals |
| `maxTimeoutSeconds` | integer | Authorization validity window in seconds. Default: `300` |
| `extra` | object | EIP-712 domain info (nullable). Fields: `name`, `version` — present for tokens like USDC |
## Payment Verification
When the agent sends a request with the `X-PAYMENT` header:
1. Prism parses the signed payment from the header
2. Forwards it to the Spectrum settlement layer
3. Spectrum executes the on-chain transfer and verifies: correct amount, correct token, correct recipient, valid signature
4. If settlement succeeds, the request proceeds and the transaction hash is returned in the `X-PAYMENT-RESPONSE` header
5. If settlement fails, the middleware returns 402 with an error
The merchant never needs to verify payments manually — the middleware handles everything between the 402 and the 200.
## Pricing Models
### Fixed Pricing
Set a static price per endpoint — every request costs the same:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"/api/weather": {
price: "$0.001",
description: "Weather data"
}
}
```
### Tiered Pricing
Different prices for different endpoints:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"/api/basic/*": {
price: "$0.0001",
description: "Basic API tier"
},
"/api/premium/*": {
price: "$0.01",
description: "Premium API tier"
},
"/api/ai/generate": {
price: "$0.50",
description: "AI generation"
}
}
```
### Dynamic Pricing
For endpoints where the price depends on the request, apply per-route middleware:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get(
"/api/compute",
prismPaymentMiddleware(config, {
"/api/compute": {
price: calculatePrice(req), // dynamic based on request
description: "Compute resources",
},
}),
(req, res) => {
res.json({ result: "Computed" });
},
);
```
x402 is an open standard — learn more at [x402.org](https://www.x402.org/). Prism implements the specification and handles the protocol complexity through the SDK, so you configure prices and the middleware does the rest.
Framework guides for TypeScript, Python, and Java
Both sides of x402: the wallet signs, Prism settles
# Agent Wallet
Source: https://developers.fd.xyz/prism/integrations/x402/wallet
How the Agent Wallet picks a network, signs inside the TEE, and returns a ready-to-submit x402 payment.
When your agent hits a paywall or receives x402 payment requirements, the Agent Wallet takes over. It reads `accepts`, picks the best network and token based on your balance, signs an ERC-3009 authorization inside the TEE, and hands back the complete signed object.
## How Signing Works
The private key never leaves the secure enclave. The wallet:
1. Receives the `paymentRequirements` object (the `accepts` array from the merchant)
2. Selects a network/token pair — based on balance availability and chain preference
3. Constructs an ERC-3009 `transferWithAuthorization` and signs it inside the TEE
4. Returns the full x402 payment object for the agent to submit
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"paymentPayload": {
"signature": "0x...",
"authorization": {
"from": "0xAgentWalletAddress",
"to": "0xMerchantAddress",
"value": "10000",
"validAfter": "0",
"validBefore": "1760000000",
"nonce": "0x..."
}
},
"paymentRequirements": {
"x402Version": 2,
"accepts": [ "..." ]
}
}
```
## Using x402 via MCP
If your agent is connected to the Agent Wallet MCP server, x402 authorization is exposed as a tool. Pass `paymentRequirements` from the merchant response and receive the signed object back — no additional formatting required.
See [Agent Wallet MCP Server](/agent-wallet/ai-integration/mcp-server) to get connected, and [x402 Payments in Agent Wallet](/agent-wallet/concepts/x402-payments) for a full breakdown of the buyer-side flow.
Connect your agent to the wallet via MCP
Deep dive into x402 from the buyer perspective
# Prism — Payment Gateway for AI Agents
Source: https://developers.fd.xyz/prism/overview
Prism is a payment gateway for AI-agent commerce — implement x402, UCP, and ACP with one integration and settle on-chain in stablecoins.
Prism is a payment gateway for AI-agent commerce: it lets your server accept payments from AI agents and settle them on-chain in stablecoins. A single integration implements the protocols a buyer's agent uses to pay — x402, UCP, and ACP — so you don't write protocol-specific code or touch a smart contract.
When an agent checks out or requests a paid resource, Prism returns the payment requirements (amount, token, chain); the agent's wallet signs an [ERC-3009](https://eips.ethereum.org/EIPS/eip-3009) authorization; and Prism's [Spectrum](/prism/architecture/overview) layer settles the stablecoin transfer on-chain — instant finality, zero chargebacks. Settlement runs on EVM chains (Base, Arbitrum, BSC, Ethereum) in the tokens you enable (FDUSD, USDC).
Integrate through the [Gateway API](/prism/api-reference/introduction), the server-side [SDKs](/prism/sdk/overview) (TypeScript, Python, Java), the [MCP server](/prism/integrations/mcp-server), or a [ready-made plugin](/prism/platforms) if you run Saleor, Medusa, Shopware, PrestaShop, or WooCommerce.
## Why agentic commerce needs a settlement layer
Protocols like x402, UCP, and ACP standardize the **commerce flow** — how an agent discovers products, builds a cart, and checks out. They stop short of **settlement**. That's the gap Prism fills: the layer that moves money from the agent's wallet to your account, verified and final on-chain. You keep your existing commerce stack; Prism handles the payment.
## Where to go next
Accept your first AI-agent payment in minutes
Ready-made plugins for Saleor, Medusa, Shopware, PrestaShop, and WooCommerce
The orchestration + Spectrum settlement layers, and how each protocol is implemented
Server-side SDKs for TypeScript, Python, and Java
Prism Gateway REST API documentation
Manage your Prism integration from any AI agent via MCP
# E-commerce Platforms
Source: https://developers.fd.xyz/prism/platforms
Official Prism plugins for Saleor, Medusa, Shopware, PrestaShop, and WooCommerce — make your store payable by AI agents, no protocol code required.
AI agents are becoming the next commerce channel. Just as merchants once added a mobile app alongside their website, they'll soon need to serve autonomous agents that shop on behalf of their customers. Prism makes that a drop-in decision: install the plugin for your platform, connect your Prism account, and your store starts accepting agent payments — settled instantly in stablecoins, with zero chargebacks.
We maintain **official, open-source extensions for five of the world's leading commerce platforms** — together powering hundreds of thousands of live storefronts. If you run one of them, you're one install away from being agent-payable. If you don't, the same open protocols let you build the integration yourself.
## Supported platforms
Each extension is open-source, MIT-licensed, and maintained by Finance District. It adds agent-commerce endpoints to your store — product discovery, checkout, and on-chain settlement — using the [Universal Commerce Protocol (UCP)](/prism/concepts/commerce-protocols) and, where noted, the [Agentic Commerce Protocol (ACP)](/prism/concepts/commerce-protocols). Full install and configuration instructions live in each repository.
UCP + ACP for your Next.js storefront. Published as npm packages — no changes to your Saleor backend.
UCP + ACP as native Medusa v2 modules. Install, configure, start — no route files, no frontend.
A UCP / x402 Prism payment handler for Shopware 6.7. Zero storefront or admin UI.
UCP + Prism payment modules for PrestaShop 1.7.8, 8.x, and 9.x.
A WordPress plugin set bringing UCP + Prism settlement to any WooCommerce 8.0+ store.
| Platform | Built as | Protocols | Requirements |
| - | - | - | - |
| **Saleor** | Next.js storefront SDK (npm) | UCP + ACP | Saleor + a Next.js storefront |
| **Medusa** | Medusa v2 backend plugin (npm) | UCP + ACP | Medusa v2, Node.js ≥ 20 |
| **Shopware** | Shopware 6.7 plugin (PHP) | UCP + x402 | Shopware ≥ 6.7.10, PHP ≥ 8.2 |
| **PrestaShop** | PrestaShop modules (PHP) | UCP + x402 | PrestaShop 1.7.8 / 8.x / 9.x |
| **WooCommerce** | WordPress plugin set (PHP) | UCP + x402 | WordPress 6.4+, WooCommerce 8.0+ |
All five extensions are available today. Each repository includes a quick-start
guide and a wiki covering architecture, configuration, and the full request
lifecycle.
## How an integration works
However you install it, every Prism extension follows the same three-step path from install to your first agent payment:
Add the plugin, module, or SDK from the platform's repository above — npm for
Saleor and Medusa, a plugin/module install for Shopware, PrestaShop, and
WooCommerce.
Generate a **Project Identify Token** in the [Prism Console](/prism/production/console)
and drop it into the extension's configuration. This links agent payments to
your merchant account and settlement address.
Your store now advertises a `/.well-known/ucp` profile. Agents discover your
catalog, create a checkout, and pay — Prism settles the stablecoin payment
on-chain and hands your store a confirmed, final order. No chargebacks, no
intermediaries.
Prism handles all the token, chain, and x402 math behind the scenes — the extension only relays. See [How It Works](/prism/concepts/how-it-works) for the full transaction lifecycle.
## Don't see your platform?
The extensions above are convenience layers over open protocols — nothing about agent commerce is locked to a specific platform. If you run a custom stack or a platform we don't yet cover, you can build the integration yourself with the same APIs and be in production quickly.
Make any store agent-payable with the Prism APIs, server-side SDKs, and the
pluggable payment-handler interface our official extensions are built on.
# Custom Integrations
Source: https://developers.fd.xyz/prism/platforms/custom
No official plugin for your platform? Make any store agent-payable with the same open protocols and APIs our extensions are built on.
Our [official extensions](/prism/platforms) are convenience layers over open protocols — nothing about agent commerce is locked to a specific platform. If you run a custom storefront, a headless build, or a platform we don't yet cover, you can add agent payments yourself with the same APIs, and you'll be in production quickly.
There are three ways in, depending on how much you want to build.
## 1. Follow the merchant integration pattern
Every official extension implements the same three-step contract, and you can implement it directly against any stack. Your server needs three things — a discovery endpoint, a checkout call, and a settle call. Prism handles all the token math, chain selection, and x402 formatting.
Expose a `/.well-known/ucp` profile that includes the Prism payment handler
(`xyz.fd.prism_payment`), fetched from your Prism account.
When an agent starts a checkout, call Prism to get the x402 payment
requirements for that order and return them in your checkout response.
On completion, forward the agent's signed payment credential to Prism's
settlement endpoint. Prism settles on-chain and returns a confirmed
transaction.
The full three-endpoint walkthrough — request/response shapes, token base
units, and settlement — the exact pattern our official extensions follow.
## 2. Drop in a server-side SDK
If your backend is in TypeScript, Python, or Java, the Prism SDKs handle authentication, request signing, and payment verification for you — often just a few lines of middleware on the route you want to protect.
Framework guides for Express, NestJS, Next.js, Fastify, and the base
language SDKs.
The Prism Gateway REST API, if you'd rather integrate without an SDK.
## 3. Bring your own payment handler
Prefer to keep your existing commerce protocol layer and only add settlement? Each official extension exposes a **pluggable payment-handler interface** — you can ship your own settlement provider as a standalone package that self-registers, without forking the core plugin. The same interface is what our Prism and dummy/test handlers are built on, so there's a working reference to model yours on in each repository.
## Understand the protocols first
If you're new to how agents discover and buy, start with the concepts — the standards are what make any of these paths interoperable.
UCP, ACP, and x402 — how AI agents discover a store, build a checkout, and pay.
Building an integration for a platform we don't cover yet? We'd love to hear
about it — [get in touch](https://fd.xyz/contact-form).
# Prism Console
Source: https://developers.fd.xyz/prism/production/console
Manage your Prism integration — Project Identify Tokens, transactions, analytics, and settings.
The [Prism Console](https://apps.fd.xyz/prism/) is the management dashboard for your Prism integration. It's where you create Project Identify Tokens, monitor transactions, and configure payment settings. Log in with your [District Pass](/overview/district-pass).
## Getting Started
1. Go to [apps.fd.xyz/prism](https://apps.fd.xyz/prism/) and sign in with your District Pass
2. Create a new project or use the default project
3. You'll land on the dashboard showing an overview of your integration
Each Project has its own Project Identify Tokens, payment configuration, and transaction history. Use separate Projects for different applications or environments.
## Project Identify Tokens
Navigate to **Project Identify Tokens** to create and manage credentials for the Prism Gateway.
* **Generate a token** — Click "Create Project Identify Token" and give it a descriptive name
* **Per-project tokens** — Each Project gets its own Project Identify Token for access control
* **Rotate tokens** — Generate a new token and deprecate the old one without downtime
* **Security** — Project Identify Tokens authenticate via the `X-API-Key` header. Never expose them in client-side code, public repositories, or logs
Treat your Project Identify Token like a password. If compromised, rotate it immediately in
the Console.
## Transaction Monitoring
The **Transactions** view shows every payment processed through your integration:
* **Real-time feed** — Transactions appear as they're processed
* **Details** — Each transaction shows amount, token, chain, status, timestamp, payer address, and transaction hash
* **Status tracking** — Pending, completed, failed, and settled states
* **Filtering** — Filter by date range, status, chain, or token
* **Export** — Download transaction data for reconciliation
Click any transaction to see the full details, including the on-chain transaction link.
## Payment Configuration
Under **Settings → Payments**, configure how your endpoints accept payments:
* **Accepted tokens** — Select which tokens to accept. Prism supports any ERC-20 token that implements [ERC-3009](https://eips.ethereum.org/EIPS/eip-3009) (`transferWithAuthorization`). If the token you need isn't listed, [contact us](/overview/resources/support).
* **Accepted chains** — Select which chains to settle on. Prism can settle on any EVM-compatible chain. If your chain isn't available yet, [let us know](/overview/resources/support).
* **Merchant wallet** — Set the wallet address where settlement funds are received
* **Default pricing** — Configure default price and currency for your endpoints
Accept payments on multiple chains for maximum compatibility with different
agent wallets.
## Analytics
The **Analytics** dashboard provides insight into your payment activity:
* **Revenue overview** — Total revenue, daily, weekly, and monthly trends
* **Transaction volume** — Number of transactions over time
* **Breakdown by endpoint** — See which endpoints generate the most revenue
* **Chain distribution** — Which chains your payments settle on
## MCP Server
Prefer managing your integration from an AI assistant? The [Prism MCP Server](https://prism-mcp.fd.xyz) (`https://prism-mcp.fd.xyz`) exposes the same data and management capabilities — payments, earnings, Project Identify Tokens, wallets, Projects — as tools your AI agent can use directly.
Connect any MCP-compatible client (Claude Desktop, Cursor, Windsurf) to `https://prism-mcp.fd.xyz` and authenticate with your District Pass. See [MCP Server](/prism/integrations/mcp-server) for setup and the full tool reference.
# Network Support
Source: https://developers.fd.xyz/prism/production/network-support
Settle on any EVM-compatible chain. Need one that isn't listed? Let us know.
Prism can settle on any EVM-compatible chain. Merchants configure which chains and tokens to accept in the [Prism Console](https://apps.fd.xyz/prism/).
## Enabled Chains
The chains below are enabled today. Need one that isn't listed? [Contact us](/overview/resources/support).
### Mainnet
| Chain | Chain ID | Settlement Time | Gas Cost |
| - | - | - | - |
| Base | 8453 | \~2 seconds | Very low |
| Arbitrum | 42161 | \~2 seconds | Very low |
| BSC | 56 | \~3 seconds | Low |
| Ethereum | 1 | \~12 seconds | Higher |
## Enabled Tokens
Prism supports any ERC-20 token that implements [ERC-3009](https://eips.ethereum.org/EIPS/eip-3009) (`transferWithAuthorization`). The tokens below are enabled today. Need one that isn't listed? [Contact us](/overview/resources/support).
| Token | Symbol | Chains |
| - | - | - |
| First Digital USD | FDUSD | Ethereum, BSC |
| USD Coin | USDC | Ethereum, Base, BSC, Arbitrum |
In x402 payment requirements, the `asset` field is the token's **ERC-20 contract address** — not the symbol shown above. See the [API Reference](/prism/api-reference/endpoints) for example values.
## Choosing a Chain
L2 chains (Base, Arbitrum) offer the fastest settlement and lowest gas. Consider these factors when choosing:
| Factor | Guidance |
| - | - |
| API monetization / micropayments | Base or Arbitrum (low gas, fast) |
| Large value transactions | Ethereum (deepest liquidity) |
| FDUSD settlement | BSC or Ethereum |
| Maximum agent compatibility | Accept multiple chains |
Accept payments on multiple chains to maximize compatibility with different
agent wallets. Settlement is simplest when both the agent and merchant operate
on the same chain.
## Environments
| Component | URL |
| - | - |
| Prism Gateway | `https://prism-gw.fd.xyz` |
| Prism Console | `https://apps.fd.xyz/prism/` |
Test your integration on production with small amounts. The API and SDK work identically regardless of transaction size.
# Webhooks
Source: https://developers.fd.xyz/prism/production/webhooks
Never miss a payment — instant event delivery so your system reacts the moment funds arrive.
Webhooks tell your server when a payment is confirmed, rejected, or expired. Prism sends a signed JSON `POST` to one
HTTPS URL per project. Signing follows the [Standard Webhooks](https://www.standardwebhooks.com/)
specification, so any Standard Webhooks library can verify the requests.
## Set up
In the Prism Console, go to **Settings** → **Webhooks**.
The URL must use `https` on port 443. Local, private, and link-local addresses are not allowed.
Prism sends a signed `webhook.test` event to your URL. Your endpoint must answer with a 2xx status
within 10 seconds, or the save is rejected. The error message names the reason, for example
`timeout` or `http_status`.
Prism shows the signing secret (`whsec_...`) once. Store it in your secret manager. You need it to
verify every request.
## Events
| Event | When it is sent |
| - | - |
| `payment.confirmed` | A payment is confirmed on-chain and settled. |
| `payment.rejected` | The payment's transaction reverted on-chain. No funds moved. |
| `payment.expired` | The transaction never landed before the authorization deadline. No funds moved. |
| `webhook.test` | You save a URL, change it, or turn a disabled endpoint back on. |
In rare cases `payment.confirmed` arrives after `payment.expired` for the same payment. Treat
`payment.confirmed` as final.
## Payload
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "5c2b1f0e-3a8d-4f6b-9a61-2f7d0c9e4b11",
"type": "payment.confirmed",
"apiVersion": "2026-09-25",
"createdAt": "2026-09-25T03:12:44Z",
"data": {
"paymentId": "0b6f2a3c-7d41-4c0e-8e5b-1a9d3f6c2e70",
"projectId": "9e1d4c7a-2b58-4f3e-a6d0-7c8b5e1f3a29",
"status": "confirmed",
"grossAmount": { "value": "100.00", "asset": "USDC" },
"feeTotal": { "value": "1.50", "asset": "USDC" },
"netAmount": { "value": "98.50", "asset": "USDC" },
"chainId": 8453,
"network": "Base",
"txHash": "0x…",
"payerAddress": "0x…",
"resource": "https://shop.example/checkout/ORDER-8812",
"description": "Order 8812",
"createdAt": "2026-09-25T03:12:40Z",
"settledAt": "2026-09-25T03:12:43Z"
}
}
```
| Field | Description |
| - | - |
| `id` | Event id. Same value as the `webhook-id` header. Stable across retries and resends. |
| `type` | Event type. |
| `apiVersion` | Payload version. |
| `createdAt` | When Prism built this event (UTC). |
| `data.paymentId` | Prism payment id. |
| `data.projectId` | Your project id. |
| `data.status` | Always `confirmed` for this event. |
| `data.grossAmount` | Amount the payer paid. |
| `data.feeTotal` | All deductions: platform fee, network costs, affiliate share, and any cashback you fund. |
| `data.netAmount` | Amount that reaches your settlement wallet. `feeTotal + netAmount = grossAmount`. |
| `data.chainId`, `data.network` | Chain the payment settled on. |
| `data.txHash` | On-chain transaction hash. |
| `data.payerAddress` | Wallet that paid. |
| `data.resource` | The resource URL the payment was for. |
| `data.description` | Payment description. May be `null`. |
| `data.createdAt` | When the payment was created (UTC). |
| `data.settledAt` | Block time of the settlement (UTC). May be `null`. |
### Rejected and expired payload
`payment.rejected` and `payment.expired` carry the same envelope. `data` has no fee, net, or
settlement fields, because nothing settled.
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"id": "6d1f0c2e-8b3a-4e57-9c14-5a2e7f9d0b63",
"type": "payment.expired",
"apiVersion": "2026-09-25",
"createdAt": "2026-10-16T03:20:00Z",
"data": {
"paymentId": "0b6c8e2f-4a91-4d3b-b7e0-3f5a1c9d2e84",
"projectId": "a91e3d7b-5c20-4f8a-9e61-2b4d7c0f8a15",
"status": "expired",
"grossAmount": { "value": "12.50", "asset": "USDC" },
"chainId": 8453,
"network": "Base",
"txHash": "0x…",
"payerAddress": "0x…",
"resource": "https://shop.example/api/order/123",
"description": "Order 123",
"createdAt": "2026-10-16T03:00:00Z"
}
}
```
`data.status` is `rejected` or `expired`, matching the event type.
Amounts are strings in token units, not in the smallest unit. `asset` is the token symbol. New
fields may be added at any time. Fields are never removed without a new `apiVersion`.
## Verify signatures
Every request has three headers:
| Header | Value |
| - | - |
| `webhook-id` | Event id. Use it to de-duplicate. |
| `webhook-timestamp` | Unix time in seconds when the request was signed. |
| `webhook-signature` | One or more space-separated `v1,` values. |
To verify a request:
1. Build the signed content: `{webhook-id}.{webhook-timestamp}.{raw body}`. Use the raw body bytes,
before any JSON parsing.
2. Take the part of your secret after `whsec_` and base64-decode it. That is the HMAC key.
3. Compute HMAC-SHA256 of the signed content and base64-encode it.
4. Accept the request if any `v1` value in `webhook-signature` matches. Use a constant-time compare.
5. Reject timestamps more than 5 minutes from your clock.
While a rotated secret is still valid, the header holds two `v1` values, one per secret.
```ts theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import crypto from "node:crypto";
export function verifyPrismWebhook(secret: string, headers: Record, rawBody: string): boolean {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
const signatures = headers["webhook-signature"];
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64");
return signatures.split(" ").some((part) => {
const [version, signature] = part.split(",");
return version === "v1" && signature.length === expected.length
&& crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
});
}
```
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import base64, hashlib, hmac, time
def verify_prism_webhook(secret: str, headers: dict, raw_body: str) -> bool:
msg_id = headers["webhook-id"]
timestamp = headers["webhook-timestamp"]
if abs(time.time() - int(timestamp)) > 300:
return False
key = base64.b64decode(secret.removeprefix("whsec_"))
expected = base64.b64encode(
hmac.new(key, f"{msg_id}.{timestamp}.{raw_body}".encode(), hashlib.sha256).digest()
).decode()
return any(
part.split(",", 1)[0] == "v1" and hmac.compare_digest(part.split(",", 1)[1], expected)
for part in headers["webhook-signature"].split(" ")
)
```
## Retries and auto-disable
* Prism tries each event up to 3 times: at once, after 1 minute, and after 5 minutes.
* Only a 2xx response counts as success. Redirects count as failures and are not followed.
* Each call times out after 10 seconds.
* After 3 failed calls in a row, or any `410 Gone`, Prism disables the endpoint and shows a banner in
**Settings** → **Webhooks**. Fix your endpoint, then turn it back on. The reachability test runs again.
* Failed `payment.rejected` and `payment.expired` calls do not count toward the 3-in-a-row limit.
A `410 Gone` on any event still disables the endpoint.
* When you turn an endpoint back on, payment events from the last 24 hours that were not sent are
delivered once. Older ones are not. Use the payments API to reconcile a longer outage.
* The delivery log shows every event with its status, attempts, and last result. You can resend a
`Failed` or `Delivered` event, one at a time. A resend keeps the same `webhook-id`.
Delivery is at-least-once while the endpoint is enabled. The same event can arrive more than once, so
de-duplicate on `webhook-id`. A strict de-duplicator also ignores a deliberate resend of an event you
already processed. That is expected.
## Delete an endpoint
Prism stops sending at once. The delivery log is kept and stays visible. Events that were still
waiting are not sent to the deleted URL. After you add a new endpoint, you can resend any event from
the old endpoint to the new one. It keeps the same `webhook-id`.
## Rotate the secret
Rotating creates a new signing secret, shown once. The old secret keeps signing for 24 hours, so you
can deploy the new one without dropping events.
## Best practices
* Return 2xx quickly, then process the event in the background.
* Return 2xx for event types you do not handle.
* Use `webhook-id` as an idempotency key.
* After an outage, reconcile with the payments API instead of relying only on webhooks.
# Quick Start
Source: https://developers.fd.xyz/prism/quickstart
From sign-up to accepting AI agent payments — create your account, set up a project, get your keys, then pick the integration path that fits your stack.
Getting Prism running is the same three steps for everyone — **create an account, set up a project, and generate an API key**. What comes after depends on what you're building. If you run one of the e-commerce platforms we have plugins for, you can be live in minutes with no protocol code. If you're building something custom, the same open APIs get you there.
This guide covers the shared setup, then points you to the right integration path.
## Step 1: Create your District Pass
Your [District Pass](/overview/district-pass) is one account for everything in Finance District — it's how you log in to the Prism Console. Sign up with just an email, no KYC or wallet connection required.
Visit [apps.fd.xyz](https://apps.fd.xyz/) and sign up with your email — or sign in if you already have an account.
Enter the confirmation code sent to your inbox. Your District Pass is now active.
## Step 2: Set up your project
Log in to the [Prism Console](https://apps.fd.xyz/prism/) with your District Pass. The Console is where you configure payments, monitor transactions, and manage credentials.
Create a new Project or use the default one. Each Project has its own API keys, payment configuration, and transaction history — use separate Projects for different applications or environments (e.g. test vs. production).
Under **Settings → Payments**, set your **merchant wallet** (where settlement funds are received) and choose the tokens and chains you want to accept. You can change these anytime.
Prefer to manage everything from an AI assistant? The [Prism MCP Server](/prism/integrations/mcp-server) exposes the same setup — projects, tokens, payments — as tools for Claude Desktop, Cursor, and other MCP clients.
## Step 3: Create your API key
In the Console, navigate to **Project Identify Tokens** and click **Create Project Identify Token**. Give it a descriptive name and copy the token — this is the key that links agent payments to your merchant account.
Keep your Project Identify Token secret. It authenticates via the `X-API-Key` header — never expose it in client-side code, public repositories, or logs. If it's compromised, rotate it in the Console.
That's the account setup done. Everything from here is integration — and how much you build depends on your stack.
## Step 4: Choose your integration path
Running Saleor, Medusa, Shopware, PrestaShop, or WooCommerce? Install our
plugin, paste your token — live in minutes, no protocol code.
Headless build or an unsupported platform? Make any store agent-payable with
the Prism APIs and server-side SDKs.
Charge AI agents per request for an API, endpoint, or piece of content using
x402 payment middleware.
### Option A: E-commerce platform (fastest)
If you already run a storefront on one of the supported platforms below, you don't write any integration code. We maintain **official, open-source extensions** that add agent-commerce endpoints to your store — product discovery, checkout, and on-chain settlement.
| Platform | Install as | Requirements |
| - | - | - |
| **Saleor** | Next.js storefront SDK (npm) | Saleor + a Next.js storefront |
| **Medusa** | Medusa v2 backend plugin (npm) | Medusa v2, Node.js ≥ 20 |
| **Shopware** | Shopware 6.7 plugin (PHP) | Shopware ≥ 6.7.10, PHP ≥ 8.2 |
| **PrestaShop** | PrestaShop modules (PHP) | PrestaShop 1.7.8 / 8.x / 9.x |
| **WooCommerce** | WordPress plugin set (PHP) | WordPress 6.4+, WooCommerce 8.0+ |
The path is the same for every platform: **install the extension → paste your Project Identify Token into its config → go live.** Your store starts advertising a `/.well-known/ucp` profile, and agents can discover your catalog, check out, and pay — settled instantly in stablecoins, with no chargebacks.
Pick your platform and follow its install guide.
### Option B: Custom storefront
No official plugin for your stack? The extensions above are convenience layers over open protocols — nothing is locked to a specific platform. Implement the same three-step merchant contract directly: advertise a `/.well-known/ucp` profile with the Prism payment handler, call Prism to prepare each checkout, and forward the signed payment credential to settle on-chain.
The merchant integration pattern, server-side SDKs, and the pluggable
payment-handler interface our official extensions are built on.
### Option C: Monetize an API or content
Not selling products — want AI agents to pay per request to access an API, endpoint, or piece of content? Protect a route with x402 payment middleware. When an agent hits it without paying, it gets a `402 Payment Required` response with payment instructions; after paying, the request goes through.
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-express
```
**Coming soon.** Python SDKs (`prism-flask`, `prism-fastapi`, `prism-django`) are not yet published to PyPI. The install command below shows the planned package.
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install finance-district
```
**Coming soon.** The Java SDK (`prism-sdk`) is not yet published to Maven Central. The dependency below shows the planned coordinates.
```xml theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
xyz.financedistrict
prism-sdk
LATEST
```
See [SDK Overview](/prism/sdk/overview) for all supported frameworks including NestJS, Next.js, FastAPI, Flask, and Django.
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import express from "express";
import { prismPaymentMiddleware } from "@1stdigital/prism-express";
const app = express();
app.use(
prismPaymentMiddleware(
{
identifyToken: process.env.PRISM_IDENTIFY_TOKEN,
baseUrl: "https://prism-gw.fd.xyz",
},
{
"/api/premium": {
price: "$0.01",
description: "Premium API access",
},
}
)
);
app.get("/api/premium", (req, res) => {
res.json({
message: "Premium content",
payer: req.payer, // wallet address that paid
});
});
app.listen(3000, () => console.log("Server running on port 3000"));
```
**Coming soon.** The `prism-fastapi` package is not yet published to PyPI. The code below shows the planned API.
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Depends
from finance_district import require_payment, PaymentVerified
app = FastAPI()
@app.get("/api/premium")
async def premium_content(
payment: PaymentVerified = Depends(require_payment(0.01, "USD"))
):
return {"content": "Premium data", "payer": payment.payer}
```
**Coming soon.** The `prism-flask` package is not yet published to PyPI. The code below shows the planned API.
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, jsonify
from finance_district import require_payment
app = Flask(__name__)
@app.route("/api/premium")
@require_payment(amount=0.01, currency="USD")
def premium_content():
return jsonify({"content": "Premium data"})
```
Start your server and hit the protected endpoint — you should get a `402 Payment Required` response with x402 payment instructions:
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
curl http://localhost:3000/api/premium
```
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Payment required to access this resource",
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"amount": "10000",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"payTo": "0xYourWallet...",
"maxTimeoutSeconds": 300,
"extra": { "name": "USD Coin", "version": "2" }
}
]
}
```
This confirms the middleware works. Any AI agent with a compatible wallet — including [Agent Wallet](/agent-wallet/overview) — can now pay and access the endpoint automatically.
To test the full payment flow, use the [Agent Wallet CLI](/agent-wallet/ai-integration/cli) or connect an Agent Wallet via [MCP](/agent-wallet/ai-integration/mcp-server) and ask the agent to access your endpoint.
## Step 5: Go live
Whichever path you took, going to production is the same:
1. Switch your Project to mainnet in the Console settings
2. Generate a mainnet Project Identify Token and update your integration
3. Set your production merchant wallet address
4. Monitor transactions in the [Prism Console](https://apps.fd.xyz/prism/)
You can test with small amounts on production chains — the API and SDKs work identically regardless of transaction size.
## What's next?
Plugins for Saleor, Medusa, Shopware, PrestaShop, and WooCommerce
Make any store agent-payable with the open protocols and APIs
Two-layer architecture and the transaction lifecycle
Manage tokens, transactions, analytics, and payment settings
# Your First Agent Order
Source: https://developers.fd.xyz/prism/resources/first-agent-order
What happens when an AI agent buys from your store — what you will see in your admin, why it paid in stablecoins, and why it is much closer to an ordinary order than it sounds.
An AI agent has bought something from you. If it is the first one, the most useful thing to know before anything else is how little about it is new. Same customer, same product, same box going out of the door. What changed is who pressed the buy button and how the money reached you, and neither of those changes what you do next.
This guide covers what you will see, what happened behind it, and the small number of things that genuinely work differently.
## There is a person behind every agent
An AI agent did not decide it wanted your product. Somebody asked it to buy something, and it went and did the work.
That somebody is your customer, exactly as they were before. They may have named your shop, or they may have described what they were after and their assistant found you. Either way the decision was theirs and the money is theirs. The agent is doing the legwork: comparing options, filling in the form, completing the checkout. It works much the way an assistant books a flight for the person they work for, or a comparison site sends a buyer your way.
This is worth holding onto, because it makes everything else easier to place. Agentic commerce is a channel, the way mobile was a channel. It is not a new kind of customer, and it has not put you in a new kind of business.
## What it looks like in your store
If you are using one of the official plugins for [WooCommerce, PrestaShop, Shopware, Medusa or Saleor](/prism/platforms), the order arrives in your normal order list with your normal order number. It sits between the orders that came in before and after it. Nothing about your admin changes and there is no separate screen to go and check.
The difference is on the payment line, which tells you the order was paid by an AI agent in stablecoins rather than by card. The shipping details are there as usual. The customer record is there as usual. Your returns policy applies as usual.
Pick and pack it the way you would anything else.
## Why the agent paid in stablecoins and not by card
This is the part that looks odd until you see it from the agent's side.
A card payment assumes a person. It assumes somebody holding a piece of plastic who can read a number off the front, take a message from their bank and tap approve. Remove the person and a card payment largely stops working. An agent has no card, no phone to receive the code, and nobody sitting beside it at three in the morning to confirm anything.
Stablecoins are simply the payment method that still works when there is no human in the loop. A stablecoin is a digital form of an ordinary currency, usually the dollar, that holds a steady value rather than moving around the way other digital assets do. The agent spends from a balance its owner funded, without needing anyone's permission at the moment of purchase.
It suits buying across borders, too. The payment behaves the same whether your customer is in the next town or on the far side of the world, with nothing for you to arrange locally. It also reaches you in seconds rather than days, because it passes through far fewer hands than a card payment does. That quietly widens who is able to buy from you: someone whose local card you could never have accepted can now pay you directly.
## What actually happened to the money
Behind the order, the sequence was short.
The buyer's agent had a wallet its owner had put money into. At checkout it signed an instruction for exactly the amount you were charging, no more and nothing open-ended. That instruction went to the address you nominated when you set up your project, and the money moved there directly.
Nobody held it along the way. It did not rest with us, with a processor, or in an account waiting to be released to you on a schedule. It went from your buyer to you.
Once the network confirms the transfer, which usually takes seconds, it is complete.
## When it is safe to send the goods
When the order shows as paid, it is paid, and you can send the goods exactly as you normally would.
One difference is worth understanding at this point. A completed transfer cannot be undone — there is no mechanism to reverse it, not by you, not by your buyer, and not by us. In practice that means a paid order stays paid. It also means that when you decide to refund somebody, you send the money back yourself rather than asking anyone to reverse anything. That is a subject of its own, and it is covered separately.
## What is genuinely different
Three things, and none of them touch how you fulfil an order.
The money arrives as stablecoins rather than in your bank account. Most of what a business pays for still moves in ordinary currency, so at some point you will convert it, on whatever cadence suits your cash flow.
Refunds are something you send rather than something you reverse. Your policy does not change, only the mechanics of paying somebody back.
And the money lands in a wallet you control rather than in an account somebody else holds for you. That is deliberate, and it comes with the responsibility you would expect: the wallet is yours to look after.
## Where to go next
Converting what you have been paid into ordinary currency and getting it
into a business bank account.
The mechanics in a little more depth, if you want to see the whole path a
payment takes.
A first agent order tends to feel like an event, and it is worth a moment — look at it, see where it came from, check the money arrived. After that it stops being interesting fairly quickly, which is the best thing that can be said about any payment method. By the tenth one it is just another order in the list.
# Getting Paid Into Your Bank Account
Source: https://developers.fd.xyz/prism/resources/off-ramp
How to off-ramp the stablecoin revenue Prism settles to you — converting it to fiat and withdrawing to an ordinary business bank account, through First Digital Trust.
Payments you accept through Prism settle on-chain, in stablecoins, to a wallet you control. Most of what a business pays for still moves in fiat: rent, salaries, suppliers, tax. The step between the two is the off-ramp — converting stablecoin revenue into the currency your expenses run in, held in an ordinary bank account.
This guide covers how to do that through First Digital Trust (FDT), a regulated trust and custody company that works with businesses holding digital assets. No integration between Prism and FDT is needed: the whole process is an account, a transfer, and an instruction.
## What is First Digital Trust
First Digital Trust is a licensed trust company providing corporate treasury services to businesses that hold digital assets. Its services cover multi-asset custody, foreign exchange, and OTC trading, run through a client portal and a service team you deal with directly. FDT is also the reserves custodian for FDUSD, one of the stablecoins Prism merchants settle in.
Accounts are opened directly with FDT, in your company's name. Onboarding runs through their team and involves the verification you would expect from any regulated financial institution.
## How the flow works
Start with a [business inquiry](https://1stdigital.com/contact-us/business-inquiry/)
at 1stdigital.com. Do this ahead of need: verification takes time, and it is
better to have the account waiting for the revenue than the other way around.
An ordinary on-chain transfer from your settlement wallet to the deposit
address FDT gives you. It works the same whether your Prism
[settlement address](/prism/architecture/overview) is an Agent Wallet or a
wallet you already manage yourself.
Place the instruction with FDT: the FX desk covers routine conversion, and the
OTC desk handles larger blocks. Nothing converts until you instruct it.
Withdraw the proceeds to your business bank account and pay expenses as usual.
After the first cycle this becomes routine treasury. Revenue accrues on-chain as orders come in, and you convert on the cadence your cash flow needs: monthly, or whenever a large invoice lands. Keep whatever share in stablecoins is useful to you and convert the rest to fiat.
## Good to know
* **The payment side is already complete before any of this starts.** Funds move from the buyer's wallet to yours in a single on-chain transaction, and nobody holds them along the way, including us. Conversion is a separate relationship you hold with FDT, on FDT's terms — see [Stablecoin Settlement](/prism/concepts/settlement) for what Prism does and where it stops.
* **Your settlement address is set during onboarding.** Configure it, along with your chains and tokens, in the [Prism Console](/prism/production/console).
* **Start from FDT's site directly.** Avoid unsolicited links in messages.
## Where to start
Open a corporate account and get onboarding underway before the revenue
arrives.
How Prism settles payments on-chain — instant finality, no chargebacks.
Once the account exists, fiat is one instruction away. From there, revenue from agent-driven orders behaves like any other revenue: it arrives, and it pays the bills.
# Refunds and Returns
Source: https://developers.fd.xyz/prism/resources/refunds-and-returns
Why sending money back works differently when the payment arrived on-chain, what stays exactly the same, and how to handle a refund when there is no processor to reverse anything.
Some orders come back. It happens in every business that sells anything, and accepting payments from AI agents does not change that. Your returns policy is still your returns policy: the same window, the same conditions, the same judgement about who gets their money back and when.
What works differently is the mechanics of sending the money. This guide covers why, and what to do about it.
## The difference has nothing to do with agents
It would be reasonable to assume that refunding an agent order is more complicated than refunding an ordinary one. It is not. By the time a return happens the agent is long gone, and the person asking for their money back is an ordinary customer with an ordinary complaint.
The difference comes from the rail the money travelled on. It would be exactly the same if a person had paid you in stablecoins directly, with no agent involved anywhere.
A card refund works by running the original payment backwards. You tell your processor to refund the order, and the payment network reverses the movement along the path it came. The money is pulled out of your account and pushed back to your customer's card, usually some days later, by somebody else's system.
A blockchain has no reverse. When the payment reached you it was a completed transfer, and there is no instruction that undoes a completed transfer. This is not a restriction anybody chose to place on you. It is simply how the rail works, and it applies equally to your customer, to us, and to everyone else.
## A refund is a payment you send
That is the whole idea, and once it lands the rest follows easily.
You are not reversing the original payment. You are making a second, separate payment in the opposite direction. The closest familiar thing is cash. The customer hands the item back across the counter and you hand the money back: two movements, rather than one movement undone.
## What that changes in practice
There are four practical consequences, and none of them are difficult.
You need somewhere to send it, and you already have that. The wallet address your customer paid from is recorded against the original order, and that is where the refund goes back to.
You need the money to be available. This is the one that catches people out. If you convert everything into your bank account the moment it arrives, there is nothing on hand to refund with. Most businesses settle into keeping a working balance that comfortably covers whatever their returns normally run at, and converting the rest.
You control the timing completely. There is no processor to submit to and no clearing period to sit through. When you decide somebody gets their money back, the money moves when you send it.
Partial refunds are simply smaller refunds. There is nothing special about them. You send back whatever you have agreed, whether that is the whole order, one item out of four, or a goodwill gesture on the delivery charge.
## Doing it through an Agent Wallet
If your Prism settlement address is a Finance District Agent Wallet, refunds are considerably less work, because you can raise one from Prism rather than going away and making a transfer by hand.
You raise the refund against the original order and say how much is going back. The request goes to your wallet, which sends the money to the address the payment came from. You are not copying wallet addresses between screens, and nobody is retyping a long string of characters correctly on a Friday afternoon.
You can also work in the wallet's own interface, where your balances, transactions and payments all sit together. That is the place to go when you want to look something up, check that a refund went out, or send money that is not attached to an order at all.
## If you use your own wallet
If you settle to a wallet you look after yourself, refunds are yours to make directly, and nothing is prepared for you. You open your wallet, take the address from the original order, and send the amount you have agreed, the same as any other transfer you would make.
That works perfectly well, and plenty of businesses run this way. It does put the care on you: checking the address is the right one, and checking the amount before it goes. Keep your own note of which order the transfer belongs to, too, because the wallet has no idea what it was for.
## Telling your customers
It is worth one line in your returns policy: refunds are sent back to the wallet the payment came from.
Most customers will never think to ask, and most would not mind either way, but the one who does care will ask before buying rather than after. Saying it plainly also heads off the conversation where somebody is waiting for money to appear on a card they never used.
Your timescales are worth stating as well, and you can afford to be generous with yourself here, because you are not quoting somebody else's clearing time. A refund reaches your customer about as quickly as their payment reached you.
## Keeping your records straight
Each refund is its own transaction with its own record, separate from the payment it relates to.
That is a little different from a card refund, which usually appears attached to the original. Here you have two entries, money in and money out, each with its own reference. Tie them together with your own order number and your accounts stay easy to follow later, when somebody asks what happened on a particular order.
## Where to go next
What an agent order is, what you see in your admin, and why it is closer to
an ordinary order than it sounds.
Converting what you keep into ordinary currency, and how much to leave
behind for returns.
Refunds on this rail ask slightly more of you, and hand you slightly more control in exchange. Nobody can reach into your balance and reverse a payment you have already received. The other side of that is that nobody else will process a refund on your behalf, so when you decide a customer gets their money back, sending it is yours to do.
# Java Servlet Integration
Source: https://developers.fd.xyz/prism/sdk/java/servlet
Protect Java web applications with blockchain micropayments
**Coming soon.** The `org.fdtech.prism:prism-servlet` artifact is not yet published to Maven Central. This page describes the planned API.
## Overview
The **prism-servlet** package provides a generic Servlet Filter for payment-protecting Java web applications using the x402 protocol. It works with any servlet-based framework (Tomcat, Jetty, Spring Boot, Jakarta EE, etc.).
Works with any Servlet 3.0+ container
Captures output before settlement validation
Standard javax.servlet.Filter interface
***
## Installation
```xml theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
org.fdtech.prism
prism-servlet
1.0.0
```
```gradle theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
implementation 'org.fdtech.prism:prism-servlet:1.0.0'
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
### Configuration via web.xml
```xml theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PrismFilter
org.fdtech.prism.servlet.PrismFilter
identifyToken
dev-key-123
baseUrl
https://prism-gw.fd.xyz
routes
/api/premium:0.01:Premium API access
/api/weather:$0.001:Weather data access
PrismFilter
/api/*
```
### Servlet Implementation
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/api/premium")
public class PremiumServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Access payer address (set by PrismFilter)
String payer = (String) request.getAttribute("prism_payer");
response.setContentType("application/json");
response.getWriter().write(String.format(
"{\"message\":\"Premium content\",\"payer\":\"%s\"}",
payer
));
}
}
```
***
## Configuration
### PrismConfig
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.fdtech.prism.core.PrismConfig;
PrismConfig config = new PrismConfig(
"your-project-identify-token", // Required: Project Identify Token
"https://prism-gw.fd.xyz", // Optional: Base URL
true // Optional: Debug mode
);
```
### Programmatic Configuration
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.fdtech.prism.servlet.PrismFilter;
import javax.servlet.FilterRegistration;
// In ServletContextInitializer or similar
public class WebAppConfig {
public void configureFilter(ServletContext context) {
PrismConfig config = new PrismConfig("dev-key-123");
PrismFilter filter = new PrismFilter(config);
// Add route configuration
filter.addRoute("/api/premium", 0.01, "Premium API");
filter.addRoute("/api/weather", "$0.001", "Weather data");
// Register filter
FilterRegistration.Dynamic registration =
context.addFilter("PrismFilter", filter);
registration.addMappingForUrlPatterns(
null, false, "/api/*"
);
}
}
```
***
## Route Configuration Format
### In web.xml
Routes are configured as colon-separated values, one per line:
```
routes
/api/premium:0.01:Premium API access
/api/weather:$0.001:Weather data
/api/data/*:0.005:Data API (wildcard)
```
**Format:** `path:price:description`
* **path**: Exact path or wildcard (`/api/*`)
* **price**: USD amount (`0.01` = $0.01 USD, or `$0.001\` string format)
* **description**: Human-readable description
***
### Programmatic Configuration
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PrismFilter filter = new PrismFilter(config);
// Exact paths
filter.addRoute("/api/premium", 0.01, "Premium API");
filter.addRoute("/api/weather", "$0.001", "Weather data");
// Wildcard matching
filter.addRoute("/api/data/*", 0.005, "Data API");
// Multiple route groups
filter.addRoute("/api/basic/*", "$0.0001", "Basic tier");
filter.addRoute("/api/premium/*", "$0.01", "Premium tier");
```
***
## Accessing Payment Information
Payment info is stored as request attributes:
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@WebServlet("/api/premium")
public class PremiumServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get payer wallet address
String payer = (String) request.getAttribute("prism_payer");
// Returns: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" or null
// Get full payment object
Map payment =
(Map) request.getAttribute("prism_payment");
/*
{
"scheme": "eip3009",
"network": "eth-sepolia",
"asset": "usdc",
"amount": "10000",
"recipient": "0x...",
"signature": "0x..."
}
*/
response.setContentType("application/json");
response.getWriter().write(
new JSONObject()
.put("message", "Premium content")
.put("payer", payer)
.put("network", payment.get("network"))
.toString()
);
}
}
```
***
### Safe Access Helper
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
public class PaymentUtils {
public static String getPayer(HttpServletRequest request) {
return (String) request.getAttribute("prism_payer");
}
public static Map getPayment(HttpServletRequest request) {
return (Map) request.getAttribute("prism_payment");
}
public static boolean hasPayer(HttpServletRequest request) {
return request.getAttribute("prism_payer") != null;
}
}
// Usage in servlet
@WebServlet("/api/data")
public class DataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
if (!PaymentUtils.hasPayer(request)) {
response.sendError(402, "Payment required");
return;
}
String payer = PaymentUtils.getPayer(request);
response.setContentType("application/json");
response.getWriter().write(
"{\"data\":[1,2,3],\"payer\":\"" + payer + "\"}"
);
}
}
```
***
## Settlement Validation
The Java Servlet filter uses **HttpServletResponseWrapper** to capture servlet output before settlement validation:
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (automatic!)
public class ResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private PrintWriter writer = new PrintWriter(buffer);
@Override
public PrintWriter getWriter() {
return writer;
}
public byte[] getCapturedOutput() {
writer.flush();
return buffer.toByteArray();
}
}
// In PrismFilter.doFilter()
ResponseWrapper wrapper = new ResponseWrapper(response);
chain.doFilter(request, wrapper); // Execute servlet - output goes to buffer
// Validate settlement BEFORE sending to client
String settlementHeader = middleware.getSettlementHeader(paymentInfo);
if (settlementHeader == null) {
// ❌ Settlement failed - send error instead of buffered output
response.setStatus(402);
response.setContentType("application/json");
response.getWriter().write(
"{\"error\":\"Payment settlement failed\"}"
);
} else {
// ✅ Settlement succeeded - send buffered output
response.setHeader("X-PAYMENT-RESPONSE", settlementHeader);
response.getOutputStream().write(wrapper.getCapturedOutput());
}
```
**Key Points:**
* Servlet writes to **wrapper**, not real response
* Output is **buffered in memory**
* After settlement check, either send buffered data or error
* Works with all response types (JSON, HTML, binary, etc.)
See [Stablecoin Settlement](/prism/concepts/settlement) for details.
***
## Error Handling
### Payment Errors
When payment is missing or invalid:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 402 Payment Required
{
"x402Version": 2,
"paymentRequired": true,
"acceptedPayments": [
{
"scheme": "eip3009",
"network": "eth-sepolia",
"asset": "usdc",
"amount": "10000",
"recipient": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"nonce": "0xabc123...",
"validBefore": 1735430400
}
],
"description": "Premium API access",
"priceUSD": "0.01"
}
```
***
### Custom Error Handling
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@WebServlet("/api/premium")
public class PremiumServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
String payer = (String) request.getAttribute("prism_payer");
if (payer == null) {
sendPaymentRequired(response);
return;
}
// Process request
String result = processRequest(payer);
response.setContentType("application/json");
response.getWriter().write(result);
} catch (Exception e) {
sendError(response, e);
}
}
private void sendPaymentRequired(HttpServletResponse response)
throws IOException {
response.setStatus(402);
response.setContentType("application/json");
response.getWriter().write(
"{\"error\":\"Payment required\"}"
);
}
private void sendError(HttpServletResponse response, Exception e)
throws IOException {
response.setStatus(500);
response.setContentType("application/json");
response.getWriter().write(
"{\"error\":\"" + e.getMessage() + "\"}"
);
}
}
```
***
## Spring Boot Integration
### Configuration Class
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.fdtech.prism.servlet.PrismFilter;
import org.fdtech.prism.core.PrismConfig;
@Configuration
public class PrismConfig {
@Bean
public FilterRegistrationBean prismFilter() {
PrismConfig config = new PrismConfig(
"dev-key-123",
"https://prism-gw.fd.xyz"
);
PrismFilter filter = new PrismFilter(config);
filter.addRoute("/api/premium", 0.01, "Premium API");
filter.addRoute("/api/weather", "$0.001", "Weather data");
FilterRegistrationBean registration =
new FilterRegistrationBean<>();
registration.setFilter(filter);
registration.addUrlPatterns("/api/*");
registration.setOrder(1); // Execute early
return registration;
}
}
```
### Spring Boot Controller
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/premium")
public Map premium(HttpServletRequest request) {
String payer = (String) request.getAttribute("prism_payer");
return Map.of(
"message", "Premium content",
"payer", payer
);
}
@GetMapping("/weather")
public Map weather(HttpServletRequest request) {
String payer = (String) request.getAttribute("prism_payer");
return Map.of(
"location", "San Francisco",
"temperature", 72,
"condition", "Sunny",
"payer", payer
);
}
}
```
***
## Testing
### JUnit 5 Tests
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PaymentIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testPaymentRequired() {
ResponseEntity response =
restTemplate.getForEntity("/api/premium", String.class);
assertEquals(HttpStatus.PAYMENT_REQUIRED, response.getStatusCode());
assertTrue(response.getBody().contains("paymentRequired"));
}
@Test
void testValidPayment() {
// Create mock payment header
String payment = "{\"scheme\":\"eip3009\",\"signature\":\"0x" +
"0".repeat(130) + "\"}";
HttpHeaders headers = new HttpHeaders();
headers.set("X-PAYMENT", payment);
HttpEntity entity = new HttpEntity<>(headers);
ResponseEntity response = restTemplate.exchange(
"/api/premium",
HttpMethod.GET,
entity,
String.class
);
// In test mode, mock signatures accepted
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getBody().contains("Premium content"));
}
}
```
***
### Mock Servlet Testing
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.mockito.Mockito.*;
class PrismFilterTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain chain;
private PrismFilter filter;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
PrismConfig config = new PrismConfig("test-key");
filter = new PrismFilter(config);
filter.addRoute("/api/premium", 0.01, "Test");
}
@Test
void testPaymentRequired() throws Exception {
when(request.getRequestURI()).thenReturn("/api/premium");
when(request.getHeader("X-PAYMENT")).thenReturn(null);
filter.doFilter(request, response, chain);
verify(response).setStatus(402);
verify(chain, never()).doFilter(any(), any());
}
}
```
***
## Production Deployment
### Environment Configuration
```properties theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# application.properties (Spring Boot)
prism.identify-token=${PRISM_IDENTIFY_TOKEN}
prism.base-url=${PRISM_BASE_URL:https://prism-gw.fd.xyz}
prism.debug=${PRISM_DEBUG:false}
# Routes configuration
prism.routes[0].path=/api/premium
prism.routes[0].price=0.01
prism.routes[0].description=Premium API
prism.routes[1].path=/api/weather
prism.routes[1].price=$0.001
prism.routes[1].description=Weather data
```
### Configuration Class
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "prism")
public class PrismProperties {
private String identifyToken;
private String baseUrl;
private boolean debug;
private List routes;
// Getters and setters
public static class RouteConfig {
private String path;
private String price;
private String description;
// Getters and setters
}
}
```
***
### Logging & Monitoring
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PremiumServlet extends HttpServlet {
private static final Logger logger =
LoggerFactory.getLogger(PremiumServlet.class);
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String payer = (String) request.getAttribute("prism_payer");
if (payer != null) {
logger.info("Payment succeeded: payer={}, path={}",
payer, request.getRequestURI());
} else {
logger.warn("Payment required: path={}, ip={}",
request.getRequestURI(), request.getRemoteAddr());
}
// Process request...
}
}
```
***
## Examples
### AI Agent API
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@WebServlet("/api/ai/chat")
public class AIChatServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String payer = (String) request.getAttribute("prism_payer");
// Parse request body
BufferedReader reader = request.getReader();
String message = new JSONObject(reader.readLine())
.getString("message");
// Call AI service
String aiResponse = callAIService(message);
// Return response
response.setContentType("application/json");
response.getWriter().write(
new JSONObject()
.put("response", aiResponse)
.put("payer", payer)
.put("creditsUsed", 1)
.toString()
);
}
}
```
***
### REST API with JAX-RS
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import javax.ws.rs.*;
import javax.ws.rs.core.*;
@Path("/api")
public class ApiResource {
@Context
private HttpServletRequest request;
@GET
@Path("/premium")
@Produces(MediaType.APPLICATION_JSON)
public Response premium() {
String payer = (String) request.getAttribute("prism_payer");
return Response.ok()
.entity(Map.of(
"message", "Premium content",
"payer", payer
))
.build();
}
}
```
***
## Troubleshooting
**Check filter mapping in web.xml:**
```xml theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PrismFilter
/api/*
```
**Verify filter order:** Prism filter should execute BEFORE authentication filters.
**Debug with logging:**
```java theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@Override
protected void doGet(HttpServletRequest request, ...) {
System.out.println("URI: " + request.getRequestURI());
System.out.println("Payment header: " + request.getHeader("X-PAYMENT"));
System.out.println("Payer: " + request.getAttribute("prism_payer"));
}
```
**Check:** Route matches filter URL pattern, payment header present and valid.
**Common causes:** 1. Insufficient balance 2. Invalid signature 3. Nonce reuse
4\. Network timeout **Check logs:** Enable debug mode in PrismConfig.
**If you see encoding problems:**
* Make sure to set `Content-Type` before writing
* Use `getWriter()` for text, `getOutputStream()` for binary
* Don't mix `getWriter()` and `getOutputStream()`
# SDK Overview
Source: https://developers.fd.xyz/prism/sdk/overview
Add AI-native payments to any stack — official SDKs for TypeScript, Python, and Java.
## Introduction
Finance District provides SDKs for TypeScript, Python, and Java, making it simple to integrate the **Prism X402 Payment Protocol** into your existing applications. Our SDKs handle authentication, request signing, and payment verification with minimal setup.
## Find Your Integration
Pick the framework you're already using:
Add payment middleware to Express apps
Guards and decorators for NestJS
API routes and middleware for Next.js
Plugin for Fastify applications
Middleware and decorators for Django
Dependencies for FastAPI routes
Decorators for Flask routes
Filters for servlet-based apps
Native Node.js HTTP server
## Language SDKs
If you don't use any of the frameworks above, start with the base SDK for your language:
Node.js and TypeScript applications
Python applications
Java applications
## What You Get
* **🔐 Authentication** - Project Identify Token management and request signing
* **💳 Payment Verification** - X402 protocol support
* **🛡️ Error Handling** - Proper error types and validation
* **📝 Type Safety** - Full type definitions
* **🚀 Framework Integration** - Drop-in middleware/decorators
* **⚡ Performance** - Production-ready
## Quick Example
Here's how simple it is to add payment verification to an existing route:
```typescript Express theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get(
"/premium-content",
fdPayment({ amount: 100, currency: "USD" }),
(req, res) => {
res.json({ content: "Your premium content" });
},
);
```
```python Django theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@require_payment(amount=100, currency='USD')
def premium_content(request):
return JsonResponse({'content': 'Your premium content'})
```
```python FastAPI theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@app.get('/premium-content')
async def premium_content(
payment: PaymentVerified = Depends(require_payment(100, 'USD'))
):
return {'content': 'Your premium content'}
```
```python Flask theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@app.route('/premium-content')
@require_payment(amount=100, currency='USD')
def premium_content():
return jsonify({'content': 'Your premium content'})
```
## Need Help?
Report issues or request features
# Python SDK
Source: https://developers.fd.xyz/prism/sdk/python
Monetize any Python API in minutes — per-call stablecoin payments, zero payment infrastructure.
**Status:** 🔜 Coming Q1 2026 The Python SDK is currently in development. This
page shows the planned API and features.
## Planned Features
Decorator-based middleware for Flask
Dependency injection for FastAPI
Full async support with asyncio
Complete type annotations
Data validation with Pydantic
Command-line tools for testing
## Installation (Planned)
`bash pip install prism-flask # or pip install prism-fastapi `
`bash poetry add prism-flask # or poetry add prism-fastapi `
`txt prism-flask==1.0.0 # or prism-fastapi==1.0.0 `
The canonical SDK config is `identify_token` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `api_key` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Planned API
### Flask Example
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, jsonify
from prism_flask import require_payment, init_prism
app = Flask(__name__)
# Initialize Prism
init_prism(
app,
identify_token='your-project-identify-token',
use_sandbox=True
)
# Public endpoint (no payment)
@app.route('/')
def home():
return jsonify({'message': 'Welcome to Prism API'})
# Protected endpoint (requires payment)
@app.route('/api/weather')
@require_payment(price=0.001, description='Weather data')
def weather():
# Access payment info
from flask import g
payment = g.payment
return jsonify({
'location': 'San Francisco',
'temperature': 72,
'condition': 'Sunny',
'payment': {
'network': payment.network,
'tx_hash': payment.tx_hash
}
})
# Premium endpoint (higher price)
@app.route('/api/premium')
@require_payment(price=0.01, description='Premium data')
def premium():
return jsonify({
'premium': True,
'data': 'Premium content'
})
if __name__ == '__main__':
app.run(debug=True)
```
### FastAPI Example
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Depends
from prism_fastapi import PrismMiddleware, require_payment, PaymentInfo
app = FastAPI()
# Add Prism middleware
app.add_middleware(
PrismMiddleware,
identify_token='your-project-identify-token',
use_sandbox=True
)
# Public endpoint (no payment)
@app.get('/')
async def home():
return {'message': 'Welcome to Prism API'}
# Protected endpoint (requires payment)
@app.get('/api/weather')
async def weather(
payment: PaymentInfo = Depends(require_payment(0.001, 'Weather data'))
):
return {
'location': 'San Francisco',
'temperature': 72,
'condition': 'Sunny',
'payment': {
'network': payment.network,
'tx_hash': payment.tx_hash
}
}
# Premium endpoint (higher price)
@app.get('/api/premium')
async def premium(
payment: PaymentInfo = Depends(require_payment(0.01, 'Premium data'))
):
return {
'premium': True,
'data': 'Premium content',
'paid_on': payment.network
}
```
### Configuration
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Flask
from prism_flask import PrismConfig
config = PrismConfig(
identify_token='your-project-identify-token',
use_sandbox=True,
base_url=None, # Optional custom URL
timeout=10.0, # Request timeout in seconds
retries=3 # Failed request retries
)
init_prism(app, config)
```
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# FastAPI
from prism_fastapi import PrismMiddleware, PrismConfig
app.add_middleware(
PrismMiddleware,
config=PrismConfig(
identify_token='your-project-identify-token',
use_sandbox=True,
timeout=10.0,
retries=3
)
)
```
### Payment Info Model
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from pydantic import BaseModel
from typing import Optional
class PaymentInfo(BaseModel):
scheme: str
network: str
asset: str
amount: str
pay_to: str
tx_hash: Optional[str] = None
valid_after: int
valid_before: int
nonce: str
class Config:
# Allow snake_case field names
alias_generator = lambda s: s
```
### Error Handling (Flask)
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, jsonify
from prism_flask import PrismError, require_payment
app = Flask(__name__)
@app.errorhandler(PrismError)
def handle_prism_error(error):
return jsonify({
'error': error.code,
'message': error.message,
'details': error.details
}), error.status_code
@app.route('/api/data')
@require_payment(price=0.01)
def get_data():
return jsonify({'data': 'content'})
```
### Error Handling (FastAPI)
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from prism_fastapi import PrismException
app = FastAPI()
@app.exception_handler(PrismException)
async def prism_exception_handler(
request: Request,
exc: PrismException
):
return JSONResponse(
status_code=exc.status_code,
content={
'error': exc.code,
'message': exc.message,
'details': exc.details
}
)
```
### Advanced Flask Patterns
#### Blueprint Support
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Blueprint
from prism_flask import require_payment
api_bp = Blueprint('api', __name__, url_prefix='/api')
@api_bp.route('/data')
@require_payment(price=0.001, description='API data')
def get_data():
return {'data': 'content'}
app.register_blueprint(api_bp)
```
#### Dynamic Pricing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import request
from prism_flask import require_payment, get_payment_price
@app.route('/api/search')
@require_payment(price=lambda: calculate_search_price(request.args))
def search():
query = request.args.get('q')
results = perform_search(query)
return {'results': results}
def calculate_search_price(args):
# Simple query: $0.001
# Complex query: $0.01
if len(args.get('q', '')) > 50:
return 0.01
return 0.001
```
#### Custom Middleware
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, g, request
from prism_flask import PrismClient
app = Flask(__name__)
prism = PrismClient(identify_token='key', use_sandbox=True)
@app.before_request
def check_payment():
# Custom payment logic
if request.path.startswith('/api/paid'):
auth_header = request.headers.get('X-PAYMENT-AUTHORIZATION')
if not auth_header:
requirements = prism.get_payment_requirements(
resource=request.path,
amount='1000000'
)
return requirements.to_402_response()
payment = prism.verify_payment(auth_header)
if payment.valid:
g.payment = payment
else:
return {'error': 'Invalid payment'}, 401
```
### Advanced FastAPI Patterns
#### Dependency Injection
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Depends
from prism_fastapi import PrismClient, PaymentInfo
app = FastAPI()
# Inject Prism client
def get_prism_client():
return PrismClient(
identify_token='your-project-identify-token',
use_sandbox=True
)
@app.get('/api/data')
async def get_data(
prism: PrismClient = Depends(get_prism_client),
payment: PaymentInfo = Depends(require_payment(0.001))
):
# Manually settle payment if needed
await prism.settle_payment(payment.nonce)
return {'data': 'content'}
```
#### Background Tasks
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import BackgroundTasks
from prism_fastapi import require_payment, PaymentInfo
@app.get('/api/process')
async def process_data(
background_tasks: BackgroundTasks,
payment: PaymentInfo = Depends(require_payment(0.01))
):
# Add settlement to background tasks
background_tasks.add_task(
settle_and_log,
payment.nonce,
payment.network
)
return {'status': 'processing'}
async def settle_and_log(nonce: str, network: str):
# Settle payment in background
await prism.settle_payment(nonce)
logger.info(f'Payment settled: {nonce} on {network}')
```
#### WebSocket Support
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import WebSocket
from prism_fastapi import verify_payment_ws
@app.websocket('/ws/stream')
async def websocket_stream(websocket: WebSocket):
await websocket.accept()
# Wait for payment
payment = await verify_payment_ws(
websocket,
price=0.001,
description='Real-time stream'
)
if payment.valid:
# Stream data
while True:
data = await get_real_time_data()
await websocket.send_json(data)
await asyncio.sleep(1)
else:
await websocket.close(code=1008, reason='Payment required')
```
### Testing Support
#### Flask Testing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import pytest
from prism_flask.testing import MockPrismClient
@pytest.fixture
def client(app):
app.config['TESTING'] = True
with app.test_client() as client:
yield client
@pytest.fixture
def mock_prism(app):
# Mock Prism client for testing
mock = MockPrismClient()
mock.setup_valid_payment(
nonce='0x123...',
tx_hash='0xabc...'
)
app.prism_client = mock
return mock
def test_payment_required(client):
response = client.get('/api/weather')
assert response.status_code == 402
assert 'X-PAYMENT' in response.headers
def test_valid_payment(client, mock_prism):
response = client.get(
'/api/weather',
headers={'X-PAYMENT-AUTHORIZATION': 'valid-token'}
)
assert response.status_code == 200
assert response.json['temperature'] == 72
```
#### FastAPI Testing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import pytest
from fastapi.testclient import TestClient
from prism_fastapi.testing import MockPrismMiddleware
@pytest.fixture
def client(app):
# Replace middleware with mock
app.user_middleware = [
m for m in app.user_middleware
if not isinstance(m, PrismMiddleware)
]
app.add_middleware(MockPrismMiddleware)
return TestClient(app)
def test_payment_required(client):
response = client.get('/api/weather')
assert response.status_code == 402
assert 'x-payment' in response.headers
def test_valid_payment(client):
response = client.get(
'/api/weather',
headers={'x-payment-authorization': 'mock-valid-token'}
)
assert response.status_code == 200
assert response.json()['temperature'] == 72
```
### CLI Tools (Planned)
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Initialize new Prism project
prism init --framework flask
# Test payment flow
prism test --endpoint http://localhost:5000/api/weather
# Generate payment signature
prism sign \
--from 0xAIAgent... \
--to 0xProvider... \
--amount 1000000 \
--nonce 0x123... \
--private-key /path/to/key
# Verify payment
prism verify \
--signature 0xabc... \
--nonce 0x123... \
--network base-sepolia
# Monitor payments
prism monitor --api-key your-key --follow
```
## Planned Features Roadmap
* Flask decorator support - FastAPI dependency injection - Basic payment
verification - Type hints and Pydantic models
* WebSocket support - Background task integration - Advanced caching - CLI
tools
* Django middleware - Starlette support - Sanic integration - Tornado handlers
* Celery integration - Redis caching - PostgreSQL tracking - Prometheus
metrics
## Why Python SDK?
Python dominates ML/AI applications
Clean, readable decorator syntax
Native async/await with FastAPI
Rich ecosystem of libraries
## Expected Use Cases
### AI/ML APIs
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI
from prism_fastapi import require_payment, PaymentInfo
app = FastAPI()
@app.post('/api/inference')
async def run_inference(
model_input: ModelInput,
payment: PaymentInfo = Depends(require_payment(0.01, 'AI inference'))
):
# Run expensive ML model
result = await ml_model.predict(model_input)
# Track usage
await track_usage(
model='gpt-4',
payment_network=payment.network,
amount=payment.amount
)
return {'result': result}
```
### Data APIs
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask
from prism_flask import require_payment
app = Flask(__name__)
@app.route('/api/stock/')
@require_payment(price=0.005, description='Real-time stock data')
def get_stock(symbol):
quote = fetch_stock_quote(symbol)
return {
'symbol': symbol,
'price': quote.price,
'change': quote.change
}
@app.route('/api/historical/')
@require_payment(price=0.05, description='Historical stock data')
def get_historical(symbol):
data = fetch_historical_data(symbol)
return {'symbol': symbol, 'data': data}
```
### Content APIs
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from prism_fastapi import require_payment
@app.get('/api/video/{video_id}')
async def stream_video(
video_id: str,
payment: PaymentInfo = Depends(require_payment(0.05, 'Video streaming'))
):
async def video_stream():
async for chunk in get_video_chunks(video_id):
yield chunk
return StreamingResponse(
video_stream(),
media_type='video/mp4'
)
```
## Get Notified
Want to be notified when the Python SDK is released?
Get email notifications for Python SDK updates
## Contribute
Interested in contributing to the Python SDK development?
Share ideas and feedback
## Alternative Solutions
While waiting for the Python SDK, you can:
Use Prism Gateway REST API with `requests` or `httpx`
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import requests
gateway_url = 'https://prism-gw.fd.xyz'
headers = {'x-project-identify-token': identify_token}
# Get payment requirements
response = requests.post(
f'{gateway_url}/api/v1/payment/requirements',
headers=headers,
json={
'resource': '/api/premium',
'amount': '1000000'
}
)
requirements = response.json()
```
Complete REST API documentation
Use TypeScript SDK with Node.js backend
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import express from 'express';
import { prismPaymentMiddleware } from '@1stdigital/prism-express';
const app = express();
app.use(prismPaymentMiddleware(
{ identifyToken: 'key', useSandbox: true },
{ '/api/data': { price: 0.01 } }
));
```
Full TypeScript documentation
# Django Integration
Source: https://developers.fd.xyz/prism/sdk/python/django
Protect Django views with blockchain micropayments
**Coming soon.** The `prism-django` package is not yet published to PyPI. This page describes the planned API.
## Overview
The **prism-django** package provides middleware for Django applications, integrating seamlessly with Django's request/response cycle and middleware stack.
Integrates with Django middleware stack
Works with Django ORM and models
Compatible with Django Admin
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install prism-django django
```
`bash poetry add prism-django django `
```
prism-django>=1.0.0
django>=4.2.0
```
***
The canonical SDK config is `identify_token` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `api_key` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Add Prism middleware
'prism_django.middleware.PrismPaymentMiddleware',
]
# Prism configuration
PRISM_CONFIG = {
'IDENTIFY_TOKEN': 'dev-key-123',
'BASE_URL': 'https://prism-gw.fd.xyz',
'DEBUG': True,
'ROUTES': {
'/api/premium/': {
'price': 0.01, # $0.01 USD
'description': 'Premium API'
}
}
}
# views.py
from django.http import JsonResponse
def premium_view(request):
# Access payer address
payer = getattr(request, 'prism_payer', None)
return JsonResponse({
'message': 'Premium content',
'payer': payer
})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/premium/', views.premium_view),
]
```
***
## Configuration
### Settings.py
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PRISM_CONFIG = {
'IDENTIFY_TOKEN': 'your-api-key',
'BASE_URL': 'https://prism-gw.fd.xyz',
'DEBUG': False,
'ROUTES': {
'/api/premium/': {
'price': 0.01,
'description': 'Premium API'
},
'/api/weather/': {
'price': 0.001,
'description': 'Weather data'
},
'/api/data/*': {
'price': 0.005,
'description': 'Data API (wildcard)'
}
}
}
```
***
## Route Protection
### URL Patterns
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# urls.py
from django.urls import path
from . import views
urlpatterns = [
# Protected routes (configured in PRISM_CONFIG)
path('api/premium/', views.premium_view),
path('api/weather/', views.weather_view),
# Free routes (not in PRISM_CONFIG)
path('api/free/', views.free_view),
]
```
***
## Accessing Payment Info
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from django.http import JsonResponse
def premium_view(request):
# Access payer address
payer = getattr(request, 'prism_payer', None)
# '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
# Access payment object
payment = getattr(request, 'prism_payment', None)
if payment:
return JsonResponse({
'message': 'Premium data',
'payer': payer,
'network': payment.get('network'),
'asset': payment.get('asset')
})
return JsonResponse({'message': 'No payment info'})
```
***
## Settlement Validation
Django middleware intercepts responses to validate settlement:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Internal implementation (automatic!)
class PrismPaymentMiddleware:
def process_response(self, request, response):
# Validate settlement
settlement_result = core.settlement_callback(...)
if not settlement_result or not settlement_result.get("success"):
# ❌ Settlement failed
return JsonResponse(
{
'error': 'Payment settlement failed',
'details': settlement_result.get('errorReason')
},
status=402
)
# ✅ Settlement succeeded
response['X-PAYMENT-RESPONSE'] = settlement_result['transaction']
return response
```
***
## Class-Based Views
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from django.views import View
from django.http import JsonResponse
class PremiumAPIView(View):
def get(self, request):
payer = getattr(request, 'prism_payer', None)
return JsonResponse({
'message': 'Premium content',
'payer': payer
})
def post(self, request):
payer = getattr(request, 'prism_payer', None)
# Process POST data
data = request.POST
return JsonResponse({
'message': 'Data received',
'payer': payer,
'data': dict(data)
})
```
***
## Django REST Framework
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class PremiumAPIView(APIView):
def get(self, request):
payer = getattr(request, 'prism_payer', None)
return Response({
'message': 'Premium content',
'payer': payer
})
# settings.py
INSTALLED_APPS = [
# ...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
}
```
***
## Testing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from django.test import TestCase, Client
import json
class PrismPaymentTests(TestCase):
def setUp(self):
self.client = Client()
def test_payment_required_without_header(self):
response = self.client.get('/api/premium/')
self.assertEqual(response.status_code, 402)
data = json.loads(response.content)
self.assertTrue(data['paymentRequired'])
def test_access_granted_with_valid_payment(self):
payment = json.dumps({
'scheme': 'eip3009',
'signature': '0x' + '0' * 130
})
response = self.client.get(
'/api/premium/',
HTTP_X_PAYMENT=payment
)
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertIn('payer', data)
def test_wildcard_route(self):
response = self.client.get('/api/data/anything/')
self.assertEqual(response.status_code, 402)
```
***
## Production Deployment
### Settings for Production
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# settings.py
import os
from pathlib import Path
# Production settings
DEBUG = False
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',')
# Prism configuration from environment
PRISM_CONFIG = {
'IDENTIFY_TOKEN': os.environ['PRISM_IDENTIFY_TOKEN'],
'BASE_URL': os.getenv('PRISM_BASE_URL', 'https://prism-gw.fd.xyz'),
'DEBUG': DEBUG,
'ROUTES': {
'/api/premium/': {
'price': 0.01,
'description': 'Premium API'
}
}
}
# Security
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
# CORS (if needed)
INSTALLED_APPS += ['corsheaders']
MIDDLEWARE.insert(0, 'corsheaders.middleware.CorsMiddleware')
CORS_ALLOWED_ORIGINS = os.getenv('CORS_ORIGINS', '').split(',')
```
### WSGI Deployment (Gunicorn)
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Install Gunicorn
pip install gunicorn
# Run with Gunicorn
gunicorn myproject.wsgi:application \
--bind 0.0.0.0:8000 \
--workers 4 \
--timeout 120 \
--access-logfile - \
--error-logfile -
```
### Docker Deployment
```dockerfile theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
EXPOSE 8000
CMD ["gunicorn", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]
```
***
## Type Hints
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from typing import Optional, Dict, Any
from django.http import JsonResponse, HttpRequest
def premium_view(request: HttpRequest) -> JsonResponse:
payer: Optional[str] = getattr(request, 'prism_payer', None)
payment: Optional[Dict[str, Any]] = getattr(request, 'prism_payment', None)
return JsonResponse({
'message': 'Premium content',
'payer': payer,
'network': payment.get('network') if payment else None
})
```
# FastAPI Integration
Source: https://developers.fd.xyz/prism/sdk/python/fastapi
Protect FastAPI endpoints with blockchain micropayments
**Coming soon.** The `prism-fastapi` package is not yet published to PyPI. This page describes the planned API.
## Overview
The **prism-fastapi** package provides async middleware for FastAPI applications, leveraging Python's modern async/await syntax for high-performance payment validation.
Full async support with Python asyncio
Works with FastAPI's Depends system
Full type hint support with Pydantic
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install prism-fastapi fastapi uvicorn
```
`bash poetry add prism-fastapi fastapi uvicorn `
```
prism-fastapi>=1.0.0
fastapi>=0.100.0
uvicorn[standard]>=0.23.0
```
***
The canonical SDK config is `identify_token` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `api_key` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Request
from prism_fastapi import prism_payment_middleware, PrismMiddlewareConfig
app = FastAPI()
# Configure Prism middleware
prism_config = PrismMiddlewareConfig(
identify_token="dev-key-123",
base_url="https://prism-gw.fd.xyz",
routes={
"/api/premium": {
"price": 0.01, # $0.01 USD
"description": "Premium API"
}
}
)
# Add middleware
app.middleware("http")(prism_payment_middleware(prism_config))
# Protected endpoint
@app.get("/api/premium")
async def premium_endpoint(request: Request):
payer = request.state.prism_payer # Wallet address
return {
"message": "Premium content",
"payer": payer
}
# Run: uvicorn main:app --reload
```
***
## Configuration
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from dataclasses import dataclass
from typing import Dict, Union
@dataclass
class RoutePaymentConfig:
price: Union[float, str] # USD price
description: str
mime_type: str = "application/json"
@dataclass
class PrismMiddlewareConfig:
identify_token: str
base_url: str = "https://prism-gw.fd.xyz"
debug: bool = False
routes: Dict[str, RoutePaymentConfig] = None
```
***
## Route Protection
### Multiple Routes
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from prism_fastapi import PrismMiddlewareConfig, RoutePaymentConfig
config = PrismMiddlewareConfig(
identify_token="your-project-identify-token",
routes={
"/api/premium": RoutePaymentConfig(
price=0.01,
description="Premium API"
),
"/api/weather": RoutePaymentConfig(
price=0.001,
description="Weather data"
),
"/api/data/*": RoutePaymentConfig(
price=0.005,
description="Data API (wildcard)"
)
}
)
app.middleware("http")(prism_payment_middleware(config))
```
***
## Accessing Payment Info
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import FastAPI, Request
@app.get("/api/premium")
async def premium_endpoint(request: Request):
# Access payer address
payer = request.state.prism_payer
# '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
# Access payment object
payment = getattr(request.state, 'prism_payment', None)
if payment:
return {
"message": "Premium data",
"payer": payer,
"network": payment.get("network"),
"asset": payment.get("asset")
}
return {"message": "No payment info"}
```
***
## Settlement Validation
FastAPI middleware intercepts responses to validate settlement:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Internal implementation (automatic!)
@app.middleware("http")
async def prism_payment_middleware(request: Request, call_next):
# ... payment validation ...
# Call endpoint
response = await call_next(request)
# Validate settlement
settlement_result = await core.settlement_callback(...)
if not settlement_result or not settlement_result.get("success"):
# ❌ Settlement failed
return JSONResponse(
status_code=402,
content={
"error": "Payment settlement failed",
"details": settlement_result.get("errorReason")
}
)
# ✅ Settlement succeeded
response.headers["X-PAYMENT-RESPONSE"] = settlement_result["transaction"]
return response
```
***
## Dependency Injection
### Payer Dependency
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from fastapi import Depends, Request
def get_payer(request: Request) -> str:
return getattr(request.state, 'prism_payer', None)
@app.get("/api/premium")
async def premium_endpoint(payer: str = Depends(get_payer)):
return {
"message": "Premium content",
"payer": payer
}
```
***
## Testing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import pytest
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_payment_required_without_header():
response = client.get("/api/premium")
assert response.status_code == 402
assert response.json()["paymentRequired"] is True
def test_access_granted_with_valid_payment():
payment = {
"scheme": "eip3009",
"signature": "0x" + "0" * 130
}
response = client.get(
"/api/premium",
headers={"X-PAYMENT": str(payment)}
)
assert response.status_code == 200
assert "payer" in response.json()
@pytest.mark.asyncio
async def test_async_endpoint():
async with AsyncClient(app=app, base_url="http://test") as ac:
response = await ac.get("/api/premium")
assert response.status_code == 402
```
***
## Production Deployment
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# main.py
from fastapi import FastAPI
from prism_fastapi import prism_payment_middleware, PrismMiddlewareConfig
import os
app = FastAPI(
title="Prism Payment API",
docs_url="/docs" if os.getenv("ENV") != "production" else None
)
# Configure Prism
config = PrismMiddlewareConfig(
identify_token=os.environ['PRISM_IDENTIFY_TOKEN'],
base_url=os.getenv("PRISM_BASE_URL", "https://prism-gw.fd.xyz"),
debug=os.getenv("DEBUG", "false").lower() == "true",
routes={
"/api/premium": {
"price": 0.01,
"description": "Premium API"
}
}
)
app.middleware("http")(prism_payment_middleware(config))
# CORS (if needed)
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOWED_ORIGINS", "*").split(","),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=int(os.getenv("PORT", 8000)),
reload=os.getenv("ENV") != "production"
)
```
### Docker Deployment
```dockerfile theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
***
## Type Hints
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from typing import Optional, Dict, Any
from fastapi import Request
@app.get("/api/premium")
async def premium_endpoint(request: Request) -> Dict[str, Any]:
payer: Optional[str] = getattr(request.state, 'prism_payer', None)
payment: Optional[Dict[str, Any]] = getattr(request.state, 'prism_payment', None)
return {
"message": "Premium content",
"payer": payer,
"network": payment.get("network") if payment else None
}
```
# Flask Integration
Source: https://developers.fd.xyz/prism/sdk/python/flask
Protect Flask APIs with blockchain micropayments
**Coming soon.** The `prism-flask` package is not yet published to PyPI. This page describes the planned API.
## Overview
The **prism-flask** package provides Flask middleware for payment-protecting your API routes using the x402 protocol. It uses Flask's decorator pattern and request context for seamless integration.
Flask decorators and context managers
Payment info in `g.prism_payer`
Single function call to configure
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install prism-flask
```
`bash poetry add prism-flask `
```txt theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
prism-flask==1.0.0
```
***
The canonical SDK config is `identify_token` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `api_key` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, g, jsonify
from prism_flask import prism_payment_middleware
from prism_sdk_core import PrismMiddlewareConfig, RoutePaymentConfig
app = Flask(__name__)
# Configure Prism middleware
prism_payment_middleware(
app,
config=PrismMiddlewareConfig(
identify_token='dev-key-123',
base_url='https://prism-gw.fd.xyz'
),
routes={
'/api/premium': RoutePaymentConfig(
price=0.01,
description='Premium API access'
)
}
)
@app.route('/api/premium')
def premium():
payer = getattr(g, 'prism_payer', None)
return jsonify({
'message': 'Premium content!',
'payer': payer
})
if __name__ == '__main__':
app.run(port=5000)
```
***
## Configuration
### Middleware Configuration
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from prism_sdk_core import PrismMiddlewareConfig
config = PrismMiddlewareConfig(
identify_token='your-project-identify-token', # Required: Your Prism API key
base_url='https://...', # Optional: Gateway URL
debug=True # Optional: Enable debug logging
)
```
### Route Configuration
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from prism_sdk_core import RoutePaymentConfig
routes = {
'/api/premium': RoutePaymentConfig(
price=0.01, # Price in USD (0.01 = $0.01)
description='Premium API' # Human-readable description
)
}
```
***
## Route Protection Patterns
### Exact Path Matching
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
prism_payment_middleware(
app,
config=config,
routes={
'/api/premium': RoutePaymentConfig(
price=0.01,
description='Premium API'
),
'/api/weather': RoutePaymentConfig(
price='$0.001',
description='Weather data'
)
}
)
# ✅ Protected: GET /api/premium
# ✅ Protected: GET /api/weather
# ❌ Not protected: GET /api/public
```
***
### Wildcard Matching
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
prism_payment_middleware(
app,
config=config,
routes={
'/api/*': RoutePaymentConfig(
price=0.005,
description='API access'
)
}
)
# ✅ Protected: GET /api/users
# ✅ Protected: GET /api/posts/123
# ❌ Not protected: GET /public
```
***
### Multiple Route Groups
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
prism_payment_middleware(
app,
config=config,
routes={
# Free tier
'/api/basic/*': RoutePaymentConfig(
price='$0.0001',
description='Basic API'
),
# Premium tier
'/api/premium/*': RoutePaymentConfig(
price='$0.01',
description='Premium API'
),
# Specific expensive endpoint
'/api/ai/generate': RoutePaymentConfig(
price='$0.50',
description='AI content generation'
)
}
)
```
***
## Accessing Payment Information
Payment info is stored in Flask's `g` context object:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import g
@app.route('/api/premium')
def premium():
# Access payer wallet address
payer = getattr(g, 'prism_payer', None)
# Returns: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb' or None
# Access full payment object
payment = getattr(g, 'prism_payment', None)
"""
{
'scheme': 'eip3009',
'network': 'eth-sepolia',
'asset': 'usdc',
'amount': '10000',
'recipient': '0x...',
'nonce': '0x...',
'validBefore': 1735430400,
'signature': '0x...'
}
"""
return jsonify({
'message': 'Premium content',
'payer': payer,
'network': payment.get('network') if payment else None
})
```
***
### Safe Access Helper
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
def get_payer():
"""Safely get payer address from request context"""
return getattr(g, 'prism_payer', None)
def get_payment():
"""Safely get full payment object from request context"""
return getattr(g, 'prism_payment', None)
@app.route('/api/data')
def data():
payer = get_payer()
if not payer:
return jsonify({'error': 'Payment required'}), 402
return jsonify({
'data': [1, 2, 3],
'payer': payer
})
```
***
## Settlement Validation
The Flask middleware uses **@app.after\_request** decorator to validate settlement before sending data:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Internal implementation (automatic!)
@app.after_request
def settlement_validation(response):
"""Validate settlement before sending response"""
settlement_result = g.get('prism_settlement_result')
if not settlement_result or not settlement_result.get('success'):
# ❌ Settlement failed - return error instead of data
error_reason = (settlement_result or {}).get('errorReason', 'Settlement processing failed')
return jsonify({
'x402Version': 2,
'error': 'Payment settlement failed',
'details': error_reason
}), 402
# ✅ Settlement succeeded - add header and return original response
response.headers['X-PAYMENT-RESPONSE'] = settlement_result['transaction']
return response
```
**Key Points:**
* `@app.after_request` runs **after** view function but **before** sending to client
* Can return a **different response** if settlement fails
* Works with all Flask response types (`jsonify()`, `make_response()`, etc.)
See [Stablecoin Settlement](/prism/concepts/settlement) for details.
***
## Error Handling
### Payment Errors
When a request lacks valid payment:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 402 Payment Required
{
"x402Version": 2,
"paymentRequired": true,
"acceptedPayments": [
{
"scheme": "eip3009",
"network": "eth-sepolia",
"asset": "usdc",
"amount": "10000",
"recipient": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"nonce": "0xabc123...",
"validBefore": 1735430400
}
],
"description": "Premium API access",
"priceUSD": "0.01"
}
```
***
### Gateway Errors
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 500 Internal Server Error
{
"x402Version": 2,
"error": "Gateway Error",
"details": "Failed to contact payment gateway",
"gateway": {
"traceId": "abc-123-xyz",
"timestamp": "2025-12-18T10:30:00Z"
}
}
```
***
### Custom Error Handlers
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from werkzeug.exceptions import HTTPException
@app.errorhandler(402)
def handle_payment_required(error):
"""Custom handler for payment required errors"""
return jsonify({
'error': 'Payment required',
'message': 'Please provide payment to access this resource',
'documentation': 'https://apps.fd.xyz/prism/'
}), 402
@app.errorhandler(500)
def handle_internal_error(error):
"""Custom handler for internal errors"""
app.logger.error(f'Internal error: {error}')
return jsonify({
'error': 'Internal server error',
'message': 'Something went wrong'
}), 500
```
***
## Testing
### Unit Testing with pytest
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import pytest
from flask import Flask
from prism_flask import prism_payment_middleware
from prism_sdk_core import PrismMiddlewareConfig, RoutePaymentConfig
@pytest.fixture
def app():
"""Create test Flask app"""
app = Flask(__name__)
prism_payment_middleware(
app,
config=PrismMiddlewareConfig(
identify_token='test-key',
base_url='http://test-gateway'
),
routes={
'/api/premium': RoutePaymentConfig(
price=0.01,
description='Test'
)
}
)
@app.route('/api/premium')
def premium():
from flask import g, jsonify
payer = getattr(g, 'prism_payer', None)
return jsonify({'message': 'Premium', 'payer': payer})
return app
@pytest.fixture
def client(app):
"""Create test client"""
return app.test_client()
def test_payment_required(client):
"""Test 402 response without payment"""
response = client.get('/api/premium')
assert response.status_code == 402
assert response.json['paymentRequired'] == True
def test_valid_payment(client):
"""Test access with valid payment"""
# Mock payment header
payment = {
'scheme': 'eip3009',
'network': 'eth-sepolia',
'asset': 'usdc',
'amount': '10000',
'signature': '0x' + '0' * 130
}
response = client.get(
'/api/premium',
headers={'X-PAYMENT': str(payment)}
)
# In test mode, mock signatures are accepted
assert response.status_code == 200
assert response.json['message'] == 'Premium'
```
***
### Integration Testing
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import requests
import json
def test_full_payment_flow():
"""Test complete payment flow with real Gateway"""
base_url = 'http://localhost:5000'
# 1. Request without payment
response = requests.get(f'{base_url}/api/premium')
assert response.status_code == 402
payment_req = response.json()['acceptedPayments'][0]
# 2. Sign payment with wallet (use web3.py)
from eth_account import Account
from eth_account.messages import encode_structured_data
private_key = 'your-test-private-key'
account = Account.from_key(private_key)
# EIP-712 structured data
structured_data = {
'types': {
'EIP712Domain': [...],
'TransferAuthorization': [...]
},
'domain': {...},
'message': payment_req
}
signed = account.sign_message(encode_structured_data(structured_data))
payment = {
**payment_req,
'signature': signed.signature.hex()
}
# 3. Send request with signed payment
response = requests.get(
f'{base_url}/api/premium',
headers={'X-PAYMENT': json.dumps(payment)}
)
assert response.status_code == 200
assert 'X-PAYMENT-RESPONSE' in response.headers # Transaction hash
```
***
## Production Deployment
### Environment Variables
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# .env
PRISM_IDENTIFY_TOKEN=your-production-identify-token
PRISM_BASE_URL=https://prism-gw.fd.xyz
FLASK_ENV=production
```
### Production Configuration
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import os
from flask import Flask
from prism_flask import prism_payment_middleware
from prism_sdk_core import PrismMiddlewareConfig, RoutePaymentConfig
app = Flask(__name__)
# Load config from environment
prism_payment_middleware(
app,
config=PrismMiddlewareConfig(
identify_token=os.getenv('PRISM_IDENTIFY_TOKEN'),
base_url=os.getenv('PRISM_BASE_URL'),
debug=os.getenv('FLASK_ENV') != 'production'
),
routes={
'/api/premium': RoutePaymentConfig(
price=0.01,
description='Premium API'
)
}
)
```
***
### Logging & Monitoring
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import logging
from flask import Flask, g
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
@app.before_request
def log_request():
"""Log incoming requests"""
logger.info(f'Request: {request.method} {request.path}')
@app.after_request
def log_response(response):
"""Log payment events"""
if response.status_code == 402:
logger.info(f'Payment required: {request.path}')
elif response.status_code == 200 and hasattr(g, 'prism_payer'):
payer = getattr(g, 'prism_payer')
tx_hash = response.headers.get('X-PAYMENT-RESPONSE')
logger.info(f'Payment succeeded: {request.path} | Payer: {payer} | TX: {tx_hash}')
return response
```
***
### WSGI Deployment (Gunicorn)
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# Install Gunicorn
pip install gunicorn
# Run with multiple workers
gunicorn -w 4 -b 0.0.0.0:5000 app:app
```
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# gunicorn.conf.py
bind = "0.0.0.0:5000"
workers = 4
worker_class = "sync"
timeout = 30
keepalive = 2
# Logging
accesslog = "/var/log/gunicorn/access.log"
errorlog = "/var/log/gunicorn/error.log"
loglevel = "info"
```
***
## Type Hints
Full type hint support with mypy:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from typing import Optional, Dict, Any
from flask import Flask, g, jsonify, Response
from prism_flask import prism_payment_middleware
from prism_sdk_core import PrismMiddlewareConfig, RoutePaymentConfig
app: Flask = Flask(__name__)
def get_payer() -> Optional[str]:
"""Get payer address from request context"""
return getattr(g, 'prism_payer', None)
def get_payment() -> Optional[Dict[str, Any]]:
"""Get payment object from request context"""
return getattr(g, 'prism_payment', None)
@app.route('/api/premium')
def premium() -> Response:
"""Payment-protected endpoint"""
payer: Optional[str] = get_payer()
return jsonify({
'message': 'Premium content',
'payer': payer
})
```
***
## Examples
### AI Agent API
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask, request, jsonify, g
from prism_flask import prism_payment_middleware
from prism_sdk_core import PrismMiddlewareConfig, RoutePaymentConfig
app = Flask(__name__)
prism_payment_middleware(
app,
config=PrismMiddlewareConfig(identify_token='your-project-identify-token'),
routes={
'/api/ai/chat': RoutePaymentConfig(
price='$0.01',
description='AI chat response'
),
'/api/ai/image': RoutePaymentConfig(
price='$0.50',
description='AI image generation'
)
}
)
@app.route('/api/ai/chat', methods=['POST'])
def ai_chat():
"""AI chat endpoint"""
data = request.get_json()
message = data.get('message')
payer = getattr(g, 'prism_payer')
# Call AI service
response = call_ai_service(message)
return jsonify({
'response': response,
'payer': payer,
'credits_used': 1
})
```
***
### Content Paywall
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
@app.route('/articles/')
def get_article(article_id):
"""Payment-protected article access"""
payer = getattr(g, 'prism_payer')
article = db.get_article(article_id)
return jsonify({
'id': article.id,
'title': article.title,
'content': article.content,
'author': article.author,
'payer': payer
})
```
***
### Premium API with Rate Limiting
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["100 per hour"]
)
@app.route('/api/premium')
@limiter.limit("10 per minute") # Additional rate limit for premium
def premium():
"""Rate-limited premium endpoint"""
payer = getattr(g, 'prism_payer')
return jsonify({
'message': 'Premium content',
'payer': payer
})
```
***
## Troubleshooting
**Make sure you installed the correct package:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install prism-flask # Not prism-sdk-core alone
```
**Check Python version:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
python --version # Requires Python 3.8+
```
**Check:** 1. Payment header is properly formatted JSON string 2. Middleware
is configured BEFORE route definitions 3. Route path matches configured route
pattern 4. Payment signature is valid **Debug:** `python @app.before_request
def debug_payment(): print(f'Path: {request.path}') print(f'Payment header:{" "} {request.headers.get("X-PAYMENT")}') print(f'Payer:{" "} {getattr(g, "prism_payer", "NOT SET")}') `
**Common causes:** 1. Insufficient balance in sender's wallet 2. Token
allowance not set for USDC contract 3. Network congestion (transaction
timeout) 4. Nonce already used (replay attack prevention) **Check logs:**
`python import logging logging.basicConfig(level=logging.DEBUG) `
**Install type stubs:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pip install types-Flask
```
**Configure mypy:**
```ini theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# mypy.ini
[mypy]
python_version = 3.8
plugins = sqlmypy
```
***
## Flask-CORS Integration
Enable CORS for browser-based clients:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Flask
from flask_cors import CORS
from prism_flask import prism_payment_middleware
app = Flask(__name__)
# Configure CORS
CORS(app, resources={
r"/api/*": {
"origins": ["https://yourapp.com"],
"methods": ["GET", "POST"],
"allow_headers": ["Content-Type", "X-PAYMENT"],
"expose_headers": ["X-PAYMENT-RESPONSE"]
}
})
# Then configure Prism
prism_payment_middleware(app, config, routes)
```
***
## Blueprint Support
Works with Flask Blueprints:
```python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
from flask import Blueprint, g, jsonify
api_bp = Blueprint('api', __name__, url_prefix='/api')
@api_bp.route('/premium')
def premium():
"""Blueprint route - payment still works!"""
payer = getattr(g, 'prism_payer')
return jsonify({'message': 'Premium', 'payer': payer})
# Register blueprint
app.register_blueprint(api_bp)
# Configure Prism with blueprint routes
prism_payment_middleware(
app,
config=config,
routes={
'/api/premium': RoutePaymentConfig(price=0.01, description='Premium')
}
)
```
# TypeScript / JavaScript SDK
Source: https://developers.fd.xyz/prism/sdk/typescript
Monetize any TypeScript API in minutes — per-call stablecoin payments, zero payment infrastructure.
## Overview
The **Prism Express Middleware** is a drop-in solution for protecting your Node.js API routes with blockchain-based micropayments using the x402 protocol.
Works out of the box with Express.js
Full TypeScript support with IntelliSense
Per-route pricing with wildcards
## What's New in v1.1
**Latest Version:** 1.1.0 - Enhanced error handling and Gateway integration
**New error classes** for better debugging and monitoring:
* `PrismGatewayError` - Preserves Gateway status codes and trace IDs
* `PrismNetworkError` - Network connectivity issues (503)
* `PrismConfigError` - SDK misconfiguration (500)
* `PrismPaymentError` - Invalid payment (402)
* `PrismValidationError` - Request validation (400)
**Benefits:**
* ✅ Type-safe error handling with `instanceof` checks
* ✅ Gateway trace IDs for backend correlation
* ✅ Timestamps for log searching
* ✅ Original status codes preserved (not all converted to 500)
**Debug production issues faster** with Gateway trace IDs:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
if (error instanceof PrismGatewayError) {
console.log('Trace ID:', error.traceId); // e.g. "abc-123-xyz"
console.log('Timestamp:', error.timestamp);
console.log('Details:', error.details); // Full error message from Gateway
}
```
Include trace IDs in support tickets for faster resolution.
**Implemented** `verifyPayment()` endpoint integration:
* Cryptographic signature verification via Gateway
* Payer address extracted and stored in `res.locals.payer`
* Proper error handling for verification failures
**Better error messages** for end-users:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Internal Error",
"details": "An internal error occurred. Please try again or contact support.",
"gateway": {
"traceId": "abc-123-xyz",
"timestamp": "2025-11-06T13:13:00Z"
}
}
```
**Before:** Generic "Failed to generate payment requirements"\
**After:** Detailed error with trace ID and timestamp
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-express
```
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
yarn add @1stdigital/prism-express
```
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pnpm add @1stdigital/prism-express
```
**Package Registry:** GitHub Packages **Scope:** `@1stdigital` **Package:**
`prism-express`
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-express
```
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import express from 'express';
import { prismPaymentMiddleware } from '@1stdigital/prism-express';
```
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const app = express();
app.use(
prismPaymentMiddleware(
{
identifyToken: process.env.PRISM_IDENTIFY_TOKEN },
{
'/api/premium': {
price: 0.01,
description: 'Premium API access'
}
}
)
);
```
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get('/api/premium', (req, res) => {
res.json({ data: 'Premium content' });
});
app.listen(3000);
```
## Basic Usage
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import express from "express";
import { prismPaymentMiddleware } from "@1stdigital/prism-express";
const app = express();
// Configure payment middleware
app.use(
prismPaymentMiddleware(
{
identifyToken: "dev-key-123",
},
{
"/api/weather": {
price: 0.001,
description: "Weather API access",
mimeType: "application/json",
},
"/api/premium/*": {
price: 0.01,
description: "Premium API endpoints",
},
},
),
);
// Public endpoint (no payment)
app.get("/", (req, res) => {
res.json({ message: "Welcome to Prism API" });
});
// Protected endpoint (requires payment)
app.get("/api/weather", (req, res) => {
res.json({
location: "San Francisco",
temperature: 72,
condition: "Sunny",
});
});
// Protected premium endpoint
app.get("/api/premium/data", (req, res) => {
res.json({
premium: true,
data: "This is premium content",
});
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
```
## Configuration
### Middleware Config
The first parameter to `prismPaymentMiddleware` is the global configuration:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismMiddlewareConfig {
identifyToken: string; // Required: Your Prism Project Identify Token
baseUrl?: string; // Optional: Gateway URL (defaults to production)
timeout?: number; // Optional: Request timeout in ms (default: 10000)
retries?: number; // Optional: Failed request retries (default: 3)
}
```
Your Prism Project Identify Token from [Client Portal](https://apps.fd.xyz/prism/)
Store in environment variable: `process.env.PRISM_IDENTIFY_TOKEN`
Prism Gateway URL. Defaults to `https://prism-gw.fd.xyz`.
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
identifyToken: 'key',
baseUrl: 'https://prism-gw.fd.xyz'
}
```
Request timeout in milliseconds
Gateway calls that exceed timeout will fail gracefully
Number of retry attempts for failed Gateway requests
### Route Configuration
The second parameter defines which routes require payment:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface RoutePaymentConfig {
price: number | string; // Required: Price per request
description?: string; // Optional: Human-readable description
mimeType?: string; // Optional: Response content type
maxTimeoutSeconds?: number; // Optional: Payment timeout
resource?: string; // Optional: Custom resource URL
}
```
Price to charge per request **Formats:** - Number: `0.001` (USDC) - String:
`"$0.001"` (explicit USD) - String: `"0.001 USDC"` (explicit token)
Use small decimals for micropayments: `0.001` = \$0.001 = 0.1¢
Human-readable description shown to users
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
price: 0.01,
description: 'Weather API - Current conditions'
}
```
Use ASCII characters (U+0000–U+007F) in `description` for best HTTP header compatibility. This value is transmitted in payment-related HTTP headers, where non-ASCII characters (e.g., em dashes, curly quotes, accented letters) may cause encoding issues across SDKs. If you need to display a Unicode description to end users, keep a separate display string in your application code.
Response content type **Common values:** - `application/json` - `text/html` -
`image/png` - `video/mp4`
Maximum time (seconds) to wait for payment
After timeout, payment authorization expires
Custom resource URL (overrides request path)
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
price: 0.01,
resource: 'https://api.example.com/v2/premium'
}
```
## Route Patterns
### Exact Match
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
'/api/weather': {
price: 0.001,
description: 'Weather data'
}
}
```
Matches:
* ✅ `/api/weather`
* ❌ `/api/weather/forecast`
* ❌ `/api/weather-data`
### Wildcard Routes
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
'/api/premium/*': {
price: 0.01,
description: 'All premium endpoints'
}
}
```
Matches:
* ✅ `/api/premium/data`
* ✅ `/api/premium/analytics`
* ✅ `/api/premium/users/123`
* ❌ `/api/public/data`
### Multiple Routes
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
'/api/basic': {
price: 0.001,
description: 'Basic tier'
},
'/api/premium': {
price: 0.01,
description: 'Premium tier'
},
'/api/enterprise/*': {
price: 0.1,
description: 'Enterprise tier'
}
}
```
### Route Priority
When multiple patterns match, **most specific wins**:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
'/api/*': { price: 0.001 }, // Generic
'/api/premium/*': { price: 0.01 }, // More specific
'/api/premium/gold': { price: 0.05 } // Most specific (used)
}
```
Request to `/api/premium/gold` → uses `0.05` price
## Accessing Payment Info
Payment details are available in route handlers via `res.locals.payment`:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get("/api/premium", (req, res) => {
const payment = res.locals.payment;
console.log("Payment scheme:", payment.scheme);
console.log("Network:", payment.network);
console.log("Token:", payment.asset);
console.log("Amount:", payment.amount);
console.log("Transaction hash:", payment.txHash);
res.json({ data: "Premium content" });
});
```
### Payment Object Type
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PaymentInfo {
scheme: string; // 'exact' | 'range' | 'any'
network: string; // 'base-sepolia' | 'ethereum' | 'bsc'
asset: string; // Token contract address
amount: string; // Amount in smallest unit
payTo: string; // Provider wallet address
txHash?: string; // Transaction hash (after settlement)
validAfter: number; // Unix timestamp
validBefore: number; // Unix timestamp
nonce: string; // Unique payment nonce
}
```
## Error Handling
The SDK provides structured error handling with specific error classes, detailed error messages, and Gateway tracing information.
### Error Classes
All Prism errors extend the base `PrismError` class and include:
* **Status code** - HTTP status code to return
* **Error code** - Machine-readable error identifier
* **Message** - Human-readable error description
* **Details** - Additional context (varies by error type)
**When:** Prism Gateway API returns 4xx or 5xx response
**Properties:**
* `statusCode` - Original HTTP status from Gateway (400, 401, 500, etc.)
* `message` - Error title from Gateway
* `details` - Detailed error description
* `traceId` - Gateway trace ID for debugging
* `timestamp` - Error timestamp from Gateway
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Internal Error",
"details": "An internal error occurred. Please try again or contact support.",
"gateway": {
"traceId": "abc-123-xyz",
"timestamp": "2025-11-06T13:13:00Z"
}
}
```
**Usage:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismGatewayError } from '@1stdigital/prism-core';
app.use((err, req, res, next) => {
if (err instanceof PrismGatewayError) {
// Log with trace ID for backend correlation
logger.error('Gateway error', {
traceId: err.traceId,
statusCode: err.statusCode,
details: err.details
});
// Alert on 5xx errors
if (err.statusCode >= 500) {
alertOps('Prism Gateway error', { traceId: err.traceId });
}
}
next(err);
});
```
**When:** Cannot reach Prism Gateway (timeout, DNS error, connection refused)
**Status Code:** 503 Service Unavailable
**Properties:**
* `message` - Network error description
* `originalError` - Original axios/network error
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Payment service unavailable",
"details": "Could not connect to Prism Gateway. Please try again later.",
"retryAfter": 60
}
```
**Usage (Retry Logic):**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismNetworkError } from '@1stdigital/prism-core';
async function getPaymentRequirementsWithRetry(client, request, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await client.getPaymentRequirements(request);
} catch (error) {
if (error instanceof PrismNetworkError) {
console.log(`Network error, retrying (${i + 1}/${maxRetries})...`);
await sleep(1000 * Math.pow(2, i)); // Exponential backoff
continue;
}
throw error; // Non-network error, don't retry
}
}
throw new Error('Max retries exceeded');
}
```
**When:** SDK is misconfigured (invalid Project Identify Token format, bad URL, etc.)
**Status Code:** 500 Internal Server Error
**Properties:**
* `message` - Configuration error description
* `details` - Configuration problem details
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Payment service misconfigured",
"details": "Please contact the administrator."
}
```
**Usage:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismConfigError } from '@1stdigital/prism-core';
app.use((err, req, res, next) => {
if (err instanceof PrismConfigError) {
// Alert developers - this is a code/config issue
alertDevs('Prism SDK misconfiguration', {
error: err.message,
details: err.details
});
// Don't expose config details to clients
return res.status(500).json({
error: 'Service temporarily unavailable'
});
}
next(err);
});
```
**When:** Payment payload is malformed or invalid
**Status Code:** 402 Payment Required
**Properties:**
* `message` - Payment validation error
* `details` - Why payment is invalid
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Invalid payment authorization",
"details": "Signature verification failed"
}
```
**When:** Request data fails validation (negative price, missing fields, etc.)
**Status Code:** 400 Bad Request
**Properties:**
* `message` - Validation error message
* `field` - Field that failed validation
* `details` - Validation error details
**Example Response:**
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
"x402Version": 2,
"error": "Validation failed",
"details": "requestedAmount must be a positive number",
"field": "requestedAmount"
}
```
### Error Response Format
All error responses follow a consistent structure:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismErrorResponse {
x402Version: number; // Protocol version (currently 2)
error: string; // Human-readable error message
details?: string; // Additional error details
gateway?: {
// Gateway-specific info (if applicable)
traceId?: string; // Trace ID for backend correlation
timestamp?: string; // ISO 8601 timestamp
};
retryAfter?: number; // Seconds to wait before retry (503 errors)
}
```
### Advanced Error Handling
#### 1. Monitoring & Alerting with Trace IDs
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismGatewayError, PrismNetworkError } from "@1stdigital/prism-core";
app.use((err, req, res, next) => {
if (err instanceof PrismGatewayError) {
// Log to monitoring service with Gateway trace ID
logger.error("Prism Gateway Error", {
traceId: err.traceId,
timestamp: err.timestamp,
statusCode: err.statusCode,
message: err.message,
details: err.details,
endpoint: req.path,
method: req.method,
});
// Alert on critical errors (5xx)
if (err.statusCode >= 500) {
alerting.critical("Prism Gateway Internal Error", {
traceId: err.traceId,
endpoint: req.path,
message: err.message,
});
}
// Return error with trace ID for support
return res.status(err.statusCode).json({
x402Version: 2,
error: err.message,
details: err.details,
support: {
traceId: err.traceId,
message: "Please contact support with this trace ID",
},
});
}
if (err instanceof PrismNetworkError) {
// Alert ops - Gateway is down
alerting.critical("Prism Gateway Unreachable", {
error: err.message,
originalError: err.originalError?.code,
});
return res.status(503).json({
x402Version: 2,
error: "Payment service temporarily unavailable",
retryAfter: 60,
});
}
next(err);
});
```
#### 2. Retry Logic with Exponential Backoff
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import {
PrismClient,
PrismNetworkError,
PrismGatewayError,
} from "@1stdigital/prism-core";
async function makePaymentRequestWithRetry(
client: PrismClient,
request: any,
maxRetries = 3,
) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await client.getPaymentRequirements(request);
} catch (error) {
// Retry on network errors
if (error instanceof PrismNetworkError) {
const delay = 1000 * Math.pow(2, attempt); // 1s, 2s, 4s
console.log(
`Network error, retrying in ${delay}ms (${attempt + 1}/${maxRetries})`,
);
await sleep(delay);
continue;
}
// Retry on Gateway 5xx errors (server issues)
if (error instanceof PrismGatewayError && error.statusCode >= 500) {
if (attempt < maxRetries - 1) {
const delay = 1000 * Math.pow(2, attempt);
console.log(
`Gateway error ${error.statusCode}, retrying in ${delay}ms`,
);
await sleep(delay);
continue;
}
}
// Don't retry on 4xx errors (client errors)
if (error instanceof PrismGatewayError && error.statusCode < 500) {
throw error;
}
throw error;
}
}
throw new Error("Max retries exceeded");
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
```
#### 3. User-Friendly Error Messages
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismGatewayError } from "@1stdigital/prism-core";
app.use((err, req, res, next) => {
if (err instanceof PrismGatewayError) {
// Map Gateway errors to user-friendly messages
const userMessages: Record = {
400: "Invalid payment request. Please check your payment details.",
401: "Payment authentication failed. Please try again.",
403: "Payment not authorized. Please contact support.",
404: "Payment resource not found.",
500: "Payment service is experiencing issues. Please try again later.",
502: "Payment gateway temporarily unavailable.",
503: "Payment service under maintenance. Please try again soon.",
};
const userMessage =
userMessages[err.statusCode] || "Payment processing failed.";
return res.status(err.statusCode).json({
error: userMessage,
support: {
message:
"If the problem persists, contact support with this information:",
traceId: err.traceId,
timestamp: err.timestamp,
},
});
}
next(err);
});
```
#### 4. Error Metrics & Analytics
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismGatewayError, PrismNetworkError } from "@1stdigital/prism-core";
import { Counter, Histogram } from "prom-client";
const paymentErrorCounter = new Counter({
name: "prism_payment_errors_total",
help: "Total payment errors by type and status",
labelNames: ["error_type", "status_code"],
});
const gatewayLatency = new Histogram({
name: "prism_gateway_latency_seconds",
help: "Prism Gateway API latency",
});
app.use((err, req, res, next) => {
if (err instanceof PrismGatewayError) {
paymentErrorCounter.inc({
error_type: "gateway",
status_code: err.statusCode,
});
// Track error by category
if (err.statusCode >= 500) {
metrics.increment("prism.gateway.server_error");
} else if (err.statusCode >= 400) {
metrics.increment("prism.gateway.client_error");
}
}
if (err instanceof PrismNetworkError) {
paymentErrorCounter.inc({
error_type: "network",
status_code: 503,
});
metrics.increment("prism.gateway.unreachable");
}
next(err);
});
```
### Debugging with Trace IDs
When reporting issues to Prism support, always include the **trace ID** from error responses:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Extract trace ID from error response
app.get("/api/paid", async (req, res) => {
try {
// ... payment logic
} catch (error) {
if (error instanceof PrismGatewayError) {
console.error("Payment failed", {
traceId: error.traceId, // ← Include in bug reports
timestamp: error.timestamp,
statusCode: error.statusCode,
message: error.message,
});
// Return trace ID to client for support tickets
return res.status(error.statusCode).json({
error: "Payment processing failed",
supportInfo: {
traceId: error.traceId,
message: "Please contact support with this trace ID",
},
});
}
}
});
```
**Example support ticket:**
```
Subject: Payment Gateway Error - 500 Internal Server Error
Gateway Trace ID: abc-123-xyz
Timestamp: 2025-11-06T13:13:00Z
Endpoint: POST /api/v1/payment/requirements
Error: "Internal database error"
```
## Advanced Usage
### Environment-Based Configuration
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const config = {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN,
};
app.use(prismPaymentMiddleware(config, routes));
```
**.env.development:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PRISM_IDENTIFY_TOKEN=dev-key-123
NODE_ENV=development
```
**.env.production:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PRISM_IDENTIFY_TOKEN=prod-key-456
NODE_ENV=production
```
### Accessing Payment Details
After successful payment verification, payment details are available in `res.locals`:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get("/api/premium", (req, res) => {
// Payment payload (decoded from X-PAYMENT header)
const payment = res.locals.payment;
// Payer wallet address (from verification)
const payerAddress = res.locals.payer;
console.log("Payment received from:", payerAddress);
console.log("Payment scheme:", payment.scheme);
console.log("Network:", payment.network);
res.json({
data: "Premium content",
paidBy: payerAddress,
});
});
```
### Rate Limiting with Payments
Combine with rate limiting for hybrid monetization:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import rateLimit from "express-rate-limit";
// Free tier: 100 requests/hour
const freeLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 100,
message: "Free tier limit reached. Please upgrade or pay per request.",
});
app.use("/api/free", freeLimiter);
// Paid tier: No rate limit, but requires payment
app.use(
"/api/paid",
prismPaymentMiddleware(config, {
"/api/paid/*": { price: 0.001 },
}),
);
```
## TypeScript Support
### Full Type Definitions
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import {
prismPaymentMiddleware,
PrismMiddlewareConfig,
RoutePaymentConfig,
PaymentInfo,
PrismError,
} from "@1stdigital/prism-express";
// Type-safe configuration
const config: PrismMiddlewareConfig = {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
timeout: 15000,
};
const routes: Record = {
"/api/data": {
price: 0.001,
description: "Data access",
},
};
// Type-safe middleware
app.use(prismPaymentMiddleware(config, routes));
// Type-safe payment info
app.get("/api/data", (req, res) => {
const payment: PaymentInfo | undefined = res.locals.payment;
if (payment) {
console.log(`Paid ${payment.amount} on ${payment.network}`);
}
res.json({ data: "Content" });
});
```
### Express Types Extension
Add types to `res.locals`:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// types/express.d.ts
import { PaymentInfo } from "@1stdigital/prism-express";
declare global {
namespace Express {
interface Locals {
payment?: PaymentInfo;
prismPrice?: number;
}
}
}
```
## Testing
### Unit Tests
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import request from "supertest";
import express from "express";
import { prismPaymentMiddleware } from "@1stdigital/prism-express";
describe("Prism Payment Middleware", () => {
let app: express.Application;
beforeEach(() => {
app = express();
app.use(
prismPaymentMiddleware(
{ identifyToken: "test-key" },
{ "/api/paid": { price: 0.01 } },
),
);
app.get("/api/paid", (req, res) => {
res.json({ data: "content" });
});
});
it("should return 402 for unpaid request", async () => {
const res = await request(app).get("/api/paid");
expect(res.status).toBe(402);
expect(res.headers["x-payment"]).toBeDefined();
});
it("should allow request with valid payment", async () => {
const paymentHeader = generateValidPayment();
const res = await request(app)
.get("/api/paid")
.set("X-PAYMENT-AUTHORIZATION", paymentHeader);
expect(res.status).toBe(200);
expect(res.body.data).toBe("content");
});
});
```
### Integration Tests with Sandbox
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { ethers } from "ethers";
describe("Payment Flow Integration", () => {
it("should complete full payment cycle", async () => {
// 1. Request protected resource
const res1 = await request(app).get("/api/paid");
expect(res1.status).toBe(402);
// 2. Parse payment requirements
const payment = JSON.parse(res1.headers["x-payment"]);
// 3. Sign authorization (with test wallet)
const wallet = new ethers.Wallet(process.env.TEST_PRIVATE_KEY!);
const signature = await wallet.signTypedData(
payment.typedData.domain,
{
TransferWithAuthorization:
payment.typedData.types.TransferWithAuthorization,
},
payment.typedData.message,
);
// 4. Retry with signature
const res2 = await request(app)
.get("/api/paid")
.set(
"X-PAYMENT-AUTHORIZATION",
JSON.stringify({
signature,
...payment.typedData.message,
}),
);
expect(res2.status).toBe(200);
expect(res2.body.data).toBe("content");
});
});
```
## Performance Optimization
### Caching Payment Requirements
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import NodeCache from "node-cache";
const cache = new NodeCache({ stdTTL: 300 }); // 5 minutes
app.use((req, res, next) => {
const cacheKey = `payment:${req.path}`;
const cached = cache.get(cacheKey);
if (cached) {
res.set("X-PAYMENT", JSON.stringify(cached));
return res.status(402).json({ error: "Payment required" });
}
next();
});
app.use(prismPaymentMiddleware(config, routes));
```
### Connection Pooling
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const config = {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN,
timeout: 5000,
retries: 2,
// Use HTTP keep-alive
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
};
```
## Migration Guide
### From v0.x to v1.x
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-express@latest
```
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Old
import { prismMiddleware } from '@prism/middleware';
// New
import { prismPaymentMiddleware } from '@1stdigital/prism-express';
```
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Old
prismMiddleware({ key: 'xxx', sandbox: true }, routes)
// New
prismPaymentMiddleware({ identifyToken: 'xxx' }, routes)
```
## Troubleshooting
**Symptoms:** Routes always return 200, no payment required
**Solutions:**
* Verify middleware is registered **before** route handlers
* Check route paths match exactly (case-sensitive)
* Ensure `identifyToken` is valid
* Check Gateway connectivity (`curl https://prism-gw.fd.xyz/health`)
**Symptoms:** `503 Service Unavailable` or `PrismNetworkError`
**Solutions:**
* Check network connectivity to Gateway
* Verify no firewall blocking outbound HTTPS to `prism-gw.fd.xyz`
* Check Gateway status page
* Implement retry logic (see Error Handling section)
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismNetworkError } from '@1stdigital/prism-core';
if (error instanceof PrismNetworkError) {
console.error('Gateway unreachable:', error.message);
// Retry or alert ops team
}
```
**Symptoms:** `401 Unauthorized` or `PrismGatewayError` with status 401
**Solutions:**
* Verify Project Identify Token in [Client Portal](https://apps.fd.xyz/prism/)
* Check environment variable: `echo $PRISM_IDENTIFY_TOKEN`
* Ensure key hasn't been revoked
* Use correct environment (sandbox vs production)
**Check error details:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
if (error instanceof PrismGatewayError && error.statusCode === 401) {
console.error('Auth error:', {
traceId: error.traceId,
details: error.details
});
}
```
**Symptoms:** `PrismGatewayError` with status 500 and trace ID
**Solutions:**
* **This is a Gateway backend issue** - not your code
* Extract and log the `traceId` from error
* Report to Prism support with trace ID
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
if (error instanceof PrismGatewayError && error.statusCode >= 500) {
console.error('Gateway internal error:', {
traceId: error.traceId, // ← Include in support ticket
timestamp: error.timestamp,
details: error.details
});
// Alert ops to contact Prism support
alertOps(`Gateway error - Trace ID: ${error.traceId}`);
}
```
**Symptoms:** Type errors during build
**Solutions:**
* Install type definitions: `npm install -D @types/express`
* Update `tsconfig.json`: `"moduleResolution": "node"`
* Ensure TypeScript version >= 4.5
## API Reference
### `prismPaymentMiddleware(config, routes)`
Creates Express middleware for x402 payment protection.
**Parameters:**
* `config` (PrismMiddlewareConfig) - Global configuration
* `routes` (Record\) - Route payment settings
**Returns:** Express middleware function
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const middleware = prismPaymentMiddleware(
{ identifyToken: "key" },
{ "/api/paid": { price: 0.01 } },
);
app.use(middleware);
```
### Error Classes
#### `PrismError` (Base Class)
Base error class for all Prism SDK errors.
**Properties:**
* `message` (string) - Error message
* `code` (string) - Error code (e.g., 'GATEWAY\_ERROR', 'NETWORK\_ERROR')
* `statusCode` (number) - HTTP status code
* `details` (any) - Additional error context
**Methods:**
* `toJSON()` - Convert error to JSON representation
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismError } from "@1stdigital/prism-core";
if (error instanceof PrismError) {
console.log(error.code); // 'GATEWAY_ERROR'
console.log(error.statusCode); // 500
console.log(error.toJSON()); // { name, message, code, statusCode, details }
}
```
#### `PrismGatewayError extends PrismError`
Gateway returned an error response (4xx or 5xx).
**Additional Properties:**
* `traceId` (string | undefined) - Gateway trace ID for debugging
* `timestamp` (string | undefined) - ISO 8601 timestamp from Gateway
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismGatewayError } from "@1stdigital/prism-core";
app.use((err, req, res, next) => {
if (err instanceof PrismGatewayError) {
logger.error("Gateway error", {
traceId: err.traceId,
statusCode: err.statusCode,
message: err.message,
details: err.details,
});
}
});
```
#### `PrismNetworkError extends PrismError`
Network connectivity issues (timeout, DNS error, connection refused).
**Additional Properties:**
* `originalError` (any) - Original network error from axios
**Status Code:** Always 503
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismNetworkError } from "@1stdigital/prism-core";
if (error instanceof PrismNetworkError) {
console.log("Gateway unreachable:", error.message);
console.log("Original error:", error.originalError);
// Implement retry logic or alert ops
}
```
#### `PrismConfigError extends PrismError`
SDK misconfiguration (invalid Project Identify Token format, bad URL, etc.).
**Status Code:** Always 500
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismConfigError } from "@1stdigital/prism-core";
if (error instanceof PrismConfigError) {
// Developer/ops issue - fix configuration
alertDevs("Prism SDK misconfigured: " + error.message);
}
```
#### `PrismPaymentError extends PrismError`
Invalid payment payload or authorization.
**Status Code:** Always 402
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismPaymentError } from "@1stdigital/prism-core";
if (error instanceof PrismPaymentError) {
// Client sent invalid payment
return res.status(402).json({
error: error.message,
details: error.details,
});
}
```
#### `PrismValidationError extends PrismError`
Request validation failed.
**Additional Properties:**
* `field` (string | undefined) - Field that failed validation
**Status Code:** Always 400
**Example:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { PrismValidationError } from "@1stdigital/prism-core";
if (error instanceof PrismValidationError) {
return res.status(400).json({
error: "Validation failed",
field: error.field,
message: error.message,
});
}
```
### Error Codes
| Code | Error Class | Description |
| - | - | - |
| `GATEWAY_ERROR` | PrismGatewayError | Gateway returned error (4xx/5xx) |
| `NETWORK_ERROR` | PrismNetworkError | Cannot reach Gateway |
| `CONFIG_ERROR` | PrismConfigError | Invalid SDK configuration |
| `PAYMENT_ERROR` | PrismPaymentError | Invalid payment |
| `VALIDATION_ERROR` | PrismValidationError | Request validation failed |
| `UNKNOWN_ERROR` | PrismError | Unclassified error |
## Resources
View source code and examples
Package on GitHub Packages
Prism Gateway REST API docs
Complete code examples
# Express.js Integration
Source: https://developers.fd.xyz/prism/sdk/typescript/express
Protect Express APIs with blockchain micropayments
## Overview
The **@1stdigital/prism-express** package provides Express.js middleware for payment-protecting your API routes using the x402 protocol. It's the reference implementation for the Prism SDK and offers the most straightforward integration.
Single middleware function, 5 lines of code
Exact paths, wildcards, and patterns
Access payer address in req.payer
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-express
```
`bash yarn add @1stdigital/prism-express `
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pnpm add @1stdigital/prism-express
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const express = require("express");
const { prismPaymentMiddleware } = require("@1stdigital/prism-express");
const app = express();
// Configure Prism middleware
app.use(
prismPaymentMiddleware(
{
identifyToken: process.env.PRISM_IDENTIFY_TOKEN || "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
},
{
"/api/premium": {
price: 0.01, // 0.01 USD
description: "Premium API access",
},
},
),
);
// Protected route - payment verified automatically
app.get("/api/premium", (req, res) => {
res.json({
message: "Premium content!",
payer: req.payer, // Wallet address that paid
});
});
app.listen(3000);
```
***
## Configuration
### Middleware Configuration
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismMiddlewareConfig {
identifyToken: string; // Your Prism Project Identify Token
baseUrl?: string; // Gateway URL (optional, defaults to production)
debug?: boolean; // Enable debug logging (default: false)
}
```
### Route Configuration
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface RoutePaymentConfig {
price: number | string; // Price in USD (0.01 = $0.01 or '$0.001' string format)
description: string; // Human-readable description
mimeType?: string; // Response MIME type (default: 'application/json')
}
type RouteConfig = Record;
```
***
## Route Protection Patterns
### Exact Path Matching
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(
prismPaymentMiddleware(config, {
"/api/premium": {
price: 0.01,
description: "Premium API",
},
"/api/weather": {
price: "$0.001",
description: "Weather data",
},
}),
);
// ✅ Protected: GET /api/premium
// ✅ Protected: GET /api/weather
// ❌ Not protected: GET /api/public
```
***
### Wildcard Matching
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(
prismPaymentMiddleware(config, {
"/api/*": {
price: 0.005,
description: "API access",
},
}),
);
// ✅ Protected: GET /api/users
// ✅ Protected: GET /api/posts/123
// ✅ Protected: POST /api/comments
// ❌ Not protected: GET /public
```
***
### Multiple Route Groups
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(
prismPaymentMiddleware(config, {
// Free tier (low price)
"/api/basic/*": {
price: "$0.0001",
description: "Basic API",
},
// Premium tier (higher price)
"/api/premium/*": {
price: "$0.01",
description: "Premium API",
},
// Specific expensive endpoint
"/api/ai/generate": {
price: "$0.50",
description: "AI content generation",
},
}),
);
```
***
### Dynamic Pricing (per-route middleware)
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Global middleware for common routes
app.use(
prismPaymentMiddleware(config, {
"/api/*": { price: 0.001, description: "API" },
}),
);
// Override for specific route with custom middleware
app.get(
"/api/expensive",
prismPaymentMiddleware(config, {
"/api/expensive": {
price: 0.1,
description: "Expensive operation",
},
}),
(req, res) => {
res.json({ result: "Expensive computation" });
},
);
```
***
## Accessing Payment Information
The middleware adds payment information to the request object:
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get("/api/premium", (req, res) => {
// Access payer wallet address
const payer = req.payer; // '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
// Access full payment object (added to res.locals)
const payment = res.locals.payment;
/*
{
scheme: 'eip3009',
network: 'eth-sepolia',
asset: 'usdc',
amount: '10000',
recipient: '0x...',
nonce: '0x...',
validBefore: 1735430400,
signature: '0x...'
}
*/
res.json({
message: "Premium content",
payer,
payment: {
network: payment.network,
asset: payment.asset,
},
});
});
```
***
## Settlement Validation
The Express middleware uses **res.end() interception** to validate settlement before sending data:
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (you don't need to write this!)
const originalEnd = res.end.bind(res);
res.end = async function (chunk, encoding, callback) {
// Perform settlement BEFORE sending response
const settlementResult = await core.settlementCallback(...);
if (!settlementResult || !settlementResult.success) {
// ❌ Settlement failed - send error instead of data
res.status(402);
return originalEnd(JSON.stringify({
error: 'Payment settlement failed',
details: settlementResult?.errorReason
}));
}
// ✅ Settlement succeeded - send original data with transaction hash
res.setHeader('X-PAYMENT-RESPONSE', settlementResult.transaction);
return originalEnd(chunk, encoding, callback);
};
```
**Key Points:**
* Works with `res.json()`, `res.send()`, `res.sendFile()`, etc.
* Settlement happens **before** data reaches the client
* Original response is replaced with 402 error if settlement fails
See [Stablecoin Settlement](/prism/concepts/settlement) for details.
***
## Error Handling
### Payment Errors
When a request lacks valid payment, the middleware returns **402 Payment Required**:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 402 Payment Required
{
"x402Version": 2,
"paymentRequired": true,
"acceptedPayments": [
{
"scheme": "eip3009",
"network": "eth-sepolia",
"asset": "usdc",
"amount": "10000",
"recipient": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"nonce": "0xabc123...",
"validBefore": 1735430400
}
],
"description": "Premium API access",
"priceUSD": "0.01"
}
```
***
### Gateway Errors
If the Prism Gateway is unreachable or returns an error:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 500 Internal Server Error
{
"x402Version": 2,
"error": "Gateway Error",
"details": "Failed to contact payment gateway",
"gateway": {
"traceId": "abc-123-xyz",
"timestamp": "2025-12-18T10:30:00Z"
}
}
```
**Include the `traceId` when contacting support!**
***
### Settlement Errors
If payment verification succeeds but settlement fails:
```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
HTTP/1.1 402 Payment Required
{
"x402Version": 2,
"error": "Payment settlement failed",
"details": "Insufficient balance"
}
```
***
### Custom Error Handling
You can add Express error handlers after the Prism middleware:
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(prismPaymentMiddleware(config, routes));
// Custom error handler
app.use((err, req, res, next) => {
if (err.name === "PrismPaymentError") {
// Handle Prism-specific errors
console.error("Payment error:", err.message);
res.status(err.statusCode || 402).json({
error: err.message,
code: err.code,
});
} else {
// Handle other errors
next(err);
}
});
```
***
## Testing
### Unit Testing with Mocks
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const request = require("supertest");
const express = require("express");
const { prismPaymentMiddleware } = require("@1stdigital/prism-express");
describe("Payment-protected routes", () => {
let app;
beforeEach(() => {
app = express();
app.use(
prismPaymentMiddleware(
{ identifyToken: "test-key", baseUrl: "http://test-gateway" },
{ "/api/premium": { price: 0.01, description: "Test" } },
),
);
app.get("/api/premium", (req, res) => {
res.json({ message: "Premium", payer: req.payer });
});
});
test("returns 402 without payment", async () => {
const response = await request(app).get("/api/premium");
expect(response.status).toBe(402);
expect(response.body.paymentRequired).toBe(true);
});
test("allows access with valid payment", async () => {
// Mock payment header (in real tests, sign with wallet)
const mockPayment = JSON.stringify({
scheme: "eip3009",
network: "eth-sepolia",
asset: "usdc",
amount: "10000",
signature: "0x" + "0".repeat(130),
});
const response = await request(app)
.get("/api/premium")
.set("X-PAYMENT", mockPayment);
// In test mode, mock signatures are accepted
expect(response.status).toBe(200);
expect(response.body.message).toBe("Premium");
});
});
```
***
### Integration Testing
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// test-server.js
const app = require("./app"); // Your Express app
const request = require("supertest");
// Use production gateway with your Project Identify Token
process.env.PRISM_BASE_URL = "https://prism-gw.fd.xyz";
process.env.PRISM_IDENTIFY_TOKEN = "your-api-key";
test("full payment flow", async () => {
// 1. Request without payment
const res1 = await request(app).get("/api/premium");
expect(res1.status).toBe(402);
const paymentReq = res1.body.acceptedPayments[0];
// 2. Sign payment with wallet (use ethers.js)
const wallet = new ethers.Wallet(process.env.TEST_PRIVATE_KEY);
const signature =
await wallet.signTypedData(/* EIP-712 domain and message */);
const payment = {
...paymentReq,
signature,
};
// 3. Send request with signed payment
const res2 = await request(app)
.get("/api/premium")
.set("X-PAYMENT", JSON.stringify(payment));
expect(res2.status).toBe(200);
expect(res2.headers["x-payment-response"]).toBeTruthy(); // Transaction hash
});
```
***
## Production Deployment
### Environment Variables
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
# .env
PRISM_IDENTIFY_TOKEN=your-production-identify-token
PRISM_BASE_URL=https://prism-gw.fd.xyz
NODE_ENV=production
```
### Production Configuration
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const app = express();
app.use(
prismPaymentMiddleware(
{
identifyToken: process.env.PRISM_IDENTIFY_TOKEN,
baseUrl: process.env.PRISM_BASE_URL,
debug: process.env.NODE_ENV !== "production", // Disable debug in prod
},
{
"/api/premium": {
price: 0.01,
description: "Premium API",
},
},
),
);
```
***
### Monitoring & Logging
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const winston = require("winston");
const logger = winston.createLogger({
/* config */
});
// Log payment events
app.use((req, res, next) => {
const originalJson = res.json.bind(res);
res.json = function (data) {
if (res.statusCode === 402) {
logger.info("Payment required", {
path: req.path,
ip: req.ip,
});
} else if (res.statusCode === 200 && req.payer) {
logger.info("Payment succeeded", {
path: req.path,
payer: req.payer,
transaction: res.getHeader("x-payment-response"),
});
}
return originalJson(data);
};
next();
});
```
***
### Rate Limiting
Combine with rate limiting to prevent abuse:
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Max 100 requests per window
message: "Too many requests, please try again later",
});
// Apply rate limiting BEFORE payment middleware
app.use(limiter);
app.use(prismPaymentMiddleware(config, routes));
```
***
## TypeScript Support
Full TypeScript support with type definitions:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import express, { Request, Response } from "express";
import {
prismPaymentMiddleware,
PrismMiddlewareConfig,
RoutePaymentConfig,
} from "@1stdigital/prism-express";
const app = express();
const config: PrismMiddlewareConfig = {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
baseUrl: "https://prism-gw.fd.xyz",
debug: false,
};
const routes: Record = {
"/api/premium": {
price: 0.01,
description: "Premium API access",
},
};
app.use(prismPaymentMiddleware(config, routes));
// Request is augmented with payer property
app.get("/api/premium", (req: Request, res: Response) => {
const payer: string | undefined = req.payer; // Type-safe!
res.json({
message: "Premium content",
payer,
});
});
```
***
## API Reference
### `prismPaymentMiddleware(config, routes)`
Creates Express middleware for payment protection.
**Parameters:**
* `config: PrismMiddlewareConfig` - SDK configuration
* `routes: Record` - Protected routes
**Returns:** `express.RequestHandler`
***
### `PrismMiddlewareConfig`
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismMiddlewareConfig {
identifyToken: string; // Required: Your Prism Project Identify Token
baseUrl?: string; // Optional: Gateway URL (default: production)
debug?: boolean; // Optional: Enable debug logging (default: false)
}
```
***
### `RoutePaymentConfig`
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface RoutePaymentConfig {
price: number | string; // Required: Price in USD
description: string; // Required: Human-readable description
mimeType?: string; // Optional: Response MIME type
}
```
***
### Request Augmentation
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
declare global {
namespace Express {
interface Request {
payer?: string; // Wallet address of payer (added by middleware)
}
}
}
```
***
## Examples
### AI Agent API
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(
prismPaymentMiddleware(config, {
"/api/ai/chat": {
price: "$0.01",
description: "AI chat response",
},
"/api/ai/image": {
price: "$0.50",
description: "AI image generation",
},
}),
);
app.post("/api/ai/chat", express.json(), (req, res) => {
const { message } = req.body;
const payer = req.payer;
// Call AI service
const response = callAI(message);
res.json({
response,
payer,
creditsUsed: 1,
});
});
```
***
### Content Paywall
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.use(
prismPaymentMiddleware(config, {
"/articles/:id": {
price: "$0.001",
description: "Article access",
},
}),
);
app.get("/articles/:id", async (req, res) => {
const article = await db.articles.findById(req.params.id);
res.json({
title: article.title,
content: article.content,
author: article.author,
payer: req.payer,
});
});
```
***
## Troubleshooting
**Check:**
1. Payment signature is valid (use correct private key)
2. Payment hasn't expired (`validBefore` timestamp)
3. Nonce hasn't been used before (replay protection)
4. Network matches (`eth-sepolia` vs `eth-mainnet`)
5. Amount matches exactly (don't modify `amount` field)
**Possible causes:** 1. Insufficient balance in sender's wallet 2. Token
allowance not set for USDC contract 3. Network congestion (transaction
timeout) 4. Gateway blockchain RPC node down **Solution:** Client should retry
after fixing the issue.
**Check order:** `javascript // ❌ Wrong order app.get('/api/premium',
handler); // Handler registered first app.use(prismPaymentMiddleware(config,
routes)); // Middleware too late // ✅ Correct order
app.use(prismPaymentMiddleware(config, routes)); // Middleware first
app.get('/api/premium', handler); // Handler after `
**Install type definitions:**
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install --save-dev @types/express
```
**Import types:**
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Request, Response } from 'express';
```
# Fastify Integration
Source: https://developers.fd.xyz/prism/sdk/typescript/fastify
Protect Fastify APIs with blockchain micropayments
## Overview
The **@1stdigital/prism-fastify** package provides a Fastify plugin for payment-protecting your API routes using the x402 protocol. It leverages Fastify's hook system for high-performance payment validation.
Fastify's async hooks for minimal overhead
Standard Fastify plugin pattern
Full TypeScript support with decorators
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-fastify fastify
```
`bash yarn add @1stdigital/prism-fastify fastify `
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pnpm add @1stdigital/prism-fastify fastify
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import Fastify from "fastify";
import prismPlugin from "@1stdigital/prism-fastify";
const app = Fastify({ logger: true });
// Register Prism plugin
await app.register(prismPlugin, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN || "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
routes: {
"/api/premium": {
price: 0.01, // $0.01 USD
description: "Premium API access",
},
},
});
// Protected route - payment verified automatically
app.get("/api/premium", async (request, reply) => {
return {
message: "Premium content!",
payer: request.prismPayer, // Wallet address
};
});
await app.listen({ port: 3000 });
```
***
## Configuration
### Plugin Options
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismFastifyOptions {
identifyToken: string; // Your Prism Project Identify Token
baseUrl?: string; // Gateway URL (optional)
debug?: boolean; // Enable debug logging
routes: Record;
}
interface RoutePaymentConfig {
price: number | string; // Price in USD
description: string; // Human-readable description
mimeType?: string; // Response MIME type
}
```
***
## Route Protection
### Plugin Registration
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
await app.register(prismPlugin, {
identifyToken: "your-project-identify-token",
routes: {
"/api/premium": {
price: 0.01,
description: "Premium API",
},
"/api/weather": {
price: "$0.001",
description: "Weather data",
},
"/api/data/*": {
price: 0.005,
description: "Data API (wildcard)",
},
},
});
```
***
## Accessing Payment Info
Payment info is added to the request object:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
app.get("/api/premium", async (request, reply) => {
// Access payer wallet address
const payer = request.prismPayer;
// '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
// Access full payment object
const payment = request.prismPayment;
/*
{
scheme: 'eip3009',
network: 'eth-sepolia',
asset: 'usdc',
amount: '10000',
signature: '0x...'
}
*/
return {
message: "Premium content",
payer,
network: payment?.network,
};
});
```
***
## Settlement Validation
Fastify uses the **onSend hook** to validate settlement before sending data:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (automatic!)
fastify.addHook('onSend', async (request, reply, payload) => {
const settlementResult = await core.settlementCallback(...);
if (!settlementResult || !settlementResult.success) {
// ❌ Settlement failed - replace payload
reply.code(402);
reply.header('Content-Type', 'application/json');
return JSON.stringify({
error: 'Payment settlement failed',
details: settlementResult?.errorReason
});
}
// ✅ Settlement succeeded - add header and return payload
reply.header('X-PAYMENT-RESPONSE', settlementResult.transaction);
return payload;
});
```
See [Stablecoin Settlement](/prism/concepts/settlement) for details.
***
## TypeScript Support
Extend Fastify types for payment properties:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import "fastify";
declare module "fastify" {
interface FastifyRequest {
prismPayer?: string;
prismPayment?: {
scheme: string;
network: string;
asset: string;
amount: string;
signature: string;
};
}
}
// Now TypeScript knows about payment properties
app.get("/api/data", async (request, reply) => {
const payer: string | undefined = request.prismPayer; // Type-safe!
return { data: [1, 2, 3], payer };
});
```
***
## Testing
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { test } from "tap";
import Fastify from "fastify";
import prismPlugin from "@1stdigital/prism-fastify";
test("payment required without header", async (t) => {
const app = Fastify();
await app.register(prismPlugin, {
identifyToken: "test-key",
routes: {
"/api/premium": { price: 0.01, description: "Test" },
},
});
app.get("/api/premium", async () => ({ message: "Premium" }));
const response = await app.inject({
method: "GET",
url: "/api/premium",
});
t.equal(response.statusCode, 402);
t.ok(response.json().paymentRequired);
});
test("access granted with valid payment", async (t) => {
const app = Fastify();
await app.register(prismPlugin, {
identifyToken: "test-key",
routes: {
"/api/premium": { price: 0.01, description: "Test" },
},
});
app.get("/api/premium", async (request) => ({
message: "Premium",
payer: request.prismPayer,
}));
const payment = JSON.stringify({
scheme: "eip3009",
signature: "0x" + "0".repeat(130),
});
const response = await app.inject({
method: "GET",
url: "/api/premium",
headers: { "X-PAYMENT": payment },
});
t.equal(response.statusCode, 200);
t.equal(response.json().message, "Premium");
});
```
***
## Production Deployment
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import Fastify from "fastify";
import prismPlugin from "@1stdigital/prism-fastify";
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || "info",
},
});
await app.register(prismPlugin, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
baseUrl: process.env.PRISM_BASE_URL,
debug: process.env.NODE_ENV !== "production",
routes: {
"/api/premium": {
price: 0.01,
description: "Premium API",
},
},
});
// Start server
await app.listen({
port: parseInt(process.env.PORT || "3000"),
host: "0.0.0.0",
});
```
# HTTP (Node.js) Integration
Source: https://developers.fd.xyz/prism/sdk/typescript/http
Protect raw Node.js HTTP APIs with blockchain micropayments
**Coming soon.** The `@1stdigital/prism-http` package is being updated for the latest x402 protocol. For Node.js applications today, please use the [Express SDK](/prism/sdk/typescript/express).
## Overview
The **@1stdigital/prism-http** package provides middleware for vanilla Node.js HTTP servers, without requiring any framework. Perfect for lightweight APIs or custom HTTP implementations.
Works with raw http/https modules
No Express, Fastify, or other framework needed
Minimal overhead, maximum performance
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-http
```
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
yarn add @1stdigital/prism-http
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const http = require("http");
const { prismPaymentMiddleware } = require("@1stdigital/prism-http");
// Create middleware
const middleware = prismPaymentMiddleware(
{
identifyToken: "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
},
{
"/api/premium": {
price: 0.01, // $0.01 USD
description: "Premium API",
},
},
);
// Create HTTP server
const server = http.createServer((req, res) => {
// Apply middleware
middleware(req, res, () => {
// This runs only if payment verified
if (req.url === "/api/premium") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
message: "Premium content",
payer: req.payer, // Wallet address
}),
);
} else {
res.writeHead(404);
res.end("Not Found");
}
});
});
server.listen(3000);
```
***
## Configuration
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismMiddlewareConfig {
identifyToken: string;
baseUrl?: string;
debug?: boolean;
}
interface RoutePaymentConfig {
price: number | string; // USD price
description: string;
mimeType?: string;
}
```
***
## Routing
### URL-based Routing
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const server = http.createServer((req, res) => {
middleware(req, res, () => {
const url = new URL(req.url, `http://${req.headers.host}`);
if (url.pathname === "/api/premium") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
message: "Premium",
payer: req.payer,
}),
);
} else if (url.pathname === "/api/weather") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
location: "SF",
temperature: 72,
payer: req.payer,
}),
);
} else {
res.writeHead(404);
res.end("Not Found");
}
});
});
```
***
## Accessing Payment Info
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const server = http.createServer((req, res) => {
middleware(req, res, () => {
// Access payer address
const payer = req.payer;
// '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
// Access payment object (in res.locals)
const payment = res.locals?.payment;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
message: "Data",
payer,
network: payment?.network,
}),
);
});
});
```
***
## Settlement Validation
HTTP middleware intercepts `res.end()` to validate settlement:
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (automatic!)
const originalEnd = res.end.bind(res);
res.end = async function(chunk, encoding, callback) {
const settlementResult = await core.settlementCallback(...);
if (!settlementResult || !settlementResult.success) {
// ❌ Settlement failed
res.statusCode = 402;
res.setHeader('Content-Type', 'application/json');
return originalEnd(JSON.stringify({
error: 'Payment settlement failed'
}));
}
// ✅ Settlement succeeded
res.setHeader('X-PAYMENT-RESPONSE', settlementResult.transaction);
return originalEnd(chunk, encoding, callback);
};
```
***
## Testing
```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
const http = require("http");
const { prismPaymentMiddleware } = require("@1stdigital/prism-http");
describe("HTTP Payment Middleware", () => {
let server;
beforeAll(() => {
const middleware = prismPaymentMiddleware(
{ identifyToken: "test-key" },
{ "/api/premium": { price: 0.01, description: "Test" } },
);
server = http.createServer((req, res) => {
middleware(req, res, () => {
res.writeHead(200);
res.end(JSON.stringify({ message: "OK", payer: req.payer }));
});
});
server.listen(0); // Random port
});
afterAll(() => server.close());
test("returns 402 without payment", async () => {
const port = server.address().port;
const response = await fetch(`http://localhost:${port}/api/premium`);
expect(response.status).toBe(402);
});
});
```
# NestJS Integration
Source: https://developers.fd.xyz/prism/sdk/typescript/nestjs
Protect NestJS APIs with blockchain micropayments using decorators
## Overview
The **@1stdigital/prism-nestjs** package provides a full-featured NestJS module with decorators, guards, and interceptors for payment-protecting your API routes.
@Payment() and @Payer() decorators
PrismModule.forRoot() configuration
Works with NestJS DI system
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-nestjs @nestjs/core @nestjs/common
```
`bash yarn add @1stdigital/prism-nestjs @nestjs/core @nestjs/common `
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pnpm add @1stdigital/prism-nestjs @nestjs/core @nestjs/common
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// app.module.ts
import { Module } from "@nestjs/common";
import { PrismModule } from "@1stdigital/prism-nestjs";
import { AppController } from "./app.controller";
@Module({
imports: [
PrismModule.forRoot({
identifyToken: process.env.PRISM_IDENTIFY_TOKEN || "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
routes: {
"/api/premium": {
price: 0.01, // $0.01 USD
description: "Premium API",
},
},
}),
],
controllers: [AppController],
})
export class AppModule {}
// app.controller.ts
import { Controller, Get } from "@nestjs/common";
import { Payment, Payer } from "@1stdigital/prism-nestjs";
@Controller("api")
export class AppController {
@Get("premium")
@Payment() // Requires payment!
getPremiumData(@Payer() payer: string) {
return {
message: "Premium content",
payer,
};
}
}
```
***
## Configuration
### Module Options
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
PrismModule.forRoot({
identifyToken: "your-project-identify-token",
baseUrl: "https://prism-gw.fd.xyz",
debug: true,
routes: {
"/api/premium": {
price: 0.01,
description: "Premium API",
},
"/api/data/*": {
price: 0.005,
description: "Data API (wildcard)",
},
},
});
```
***
## Decorators
### @Payment() Decorator
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Controller, Get } from "@nestjs/common";
import { Payment } from "@1stdigital/prism-nestjs";
@Controller("api")
export class DataController {
// Payment required
@Get("premium")
@Payment()
getPremium() {
return { data: "Premium content" };
}
// No payment required
@Get("free")
getFree() {
return { data: "Free content" };
}
}
```
### @Payer() Decorator
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Controller, Get } from "@nestjs/common";
import { Payment, Payer } from "@1stdigital/prism-nestjs";
@Controller("api")
export class DataController {
@Get("premium")
@Payment()
getPremium(@Payer() payer: string) {
// payer = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
return {
message: "Premium data",
payer,
};
}
}
```
***
## Accessing Payment Info
### Request Context
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Controller, Get, Req } from "@nestjs/common";
import { Payment } from "@1stdigital/prism-nestjs";
import { Request } from "express";
@Controller("api")
export class DataController {
@Get("premium")
@Payment()
getPremium(@Req() request: Request) {
// Access via request object
const payer = request.payer;
const payment = request.locals?.payment;
return {
message: "Premium data",
payer,
network: payment?.network,
};
}
}
```
***
## Settlement Validation
NestJS uses an **Interceptor** to validate settlement:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (automatic!)
@Injectable()
export class PrismSettlementInterceptor implements NestInterceptor {
async intercept(context: ExecutionContext, next: CallHandler) {
return next.handle().pipe(
mergeMap(async (data) => {
const response = context.switchToHttp().getResponse();
const settlementResult = await this.settlementCallback(...);
if (!settlementResult || !settlementResult.success) {
// ❌ Settlement failed
response.status(402);
return {
error: 'Payment settlement failed',
details: settlementResult?.errorReason
};
}
// ✅ Settlement succeeded
response.header('X-PAYMENT-RESPONSE', settlementResult.transaction);
return data;
})
);
}
}
```
***
## Testing
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { Test, TestingModule } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import * as request from "supertest";
import { AppModule } from "./app.module";
describe("PrismModule (e2e)", () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it("returns 402 without payment", () => {
return request(app.getHttpServer())
.get("/api/premium")
.expect(402)
.expect((res) => {
expect(res.body.paymentRequired).toBe(true);
});
});
it("returns 200 with valid payment", () => {
const payment = JSON.stringify({
scheme: "eip3009",
signature: "0x" + "0".repeat(130),
});
return request(app.getHttpServer())
.get("/api/premium")
.set("X-PAYMENT", payment)
.expect(200)
.expect((res) => {
expect(res.body.message).toBe("Premium content");
});
});
});
```
***
## Production Deployment
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// main.ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ["error", "warn", "log"],
});
// Enable CORS if needed
app.enableCors({
origin: process.env.ALLOWED_ORIGINS?.split(","),
credentials: true,
});
const port = parseInt(process.env.PORT || "3000");
await app.listen(port);
console.log(`NestJS + Prism running on port ${port}`);
}
bootstrap();
```
# Next.js Integration
Source: https://developers.fd.xyz/prism/sdk/typescript/nextjs
Protect Next.js API routes with blockchain micropayments
## Overview
The **@1stdigital/prism-nextjs** package provides middleware for Next.js API routes and App Router route handlers. Supports both Pages Router and App Router architectures.
Support for Next.js 13+ App Router
Works with traditional API routes
Compatible with Edge Runtime
***
## Installation
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
npm install @1stdigital/prism-nextjs next
```
`bash yarn add @1stdigital/prism-nextjs next `
```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
pnpm add @1stdigital/prism-nextjs next
```
***
The canonical SDK config is `identifyToken` (`PRISM_IDENTIFY_TOKEN` env var) — formerly `apiKey` / `PRISM_API_KEY`. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.
## Quick Start (App Router)
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// app/api/premium/route.ts
import { NextRequest, NextResponse } from "next/server";
import { withPrismPayment } from "@1stdigital/prism-nextjs";
async function handler(request: NextRequest) {
// Access payer from request
const payer = (request as any).payer;
return NextResponse.json({
message: "Premium content",
payer,
});
}
// Wrap handler with payment middleware
export const GET = withPrismPayment(handler, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN || "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
price: 0.01, // $0.01 USD
description: "Premium API",
});
```
***
## Quick Start (Pages Router)
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// pages/api/premium.ts
import { NextApiRequest, NextApiResponse } from "next";
import { createPrismMiddleware } from "@1stdigital/prism-nextjs";
const prismMiddleware = createPrismMiddleware({
identifyToken: process.env.PRISM_IDENTIFY_TOKEN || "dev-key-123",
baseUrl: "https://prism-gw.fd.xyz",
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
// Apply middleware
const paymentResult = await prismMiddleware(req, res, {
price: 0.01, // $0.01 USD
description: "Premium API",
});
if (!paymentResult) return; // Middleware handled response
// Payment verified
res.status(200).json({
message: "Premium content",
payer: (req as any).payer,
});
}
```
***
## Configuration
### App Router Options
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismRouteConfig {
identifyToken: string;
baseUrl?: string;
debug?: boolean;
price: number | string; // USD price
description: string;
mimeType?: string;
}
```
### Pages Router Options
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
interface PrismMiddlewareConfig {
identifyToken: string;
baseUrl?: string;
debug?: boolean;
}
interface RoutePaymentConfig {
price: number | string;
description: string;
mimeType?: string;
}
```
***
## App Router Routes
### Single Route
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// app/api/premium/route.ts
import { withPrismPayment } from "@1stdigital/prism-nextjs";
async function handler(request: NextRequest) {
return NextResponse.json({ data: "Premium" });
}
export const GET = withPrismPayment(handler, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
price: 0.01,
description: "Premium API",
});
```
### Multiple Methods
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// app/api/data/route.ts
import { withPrismPayment } from "@1stdigital/prism-nextjs";
async function getHandler(request: NextRequest) {
return NextResponse.json({ data: "GET data" });
}
async function postHandler(request: NextRequest) {
const body = await request.json();
return NextResponse.json({ received: body });
}
export const GET = withPrismPayment(getHandler, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
price: 0.01,
description: "Get data",
});
export const POST = withPrismPayment(postHandler, {
identifyToken: process.env.PRISM_IDENTIFY_TOKEN!,
price: 0.02,
description: "Post data",
});
```
***
## Accessing Payment Info
### App Router
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
async function handler(request: NextRequest) {
// Payer address attached to request
const payer = (request as any).payer;
// '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
// Payment object in custom property
const payment = (request as any).prismPayment;
return NextResponse.json({
message: "Data",
payer,
network: payment?.network,
});
}
```
### Pages Router
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const paymentResult = await prismMiddleware(req, res, {
price: 0.01,
description: "Premium",
});
if (!paymentResult) return;
// Access payer
const payer = (req as any).payer;
const payment = (res as any).locals?.payment;
res.json({ payer, network: payment?.network });
}
```
***
## Settlement Validation
**Coming soon: transaction hash in the `X-PAYMENT-RESPONSE` response header.** The Next.js SDK currently confirms settlement internally before returning the response, but does not yet surface the transaction hash to the client. If your application needs the on-chain transaction hash on the client side, use the [Express SDK](/prism/sdk/typescript/express) — it returns this header today.
Next.js wraps the Response object to validate settlement:
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// Internal implementation (automatic!)
async function withPrismPayment(handler, config) {
return async (request: NextRequest) => {
// ... payment validation ...
// Execute handler
const response = await handler(request);
// Validate settlement before returning
const settlementResult = await core.settlementCallback(...);
if (!settlementResult || !settlementResult.success) {
// ❌ Settlement failed
return NextResponse.json(
{ error: 'Payment settlement failed' },
{ status: 402 }
);
}
// ✅ Settlement succeeded
response.headers.set('X-PAYMENT-RESPONSE', settlementResult.transaction);
return response;
};
}
```
***
## Testing
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { NextRequest } from "next/server";
import { GET } from "./app/api/premium/route";
describe("Next.js Payment Routes", () => {
it("returns 402 without payment", async () => {
const request = new NextRequest("http://localhost:3000/api/premium");
const response = await GET(request);
expect(response.status).toBe(402);
const body = await response.json();
expect(body.paymentRequired).toBe(true);
});
it("returns 200 with valid payment", async () => {
const payment = JSON.stringify({
scheme: "eip3009",
signature: "0x" + "0".repeat(130),
});
const request = new NextRequest("http://localhost:3000/api/premium", {
headers: { "X-PAYMENT": payment },
});
const response = await GET(request);
expect(response.status).toBe(200);
const body = await response.json();
expect(body.message).toBe("Premium content");
});
});
```
***
## Production Deployment
```typescript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// next.config.js
module.exports = {
env: {
PRISM_IDENTIFY_TOKEN: process.env.PRISM_IDENTIFY_TOKEN,
PRISM_BASE_URL: process.env.PRISM_BASE_URL
},
// Enable edge runtime (optional)
experimental: {
runtime: 'edge'
}
};
// Vercel deployment
// vercel.json
{
"env": {
"PRISM_IDENTIFY_TOKEN": "@prism-identify-token",
"PRISM_BASE_URL": "@prism-base-url"
}
}
```