# Create Agent
Source: https://docs.agentwallex.com/api-reference/agents-create
POST /api/v1/agents
Create a new AI agent with an MPC-secured wallet.
Create a new agent with an automatically provisioned MPC-secured wallet. The wallet address is generated using Distributed Key Generation (DKG) and is ready to receive funds immediately.
## Request Body
Display name for the agent. Must be unique within your account.
Optional description of the agent's purpose.
CAIP-2 chain identifier for the agent's wallet. See [Supported Chains](/platform/supported-chains) for available options.
Examples: `eip155:1` (Ethereum), `eip155:8453` (Base), `eip155:84532` (Base Sepolia testnet)
JSON-encoded metadata string for custom key-value pairs.
## Response
Unique agent identifier (e.g., `agent_abc123`).
Agent display name.
On-chain wallet address.
CAIP-2 chain identifier.
Agent status: `active` or `inactive`.
ISO 8601 creation timestamp.
## Example
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/agents \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_name": "research-bot",
"agent_description": "Market research automation agent",
"chain": "eip155:84532",
"metadata": "{\"team\":\"growth\"}"
}'
```
```typescript TypeScript theme={null}
const agent = await aw.agents.create({
name: "research-bot",
chain: "eip155:84532",
metadata: { team: "growth" },
});
```
```python Python theme={null}
agent = await aw.agents.create(
name="research-bot",
chain="eip155:84532",
metadata={"team": "growth"},
)
```
```json Response theme={null}
{
"id": "agent_abc123",
"agent_name": "research-bot",
"agent_description": "Market research automation agent",
"wallet": {
"address": "0x1234567890abcdef1234567890abcdef12345678",
"chain": "eip155:84532"
},
"status": "active",
"created_at": "2025-06-01T10:00:00Z"
}
```
# Get Agent
Source: https://docs.agentwallex.com/api-reference/agents-get
GET /api/v1/agents/{id}
Retrieve a single agent by ID, including wallet address and current status.
Retrieve the full details of a single agent, including wallet address, status, metadata, and creation timestamp.
## Path Parameters
The unique agent identifier (e.g., `agent_abc123`).
## Response
Unique agent identifier.
Agent display name.
Agent description.
On-chain wallet address.
CAIP-2 chain identifier.
Current status: `active` or `inactive`.
JSON-encoded metadata string.
ISO 8601 creation timestamp.
## Example
```bash cURL theme={null}
curl -X GET https://api.agentwallex.com/api/v1/agents/agent_abc123 \
-H "X-API-Key: awx_your_api_key"
```
```typescript TypeScript theme={null}
const agent = await aw.agents.get("agent_abc123");
```
```python Python theme={null}
agent = await aw.agents.get("agent_abc123")
```
```json Response theme={null}
{
"id": "agent_abc123",
"agent_name": "research-bot",
"agent_description": "Market research automation agent",
"wallet": {
"address": "0x1234567890abcdef1234567890abcdef12345678",
"chain": "eip155:84532"
},
"status": "active",
"metadata": "{\"team\":\"growth\"}",
"created_at": "2025-06-01T10:00:00Z"
}
```
# List Agents
Source: https://docs.agentwallex.com/api-reference/agents-list
GET /api/v1/agents
List all agents for your account with optional filtering.
Retrieve a paginated list of agents associated with your account. Supports filtering by status and chain.
## Query Parameters
Page number (1-indexed).
Number of items per page. Maximum: 100.
Filter by agent status. Values: `active`, `inactive`.
Filter by CAIP-2 chain identifier (e.g., `eip155:84532`).
## Response
Array of agent objects. Each agent includes `id`, `agent_name`, `wallet`, `status`, and `created_at`.
Total number of agents matching the query.
Whether more pages are available.
## Example
```bash cURL theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/agents?page_num=1&page_size=20&status=active&chain=eip155:84532" \
-H "X-API-Key: awx_your_api_key"
```
```typescript TypeScript theme={null}
const { agents, pagination } = await aw.agents.list({
limit: 20,
offset: 0,
status: "active",
});
```
```python Python theme={null}
result = await aw.agents.list(limit=20, offset=0, status="active")
```
```json Response theme={null}
{
"data": [
{
"id": "agent_abc123",
"agent_name": "research-bot",
"wallet": {
"address": "0x1234...5678",
"chain": "eip155:84532"
},
"status": "active",
"created_at": "2025-06-01T10:00:00Z"
}
],
"total": 3,
"has_more": false
}
```
# API Reference Overview
Source: https://docs.agentwallex.com/api-reference/overview
Base URLs, authentication, pagination, and error contract for the AgentWallex REST API.
## Base URLs
```
Sandbox: https://api-sandbox.agentwallex.com/api/v1
Production: https://api.agentwallex.com/api/v1
```
Use the sandbox URL for development and testing. Switch to production only when you are ready to transact with real funds.
## Authentication
All API requests must include one of the following authentication headers:
| Method | Header | Example |
| ---------- | --------------- | ------------------------------------- |
| API Key | `X-API-Key` | `X-API-Key: awx_your_api_key` |
| JWT Bearer | `Authorization` | `Authorization: Bearer eyJhbGciOi...` |
```bash theme={null}
# API key authentication
curl -X GET https://api.agentwallex.com/api/v1/agents \
-H "X-API-Key: awx_your_api_key"
# JWT authentication
curl -X GET https://api.agentwallex.com/api/v1/agents \
-H "Authorization: Bearer eyJhbGciOi..."
```
See [Authentication](/introduction/authentication) for full details on obtaining and managing credentials.
## Pagination
All list endpoints support pagination with the following query parameters:
| Parameter | Default | Max | Description |
| ----------- | ------- | --- | ------------------------ |
| `page_num` | 1 | -- | Page number (1-indexed) |
| `page_size` | 20 | 100 | Number of items per page |
Response format:
```json theme={null}
{
"data": [],
"total": 42,
"has_more": true
}
```
## Error Contract
All errors follow a consistent format:
```json theme={null}
{
"code": "invalid_request",
"type": "invalid_request_error",
"message": "human readable error description"
}
```
### Error Types
| Type | HTTP Status | Description |
| ----------------------- | ----------- | ---------------------------------- |
| `invalid_request_error` | 400 | Invalid request body or parameters |
| `authentication_error` | 401 | Missing or invalid credentials |
| `authorization_error` | 403 | Insufficient permissions |
| `not_found_error` | 404 | Resource does not exist |
| `rate_limit_error` | 429 | Rate limit exceeded |
| `internal_error` | 500 | Server-side error |
See [Error Handling](/guides/error-handling) for detailed guidance on handling errors.
## API Sections
Create and manage AI agent wallets.
Send payments and query transaction history.
Configure spending limits and access controls.
Register and manage webhook endpoints.
Trigger x402 micropayment negotiation.
Manage x402 session budgets.
# Create Policy
Source: https://docs.agentwallex.com/api-reference/policies-create
POST /api/v1/policies
Create a new policy and attach it to an agent.
Policies control what transactions an agent is allowed to execute. Every transaction is evaluated against the agent's policies before MPC signing.
### Request Body
Agent to attach this policy to.
Policy type. Values: `spending_limit`, `address_control`, `token_control`, `velocity_control`, `schedule`, `human_approval`.
Policy rules object. Structure depends on `type`.
Max per-transaction amount.
Rolling 24-hour total.
Rolling 30-day total.
Whitelisted recipient addresses.
Blacklisted addresses.
Permitted token symbols (e.g., `["USDC", "USDT"]`).
Maximum number of transactions in the window.
Time window in seconds.
IANA timezone (e.g., `America/New_York`).
Object with `start` and `end` hour (0-23).
Allowed days (1=Monday, 7=Sunday).
Amount above which approval is required.
Time before auto-reject.
Email addresses of approvers.
### Example
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/policies \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_abc123",
"type": "spending_limit",
"rules": {
"max_transaction_amount": "500",
"daily_limit": "5000",
"monthly_limit": "50000"
}
}'
```
# Delete Policy
Source: https://docs.agentwallex.com/api-reference/policies-delete
DELETE /api/v1/policies/{id}
Remove a policy from an agent.
### Path Parameters
The policy ID to delete (e.g., `pol_abc123`).
Deleting a policy removes the constraint immediately. Ensure you have other policies in place to maintain security.
### Example
```bash theme={null}
curl -X DELETE https://api.agentwallex.com/api/v1/policies/pol_abc123 \
-H "X-API-Key: awx_your_api_key"
```
# Get Policy
Source: https://docs.agentwallex.com/api-reference/policies-get
GET /api/v1/policies/{id}
Retrieve a single policy by ID.
### Path Parameters
The policy ID (e.g., `pol_abc123`).
### Example
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/policies/pol_abc123 \
-H "X-API-Key: awx_your_api_key"
```
# List Policies
Source: https://docs.agentwallex.com/api-reference/policies-list
GET /api/v1/policies
Retrieve all policies, optionally filtered by agent.
### Query Parameters
Filter by agent ID.
Page number.
Items per page. Maximum: 100.
### Example
```bash theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/policies?agent_id=agent_abc123" \
-H "X-API-Key: awx_your_api_key"
```
# Update Policy
Source: https://docs.agentwallex.com/api-reference/policies-update
PUT /api/v1/policies/{id}
Update an existing policy's rules.
### Path Parameters
The policy ID to update (e.g., `pol_abc123`).
### Request Body
Updated policy rules object. Structure depends on the policy's `type`.
### Example
```bash theme={null}
curl -X PUT https://api.agentwallex.com/api/v1/policies/pol_abc123 \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"rules": {
"max_transaction_amount": "1000",
"daily_limit": "10000"
}
}'
```
# Create Transaction
Source: https://docs.agentwallex.com/api-reference/transactions-create
POST /api/v1/transactions
Submit an on-chain payment through an agent's MPC-secured wallet.
Submit a new transaction through an agent's wallet. The transaction passes through the policy engine for validation, then is signed via MPC and broadcast to the blockchain.
## Request Body
The agent whose wallet will send the transaction.
Transaction direction. Currently only `outbound` is supported.
Transaction type. Values: `transfer`.
Sender address. If omitted, the agent's wallet address is used.
Recipient on-chain address.
Amount to send as a decimal string (e.g., `"10.5"`).
Token symbol (e.g., `USDC`, `USDT`, `ETH`).
CAIP-2 chain identifier (e.g., `eip155:84532`).
Optional memo or reference string.
## Response
Unique transaction identifier.
On-chain transaction hash (available after broadcast).
Transaction status: `pending`, `confirmed`, `failed`.
Amount sent.
Token symbol.
Network gas fee paid.
ISO 8601 timestamp.
## Example
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/transactions \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_abc123",
"direction": "outbound",
"type": "transfer",
"to_address": "0xabcdef1234567890abcdef1234567890abcdef12",
"amount": "10.5",
"token": "USDC",
"chain": "eip155:84532",
"memo": "service payment"
}'
```
```typescript TypeScript theme={null}
const tx = await aw.payments.send({
agentId: "agent_abc123",
to: "0xabcdef1234567890abcdef1234567890abcdef12",
amount: "10.50",
token: "USDC",
memo: "service payment",
});
```
```python Python theme={null}
tx = await aw.payments.send(
agent_id="agent_abc123",
to="0xabcdef1234567890abcdef1234567890abcdef12",
amount="10.50",
token="USDC",
memo="service payment",
)
```
```json Response theme={null}
{
"id": "tx_xyz789",
"hash": "0xabc123def456...",
"status": "confirmed",
"amount": "10.5",
"token": "USDC",
"fee": "0.001",
"created_at": "2025-06-15T14:30:00Z"
}
```
# Get Transaction
Source: https://docs.agentwallex.com/api-reference/transactions-get
GET /api/v1/transactions/{id}
Retrieve a single transaction by ID, including on-chain hash and confirmation status.
Retrieve the full details of a single transaction, including on-chain hash, amount, token, fees, and current status.
## Path Parameters
The unique transaction identifier (e.g., `tx_xyz789`).
## Response
Unique transaction identifier.
On-chain transaction hash.
Agent that initiated the transaction.
Transaction direction: `outbound`.
Transaction type: `transfer`.
Sender address.
Recipient address.
Amount sent.
Token symbol.
CAIP-2 chain identifier.
Network gas fee paid.
Current status: `pending`, `confirmed`, `failed`.
Optional memo string.
ISO 8601 creation timestamp.
## Example
```bash cURL theme={null}
curl -X GET https://api.agentwallex.com/api/v1/transactions/tx_xyz789 \
-H "X-API-Key: awx_your_api_key"
```
```typescript TypeScript theme={null}
const tx = await aw.payments.get("tx_xyz789");
```
```python Python theme={null}
tx = await aw.payments.get("tx_xyz789")
```
```json Response theme={null}
{
"id": "tx_xyz789",
"hash": "0xabc123def456789abc123def456789abc123def456789abc123def456789abcd",
"agent_id": "agent_abc123",
"direction": "outbound",
"type": "transfer",
"from_address": "0x1234567890abcdef1234567890abcdef12345678",
"to_address": "0xabcdef1234567890abcdef1234567890abcdef12",
"amount": "10.5",
"token": "USDC",
"chain": "eip155:84532",
"fee": "0.001",
"status": "confirmed",
"memo": "service payment",
"created_at": "2025-06-15T14:30:00Z"
}
```
# List Transactions
Source: https://docs.agentwallex.com/api-reference/transactions-list
GET /api/v1/transactions
Retrieve a paginated list of transactions with optional filtering.
List transactions across your account or filtered by agent and status.
## Query Parameters
Page number (1-indexed).
Number of items per page. Maximum: 100.
Filter by agent ID.
Filter by transaction status. Values: `pending`, `confirmed`, `failed`.
## Response
Array of transaction objects. Each includes `id`, `hash`, `agent_id`, `amount`, `token`, `status`, and `created_at`.
Total number of transactions matching the query.
Whether more pages are available.
## Example
```bash cURL theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/transactions?agent_id=agent_abc123&status=confirmed&page_size=50" \
-H "X-API-Key: awx_your_api_key"
```
```typescript TypeScript theme={null}
const { transactions } = await aw.payments.list({
agentId: "agent_abc123",
limit: 50,
status: "confirmed",
});
```
```python Python theme={null}
result = await aw.payments.list(
agent_id="agent_abc123",
limit=50,
status="confirmed",
)
```
```json Response theme={null}
{
"data": [
{
"id": "tx_xyz789",
"hash": "0xabc123def456...",
"agent_id": "agent_abc123",
"direction": "outbound",
"to_address": "0xabcd...ef12",
"amount": "10.5",
"token": "USDC",
"chain": "eip155:84532",
"status": "confirmed",
"created_at": "2025-06-15T14:30:00Z"
}
],
"total": 25,
"has_more": true
}
```
# Create Webhook
Source: https://docs.agentwallex.com/api-reference/webhooks-create
POST /api/v1/webhooks
Register a new webhook endpoint to receive real-time event notifications.
Register a new webhook endpoint to receive real-time event notifications via HTTP POST.
### Request Body
The HTTPS URL that will receive webhook events.
List of event types to subscribe to. See [Webhooks](/features/webhooks) for available event types.
Signing secret used to verify webhook payloads. Must start with `whsec_`.
### Example
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-app.com/webhooks/agentwallex",
"events": ["payment.completed", "payment.failed", "policy.violated"],
"secret": "whsec_your_signing_secret"
}'
```
```json Response theme={null}
{
"id": "whk_abc123",
"url": "https://your-app.com/webhooks/agentwallex",
"events": ["payment.completed", "payment.failed", "policy.violated"],
"status": "active",
"created_at": "2025-06-01T10:00:00Z"
}
```
# Delete Webhook
Source: https://docs.agentwallex.com/api-reference/webhooks-delete
DELETE /api/v1/webhooks/{id}
Remove a webhook endpoint. No further events will be delivered.
### Path Parameters
The webhook ID to delete (e.g., `whk_abc123`).
### Example
```bash theme={null}
curl -X DELETE https://api.agentwallex.com/api/v1/webhooks/whk_abc123 \
-H "X-API-Key: awx_your_api_key"
```
# Get Webhook
Source: https://docs.agentwallex.com/api-reference/webhooks-get
GET /api/v1/webhooks/{id}
Retrieve a single webhook endpoint by ID.
### Path Parameters
The webhook ID (e.g., `whk_abc123`).
### Example
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/webhooks/whk_abc123 \
-H "X-API-Key: awx_your_api_key"
```
# List Webhooks
Source: https://docs.agentwallex.com/api-reference/webhooks-list
GET /api/v1/webhooks
List all registered webhook endpoints.
### Example
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/webhooks \
-H "X-API-Key: awx_your_api_key"
```
# Test Webhook
Source: https://docs.agentwallex.com/api-reference/webhooks-test
POST /api/v1/webhooks/{id}/test
Send a test event to a webhook endpoint to verify your handler is working correctly.
### Path Parameters
The webhook ID to test (e.g., `whk_abc123`).
### Example
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks/whk_abc123/test \
-H "X-API-Key: awx_your_api_key"
```
# Update Webhook
Source: https://docs.agentwallex.com/api-reference/webhooks-update
PUT /api/v1/webhooks/{id}
Update a webhook's URL, events, or secret.
### Path Parameters
The webhook ID to update (e.g., `whk_abc123`).
### Request Body
Updated HTTPS URL for the webhook endpoint.
Updated list of event types to subscribe to.
Updated signing secret. Must start with `whsec_`.
### Example
```bash theme={null}
curl -X PUT https://api.agentwallex.com/api/v1/webhooks/whk_abc123 \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"events": ["payment.completed", "payment.failed", "policy.violated", "agent.frozen"]
}'
```
# x402 Pay
Source: https://docs.agentwallex.com/api-reference/x402-pay
POST /api/v1/x402/pay
Trigger an x402 payment negotiation for a target URL.
Negotiate and complete one x402 payment for a target URL. AgentWallex evaluates the agent's policies, signs the payment via MPC, and returns the payment info needed to access the paid resource.
## Request Body
The agent whose wallet will fund the payment.
The x402-enabled URL to pay for (e.g., `https://paid-api.example.com/v1/data`).
Optional session ID to deduct from an existing session budget. See [x402 Sessions](/api-reference/x402-sessions).
CAIP-2 chain identifier for payment settlement (e.g., `eip155:84532`). If omitted, the agent's default chain is used.
## Response
Internal ledger entry ID for this payment.
Payment amount.
Platform fee deducted.
Fee percentage applied (based on tiered pricing).
Token used for payment (e.g., `USDC`).
Chain used for settlement.
Payment status: `completed`, `pending`, `failed`.
The `PAYMENT-SIGNATURE` value to include in the retry request to the target URL.
## Example
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/pay \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_abc123",
"target_url": "https://paid-api.example.com/v1/data",
"session_id": "sess_xyz789",
"chain": "eip155:84532"
}'
```
```typescript TypeScript theme={null}
const result = await aw.x402.pay({
agentId: "agent_abc123",
targetUrl: "https://paid-api.example.com/v1/data",
sessionId: "sess_xyz789",
chain: "eip155:84532",
});
```
```python Python theme={null}
result = await aw.x402.pay(
agent_id="agent_abc123",
target_url="https://paid-api.example.com/v1/data",
session_id="sess_xyz789",
chain="eip155:84532",
)
```
```json Response theme={null}
{
"ledger_id": "ldg_abc123",
"amount": "0.10",
"fee_amount": "0.002",
"fee_rate": "2.0",
"token": "USDC",
"chain": "eip155:84532",
"status": "completed",
"payment_signature": "base64_encoded_signature..."
}
```
## Related Endpoints
| Endpoint | Description |
| --------------------------------- | -------------------------------------------------- |
| `POST /x402/check` | Check if a URL supports x402 payment negotiation |
| `POST /x402/facilitator/verify` | Verify a payment signature (for service providers) |
| `POST /x402/facilitator/settle` | Settle a verified payment (for service providers) |
| `GET /x402/facilitator/supported` | List supported chains for x402 |
| `GET /x402/fees/tiers` | Get current fee tier schedule |
# Create x402 Session
Source: https://docs.agentwallex.com/api-reference/x402-sessions-create
POST /api/v1/x402/sessions
Create a new x402 payment session with a spending budget.
Sessions let you pre-authorize a spending budget for repeated x402 API calls. Payments within a session are deducted from the session budget without requiring individual approval for each call.
### Request Body
The agent whose wallet funds the session.
Maximum total amount the session can spend (e.g., `"100.00"`).
CAIP-2 chain identifier for settlement (e.g., `eip155:84532`).
Session time-to-live in seconds. The session expires after this duration.
Optional list of URLs this session is authorized to pay. If omitted, all x402-enabled URLs are allowed.
### Example
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/sessions \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_abc123",
"budget_limit": "100.00",
"chain": "eip155:84532",
"ttl_seconds": 3600,
"allowed_urls": ["https://paid-api.example.com/v1/data"]
}'
```
```typescript TypeScript theme={null}
const session = await aw.x402.createSession({
agentId: "agent_abc123",
budgetLimit: "100.00",
chain: "eip155:84532",
ttlSeconds: 3600,
allowedUrls: ["https://paid-api.example.com/v1/data"],
});
```
```python Python theme={null}
session = await aw.x402.create_session(
agent_id="agent_abc123",
budget_limit="100.00",
chain="eip155:84532",
ttl_seconds=3600,
allowed_urls=["https://paid-api.example.com/v1/data"],
)
```
```json Response theme={null}
{
"id": "sess_xyz789",
"agent_id": "agent_abc123",
"budget_limit": "100.00",
"budget_spent": "0.00",
"budget_remaining": "100.00",
"chain": "eip155:84532",
"status": "active",
"expires_at": "2025-06-15T15:30:00Z",
"created_at": "2025-06-15T14:30:00Z"
}
```
# Delete x402 Session
Source: https://docs.agentwallex.com/api-reference/x402-sessions-delete
DELETE /api/v1/x402/sessions/{id}
Terminate a session and release any remaining budget.
### Path Parameters
The session ID to delete (e.g., `sess_xyz789`).
Deleting a session does not refund already-spent amounts. Only the unspent budget is released back to the agent's balance.
### Example
```bash theme={null}
curl -X DELETE https://api.agentwallex.com/api/v1/x402/sessions/sess_xyz789 \
-H "X-API-Key: awx_your_api_key"
```
# Get x402 Session
Source: https://docs.agentwallex.com/api-reference/x402-sessions-get
GET /api/v1/x402/sessions/{id}
Retrieve a single session including current budget status.
### Path Parameters
The session ID (e.g., `sess_xyz789`).
### Example
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/x402/sessions/sess_xyz789 \
-H "X-API-Key: awx_your_api_key"
```
# List x402 Sessions
Source: https://docs.agentwallex.com/api-reference/x402-sessions-list
GET /api/v1/x402/sessions
List all x402 sessions for your account.
### Example
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/x402/sessions \
-H "X-API-Key: awx_your_api_key"
```
# Pay with x402 Session
Source: https://docs.agentwallex.com/api-reference/x402-sessions-pay
POST /api/v1/x402/sessions/{id}/pay
Make a payment using an existing session budget.
### Path Parameters
The session ID to pay from (e.g., `sess_xyz789`).
### Request Body
The x402-enabled URL to pay for.
### Example
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/sessions/sess_xyz789/pay \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"target_url": "https://paid-api.example.com/v1/data"
}'
```
```typescript TypeScript theme={null}
await aw.x402.sessionPay("sess_xyz789", {
targetUrl: "https://paid-api.example.com/v1/data",
});
```
# Changelog
Source: https://docs.agentwallex.com/changelog/overview
Recent updates, new features, and improvements to the AgentWallex platform.
## March 2026
### March 15, 2026 — Mintlify Documentation Launch
* Launched new documentation site powered by Mintlify with interactive API playground.
* Added multi-language support: English, Simplified Chinese, Traditional Chinese, Japanese, Korean, Vietnamese, Spanish, and French.
* API reference pages now include interactive request builders.
### March 5, 2026 — Python SDK v0.4.0
* Added `http_interceptor()` for automatic x402 challenge handling in Python.
* Improved async error handling with retry backoff.
* Added type hints for all public methods.
## February 2026
### February 20, 2026 — x402 Session Budgets
* New `POST /x402/sessions` endpoint for pre-authorized spending budgets.
* Sessions support `allowed_urls` for URL-scoped authorization.
* Added `POST /x402/sessions/:id/pay` for session-scoped payments.
* SDK methods: `aw.x402.createSession()`, `aw.x402.sessionPay()`.
### February 10, 2026 — Policy Templates
* New policy template system: create, apply, and reuse policy configurations.
* Three built-in templates: `conservative`, `standard`, `permissive`.
* API endpoints: `GET/POST/PUT/DELETE /policy-templates`.
* SDK methods: `aw.policies.createTemplate()`, `aw.policies.applyTemplate()`.
## January 2026
### January 25, 2026 — Webhook Delivery History
* New `GET /webhooks/:id/deliveries` endpoint to inspect delivery history.
* View status codes, response times, and failure reasons for each delivery.
* Added `POST /webhooks/:id/test` for sending test events.
### January 15, 2026 — Base Mainnet Support
* Added Base (`eip155:8453`) as an active chain for agent wallets and x402 settlement.
* USDC support on Base for both direct transactions and x402 micropayments.
### January 5, 2026 — TypeScript SDK v0.6.0
* Added `x402.httpInterceptor()` for automatic 402 challenge handling.
* New typed error classes: `PolicyViolationError`, `AuthenticationError`, `NotFoundError`, `RateLimitError`.
* Improved TypeScript type exports.
## December 2025
### December 15, 2025 — Human Approval Routing
* Transactions above a configurable threshold can now be routed to human review.
* New webhook event: `approval.requested`.
* Dashboard support for one-click approve/reject.
* Configurable timeout with auto-reject.
### December 1, 2025 — Initial Public Beta
* AgentWallex platform launch with MPC wallets (via Paratro), policy engine, and x402 micropayments.
* Supported chains: Ethereum, BNB Smart Chain, Polygon, Tron, Bitcoin.
* TypeScript SDK v0.1.0 and Python SDK v0.1.0.
* REST API v1 with agents, transactions, policies, and webhooks.
# MPC Wallets
Source: https://docs.agentwallex.com/features/mpc-wallets
How AgentWallex uses 2-of-3 threshold MPC signing via Paratro to secure agent wallets.
## Overview
Every agent wallet in AgentWallex is secured by Multi-Party Computation (MPC). The full private key is **never reconstructed** — not in memory, not on disk, not anywhere. Instead, cryptographic key shards are distributed across three independent parties, and any two can cooperate to sign a transaction.
## How MPC Works
Traditional wallets store a single private key. If that key is stolen, all funds are lost. MPC eliminates this single point of failure.
### 2-of-3 Threshold Signing
AgentWallex uses Paratro's 2-of-3 threshold MPC protocol. Three key shards are generated, and any two are sufficient to produce a valid signature:
| Shard | Holder | Role |
| ------- | --------------------------- | ------------------------------ |
| Shard 1 | AgentWallex signing service | Active signing participant |
| Shard 2 | Independent custodian node | Active signing participant |
| Shard 3 | Cold storage | Recovery and disaster recovery |
During normal operation, Shard 1 and Shard 2 cooperate to sign transactions. Shard 3 remains offline and is only used for recovery scenarios.
### Security Properties
* **No single point of compromise** — An attacker must compromise two independent systems simultaneously.
* **No key reconstruction** — The full private key is never assembled in any single location.
* **Forward secrecy** — Regular shard rotation (proactive secret sharing) invalidates old shards.
* **Same wallet address** — Shard rotation does not change the wallet's on-chain address.
## Key Generation
Keys are generated using Distributed Key Generation (DKG):
Each of the 3 MPC nodes independently generates a random share.
The shares are combined cryptographically to produce a public key (and corresponding wallet address).
Each node retains only its own shard. The full private key never exists.
```typescript theme={null}
// When you create an agent, DKG happens automatically
const agent = await aw.agents.create({
name: "my-agent",
chain: "eip155:8453",
});
// The wallet address is derived from the distributed public key
console.log(agent.wallet.address); // 0x...
```
## Key Rotation
Key shards are rotated periodically using a technique called **proactive secret sharing**. This process:
1. Generates new shards that correspond to the same public key.
2. Distributes the new shards to all three parties.
3. Destroys the old shards.
After rotation, even if an attacker had previously stolen a shard, it becomes cryptographically useless.
Key rotation is automatic and does not require any action from the developer. The wallet address remains the same.
## Emergency Freeze
Any authorized party can instantly freeze an agent's wallet, preventing all transactions:
```typescript SDK theme={null}
// Freeze — immediate, no transactions can be signed
await aw.agents.freeze("agent_abc123");
// Unfreeze — subject to mandatory cool-down period
await aw.agents.unfreeze("agent_abc123");
```
```bash API theme={null}
# Freeze
curl -X PUT https://api.agentwallex.com/api/v1/agents/agent_abc123/status \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "inactive"}'
# Unfreeze
curl -X PUT https://api.agentwallex.com/api/v1/agents/agent_abc123/status \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "active"}'
```
After freezing a wallet, there is a mandatory 10-minute cool-down period before it can be unfrozen. This prevents an attacker from immediately re-enabling a wallet they have frozen and unfrozen.
## Infrastructure Safety Net
Beyond developer-configured policies, Paratro enforces hard limits at the MPC signing level that **cannot be overridden** by API calls:
| Control | Default |
| ------------------ | ------------------------ |
| Absolute daily cap | \$50,000 |
| Anomaly detection | ML-based, always enabled |
| Emergency freeze | Always available |
| Cool-down period | 10 minutes after freeze |
These limits act as a last line of defense, even if your API key is compromised or your business-layer policies are misconfigured.
# Policy Engine
Source: https://docs.agentwallex.com/features/policy-engine
Configure per-agent spending limits, address whitelists, velocity controls, and human approval routing.
## Overview
The policy engine evaluates every transaction before it reaches the MPC signing layer. Policies are per-agent and can be updated at any time via the SDK or REST API. The first policy violation stops the transaction immediately.
## Policy Types
### Spending Limits
Control how much an agent can spend:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
maxTransactionAmount: "500", // Max per single transaction (USDC)
dailyLimit: "5000", // Rolling 24-hour total
monthlyLimit: "50000", // Rolling 30-day total
});
```
| Rule | Description | Window |
| ---------------------- | ----------------------------------- | --------------- |
| `maxTransactionAmount` | Maximum amount for a single payment | Per transaction |
| `dailyLimit` | Maximum total over rolling 24 hours | Rolling window |
| `monthlyLimit` | Maximum total over rolling 30 days | Rolling window |
### Address Controls
Restrict which addresses an agent can send to:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
// Whitelist mode: only send to these addresses
allowedAddresses: [
"0xTrustedVendor1",
"0xTrustedVendor2",
"0xTrustedExchange",
],
// Blacklist mode: block specific addresses
blockedAddresses: [
"0xKnownScam",
],
});
```
If `allowedAddresses` is set, only those addresses are permitted. If both `allowedAddresses` and `blockedAddresses` are set, `allowedAddresses` takes priority.
### Token Controls
Restrict which tokens an agent can transact with:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
allowedTokens: ["USDC", "USDT"], // Only stablecoins
});
```
### Velocity Controls
Limit transaction frequency to prevent runaway agents:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
velocityLimit: {
maxCount: 100, // Max number of transactions
windowSeconds: 3600, // Per hour
},
});
```
### Time-Based Controls
Restrict when transactions can occur:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
schedule: {
timezone: "America/New_York",
allowedHours: { start: 9, end: 17 }, // 9 AM - 5 PM
allowedDays: [1, 2, 3, 4, 5], // Monday - Friday
},
});
```
### Human Approval
Route high-value transactions to human review:
```typescript theme={null}
await aw.policies.update("agent_abc123", {
requireHumanApproval: true,
humanApprovalThreshold: "1000", // Transactions above $1000
approvalTimeout: 3600, // 1 hour to approve before auto-reject
approvers: [
"user_admin1@company.com",
"user_admin2@company.com",
],
});
```
Human approval is available on Growth and Enterprise plans. When a transaction requires approval, a webhook event is sent and the transaction enters a `pending_approval` state.
## Policy Evaluation Order
Policies are checked in this order. The first failure stops the transaction:
Is the agent active (not frozen)?
Is this token in the `allowedTokens` list?
Is the recipient in `allowedAddresses` and not in `blockedAddresses`?
Does this exceed `maxTransactionAmount`?
Would this exceed the rolling daily total?
Would this exceed the rolling monthly total?
Has the agent exceeded its transaction rate (`velocityLimit`)?
Is this within allowed hours and days?
Does this require human review based on the threshold?
Paratro-enforced hard limits (cannot be overridden).
## Policy Violation Events
When a policy blocks a transaction, the API returns a detailed error:
```json theme={null}
{
"code": "policy_violation",
"type": "invalid_request_error",
"message": "Transaction would exceed daily limit"
}
```
You can also receive violations as webhook events:
```typescript theme={null}
await aw.webhooks.create({
url: "https://your-app.com/webhooks",
events: ["policy.violated"],
});
```
## Policy Templates
Use templates for common configurations:
```typescript theme={null}
// Conservative: tight limits for testing
await aw.policies.applyTemplate("agent_abc123", "conservative");
// Standard: balanced limits for production
await aw.policies.applyTemplate("agent_abc123", "standard");
// Custom: define and reuse your own templates
await aw.policies.createTemplate("my-template", {
maxTransactionAmount: "200",
dailyLimit: "2000",
allowedTokens: ["USDC"],
velocityLimit: { maxCount: 50, windowSeconds: 3600 },
});
await aw.policies.applyTemplate("agent_abc123", "my-template");
```
## Best Practices
Start restrictive, expand gradually. Begin with tight limits and increase as you gain confidence in your agent's behavior.
* **Use allowedAddresses** — Whitelist trusted addresses rather than relying solely on amount limits.
* **Enable human approval for high-value** — Set a threshold above which humans review transactions.
* **Monitor policy violations** — Track violations via webhooks to identify misconfigured agents.
* **Use velocity limits** — Prevent runaway loops where an agent repeatedly attempts transactions.
* **Review policies weekly** — As agent behaviors evolve, update policies to match.
# Webhooks
Source: https://docs.agentwallex.com/features/webhooks
Receive real-time notifications for payments, policy violations, and agent events.
## Overview
Webhooks deliver real-time event notifications to your application via HTTP POST requests. Use them to react to payments, policy violations, agent status changes, and x402 session events.
## Setting Up Webhooks
### Via SDK
```typescript theme={null}
const webhook = await aw.webhooks.create({
url: "https://your-app.com/webhooks/agentwallex",
events: [
"payment.completed",
"payment.failed",
"agent.frozen",
"policy.violated",
],
secret: "whsec_your_signing_secret",
});
```
### Via API
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-app.com/webhooks/agentwallex",
"events": ["payment.completed", "payment.failed", "agent.frozen", "policy.violated"],
"secret": "whsec_your_signing_secret"
}'
```
## Event Types
| Event | Description |
| ---------------------- | ---------------------------------------------- |
| `payment.completed` | Transaction confirmed on-chain |
| `payment.failed` | Transaction failed or reverted |
| `payment.pending` | Transaction submitted, awaiting confirmation |
| `agent.frozen` | Agent wallet was frozen |
| `agent.unfrozen` | Agent wallet was unfrozen |
| `policy.violated` | Transaction rejected by policy engine |
| `x402.session.expired` | x402 session budget or TTL exceeded |
| `approval.requested` | High-value transaction awaiting human approval |
## Webhook Payload
Every webhook delivery includes a JSON payload with this structure:
```json theme={null}
{
"id": "evt_abc123",
"type": "payment.completed",
"created_at": "2025-06-15T14:30:00Z",
"data": {
"transaction_id": "tx_xyz789",
"agent_id": "agent_abc123",
"amount": "50.00",
"token": "USDC",
"chain": "eip155:8453",
"hash": "0xabc...def",
"status": "confirmed"
}
}
```
## Signature Verification
Every webhook delivery includes a signature header for verification. Always verify signatures before processing webhook events.
### How It Works
AgentWallex signs each webhook payload using the secret you provided at registration. The signature is sent in the `X-AgentWallex-Signature` header.
### Verification Example
```typescript TypeScript theme={null}
import crypto from "crypto";
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expected = crypto
.createHmac("sha256", secret)
.update(payload)
.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
// In your webhook handler
app.post("/webhooks/agentwallex", (req, res) => {
const signature = req.headers["x-agentwallex-signature"] as string;
const isValid = verifyWebhookSignature(
JSON.stringify(req.body),
signature,
"whsec_your_signing_secret"
);
if (!isValid) {
return res.status(401).send("Invalid signature");
}
// Process the event
const event = req.body;
console.log(`Received ${event.type} event`);
res.status(200).send("OK");
});
```
```python Python theme={null}
import hmac
import hashlib
def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
expected = hmac.new(
secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
```
Always use constant-time comparison (e.g., `timingSafeEqual` or `hmac.compare_digest`) when verifying signatures to prevent timing attacks.
## Testing Webhooks
Send a test event to your webhook endpoint:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/webhooks/whk_abc123/test \
-H "X-API-Key: awx_your_api_key"
```
## Viewing Deliveries
Check the delivery history for a webhook:
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/webhooks/whk_abc123/deliveries \
-H "X-API-Key: awx_your_api_key"
```
## Managing Webhooks
```bash theme={null}
# List all webhooks
GET /webhooks
# Get a specific webhook
GET /webhooks/:id
# Update a webhook
PUT /webhooks/:id
# Delete a webhook
DELETE /webhooks/:id
```
## Best Practices
Respond to webhook deliveries with a 2xx status code within 5 seconds. If your handler needs to do heavy processing, acknowledge the webhook immediately and process asynchronously.
* **Always verify signatures** before processing events.
* **Handle duplicates** — Webhook deliveries may be retried. Use the `id` field for idempotency.
* **Return 200 quickly** — Acknowledge receipt before doing heavy processing.
* **Monitor delivery failures** — Check the deliveries endpoint for failed deliveries.
* **Use specific event filters** — Subscribe only to the events you need rather than receiving all events.
# x402 Micropayments
Source: https://docs.agentwallex.com/features/x402-micropayments
Pay-per-API-call using the HTTP 402 protocol — session budgets, automatic negotiation, and settlement.
## What is x402?
x402 is a machine-to-machine payment protocol built around HTTP `402 Payment Required`. It enables AI agents to automatically pay for API access without human intervention. AgentWallex implements x402 v2 with EIP-3009 authorization payloads.
## x402 v2 Headers
The protocol uses three HTTP headers:
| Header | Direction | Purpose |
| ------------------- | ---------------- | ------------------------------- |
| `PAYMENT-REQUIRED` | Server to Client | 402 challenge with pricing info |
| `PAYMENT-SIGNATURE` | Client to Server | Signed payment payload |
| `PAYMENT-RESPONSE` | Server to Client | Settlement confirmation |
## Payment Flow
```
Client Agent Paid API AgentWallex
| | |
|-- GET /resource ------>| |
|<-- 402 + PAYMENT-REQUIRED |
| | |
|-- POST /api/v1/x402/pay -----------------------> |
| | (sign + policy) |
|<-- payment_info | |
| | |
|-- GET /resource + PAYMENT-SIGNATURE -----------> |
|<-- 200 + PAYMENT-RESPONSE |
```
The agent sends a standard HTTP request to a paid API endpoint.
The API responds with HTTP 402 and a `PAYMENT-REQUIRED` header containing pricing details (amount, token, chain, payTo address).
The agent sends the payment details to `POST /x402/pay`. AgentWallex evaluates policies and signs the payment.
The agent retries the original request with the `PAYMENT-SIGNATURE` header attached.
The API verifies the payment signature (via the AgentWallex facilitator) and returns the resource.
## Using x402 APIs
### Check if a URL Supports x402
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/check \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"url": "https://paid-api.example.com/v1/data"}'
```
### Create a Session Budget
Sessions let you pre-authorize a spending budget for repeated API calls:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/sessions \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_uuid",
"budget_limit": "100.00",
"chain": "eip155:84532",
"ttl_seconds": 3600,
"allowed_urls": ["https://paid-api.example.com/v1/data"]
}'
```
### Trigger Payment Negotiation
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/pay \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_uuid",
"target_url": "https://paid-api.example.com/v1/data",
"session_id": "optional_session_uuid",
"chain": "eip155:84532"
}'
```
The response includes `payment_info` with:
| Field | Description |
| ------------ | ------------------------- |
| `ledger_id` | Internal ledger entry ID |
| `amount` | Payment amount |
| `fee_amount` | Platform fee deducted |
| `fee_rate` | Fee percentage applied |
| `token` | Token used (e.g., USDC) |
| `chain` | Chain used for settlement |
| `status` | Payment status |
## SDK Integration
### Automatic HTTP Interceptor
The TypeScript SDK provides an interceptor that handles the full x402 flow automatically:
```typescript theme={null}
const fetchWithPayment = aw.x402.httpInterceptor({
agentId: "agent_abc123",
chain: "eip155:84532",
});
// This automatically handles 402 challenges
const response = await fetchWithPayment("https://paid-api.example.com/v1/data");
const data = await response.json();
```
### Manual Flow
```typescript theme={null}
// 1. Create a session budget
const session = await aw.x402.createSession({
agentId: "agent_abc123",
budgetLimit: "100.00",
chain: "eip155:84532",
ttlSeconds: 3600,
allowedUrls: ["https://paid-api.example.com/v1/data"],
});
// 2. Pay for an API call
const result = await aw.x402.pay({
agentId: "agent_abc123",
targetUrl: "https://paid-api.example.com/v1/data",
sessionId: session.id,
chain: "eip155:84532",
});
// 3. Or pay using the session directly
await aw.x402.sessionPay(session.id, {
targetUrl: "https://paid-api.example.com/v1/data",
});
```
## For Service Providers
If you expose paid APIs, your server should return an x402 v2 challenge when payment is missing.
### Return 402 with PAYMENT-REQUIRED
Encode a JSON challenge (base64) into the `PAYMENT-REQUIRED` header:
```json theme={null}
{
"x402Version": 2,
"resource": "https://your-api.com/v1/data",
"accepts": [
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "0.10",
"asset": "USDC",
"payTo": "0xYourAddress",
"maxTimeoutSeconds": 300
}
]
}
```
### Verify and Settle
Use the AgentWallex facilitator endpoints:
```bash theme={null}
# Verify a payment signature
POST /api/v1/x402/facilitator/verify
# Settle a verified payment
POST /api/v1/x402/facilitator/settle
# Query supported chains
GET /api/v1/x402/facilitator/supported
```
## Operational Defaults
| Parameter | Value |
| -------------------- | ------------------------------------------------------- |
| Settlement interval | 300 seconds |
| Settlement threshold | \$10.00 |
| Max settlement delay | 3,600 seconds |
| Supported chains | `eip155:84532`, `eip155:8453`, `eip155:1`, `eip155:137` |
# Best Practices
Source: https://docs.agentwallex.com/guides/best-practices
Security tips, policy setup, monitoring recommendations, and a production readiness checklist.
## Security
Never expose API keys in client-side code, public repositories, or application logs.
* **Store API keys in a secrets manager** — Use AWS Secrets Manager, HashiCorp Vault, or your platform's secrets solution. Avoid `.env` files in production.
* **Rotate keys every 90 days** — Set a recurring reminder. See [API Keys](/introduction/api-keys) for rotation instructions.
* **Use separate keys per environment** — Never share keys between development, staging, and production.
* **Enable IP allowlisting** — On Growth and Enterprise plans, restrict API access to known server IPs.
* **Use sandbox for testing** — Never test with production keys or real funds.
## Policy Configuration
Start with the most restrictive policies possible and gradually relax them as you gain confidence in your agent's behavior.
### Recommended Starting Policies
```typescript theme={null}
await aw.policies.update("agent_abc123", {
// Start with low limits
maxTransactionAmount: "100",
dailyLimit: "1000",
monthlyLimit: "10000",
// Whitelist trusted addresses only
allowedAddresses: ["0xTrustedVendor1", "0xTrustedVendor2"],
// Restrict to stablecoins
allowedTokens: ["USDC"],
// Prevent runaway loops
velocityLimit: {
maxCount: 50,
windowSeconds: 3600,
},
// Human review for larger amounts
requireHumanApproval: true,
humanApprovalThreshold: "500",
});
```
### Policy Tips
* **Use allowedAddresses** — Whitelisting is more secure than blacklisting.
* **Set velocity limits** — Prevent agents from entering infinite transaction loops.
* **Enable human approval** — For amounts above a meaningful threshold.
* **Review weekly** — Adjust policies as agent behavior patterns become clear.
* **Use templates** — Create reusable templates for common configurations.
## Monitoring
### Subscribe to Key Events
```typescript theme={null}
await aw.webhooks.create({
url: "https://your-app.com/webhooks",
events: [
"payment.completed",
"payment.failed",
"policy.violated",
"agent.frozen",
],
});
```
### What to Monitor
| Metric | Why |
| ------------------------- | ----------------------------------------------------- |
| Policy violations | Indicates misconfigured agents or unexpected behavior |
| Failed transactions | May indicate insufficient funds or chain issues |
| Freeze events | Triggered by anomaly detection or manual action |
| Daily spend per agent | Catch budget overruns early |
| API error rates | Detect integration issues |
| Webhook delivery failures | Ensure your handler is healthy |
### Audit Logs
Review audit logs regularly for unexpected activity:
```bash theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/audit-logs?page_num=1&page_size=50" \
-H "X-API-Key: awx_your_api_key"
```
## Production Readiness Checklist
Use this checklist before going live:
* [ ] **API keys** — Production keys created and stored in a secrets manager
* [ ] **Environment** — SDK initialized with `environment: "production"`
* [ ] **Policies configured** — Per-agent spending limits, address whitelists, and velocity controls
* [ ] **Human approval** — Enabled for high-value transactions with appropriate thresholds
* [ ] **Webhooks registered** — Handlers deployed for `payment.completed`, `payment.failed`, and `policy.violated`
* [ ] **Webhook signatures verified** — Handler validates `X-AgentWallex-Signature` on every delivery
* [ ] **Error handling** — SDK errors caught and logged with retry logic for transient failures
* [ ] **Monitoring** — Alerts set for policy violations, failed transactions, and freeze events
* [ ] **Audit log access** — Team members can view audit logs in the dashboard
* [ ] **Emergency procedures** — Documented how to freeze an agent and who has authority
* [ ] **Key rotation schedule** — Calendar reminder set for 90-day key rotation
* [ ] **Sandbox testing** — All flows tested end-to-end on testnet before switching to production
* [ ] **Wallet funding** — Production wallets funded with sufficient balance for expected transaction volume
* [ ] **Rate limits understood** — Application handles 429 responses with exponential backoff
The AgentWallex team is available to review your integration before you go live. Contact [support@agentwallex.com](mailto:support@agentwallex.com) for a pre-launch review.
# Error Handling
Source: https://docs.agentwallex.com/guides/error-handling
Error format, error types, and how to handle errors in the SDK and REST API.
## Error Format
All AgentWallex API errors follow a consistent JSON format:
```json theme={null}
{
"code": "invalid_request",
"type": "invalid_request_error",
"message": "human readable error description"
}
```
| Field | Description |
| --------- | ---------------------------------------------------------------------------- |
| `code` | Machine-readable error code (e.g., `policy_violation`, `insufficient_funds`) |
| `type` | Error category (see table below) |
| `message` | Human-readable description of what went wrong |
## Error Types
| Type | HTTP Status | Description |
| ----------------------- | ----------- | --------------------------------------------------- |
| `invalid_request_error` | 400 | The request body or parameters are invalid |
| `authentication_error` | 401 | Missing or invalid API key / token |
| `authorization_error` | 403 | Valid credentials but insufficient permissions |
| `not_found_error` | 404 | The requested resource does not exist |
| `rate_limit_error` | 429 | Too many requests — retry after the indicated delay |
| `internal_error` | 500 | Server-side error — contact support if persistent |
## Common Error Codes
| Code | Type | Description |
| --------------------- | ----------------------- | ------------------------------------------------- |
| `policy_violation` | `invalid_request_error` | Transaction blocked by policy engine |
| `insufficient_funds` | `invalid_request_error` | Wallet balance too low for the transaction |
| `agent_frozen` | `invalid_request_error` | Agent is frozen — unfreeze before transacting |
| `invalid_chain` | `invalid_request_error` | Unsupported or invalid chain ID |
| `invalid_token` | `invalid_request_error` | Token not supported on the specified chain |
| `invalid_address` | `invalid_request_error` | Malformed recipient address |
| `session_expired` | `invalid_request_error` | x402 session has expired or exceeded budget |
| `rate_limit_exceeded` | `rate_limit_error` | API rate limit reached |
| `approval_timeout` | `invalid_request_error` | Human approval was not granted within the timeout |
## SDK Error Handling
### TypeScript
The TypeScript SDK provides typed error classes for specific error types:
```typescript theme={null}
import {
AgentWallexError,
PolicyViolationError,
} from "@agentwallex/sdk";
try {
const tx = await aw.payments.send({
agentId: "agent_abc123",
to: "0xRecipientAddress",
amount: "50.00",
token: "USDC",
});
} catch (error) {
if (error instanceof PolicyViolationError) {
console.log(`Policy violated: ${error.rule}`);
console.log(`Details: ${error.message}`);
// Handle: adjust amount, use different address, etc.
} else if (error instanceof AgentWallexError) {
console.log(`API error [${error.code}]: ${error.message}`);
switch (error.code) {
case "insufficient_funds":
// Top up the wallet
break;
case "agent_frozen":
// Unfreeze or use a different agent
break;
case "rate_limit_exceeded":
// Wait and retry
break;
default:
// Log and alert
break;
}
} else {
// Network error or unexpected exception
console.error("Unexpected error:", error);
}
}
```
### Python
```python theme={null}
from agentwallex import AgentWallexError, PolicyViolationError
try:
tx = await aw.payments.send(
agent_id="agent_abc123",
to="0xRecipientAddress",
amount="50.00",
token="USDC",
)
except PolicyViolationError as e:
print(f"Policy violated: {e.rule}")
print(f"Details: {e.message}")
except AgentWallexError as e:
print(f"API error [{e.code}]: {e.message}")
except Exception as e:
print(f"Unexpected error: {e}")
```
## Retry Strategy
Use exponential backoff for retries. Only retry on `rate_limit_error` and `internal_error`. Do not retry `invalid_request_error` or `authentication_error` — those require fixing the request.
```typescript theme={null}
async function withRetry(
fn: () => Promise,
maxRetries: number = 3
): Promise {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (
error instanceof AgentWallexError &&
(error.type === "rate_limit_error" || error.type === "internal_error") &&
attempt < maxRetries
) {
const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
throw new Error("Max retries exceeded");
}
// Usage
const tx = await withRetry(() =>
aw.payments.send({
agentId: "agent_abc123",
to: "0xRecipientAddress",
amount: "50.00",
token: "USDC",
})
);
```
## HTTP Status Code Reference
| Status | Meaning | Action |
| ------ | ------------ | ------------------------------------------------- |
| 200 | Success | Process the response |
| 201 | Created | Resource was created successfully |
| 400 | Bad Request | Fix the request parameters |
| 401 | Unauthorized | Check your API key |
| 403 | Forbidden | Check permissions / plan tier |
| 404 | Not Found | Verify the resource ID exists |
| 429 | Rate Limited | Wait and retry with backoff |
| 500 | Server Error | Retry with backoff; contact support if persistent |
# Wallet Operations
Source: https://docs.agentwallex.com/guides/wallet-operations
Create wallets, fund them, send payments, check balances, and manage agent status.
## Create an Agent Wallet
Every agent gets its own MPC-secured wallet. Specify the chain and initial policies at creation time.
```typescript TypeScript theme={null}
const agent = await aw.agents.create({
name: "payment-agent",
chain: "eip155:8453", // Base mainnet
policies: {
maxTransactionAmount: "500",
dailyLimit: "5000",
allowedTokens: ["USDC"],
},
metadata: { team: "growth" },
});
console.log(`Agent ID: ${agent.id}`);
console.log(`Wallet address: ${agent.wallet.address}`);
console.log(`Chain: ${agent.wallet.chain}`);
```
```python Python theme={null}
agent = await aw.agents.create(
name="payment-agent",
chain="eip155:8453",
policies={
"max_transaction_amount": "500",
"daily_limit": "5000",
"allowed_tokens": ["USDC"],
},
metadata={"team": "growth"},
)
print(f"Agent ID: {agent.id}")
print(f"Wallet address: {agent.wallet.address}")
```
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/agents \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_name": "payment-agent",
"chain": "eip155:8453",
"metadata": "{\"team\":\"growth\"}"
}'
```
## Fund the Wallet
Send tokens to the agent's wallet address. The wallet address is a standard on-chain address that can receive tokens from any source.
In sandbox mode (`eip155:84532`), use a testnet faucet to get test tokens. No real funds are needed.
For x402 operations, you can also deposit via the balance endpoint:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/x402/balances/deposit-address \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"agent_id": "agent_abc123", "chain": "eip155:8453"}'
```
## Send a Payment
Execute an on-chain payment through the agent. The transaction passes through the policy engine and MPC signing before broadcast.
```typescript TypeScript theme={null}
const tx = await aw.payments.send({
agentId: "agent_abc123",
to: "0xRecipientAddress",
amount: "50.00",
token: "USDC",
memo: "Payment for API access",
});
console.log(`Transaction ID: ${tx.id}`);
console.log(`Hash: ${tx.hash}`);
console.log(`Status: ${tx.status}`); // "pending" -> "confirmed"
console.log(`Fee: ${tx.fee}`); // Network gas fee
```
```python Python theme={null}
tx = await aw.payments.send(
agent_id="agent_abc123",
to="0xRecipientAddress",
amount="50.00",
token="USDC",
memo="Payment for API access",
)
print(f"Hash: {tx.hash}")
print(f"Status: {tx.status}")
```
```bash cURL theme={null}
curl -X POST https://api.agentwallex.com/api/v1/transactions \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "agent_abc123",
"direction": "outbound",
"type": "transfer",
"to_address": "0xRecipientAddress",
"amount": "50.00",
"token": "USDC",
"chain": "eip155:8453",
"memo": "Payment for API access"
}'
```
## Check Balance
Query the x402 balance for an agent:
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/x402/balances \
-H "X-API-Key: awx_your_api_key"
```
## List Transactions
View transaction history for an agent:
```typescript TypeScript theme={null}
const { transactions } = await aw.payments.list({
agentId: "agent_abc123",
limit: 50,
status: "confirmed",
});
transactions.forEach(tx => {
console.log(`${tx.amount} ${tx.token} -> ${tx.to} (${tx.status})`);
});
```
```bash cURL theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/transactions?agent_id=agent_abc123&status=confirmed&page_size=50" \
-H "X-API-Key: awx_your_api_key"
```
## Freeze and Unfreeze
Instantly stop all transactions for an agent. Useful for emergencies or scheduled maintenance.
### Freeze
```typescript TypeScript theme={null}
await aw.agents.freeze("agent_abc123");
// All transactions are now blocked
```
```bash cURL theme={null}
curl -X PUT https://api.agentwallex.com/api/v1/agents/agent_abc123/status \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "inactive"}'
```
### Unfreeze
```typescript TypeScript theme={null}
// Subject to 10-minute cool-down after freeze
await aw.agents.unfreeze("agent_abc123");
```
```bash cURL theme={null}
curl -X PUT https://api.agentwallex.com/api/v1/agents/agent_abc123/status \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "active"}'
```
There is a mandatory 10-minute cool-down period after freezing before you can unfreeze. Attempting to unfreeze earlier will return an error.
## Delete an Agent
Permanently delete an agent and its wallet. This action is irreversible.
```bash theme={null}
curl -X DELETE https://api.agentwallex.com/api/v1/agents/agent_abc123 \
-H "X-API-Key: awx_your_api_key"
```
Ensure the wallet balance is zero before deleting. Any remaining funds will be inaccessible after deletion.
# API Keys
Source: https://docs.agentwallex.com/introduction/api-keys
Create, manage, and rotate API keys for AgentWallex integrations.
## Overview
API keys authenticate your server-side applications with the AgentWallex API. Each key starts with the `awx_` prefix and is tied to your account.
## Creating API Keys
Create API keys through the dashboard or the REST API (requires JWT authentication):
### Via Dashboard
1. Log in to the [AgentWallex Dashboard](https://app.agentwallex.com).
2. Navigate to **Settings > API Keys**.
3. Click **Create API Key**.
4. Give the key a descriptive name (e.g., `production-backend`, `staging-ci`).
5. Copy and securely store the key — it is only shown once.
### Via API
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/api-keys \
-H "Authorization: Bearer eyJhbGciOi..." \
-H "Content-Type: application/json" \
-d '{"name": "production-backend"}'
```
The full API key is only returned once at creation time. Store it immediately in a secure secrets manager.
## Listing API Keys
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/api-keys \
-H "Authorization: Bearer eyJhbGciOi..."
```
The response includes key metadata but never the full key value:
```json theme={null}
{
"data": [
{
"id": "key_abc123",
"name": "production-backend",
"prefix": "awx_...x4f2",
"created_at": "2025-06-01T10:00:00Z",
"last_used_at": "2025-06-15T14:30:00Z"
}
]
}
```
## Rotating API Keys
Create a new API key via the dashboard or API.
Deploy the new key to your application's environment variables.
Confirm that API calls succeed with the new key.
Remove the old key to prevent unauthorized access:
```bash theme={null}
curl -X DELETE https://api.agentwallex.com/api/v1/api-keys/key_abc123 \
-H "Authorization: Bearer eyJhbGciOi..."
```
Rotate API keys at least every 90 days. Set a calendar reminder or automate rotation with your CI/CD pipeline.
## Rate Limits
API rate limits depend on your plan tier:
| Plan | Requests/min | Requests/day | Concurrent connections |
| ---------- | ------------ | ------------ | ---------------------- |
| Starter | 60 | 10,000 | 5 |
| Growth | 300 | 100,000 | 25 |
| Enterprise | Custom | Custom | Custom |
When you exceed the rate limit, the API returns a `429 Too Many Requests` response with a `Retry-After` header:
```json theme={null}
{
"code": "rate_limit_exceeded",
"type": "rate_limit_error",
"message": "Rate limit exceeded. Retry after 30 seconds."
}
```
Rate limits are applied per API key. If you need higher limits, contact the AgentWallex team or upgrade your plan.
## Best Practices
* **One key per environment** — Use separate keys for development, staging, and production.
* **Name keys descriptively** — Include the environment and service name (e.g., `prod-payment-service`).
* **Monitor usage** — Check `last_used_at` to identify unused keys that should be deleted.
* **Never share keys** — Each team member or service should have its own key.
* **Use a secrets manager** — Store keys in AWS Secrets Manager, HashiCorp Vault, or similar tools rather than in `.env` files on disk.
# Authentication
Source: https://docs.agentwallex.com/introduction/authentication
How to authenticate with the AgentWallex API using API keys or JWT tokens.
## Authentication Methods
AgentWallex supports two authentication methods:
| Method | Header | Use Case |
| ---------------- | ------------------------------ | -------------------------------------- |
| API Key | `X-API-Key: awx_...` | SDK and server-to-server integrations |
| JWT Bearer Token | `Authorization: Bearer eyJ...` | Web app, OAuth, and dashboard sessions |
## API Key Authentication
API keys are the recommended approach for server-side and SDK integrations. Every key starts with the `awx_` prefix.
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/agents \
-H "X-API-Key: awx_your_api_key"
```
Never expose your API key in client-side code, public repositories, or logs. Always load it from environment variables.
### Environment Variables
Store your API key as an environment variable:
```bash .env theme={null}
AGENTWALLEX_API_KEY=awx_your_api_key
```
```typescript TypeScript theme={null}
import { AgentWallex } from "@agentwallex/sdk";
const aw = new AgentWallex({
apiKey: process.env.AGENTWALLEX_API_KEY!,
});
```
```python Python theme={null}
import os
from agentwallex import AgentWallex
aw = AgentWallex(api_key=os.environ["AGENTWALLEX_API_KEY"])
```
## JWT Bearer Token Authentication
For web applications and OAuth flows, use JWT bearer tokens. Tokens are obtained through the Google OAuth flow:
Redirect the user to the Google OAuth endpoint:
```
GET /auth/google/redirect
```
After authentication, Google redirects to your callback URL with a one-time code:
```
GET /auth/google/callback
```
Exchange the one-time code for access and refresh tokens:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/auth/exchange \
-H "Content-Type: application/json" \
-d '{"exchange_code": "one_time_code"}'
```
Include the access token in the `Authorization` header:
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/agents \
-H "Authorization: Bearer eyJhbGciOi..."
```
### Refreshing Tokens
Access tokens expire. Use the refresh token to obtain a new access token:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/auth/refresh \
-H "Content-Type: application/json" \
-d '{"refresh_token": "your_refresh_token"}'
```
### Logout
Invalidate the current session:
```bash theme={null}
curl -X POST https://api.agentwallex.com/api/v1/auth/logout \
-H "Authorization: Bearer eyJhbGciOi..."
```
## Security Best Practices
Follow these practices to keep your integration secure.
* **Use environment variables** — Never hardcode API keys in source code.
* **Rotate keys regularly** — Rotate API keys at least every 90 days. See [API Keys](/introduction/api-keys) for rotation instructions.
* **Use the minimum scope needed** — Create separate API keys per environment (sandbox vs. production).
* **Enable IP allowlisting** — Available on Growth and Enterprise plans to restrict API access to known IPs.
* **Monitor audit logs** — Review authentication events in the dashboard or via `GET /audit-logs`.
* **Use sandbox for development** — Never test with production keys or real funds.
# What is AgentWallex?
Source: https://docs.agentwallex.com/introduction/overview
MPC-secured payment gateway for AI agents — send on-chain payments without exposing private keys.
## Overview
AgentWallex is an MPC-secured wallet infrastructure and payment gateway purpose-built for AI agents. It enables autonomous agents to transact on-chain — sending payments, paying for APIs, and managing funds — without ever exposing private keys.
Built on [Paratro](https://paratro.com)'s 2-of-3 threshold MPC protocol, AgentWallex ensures that no single party ever holds a complete private key. A configurable policy engine evaluates every transaction before it reaches the signing layer, giving developers fine-grained control over what their agents can do.
## How It Works
Your AI agent calls the AgentWallex SDK or REST API with transaction details (recipient, amount, token).
The request passes through the policy engine, which checks spending limits, address whitelists, token restrictions, velocity controls, and schedule rules.
If the policy check passes, the transaction is signed using 2-of-3 threshold MPC. The full private key is never reconstructed in memory.
The signed transaction is submitted to the blockchain. AgentWallex monitors confirmation and delivers a webhook event when complete.
## Supported Providers and Chains
| Chain | Chain ID | Status | Tokens |
| ---------------------- | ---------------- | ----------- | ----------------- |
| Ethereum | `eip155:1` | Active | ETH, USDC, USDT |
| Base | `eip155:8453` | Active | ETH, USDC |
| Polygon | `eip155:137` | Active | MATIC, USDC, USDT |
| BNB Smart Chain | `eip155:56` | Active | BNB, USDC, USDT |
| Tron | `tron:mainnet` | Active | TRX, USDT |
| Bitcoin | `bip122:mainnet` | Active | BTC |
| Base Sepolia (testnet) | `eip155:84532` | Active | ETH, USDC |
| Solana | `solana:mainnet` | Coming Soon | SOL, USDC |
| Avalanche | `eip155:43114` | Coming Soon | AVAX, USDC |
| Arbitrum | `eip155:42161` | Coming Soon | ETH, USDC |
## Key Features
2-of-3 threshold signing powered by Paratro. No single party ever holds the full key.
Per-agent spending limits, address whitelists, velocity controls, and human approval routing.
Pay-per-API-call using the HTTP 402 protocol. Session budgets and automatic payment negotiation.
Real-time notifications for payments, policy violations, agent status changes, and more.
## Next Steps
Integrate AgentWallex in under 5 minutes.
Set up API keys and authentication.
Full REST API documentation.
Get started with the official TypeScript SDK.
# Quickstart
Source: https://docs.agentwallex.com/introduction/quickstart
Integrate AgentWallex in under 5 minutes — create an agent wallet and send your first payment.
## Prerequisites
* Node.js 18+ or Python 3.9+
* An AgentWallex API key (`awx_...`) — [sign up for early access](https://agentwallex.com)
* Basic understanding of blockchain transactions
## Installation
```bash npm theme={null}
npm install @agentwallex/sdk
```
```bash yarn theme={null}
yarn add @agentwallex/sdk
```
```bash pnpm theme={null}
pnpm add @agentwallex/sdk
```
```bash pip theme={null}
pip install agentwallex
```
## Step-by-Step Integration
Create an AgentWallex client with your API key. Use `sandbox` for testing and `production` for mainnet.
```typescript TypeScript theme={null}
import { AgentWallex } from "@agentwallex/sdk";
const aw = new AgentWallex({
apiKey: process.env.AGENTWALLEX_API_KEY!,
environment: "sandbox", // use "production" for mainnet
});
```
```python Python theme={null}
from agentwallex import AgentWallex
aw = AgentWallex(
api_key=os.environ["AGENTWALLEX_API_KEY"],
environment="sandbox", # use "production" for mainnet
)
```
Each agent gets its own MPC-secured wallet with configurable policies.
```typescript TypeScript theme={null}
const agent = await aw.agents.create({
name: "my-trading-agent",
chain: "eip155:84532",
policies: {
maxTransactionAmount: "100", // USDC
dailyLimit: "1000",
allowedAddresses: ["0x..."],
},
});
console.log(`Agent ID: ${agent.id}`);
console.log(`Wallet: ${agent.wallet.address}`);
```
```python Python theme={null}
agent = await aw.agents.create(
name="my-trading-agent",
chain="eip155:84532",
policies={
"max_transaction_amount": "100",
"daily_limit": "1000",
"allowed_addresses": ["0x..."],
},
)
print(f"Agent ID: {agent.id}")
print(f"Wallet: {agent.wallet.address}")
```
Send testnet tokens to your agent's wallet address. On Base Sepolia, you can use a [faucet](https://www.coinbase.com/faucets/base-ethereum-goerli-faucet) to get test USDC.
In sandbox mode, your agent wallet is on a testnet. No real funds are at risk.
Execute an on-chain payment through the agent.
```typescript TypeScript theme={null}
const tx = await aw.payments.send({
agentId: agent.id,
to: "0xRecipientAddress",
amount: "10.00",
token: "USDC",
});
console.log(`Transaction hash: ${tx.hash}`);
console.log(`Status: ${tx.status}`); // "confirmed"
```
```python Python theme={null}
tx = await aw.payments.send(
agent_id=agent.id,
to="0xRecipientAddress",
amount="10.00",
token="USDC",
)
print(f"Transaction hash: {tx.hash}")
print(f"Status: {tx.status}") # "confirmed"
```
## What Happens Under the Hood
1. **Policy Check** — The policy engine validates the transaction against your agent's rules (spending limits, address whitelist, velocity controls).
2. **MPC Signing** — The transaction is signed using 2-of-3 threshold MPC. No single party ever holds the full key.
3. **Broadcast** — The signed transaction is submitted to the network.
4. **Confirmation** — AgentWallex monitors and confirms the transaction, then delivers a webhook event.
## Next Steps
Full SDK reference with all methods and types.
HTTP endpoints for custom integrations.
Enable pay-per-API-call for your agents.
Configure spending controls and security rules.
# Why AgentWallex?
Source: https://docs.agentwallex.com/introduction/why-agentwallex
The problems AgentWallex solves and what makes it different from traditional wallet solutions.
## The Problem
AI agents are increasingly autonomous — they browse the web, call APIs, and make decisions. But when an agent needs to **pay** for something, the options are limited and dangerous:
* **Giving agents private keys** means a single prompt injection or bug can drain the wallet entirely.
* **Human-in-the-loop for every payment** defeats the purpose of autonomous agents.
* **Traditional wallet infrastructure** was designed for humans clicking buttons, not machines making thousands of decisions per hour.
Storing private keys in agent memory or environment variables is the number one cause of AI agent fund loss. A compromised agent with a private key has unlimited access to all funds.
## What AgentWallex Does Differently
### No Private Key Exposure
AgentWallex uses 2-of-3 threshold MPC signing via Paratro. The full private key is **never reconstructed** — not in memory, not on disk, not anywhere. Even if your agent or API key is compromised, the attacker cannot sign transactions alone.
### Policy Engine as a Safety Net
Every transaction passes through a configurable policy engine before signing. Set per-agent limits on:
* **Transaction amount** — cap individual payments
* **Daily and monthly totals** — rolling spending limits
* **Allowed addresses** — whitelist trusted recipients
* **Token restrictions** — limit to stablecoins only
* **Velocity controls** — prevent runaway transaction loops
* **Time-based rules** — restrict to business hours
* **Human approval** — route high-value transactions to human review
### Infrastructure Safety Net
Even if your business-layer policies are misconfigured, Paratro enforces hard limits at the MPC signing level that **cannot be overridden** by API calls:
| Control | Default |
| ------------------ | ------------------------- |
| Absolute daily cap | \$50,000 |
| Anomaly detection | ML-based, always on |
| Emergency freeze | Instant, always available |
| Cool-down period | 10 min after freeze |
### x402 Native Support
AgentWallex natively supports the x402 machine-to-machine payment protocol. Your agents can automatically negotiate and pay for API access using HTTP 402 headers — no human intervention needed.
## Who Uses AgentWallex
Teams building autonomous agents that need to transact on-chain — paying for data, APIs, or services.
Services that want to monetize their APIs using x402 micropayments with instant on-chain settlement.
Projects that need secure, policy-controlled wallet infrastructure for programmatic on-chain operations.
## Key Differentiators
| Feature | Traditional Wallets | AgentWallex |
| ----------------- | ------------------------ | -------------------------- |
| Key storage | Single private key | 2-of-3 MPC shards |
| Access control | All-or-nothing | Per-agent policies |
| Payment protocols | Manual tx signing | x402 automatic negotiation |
| Spending limits | None (or contract-level) | Configurable per agent |
| Human oversight | None or full | Threshold-based routing |
| Audit trail | Block explorer only | Full API + policy logs |
| Multi-chain | Per-wallet | Single API, many chains |
## Next Steps
Get your first agent transacting in under 5 minutes.
Deep dive into the four security layers.
# Security Architecture
Source: https://docs.agentwallex.com/platform/architecture
Four layers of security — identity, policy engine, MPC signing, and human-in-the-loop — protect your agents.
## Overview
AgentWallex is built on the principle that AI agents should **never have access to private keys**. Instead, transactions are signed using Multi-Party Computation (MPC), where no single party ever holds the complete key.
The platform enforces security through four independent layers. A transaction must pass through all of them before it is broadcast to the blockchain.
## Four Layers of Security
### Layer 1: Identity and Authentication
Every API request is authenticated using a two-token system:
* **API Key** (`awx_...`) — Long-lived, identifies your account. Store securely in environment variables.
* **Session Token** — Short-lived, scoped to specific agents and operations. Automatically rotated.
```typescript theme={null}
// API key authenticates your account
const aw = new AgentWallex({ apiKey: process.env.AGENTWALLEX_API_KEY! });
// Session tokens are managed internally by the SDK
// Each agent gets its own scoped session
```
**Key properties:**
| Property | Detail |
| ------------------ | --------------------------- |
| Key rotation | Without downtime |
| Session expiry | Configurable: 1-24 hours |
| Permission scoping | Per-agent |
| IP allowlisting | Growth and Enterprise plans |
### Layer 2: Policy Engine
Every transaction must pass through the policy engine before signing. Policies are evaluated in order — the first violation stops the transaction.
The policy engine supports:
* Spending limits (per-transaction, daily, monthly)
* Address whitelists and blacklists
* Token restrictions
* Velocity controls (rate limiting)
* Time-based schedule rules
* Human approval routing
See [Policy Engine](/features/policy-engine) for full configuration details.
### Layer 3: MPC Signing (Paratro)
AgentWallex uses Paratro's 2-of-3 threshold MPC protocol:
| Shard | Holder | Purpose |
| ------- | --------------------------- | -------------- |
| Shard 1 | AgentWallex signing service | Active signing |
| Shard 2 | Independent custodian node | Active signing |
| Shard 3 | Cold storage | Recovery only |
**Critical security properties:**
* The full private key is **never reconstructed** in memory
* Any 2 of 3 shards can sign a transaction
* Compromise of a single shard does not compromise the wallet
* Key generation uses Distributed Key Generation (DKG) — no single party ever sees the full key
### Layer 4: Human-in-the-Loop
For high-value or unusual transactions, AgentWallex can route to human approval:
* Transactions above a configurable threshold
* Transactions to new (unseen) addresses
* Unusual patterns detected by anomaly monitoring
```json theme={null}
{
"event": "approval.requested",
"data": {
"transactionId": "tx_pending_123",
"agentId": "agent_abc123",
"amount": "2500.00",
"reason": "Amount exceeds humanApprovalThreshold (1000)",
"expiresAt": "2025-01-15T11:00:00Z"
}
}
```
Approvals can be handled via the dashboard, API, or webhook integration.
## Two-Layer Policy Architecture
AgentWallex enforces policies at two independent levels:
### Business Layer (Developer-Configured)
Your custom rules — spending limits, whitelists, velocity controls. These are set via the API or dashboard and can be updated at any time.
### Infrastructure Safety Net (Paratro-Enforced)
Hard limits enforced at the MPC signing level that **cannot be overridden** by API calls:
| Control | Default | Description |
| ------------------ | ---------------- | ------------------------------------------ |
| Absolute daily cap | \$50,000 | Hard ceiling regardless of business policy |
| Anomaly detection | Enabled | ML-based pattern analysis |
| Emergency freeze | Always available | Instant wallet lockdown |
| Cool-down period | 10 minutes | After freeze, cannot unfreeze immediately |
Even if your API key is compromised, the infrastructure safety net prevents catastrophic loss. The attacker cannot override Paratro-enforced limits.
## Key Management Lifecycle
### Key Generation
Keys are generated using Distributed Key Generation (DKG). At no point does any party see the full private key:
1. Each of the 3 MPC nodes generates a random share.
2. Shares are combined cryptographically to produce a public key.
3. The corresponding private key exists only as distributed shards.
### Key Rotation
Key shards are rotated periodically without changing the wallet address. This is called "proactive secret sharing" — old shards become useless after rotation.
### Emergency Freeze
Any authorized party can instantly freeze a wallet:
```typescript SDK theme={null}
await aw.agents.freeze("agent_abc123");
```
```bash API theme={null}
curl -X PUT https://api.agentwallex.com/api/v1/agents/agent_abc123/status \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{"status": "inactive"}'
```
Frozen wallets cannot sign any transactions until explicitly unfrozen (with a mandatory cool-down period).
## Audit Logging
Every action is logged immutably:
* All API requests (with IP, user agent, timestamp)
* All policy evaluations (pass/fail with reason)
* All signing operations
* All freeze/unfreeze events
* All webhook deliveries
| Plan | Log Retention |
| ---------- | ------------- |
| Starter | 90 days |
| Growth | 1 year |
| Enterprise | Custom |
Query audit logs via the API:
```bash theme={null}
curl -X GET "https://api.agentwallex.com/api/v1/audit-logs?page_num=1&page_size=20" \
-H "X-API-Key: awx_your_api_key"
```
# Pricing
Source: https://docs.agentwallex.com/platform/pricing
AgentWallex pricing tiers, x402 fee schedule, and plan comparison.
## x402 Fee Tiers
The x402 micropayment protocol uses a tiered fee structure based on transaction amount. Fees are deducted automatically during settlement.
| Transaction Amount | Fee Rate |
| ------------------ | -------- |
| $0 - $10 | 2.0% |
| $10 - $100 | 1.0% |
| $100 - $1,000 | 0.5% |
| \$1,000+ | 0.25% |
Query the current fee schedule programmatically:
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/x402/fees/tiers
```
```json theme={null}
{
"tiers": [
{ "min_amount": "0", "max_amount": "10", "percentage": "2.0" },
{ "min_amount": "10", "max_amount": "100", "percentage": "1.0" },
{ "min_amount": "100", "max_amount": "1000", "percentage": "0.5" },
{ "min_amount": "1000", "max_amount": "", "percentage": "0.25" }
]
}
```
Always use the `/x402/fees/tiers` endpoint to display current rates in your UI rather than hardcoding values.
## Platform Plans
| Feature | Starter | Growth | Enterprise |
| ------------------------ | ---------- | ----------- | ---------- |
| Agent wallets | Up to 10 | Up to 100 | Unlimited |
| API rate limit | 60 req/min | 300 req/min | Custom |
| Daily request limit | 10,000 | 100,000 | Custom |
| x402 sessions | 50 active | 500 active | Unlimited |
| Audit log retention | 90 days | 1 year | Custom |
| IP allowlisting | -- | Included | Included |
| Human approval routing | -- | Included | Included |
| Dedicated support | -- | -- | Included |
| Custom MPC configuration | -- | -- | Included |
| SLA | -- | 99.9% | 99.99% |
## Settlement Parameters
x402 settlement operates on the following defaults:
| Parameter | Value |
| -------------------- | ----------------------- |
| Settlement interval | 300 seconds (5 minutes) |
| Settlement threshold | \$10.00 |
| Max settlement delay | 3,600 seconds (1 hour) |
Settlement parameters can be customized on Enterprise plans. Contact the AgentWallex team for details.
## Direct Transactions
For direct on-chain payments (not x402), AgentWallex charges:
| Type | Fee |
| ------------------- | ----------------------------------- |
| Transaction signing | No platform fee |
| Network gas | Pass-through (paid by agent wallet) |
| Wallet creation | Free |
| Policy evaluation | Free |
AgentWallex does not add a platform fee on top of direct transactions. You only pay the blockchain network gas fee, which is deducted from the agent's wallet balance.
# Supported Chains
Source: https://docs.agentwallex.com/platform/supported-chains
Blockchain networks supported by AgentWallex — active chains, testnets, and upcoming additions.
## Active Chains
AgentWallex currently supports the following blockchain networks for agent wallets and transactions:
| Chain | Chain ID | Type | Supported Tokens |
| --------------- | ---------------- | ----------- | --------------------- |
| Ethereum | `eip155:1` | EVM Mainnet | ETH, USDC, USDT, DAI |
| Base | `eip155:8453` | EVM L2 | ETH, USDC |
| Polygon | `eip155:137` | EVM L2 | MATIC, USDC, USDT |
| BNB Smart Chain | `eip155:56` | EVM Mainnet | BNB, USDC, USDT, BUSD |
| Tron | `tron:mainnet` | Non-EVM | TRX, USDT |
| Bitcoin | `bip122:mainnet` | UTXO | BTC |
## Testnets
Use testnets for development and testing — no real funds at risk:
| Chain | Chain ID | Faucet |
| ---------------- | ----------------- | ------------------------------------------------------------------------------- |
| Base Sepolia | `eip155:84532` | [Coinbase Faucet](https://www.coinbase.com/faucets/base-ethereum-goerli-faucet) |
| Ethereum Sepolia | `eip155:11155111` | [Sepolia Faucet](https://sepoliafaucet.com) |
| Polygon Amoy | `eip155:80002` | [Polygon Faucet](https://faucet.polygon.technology) |
When initializing the SDK with `environment: "sandbox"`, all operations automatically use testnet chain IDs.
## x402 Supported Chains
The x402 micropayment protocol currently supports a subset of chains for payment negotiation and settlement:
| Chain | Chain ID | Settlement Token |
| ---------------------- | -------------- | ---------------- |
| Base Sepolia (testnet) | `eip155:84532` | USDC |
| Base | `eip155:8453` | USDC |
| Ethereum | `eip155:1` | USDC |
| Polygon | `eip155:137` | USDC |
Query the supported chains programmatically:
```bash theme={null}
curl -X GET https://api.agentwallex.com/api/v1/x402/facilitator/supported
```
## Coming Soon
The following chains are on the roadmap:
| Chain | Chain ID | Expected | Notes |
| ----------------- | ---------------- | -------- | ----------------- |
| Solana | `solana:mainnet` | Q2 2026 | SPL token support |
| Avalanche C-Chain | `eip155:43114` | Q2 2026 | EVM compatible |
| Arbitrum One | `eip155:42161` | Q3 2026 | EVM L2 |
Want a chain that is not listed here? Contact the AgentWallex team at [support@agentwallex.com](mailto:support@agentwallex.com) or request it through the dashboard.
## Chain ID Format
AgentWallex uses [CAIP-2](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md) chain identifiers:
* **EVM chains**: `eip155:` (e.g., `eip155:1` for Ethereum mainnet)
* **Bitcoin**: `bip122:mainnet`
* **Tron**: `tron:mainnet`
* **Solana** (coming soon): `solana:mainnet`
When creating agents or transactions, always use the full CAIP-2 chain ID:
```typescript theme={null}
const agent = await aw.agents.create({
name: "my-agent",
chain: "eip155:8453", // Base mainnet
});
```
# SDK Overview
Source: https://docs.agentwallex.com/sdks/overview
Official AgentWallex SDKs for TypeScript and Python — feature matrix and installation.
## Official SDKs
AgentWallex provides official SDKs for the two most popular languages in AI agent development:
`@agentwallex/sdk` on npm. Full-featured with TypeScript types, x402 HTTP interceptor, and async/await support.
`agentwallex` on PyPI. Native async support, typed models, and full API coverage.
## Quick Install
```bash npm theme={null}
npm install @agentwallex/sdk
```
```bash yarn theme={null}
yarn add @agentwallex/sdk
```
```bash pip theme={null}
pip install agentwallex
```
## Feature Matrix
| Feature | TypeScript | Python |
| ------------------------------------ | ---------- | ------ |
| Agent CRUD | Yes | Yes |
| Send payments | Yes | Yes |
| Policy management | Yes | Yes |
| x402 pay | Yes | Yes |
| x402 session management | Yes | Yes |
| x402 HTTP interceptor | Yes | Yes |
| Webhook management | Yes | Yes |
| Typed error classes | Yes | Yes |
| Async/await | Yes | Yes |
| TypeScript types / Python type hints | Yes | Yes |
| Sandbox + production environments | Yes | Yes |
| Custom timeout configuration | Yes | Yes |
| Automatic retry with backoff | Yes | Yes |
## Minimum Requirements
| SDK | Runtime | Version |
| ---------- | ------- | ------- |
| TypeScript | Node.js | 18+ |
| Python | CPython | 3.9+ |
## REST API
If your language is not listed above, you can use the [REST API](/api-reference/overview) directly. The API is fully documented with request/response examples for every endpoint.
Community SDKs for Go, Rust, and Java are on the roadmap. If you are interested in contributing, reach out at [support@agentwallex.com](mailto:support@agentwallex.com).
# Python SDK
Source: https://docs.agentwallex.com/sdks/python
Complete reference for the agentwallex Python package — async-first with full API coverage.
## Installation
```bash theme={null}
pip install agentwallex
```
**Requirements:** Python 3.9+
## Client Initialization
```python theme={null}
import os
from agentwallex import AgentWallex
aw = AgentWallex(
api_key=os.environ["AGENTWALLEX_API_KEY"],
environment="sandbox", # "sandbox" or "production"
timeout=30, # Request timeout in seconds (default: 30)
)
```
| Parameter | Type | Default | Description |
| ------------- | ----- | ----------- | --------------------------------------- |
| `api_key` | `str` | Required | Your API key (`awx_...`) |
| `environment` | `str` | `"sandbox"` | `"sandbox"` or `"production"` |
| `base_url` | `str` | `None` | Custom base URL (overrides environment) |
| `timeout` | `int` | `30` | Request timeout in seconds |
The Python SDK is fully async. All methods return coroutines and should be awaited.
## Agents
### `aw.agents.create()`
Create a new agent with an MPC-secured wallet.
```python theme={null}
agent = await aw.agents.create(
name="my-agent",
chain="eip155:8453",
policies={
"max_transaction_amount": "100",
"daily_limit": "1000",
"allowed_addresses": ["0x..."],
"allowed_tokens": ["USDC"],
},
metadata={"team": "growth"},
)
print(f"Agent ID: {agent.id}")
print(f"Wallet: {agent.wallet.address}")
```
### `aw.agents.get(agent_id)`
```python theme={null}
agent = await aw.agents.get("agent_abc123")
```
### `aw.agents.list()`
```python theme={null}
result = await aw.agents.list(
limit=20,
offset=0,
status="active",
)
for agent in result.agents:
print(f"{agent.name}: {agent.wallet.address}")
```
### `aw.agents.freeze(agent_id)` / `aw.agents.unfreeze(agent_id)`
```python theme={null}
# Freeze — immediate
await aw.agents.freeze("agent_abc123")
# Unfreeze — subject to 10-minute cool-down
await aw.agents.unfreeze("agent_abc123")
```
## Payments
### `aw.payments.send()`
Send a direct on-chain payment.
```python theme={null}
tx = await aw.payments.send(
agent_id="agent_abc123",
to="0xRecipientAddress",
amount="50.00",
token="USDC",
memo="Payment for API access",
)
print(f"Hash: {tx.hash}")
print(f"Status: {tx.status}")
print(f"Fee: {tx.fee}")
```
### `aw.payments.get(transaction_id)`
```python theme={null}
tx = await aw.payments.get("tx_xyz789")
```
### `aw.payments.list()`
```python theme={null}
result = await aw.payments.list(
agent_id="agent_abc123",
limit=50,
status="confirmed",
)
for tx in result.transactions:
print(f"{tx.amount} {tx.token} -> {tx.status}")
```
## x402 Micropayments
### `aw.x402.create_session()`
```python theme={null}
session = await aw.x402.create_session(
agent_id="agent_abc123",
budget_limit="100.00",
chain="eip155:84532",
ttl_seconds=3600,
allowed_urls=["https://paid-api.example.com/v1/data"],
)
```
### `aw.x402.check()`
```python theme={null}
info = await aw.x402.check(url="https://paid-api.example.com/v1/data")
```
### `aw.x402.pay()`
```python theme={null}
result = await aw.x402.pay(
agent_id="agent_abc123",
target_url="https://paid-api.example.com/v1/data",
session_id=session.id,
chain="eip155:84532",
)
```
### `aw.x402.session_pay(session_id, target_url)`
```python theme={null}
await aw.x402.session_pay(
session.id,
target_url="https://paid-api.example.com/v1/data",
)
```
### `aw.x402.http_interceptor()`
Create an interceptor that automatically handles x402 v2 challenges:
```python theme={null}
fetch_with_payment = aw.x402.http_interceptor(
agent_id="agent_abc123",
chain="eip155:84532",
)
# Automatically handles 402 -> pay -> retry
response = await fetch_with_payment("https://paid-api.example.com/v1/data")
data = response.json()
```
## Policies
### `aw.policies.update()`
```python theme={null}
await aw.policies.update(
"agent_abc123",
max_transaction_amount="200",
daily_limit="2000",
allowed_addresses=["0xAddr1", "0xAddr2"],
velocity_limit={"max_count": 100, "window_seconds": 3600},
)
```
### `aw.policies.get(agent_id)`
```python theme={null}
policies = await aw.policies.get("agent_abc123")
```
### `aw.policies.apply_template()`
```python theme={null}
await aw.policies.apply_template("agent_abc123", "conservative")
```
## Webhooks
### `aw.webhooks.create()`
```python theme={null}
webhook = await aw.webhooks.create(
url="https://your-app.com/webhooks/agentwallex",
events=[
"payment.completed",
"payment.failed",
"agent.frozen",
"policy.violated",
],
secret="whsec_your_signing_secret",
)
```
## Error Handling
```python theme={null}
from agentwallex import AgentWallexError, PolicyViolationError
try:
tx = await aw.payments.send(
agent_id="agent_abc123",
to="0xRecipientAddress",
amount="50.00",
token="USDC",
)
except PolicyViolationError as e:
print(f"Policy violated: {e.rule}")
print(f"Details: {e.message}")
except AgentWallexError as e:
print(f"API error [{e.code}]: {e.message}")
except Exception as e:
print(f"Unexpected error: {e}")
```
| Error Class | When Raised |
| ---------------------- | ------------------------------------ |
| `AgentWallexError` | Base class for all API errors |
| `PolicyViolationError` | Transaction blocked by policy engine |
| `AuthenticationError` | Invalid or missing API key |
| `NotFoundError` | Resource does not exist |
| `RateLimitError` | Rate limit exceeded |
## Type Hints
The Python SDK includes full type hints for IDE support and static analysis:
```python theme={null}
from agentwallex.types import (
Agent,
Payment,
Transaction,
Policy,
X402Session,
WebhookEvent,
)
```
## Usage with asyncio
The SDK is async-first. Use it within an async context:
```python theme={null}
import asyncio
from agentwallex import AgentWallex
async def main():
aw = AgentWallex(api_key="awx_your_api_key", environment="sandbox")
agent = await aw.agents.create(
name="my-agent",
chain="eip155:84532",
)
print(f"Created agent: {agent.id}")
asyncio.run(main())
```
# TypeScript SDK
Source: https://docs.agentwallex.com/sdks/typescript
Complete reference for the @agentwallex/sdk package — agents, payments, x402, policies, and webhooks.
## Installation
```bash npm theme={null}
npm install @agentwallex/sdk
```
```bash yarn theme={null}
yarn add @agentwallex/sdk
```
```bash pnpm theme={null}
pnpm add @agentwallex/sdk
```
## Client Initialization
```typescript theme={null}
import { AgentWallex } from "@agentwallex/sdk";
const aw = new AgentWallex({
apiKey: process.env.AGENTWALLEX_API_KEY!,
environment: "sandbox", // "sandbox" | "production"
baseUrl: undefined, // Custom endpoint (optional)
timeout: 30000, // Request timeout in ms (default: 30000)
});
```
| Parameter | Type | Default | Description |
| ------------- | --------------------------- | ----------- | --------------------------------------- |
| `apiKey` | `string` | Required | Your API key (`awx_...`) |
| `environment` | `"sandbox" \| "production"` | `"sandbox"` | Target environment |
| `baseUrl` | `string` | -- | Custom base URL (overrides environment) |
| `timeout` | `number` | `30000` | Request timeout in milliseconds |
## Agents
### `aw.agents.create(params)`
Create a new agent with an MPC-secured wallet.
```typescript theme={null}
const agent = await aw.agents.create({
name: "my-agent",
chain: "eip155:8453",
policies: {
maxTransactionAmount: "100",
dailyLimit: "1000",
allowedAddresses: ["0x..."],
allowedTokens: ["USDC"],
requireHumanApproval: false,
},
metadata: { team: "growth" },
});
```
**Returns:**
| Field | Type | Description |
| ---------------- | -------- | ------------------------ |
| `id` | `string` | Unique agent identifier |
| `name` | `string` | Agent display name |
| `wallet.address` | `string` | On-chain wallet address |
| `wallet.chain` | `string` | CAIP-2 chain identifier |
| `status` | `string` | `"active"` or `"frozen"` |
| `createdAt` | `string` | ISO 8601 timestamp |
### `aw.agents.get(agentId)`
Retrieve an agent by ID.
```typescript theme={null}
const agent = await aw.agents.get("agent_abc123");
```
### `aw.agents.list(params?)`
List all agents for your account.
```typescript theme={null}
const { agents, pagination } = await aw.agents.list({
limit: 20,
offset: 0,
status: "active",
});
```
### `aw.agents.freeze(agentId)`
Immediately freeze an agent's wallet, preventing all transactions.
```typescript theme={null}
await aw.agents.freeze("agent_abc123");
```
### `aw.agents.unfreeze(agentId)`
Re-enable an agent's wallet after a freeze (subject to 10-minute cool-down).
```typescript theme={null}
await aw.agents.unfreeze("agent_abc123");
```
## Payments
### `aw.payments.send(params)`
Send a direct on-chain payment.
```typescript theme={null}
const tx = await aw.payments.send({
agentId: "agent_abc123",
to: "0xRecipientAddress",
amount: "50.00",
token: "USDC",
memo: "Payment for API access",
});
```
**Returns:**
| Field | Type | Description |
| -------- | -------- | -------------------------------------- |
| `id` | `string` | Transaction ID |
| `hash` | `string` | On-chain transaction hash |
| `status` | `string` | `"pending"`, `"confirmed"`, `"failed"` |
| `amount` | `string` | Amount sent |
| `token` | `string` | Token symbol |
| `fee` | `string` | Network gas fee paid |
### `aw.payments.get(transactionId)`
Get transaction details and status.
```typescript theme={null}
const tx = await aw.payments.get("tx_xyz789");
```
### `aw.payments.list(params)`
List transactions for an agent.
```typescript theme={null}
const { transactions } = await aw.payments.list({
agentId: "agent_abc123",
limit: 50,
status: "confirmed",
});
```
## x402 Micropayments
### `aw.x402.createSession(params)`
Create an x402 payment session with a spending budget.
```typescript theme={null}
const session = await aw.x402.createSession({
agentId: "agent_abc123",
budgetLimit: "100.00",
chain: "eip155:84532",
ttlSeconds: 3600,
allowedUrls: ["https://paid-api.example.com/v1/data"],
});
```
### `aw.x402.check(params)`
Check whether a target URL supports x402 payment negotiation.
```typescript theme={null}
const info = await aw.x402.check({
url: "https://paid-api.example.com/v1/data",
});
```
### `aw.x402.pay(params)`
Negotiate and complete one x402 payment.
```typescript theme={null}
const result = await aw.x402.pay({
agentId: "agent_abc123",
targetUrl: "https://paid-api.example.com/v1/data",
sessionId: session.id, // optional
chain: "eip155:84532", // optional
});
```
### `aw.x402.sessionPay(sessionId, params)`
Pay using an existing session budget.
```typescript theme={null}
await aw.x402.sessionPay(session.id, {
targetUrl: "https://paid-api.example.com/v1/data",
});
```
### `aw.x402.httpInterceptor(params)`
Create an HTTP fetch wrapper that automatically handles x402 v2 challenges:
```typescript theme={null}
const fetchWithPayment = aw.x402.httpInterceptor({
agentId: "agent_abc123",
chain: "eip155:84532",
});
// Automatically handles 402 -> pay -> retry flow
const response = await fetchWithPayment("https://paid-api.example.com/v1/data");
const data = await response.json();
```
The interceptor:
1. Reads the `PAYMENT-REQUIRED` header from a 402 response
2. Submits payment via AgentWallex
3. Retries the request with the `PAYMENT-SIGNATURE` header
## Policies
### `aw.policies.update(agentId, policies)`
Update an agent's spending policies.
```typescript theme={null}
await aw.policies.update("agent_abc123", {
maxTransactionAmount: "200",
dailyLimit: "2000",
allowedAddresses: ["0xAddr1", "0xAddr2"],
velocityLimit: { maxCount: 100, windowSeconds: 3600 },
});
```
### `aw.policies.get(agentId)`
Get current policies for an agent.
```typescript theme={null}
const policies = await aw.policies.get("agent_abc123");
```
### `aw.policies.applyTemplate(agentId, templateName)`
Apply a policy template to an agent.
```typescript theme={null}
await aw.policies.applyTemplate("agent_abc123", "conservative");
```
### `aw.policies.createTemplate(name, rules)`
Create a reusable policy template.
```typescript theme={null}
await aw.policies.createTemplate("my-template", {
maxTransactionAmount: "200",
dailyLimit: "2000",
allowedTokens: ["USDC"],
velocityLimit: { maxCount: 50, windowSeconds: 3600 },
});
```
## Webhooks
### `aw.webhooks.create(params)`
Register a webhook endpoint.
```typescript theme={null}
const webhook = await aw.webhooks.create({
url: "https://your-app.com/webhooks/agentwallex",
events: [
"payment.completed",
"payment.failed",
"agent.frozen",
"policy.violated",
],
secret: "whsec_your_signing_secret",
});
```
## Error Handling
The SDK provides typed error classes:
```typescript theme={null}
import {
AgentWallexError,
PolicyViolationError,
} from "@agentwallex/sdk";
try {
await aw.payments.send({ ... });
} catch (error) {
if (error instanceof PolicyViolationError) {
console.log(`Policy violated: ${error.rule}`);
console.log(`Details: ${error.message}`);
} else if (error instanceof AgentWallexError) {
console.log(`API error: ${error.code} - ${error.message}`);
}
}
```
| Error Class | When Thrown |
| ---------------------- | ------------------------------------ |
| `AgentWallexError` | Base class for all API errors |
| `PolicyViolationError` | Transaction blocked by policy engine |
| `AuthenticationError` | Invalid or missing API key |
| `NotFoundError` | Resource does not exist |
| `RateLimitError` | Rate limit exceeded |
## TypeScript Types
All types are exported from the package:
```typescript theme={null}
import type {
Agent,
Payment,
Transaction,
Policy,
X402Session,
WebhookEvent,
} from "@agentwallex/sdk";
```