npm package: @perkos/contracts-erc8004
Description: ERC-8004 Decentralized AI Agent Registry contract ABIs and utilities
Author: PerkOS
Latest version: 1.0.1

# @perkos/contracts-erc8004

ERC-8004 Decentralized AI Agent Registry contract ABIs and utilities. Provides TypeScript types and ABIs for interacting with ERC-8004 compliant smart contracts.

## Installation

```bash
npm install @perkos/contracts-erc8004
```

## Overview

ERC-8004 defines three core registries for decentralized AI agent management:

- **IdentityRegistry**: NFT-based agent identity with metadata and wallet management
- **ReputationRegistry**: Client feedback system with filtering by tags and reviewers
- **ValidationRegistry**: Request-response validation model for third-party attestations

## Usage

### Identity Registry

Register and manage agent identities as ERC-721 NFTs.

```typescript
import { createPublicClient, createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
import { IDENTITY_REGISTRY_ABI, type MetadataEntry } from '@perkos/contracts-erc8004';

const IDENTITY_REGISTRY = '0x...'; // Contract address

const publicClient = createPublicClient({
  chain: base,
  transport: http()
});

// Get agent info
const tokenURI = await publicClient.readContract({
  address: IDENTITY_REGISTRY,
  abi: IDENTITY_REGISTRY_ABI,
  functionName: 'tokenURI',
  args: [1n] // agentId
});

const owner = await publicClient.readContract({
  address: IDENTITY_REGISTRY,
  abi: IDENTITY_REGISTRY_ABI,
  functionName: 'ownerOf',
  args: [1n]
});

// Get metadata
const description = await publicClient.readContract({
  address: IDENTITY_REGISTRY,
  abi: IDENTITY_REGISTRY_ABI,
  functionName: 'getMetadata',
  args: [1n, 'description']
});

// Get all agents by owner
const agentIds = await publicClient.readContract({
  address: IDENTITY_REGISTRY,
  abi: IDENTITY_REGISTRY_ABI,
  functionName: 'getAgentsByOwner',
  args: ['0x...']
});

// Register new agent with metadata
const metadata: MetadataEntry[] = [
  { key: 'description', value: 'AI Assistant Agent' },
  { key: 'capabilities', value: 'chat,analysis,code' }
];

const hash = await walletClient.writeContract({
  address: IDENTITY_REGISTRY,
  abi: IDENTITY_REGISTRY_ABI,
  functionName: 'register',
  args: ['ipfs://...', metadata]
});
```

### Reputation Registry

Submit and query client feedback for agents.

```typescript
import { REPUTATION_REGISTRY_ABI, type Feedback, type ReputationSummary } from '@perkos/contracts-erc8004';

const REPUTATION_REGISTRY = '0x...';

// Get reputation summary
const [count, averageScore] = await publicClient.readContract({
  address: REPUTATION_REGISTRY,
  abi: REPUTATION_REGISTRY_ABI,
  functionName: 'getSummary',
  args: [
    1n,           // agentId
    [],           // clientAddresses (empty = all)
    '',           // tag1 filter (empty = all)
    ''            // tag2 filter (empty = all)
  ]
});

// Get detailed feedback
const feedback = await publicClient.readContract({
  address: REPUTATION_REGISTRY,
  abi: REPUTATION_REGISTRY_ABI,
  functionName: 'getFeedbackDetails',
  args: [1n, '0x...', 0n] // agentId, clientAddress, index
});

// Submit feedback (score 0-100)
const hash = await walletClient.writeContract({
  address: REPUTATION_REGISTRY,
  abi: REPUTATION_REGISTRY_ABI,
  functionName: 'giveFeedback',
  args: [
    1n,                    // agentId
    85,                    // score (0-100)
    'quality',             // tag1
    'speed',               // tag2
    '/api/chat',           // endpoint
    'ipfs://...',          // feedbackURI
    '0x...'                // feedbackHash
  ]
});

// Simple feedback (score only)
const hash = await walletClient.writeContract({
  address: REPUTATION_REGISTRY,
  abi: REPUTATION_REGISTRY_ABI,
  functionName: 'giveFeedback',
  args: [1n, 90] // agentId, score
});
```

### Validation Registry

Request and respond to third-party validations.

