> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentwallex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Tài liệu tham khảo đầy đủ cho gói agentwallex Python — async-first với phủ sóng API đầy đủ.

## Cài đặt

```bash theme={null}
pip install agentwallex
```

**Yêu cầu:** Python 3.9+

## Khởi tạo Client

```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)
)
```

| Tham số       | Kiểu  | Mặc định    | Mô tả                                    |
| ------------- | ----- | ----------- | ---------------------------------------- |
| `api_key`     | `str` | Bắt buộc    | Khóa API của bạn (`awx_...`)             |
| `environment` | `str` | `"sandbox"` | `"sandbox"` hoặc `"production"`          |
| `base_url`    | `str` | `None`      | URL cơ sở tùy chỉnh (ghi đè environment) |
| `timeout`     | `int` | `30`        | Timeout yêu cầu tính bằng giây           |

<Note>
  SDK Python hoàn toàn async. Tất cả phương thức trả về coroutine và cần được await.
</Note>

## Tác nhân

### `aw.agents.create()`

Tạo tác nhân mới với ví MPC được bảo mật.

```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")
```

## Thanh toán

### `aw.payments.send()`

Gửi thanh toán on-chain trực tiếp.

```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}")
```

## Thanh toán nhỏ x402

### `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()`

Tạo bộ chặn tự động xử lý thách thức x402 v2:

```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()
```

## Chính sách

### `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")
```

## Webhook

### `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",
)
```

## Xử lý Lỗi

```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}")
```

| Lớp Lỗi                | Khi nào được ném                         |
| ---------------------- | ---------------------------------------- |
| `AgentWallexError`     | Lớp cơ sở cho tất cả lỗi API             |
| `PolicyViolationError` | Giao dịch bị chặn bởi công cụ chính sách |
| `AuthenticationError`  | Khóa API không hợp lệ hoặc bị thiếu      |
| `NotFoundError`        | Tài nguyên không tồn tại                 |
| `RateLimitError`       | Vượt quá giới hạn tốc độ                 |

## Type Hints

SDK Python bao gồm type hints đầy đủ cho hỗ trợ IDE và phân tích tĩnh:

```python theme={null}
from agentwallex.types import (
    Agent,
    Payment,
    Transaction,
    Policy,
    X402Session,
    WebhookEvent,
)
```

## Sử dụng với asyncio

SDK là async-first. Sử dụng trong ngữ cảnh async:

```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())
```
