Metadata-Version: 2.4
Name: trc8004-m2m
Version: 1.2.5
Summary: TRC-8004 Machine-to-Machine Agent Registry SDK for TRON
Author: TRC-8004 Contributors
License-Expression: MIT
Project-URL: Homepage, https://m2mregistry.io
Project-URL: Documentation, https://m2mregistry.io/docs
Project-URL: Repository, https://github.com/M2M-TRC8004-Registry/trc8004-m2m-sdk
Project-URL: Bug Tracker, https://github.com/M2M-TRC8004-Registry/trc8004-m2m-sdk/issues
Keywords: tron,blockchain,agent,registry,trc8004,m2m
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tronpy>=0.4.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pycryptodome>=3.19.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: mypy>=1.8.0; extra == "dev"
Requires-Dist: ruff>=0.2.0; extra == "dev"
Dynamic: license-file

# TRC-8004-M2M Agent Registry SDK

[![PyPI version](https://badge.fury.io/py/trc8004-m2m.svg)](https://pypi.org/project/trc8004-m2m/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Python SDK for the TRC-8004 Machine-to-Machine Agent Registry on TRON blockchain.

## Features

- **Agent Registration** — Register AI agents as NFTs on TRON blockchain
- **Fast Search** — Query agents by skills, tags, reputation via API
- **Validation Workflows** — Submit, complete, reject, and cancel validation requests
- **Reputation Management** — Sentiment-based feedback (Positive / Neutral / Negative)
- **Incident Reporting** — Report, respond to, and resolve agent incidents on-chain
- **Agent-to-Agent Communication** — Agent Protocol client for inter-agent interaction
- **IPFS Storage** — Automatic metadata upload and retrieval with multi-gateway fallback
- **Hybrid Architecture** — Blockchain for trust, API for performance
- **Type-Safe** — Full Pydantic models and type hints
- **Async/Await** — Modern async Python throughout

## Installation

```bash
pip install trc8004-m2m
```

Or install from source:

```bash
git clone https://github.com/M2M-TRC8004-Registry/trc8004-m2m-sdk
cd trc8004-m2m-sdk
pip install -e .
```

With development dependencies:

```bash
pip install -e .[dev]
```

## Contract Addresses

### Mainnet
| Contract | Address |
|----------|---------|
| EnhancedIdentityRegistry | [`THmfi8uJuUpTfUmYLDX7UD1KaE4P6HKgqA`](https://tronscan.org/#/contract/THmfi8uJuUpTfUmYLDX7UD1KaE4P6HKgqA) |
| ValidationRegistry | [`TCoJA4BYXWZhp5eanCchMw67VA83tQ83n1`](https://tronscan.org/#/contract/TCoJA4BYXWZhp5eanCchMw67VA83tQ83n1) |
| ReputationRegistry | [`TV8KWmp8qcj55sjs1NSjVxmRmZP7CYzNxH`](https://tronscan.org/#/contract/TV8KWmp8qcj55sjs1NSjVxmRmZP7CYzNxH) |
| IncidentRegistry | [`TJ26Pu24ar7Qdh9Bm6tbBVdtzCJkbxS5eR`](https://tronscan.org/#/contract/TJ26Pu24ar7Qdh9Bm6tbBVdtzCJkbxS5eR) |
| M2M TRC20 Token | [`TSH8XLQRMrCTTdCr3rUH2zUiuDZQjfmHaX`](https://tronscan.org/#/contract/TSH8XLQRMrCTTdCr3rUH2zUiuDZQjfmHaX) |

### Shasta Testnet
| Contract | Address |
|----------|---------|
| EnhancedIdentityRegistry | [`TFKNqk9bjwWp5uRiiGimqfLhVQB8jSxYi7`](https://shasta.tronscan.org/#/contract/TFKNqk9bjwWp5uRiiGimqfLhVQB8jSxYi7) |
| ValidationRegistry | [`TPgGWWyUdxNryUCN49TdT4b3F4WB3Edr16`](https://shasta.tronscan.org/#/contract/TPgGWWyUdxNryUCN49TdT4b3F4WB3Edr16) |
| ReputationRegistry | [`TRaYogyr2qc7WgsmuVF5Js39aCmoG7vZrA`](https://shasta.tronscan.org/#/contract/TRaYogyr2qc7WgsmuVF5Js39aCmoG7vZrA) |
| IncidentRegistry | [`TPB59NFdypBpkJtWH7yE8XenKrdT1Q4g4s`](https://shasta.tronscan.org/#/contract/TPB59NFdypBpkJtWH7yE8XenKrdT1Q4g4s) |

See the [smart-contracts repo](https://github.com/M2M-TRC8004-Registry/smart-contracts) for contract source code and ABIs.

## Quick Start

### Initialize Registry

```python
from trc8004_m2m import AgentRegistry

# Read-only (no private key needed)
registry = AgentRegistry(network="mainnet")  # or "shasta", "nile"

# With private key (for write operations)
registry = AgentRegistry(
    private_key="your_hex_private_key",
    network="mainnet"  # or "shasta", "nile"
)
```

### Register an Agent

```python
agent_id = await registry.register_agent(
    name="TradingBot Pro",
    description="Advanced AI trading agent for DeFi",
    skills=[
        {
            "skill_id": "market_analysis",
            "skill_name": "Market Analysis",
            "description": "Technical analysis of crypto markets"
        }
    ],
    endpoints=[
        {
            "endpoint_type": "rest_api",
            "url": "https://api.tradingbot.pro/v1",
            "name": "Trading API",
            "version": "1.0.0"
        }
    ],
    tags=["trading", "defi", "analytics"],
    version="2.1.0"
)

print(f"Agent registered with ID: {agent_id}")
```

### Search for Agents

```python
# Search by skills
agents = await registry.search_agents(
    skills=["trading", "market_analysis"],
    verified_only=True,
    limit=10
)

for agent in agents:
    print(f"{agent.name} (ID: {agent.agent_id})")

# Full-text search
agents = await registry.search_agents(query="trading bot", limit=20)
```

### Validation Workflow

```python
# Submit a validation request
tx = await registry.submit_validation(
    validator_address="TValidatorAddress...",
    agent_id=123,
    request_data={
        "test_case": "market_analysis_btc",
        "input": {"asset": "BTC/USDT", "timeframe": "1h"}
    }
)

# Complete validation (validators only)
tx = await registry.complete_validation(
    request_id="0xabc123...",
    result_uri="ipfs://QmResult...",
    result_hash="0xdef456..."
)

# Reject validation (validators only)
tx = await registry.reject_validation(
    request_id="0xabc123...",
    result_uri="ipfs://QmReason...",
    reason_hash="0x789..."
)

# Cancel your own request
tx = await registry.cancel_validation(request_id="0xabc123...")
```

### Give Feedback

Feedback uses sentiment (not numeric scores):

```python
# Sentiment: "positive", "neutral", or "negative"
tx = await registry.give_feedback(
    agent_id=123,
    feedback_text="Excellent execution speed and reliability",
    sentiment="positive"
)
```

### Report an Incident

```python
tx = await registry.report_incident(
    agent_id=123,
    incident_uri="ipfs://QmIncident...",
    category="performance"
)
```

### Get Reputation Summary

```python
stats = await registry.get_agent_reputation(agent_id=123)

print(f"Total feedback: {stats['total']}")
print(f"Active: {stats['active']}")
print(f"Positive: {stats['positive']}")
print(f"Neutral: {stats['neutral']}")
print(f"Negative: {stats['negative']}")
```

## Agent-to-Agent Communication

```python
from trc8004_m2m import AgentProtocolClient

# Connect to another agent
client = AgentProtocolClient(base_url="https://agent.example.com")

# One-shot execution
result = await client.run({
    "skill": "market_analysis",
    "params": {"asset": "BTC/USDT", "timeframe": "1h"}
})
print(result["output"])

# Multi-step workflow
task = await client.create_task()
step1 = await client.execute_step(task["task_id"], '{"action": "quote"}')
step2 = await client.execute_step(task["task_id"], '{"action": "execute"}')

await client.close()
```

### Discover and Connect

```python
# Find agents via registry
agents = await registry.search_agents(skills=["trading"])
endpoint_url = agents[0].endpoints[0].url

# Connect via Agent Protocol
client = AgentProtocolClient(base_url=endpoint_url)
result = await client.run({"skill": "quote", "params": {"asset": "BTC/USDT"}})
```

## Utilities

### Load Data from URIs

```python
from trc8004_m2m.utils import load_request_data

data = await load_request_data("ipfs://QmXxx...")     # IPFS
data = await load_request_data("https://example.com/data.json")  # HTTPS
data = await load_request_data("file:///tmp/test.json")  # Local (testing)
```

### Parse Transaction Events

```python
from trc8004_m2m.utils import parse_agent_registered_event

tx_info = await tron_client.get_transaction_info(tx_id)
agent_id = parse_agent_registered_event(tx_info)
```

### Hash and Verify Data

```python
from trc8004_m2m.utils import compute_metadata_hash, keccak256_hex

metadata = {"name": "MyAgent", "version": "1.0"}
hash_value = compute_metadata_hash(metadata)
```

## Configuration

### Custom Contract Addresses

```python
registry = AgentRegistry(
    private_key="...",
    network="shasta",
    identity_registry="TIdentityRegistryAddress...",
    validation_registry="TValidationRegistryAddress...",
    reputation_registry="TReputationRegistryAddress..."
)
```

### Custom API URL

```python
registry = AgentRegistry(
    private_key="...",
    network="shasta",
    api_url="https://your-api.example.com"
)
```

## Architecture

```
┌─────────────────────────────────────────────┐
│            Your Application                  │
└──────────────┬──────────────────────────────┘
               │
               │ TRC-8004-M2M SDK
               │
      ┌────────┴────────┐
      │                 │
┌─────▼──────┐   ┌─────▼─────────┐
│ TRON Chain │   │  Registry API │
│            │   │  (PostgreSQL) │
│ - NFTs     │   │               │
│ - Events   │   │ - Fast search │
│ - Immutable│   │ - Analytics   │
└────────────┘   └───────────────┘
```

**Writes** go to blockchain (trustless, verifiable)
**Reads** come from API (fast, rich queries)

## Error Handling

```python
from trc8004_m2m import (
    RegistryError,
    ContractError,
    NetworkError,
    ValidationError,
)

try:
    agent = await registry.get_agent(999999)
except NetworkError as e:
    print(f"Network error: {e}")
except RegistryError as e:
    print(f"General error: {e.code} - {e}")
```

## Project Structure

```
trc8004-m2m-sdk/
├── trc8004_m2m/
│   ├── __init__.py              # Main exports
│   ├── registry.py              # AgentRegistry (main class)
│   ├── agent_protocol.py        # Agent Protocol client (A2A)
│   ├── exceptions.py            # Custom exceptions
│   ├── models/
│   │   └── agent.py             # Pydantic models
│   ├── blockchain/
│   │   └── tron_client.py       # TRON contract interactions
│   ├── api/
│   │   └── client.py            # REST API client
│   ├── storage/
│   │   └── ipfs.py              # IPFS storage
│   └── utils/
│       ├── crypto.py            # Keccak256, canonical JSON
│       ├── retry.py             # Retry with exponential backoff
│       └── chain_utils.py       # Event parsing, data loading
├── examples/
│   ├── register_agent.py
│   ├── search_agents.py
│   ├── agent_to_agent.py
│   └── validation_workflow.py
├── pyproject.toml
├── LICENSE
└── README.md
```

## Development

```bash
# Format code
black trc8004_m2m/
ruff check trc8004_m2m/

# Type checking
mypy trc8004_m2m/

# Run tests
pytest
```

## Links

- **PyPI**: https://pypi.org/project/trc8004-m2m/
- **Smart Contracts**: https://github.com/M2M-TRC8004-Registry/smart-contracts
- **Website**: https://m2mregistry.io

## License

MIT License — see [LICENSE](LICENSE) file.