```typescript
import {
  VALIDATION_REGISTRY_ABI,
  ValidationStatus,
  isValidationApproved,
  getValidationStatusString,
  type ValidationRequest,
  type ValidationSummary
} from '@perkos/contracts-erc8004';

const VALIDATION_REGISTRY = '0x...';

// Request validation
const requestHash = await walletClient.writeContract({
  address: VALIDATION_REGISTRY,
  abi: VALIDATION_REGISTRY_ABI,
  functionName: 'validationRequest',
  args: [
    '0x...',              // validatorAddress
    1n,                   // agentId
    'ipfs://...',         // requestURI
    '0x...'               // requestDataHash
  ]
});

// Get validation status
const [status, agentId, validator, response, tag] = await publicClient.readContract({
  address: VALIDATION_REGISTRY,
  abi: VALIDATION_REGISTRY_ABI,
  functionName: 'getValidationStatus',
  args: [requestHash]
});

// Check if approved
if (isValidationApproved(status)) {
  console.log('Validation approved!');
}

// Get status string
console.log(getValidationStatusString(status)); // 'approved' | 'pending' | 'rejected' | etc.

// Get validation statistics
const summary = await publicClient.readContract({
  address: VALIDATION_REGISTRY,
  abi: VALIDATION_REGISTRY_ABI,
  functionName: 'getValidationStatistics',
  args: [1n]
});

// Check for specific validation type
const hasSecurityAudit = await publicClient.readContract({
  address: VALIDATION_REGISTRY,
  abi: VALIDATION_REGISTRY_ABI,
  functionName: 'hasApprovedValidation',
  args: [1n, 'security']
});

// Respond to validation (validator only)
await walletClient.writeContract({
  address: VALIDATION_REGISTRY,
  abi: VALIDATION_REGISTRY_ABI,
  functionName: 'validationResponse',
  args: [
    requestHash,          // requestHash
    85,                   // response (0-100)
    'ipfs://...',         // responseURI
    '0x...',              // responseDataHash
    'security'            // tag
  ]
});
```

## API Reference

### ABIs

```typescript
import {
  IDENTITY_REGISTRY_ABI,
  REPUTATION_REGISTRY_ABI,
  VALIDATION_REGISTRY_ABI,
  ERC8004_ABIS
} from '@perkos/contracts-erc8004';

// Combined ABIs object
const { IdentityRegistry, ReputationRegistry, ValidationRegistry } = ERC8004_ABIS;
```

### Types

```typescript
import type {
  Hex,
  MetadataEntry,
  Feedback,
  ReputationSummary,
  ValidationStatus,
  ValidationRequest,
  ValidationSummary
} from '@perkos/contracts-erc8004';
```

#### MetadataEntry

```typescript
interface MetadataEntry {
  key: string;
  value: string;
}
```

#### Feedback

```typescript
interface Feedback {
  client: Address;
  score: number;        // 0-100
  tag1: string;
  tag2: string;
  endpoint: string;
  feedbackURI: string;
  feedbackHash: Hex;
  timestamp: bigint;
  isRevoked: boolean;
  responseURI: string;
  responseHash: Hex;
}
```

#### ReputationSummary

```typescript
interface ReputationSummary {
  count: bigint;
  averageScore: number; // 0-100
}
```

#### ValidationStatus

```typescript
enum ValidationStatus {
  None = 0,
  Pending = 1,
  Approved = 2,
  Rejected = 3,
  Cancelled = 4
}
```

#### ValidationRequest

```typescript
interface ValidationRequest {
  agentId: bigint;
  requester: Address;
  validatorAddress: Address;
  requestURI: string;
  requestDataHash: Hex;
  requestedAt: bigint;
  status: ValidationStatus;
  response: number;     // 0-100
  responseURI: string;
  responseDataHash: Hex;
  tag: string;
  respondedAt: bigint;
}
```

#### ValidationSummary

```typescript
interface ValidationSummary {
  totalRequests: bigint;
  approvedCount: bigint;
  rejectedCount: bigint;
  pendingCount: bigint;
  averageResponse: number; // 0-100
}
```

### Constants

#### VALIDATION_TAGS

```typescript
import { VALIDATION_TAGS } from '@perkos/contracts-erc8004';

// Pre-defined validation tags per EIP-8004
VALIDATION_TAGS.SECURITY    // 'security'
VALIDATION_TAGS.COMPLIANCE  // 'compliance'
VALIDATION_TAGS.PERFORMANCE // 'performance'
VALIDATION_TAGS.IDENTITY    // 'identity'
VALIDATION_TAGS.CAPABILITY  // 'capability'
VALIDATION_TAGS.KYC         // 'kyc'
VALIDATION_TAGS.AML         // 'aml'
```

