> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.adid.dev/llms.txt.
> For full documentation content, see https://docs.adid.dev/llms-full.txt.

# Agent Trust Registry Smart Contract

The Agent Trust Registry is an on-chain smart contract (inspired by ERC-8004) that manages AI agent identity, reputation scoring, capability registration, and validator hooks.

## Interface

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IAgentTrustRegistry {
    enum AgentState { Registered, Active, Suspended, Decommissioned }
    enum AutonomyLevel { Intern, Junior, Senior, Principal }

    struct AgentRecord {
        string agentDid;
        string operatorDid;
        uint8 trustScore;
        AgentState state;
        AutonomyLevel autonomy;
        uint256 registeredAt;
        uint256 lastUpdated;
        uint256 totalActions;
        uint256 successfulActions;
    }

    struct Attestation {
        string validatorDid;
        uint8 score;
        string attestationType;
        uint256 issuedAt;
    }

    // Events
    event AgentRegistered(string indexed agentDid, string operatorDid);
    event TrustScoreUpdated(string indexed agentDid, uint8 oldScore, uint8 newScore, string reason);
    event AgentStateChanged(string indexed agentDid, AgentState oldState, AgentState newState);
    event AgentPromoted(string indexed agentDid, AutonomyLevel oldLevel, AutonomyLevel newLevel);
    event AgentDecommissioned(string indexed agentDid);
    event AttestationAdded(string indexed agentDid, string validatorDid, uint8 score);
    event ValidatorRegistered(address indexed validator, string validatorDid);

    // Agent lifecycle
    function registerAgent(
        string calldata agentDid,
        string calldata operatorDid,
        string[] calldata capabilities
    ) external;

    function getAgent(string calldata agentDid) external view returns (AgentRecord memory);

    function setAgentState(string calldata agentDid, AgentState state) external;

    function decommissionAgent(string calldata agentDid) external;

    // Trust scoring
    function updateTrustScore(string calldata agentDid, int8 delta, string calldata reason) external;

    function getTrustScore(string calldata agentDid) external view returns (uint8);

    function recordAction(string calldata agentDid, bool success) external;

    // Autonomy
    function promoteAgent(string calldata agentDid, AutonomyLevel level) external;

    function getAutonomyLevel(string calldata agentDid) external view returns (AutonomyLevel);

    // Attestations
    function addAttestation(
        string calldata agentDid,
        string calldata validatorDid,
        uint8 score,
        string calldata attestationType
    ) external;

    function getAttestations(string calldata agentDid) external view returns (Attestation[] memory);

    // Validators
    function registerValidator(address validator, string calldata validatorDid) external;

    function isValidator(address account) external view returns (bool);

    // Discovery
    function searchAgents(
        uint8 minTrustScore,
        AgentState state,
        uint256 offset,
        uint256 limit
    ) external view returns (AgentRecord[] memory);

    function getAgentCount() external view returns (uint256);
}
```

## Key Functions

### registerAgent

Registers a new AI agent on-chain.

```solidity
function registerAgent(
    string calldata agentDid,
    string calldata operatorDid,
    string[] calldata capabilities
) external;
```

**Requirements:**

* `msg.sender` must be the operator's address
* Agent DID must not already exist
* Sets initial state to `Registered`, autonomy to `Intern`, trust score to 50

### updateTrustScore

Adjusts an agent's trust score by a signed delta.

```solidity
function updateTrustScore(string calldata agentDid, int8 delta, string calldata reason) external;
```

**Requirements:**

* Caller must be authorized (platform service or validator)
* Score is clamped to \[0, 100]
* Emits `TrustScoreUpdated` event

### decommissionAgent

Permanently decommissions an agent.

```solidity
function decommissionAgent(string calldata agentDid) external;
```

**Effects:**

* State set to `Decommissioned`
* Trust score set to 0
* Emits `AgentDecommissioned` event
* Should be followed by credential batch revocation (off-chain)

## Interaction Examples

### Register an Agent

```javascript
const agentRegistry = new ethers.Contract(AGENT_TRUST_REGISTRY_ADDRESS, ABI, operatorSigner);

const tx = await agentRegistry.registerAgent(
  'did:adi:agent:7f3a9b2e...',
  'did:adi:operator001...',
  ['shopping', 'price-comparison']
);
await tx.wait();
```

### Query Trust Score

```javascript
const score = await agentRegistry.getTrustScore('did:adi:agent:7f3a9b2e...');
console.log('Trust score:', score); // 85
```

### Record an Action

```javascript
// Called by the platform after each agent action
const tx = await agentRegistry.recordAction('did:adi:agent:7f3a9b2e...', true); // success
await tx.wait();
```

### Add a Validator Attestation

```javascript
// Called by a registered validator
const tx = await agentRegistry.addAttestation(
  'did:adi:agent:7f3a9b2e...',
  'did:adi:auditor001...',
  15,                          // score boost
  'safety-audit'               // attestation type
);
await tx.wait();
```

### Search Agents

```javascript
const agents = await agentRegistry.searchAgents(
  80,                          // minTrustScore
  1,                           // AgentState.Active
  0,                           // offset
  20                           // limit
);
agents.forEach(a => console.log(a.agentDid, a.trustScore));
```

## Gas Costs

| Operation         | Estimated Gas |
| ----------------- | ------------- |
| registerAgent     | \~250,000     |
| getAgent          | 0 (view)      |
| updateTrustScore  | \~55,000      |
| recordAction      | \~45,000      |
| promoteAgent      | \~50,000      |
| addAttestation    | \~120,000     |
| decommissionAgent | \~60,000      |
| searchAgents      | 0 (view)      |

## Access Control

| Function          | Authorized Callers                            |
| ----------------- | --------------------------------------------- |
| registerAgent     | Operator address                              |
| setAgentState     | Operator address                              |
| decommissionAgent | Operator address                              |
| updateTrustScore  | Platform service, registered validators       |
| recordAction      | Platform service                              |
| promoteAgent      | Operator address (with score threshold check) |
| addAttestation    | Registered validators only                    |
| registerValidator | Contract admin                                |

## Events for Off-Chain Indexing

All state changes emit events that the IDA API indexes in PostgreSQL for fast querying. The indexer listens for:

* `AgentRegistered` -- new agent in the registry
* `TrustScoreUpdated` -- update cached trust score
* `AgentStateChanged` -- update agent state
* `AgentPromoted` -- update autonomy level
* `AgentDecommissioned` -- trigger credential revocation cascade
* `AttestationAdded` -- update attestation list