#### FEEDBACK_TAGS

```typescript
import { FEEDBACK_TAGS } from '@perkos/contracts-erc8004';

// Pre-defined feedback tags per EIP-8004
FEEDBACK_TAGS.QUALITY     // 'quality'
FEEDBACK_TAGS.SPEED       // 'speed'
FEEDBACK_TAGS.RELIABILITY // 'reliability'
FEEDBACK_TAGS.ACCURACY    // 'accuracy'
FEEDBACK_TAGS.SUPPORT     // 'support'
```

### Utility Functions

```typescript
import {
  isValidationApproved,
  getValidationStatusString,
  getScorePercentage,
  isScoreApproved
} from '@perkos/contracts-erc8004';

// Check if validation is approved
isValidationApproved(ValidationStatus.Approved);  // true

// Get human-readable status
getValidationStatusString(ValidationStatus.Pending);  // 'pending'

// Normalize score to 0-100 range
getScorePercentage(85);  // 85

// Check if score indicates approval (>50)
isScoreApproved(85);  // true
isScoreApproved(30);  // false
```

## Contract Functions

### Identity Registry

| Function | Description |
|----------|-------------|
| `register(agentURI, metadata?)` | Register new agent identity |
| `setAgentURI(agentId, newURI)` | Update agent URI |
| `setMetadata(agentId, key, value)` | Set metadata entry |
| `setAgentWallet(agentId, newWallet, deadline, signature)` | Update agent wallet |
| `tokenURI(agentId)` | Get agent URI |
| `ownerOf(agentId)` | Get agent owner |
| `getMetadata(agentId, key)` | Get metadata value |
| `getAgentWallet(agentId)` | Get agent wallet address |
| `getAgentsByOwner(owner)` | Get all agents owned by address |
| `totalAgents()` | Get total registered agents |

### Reputation Registry

| Function | Description |
|----------|-------------|
| `giveFeedback(agentId, score, ...)` | Submit feedback |
| `revokeFeedback(agentId, index)` | Revoke feedback |
| `appendResponse(agentId, client, index, responseURI, hash)` | Add agent response |
| `getSummary(agentId, clients, tag1, tag2)` | Get reputation summary |
| `readFeedback(agentId, client, index)` | Read specific feedback |
| `readAllFeedback(agentId, clients, tag1, tag2, includeRevoked)` | Read all feedback |
| `getFeedbackDetails(agentId, client, index)` | Get full feedback details |
| `getClients(agentId)` | Get all feedback clients |

### Validation Registry

| Function | Description |
|----------|-------------|
| `validationRequest(validator, agentId, requestURI, hash)` | Request validation |
| `validationResponse(requestHash, response, responseURI, hash, tag)` | Submit response |
| `cancelValidation(requestHash)` | Cancel validation request |
| `getValidationStatus(requestHash)` | Get validation status |
| `getValidation(requestHash)` | Get full validation details |
| `getSummary(agentId, validators, tag)` | Get validation summary |
| `hasApprovedValidation(agentId, tag)` | Check for approved validation |
| `getValidationStatistics(agentId)` | Get agent validation stats |
| `getAgentValidations(agentId)` | Get all validation hashes |
| `getPendingRequests(validator)` | Get pending requests for validator |

## Events

### Identity Registry Events

- `Registered(agentId, agentURI, owner)`
- `URIUpdated(agentId, newURI, updatedBy)`
- `MetadataSet(agentId, indexedKey, metadataKey, metadataValue)`
- `AgentWalletUpdated(agentId, oldWallet, newWallet)`

### Reputation Registry Events

- `NewFeedback(agentId, clientAddress, score, tag1, tag2, endpoint, feedbackURI, feedbackHash)`
- `FeedbackRevoked(agentId, clientAddress, feedbackIndex)`
- `ResponseAppended(agentId, clientAddress, feedbackIndex, responder, responseURI)`

### Validation Registry Events

- `ValidationRequested(requestHash, agentId, validatorAddress, requestURI, requestDataHash)`
- `ValidationResponseSubmitted(requestHash, agentId, validatorAddress, response, tag)`
- `ValidationCancelled(requestHash, agentId, cancelledBy)`

## Related Packages

- [@perkos/types-x402](https://www.npmjs.com/package/@perkos/types-x402) - Core x402 types
- [@perkos/service-x402](https://www.npmjs.com/package/@perkos/service-x402) - x402 service orchestrator

## License

MIT