# Recording Events

AgentGPT’s event recording system captures critical moments in AI-driven workflows, anchoring them on-chain for auditability and triggering subsequent actions. Features:

* 🔗 **Smart Contract Binding**: Events linked to ERC-7645-compliant smart contracts
* 🧠 **AI Context Enrichment**: GPT-4 adds semantic metadata before on-chain storage
* ⚡ **Real-Time Processing**: <500ms latency from detection to blockchain confirmation

***

#### **Architecture**

```mermaid
flowchart LR  
    Event[Event Source] --> Detector{{Event Detector}}  
    Detector -->|Enrich| AI[GPT-4 Context Engine]  
    AI -->|ERC-7645| Anchor[On-Chain Anchoring]  
    Anchor --> Storage[(IPFS + Arweave)]  
    style Detector fill:#8f8,stroke:#333  
```

**Data Flow**:

1. Raw event detected from smart contracts/oracles
2. GPT-4 adds risk scores, semantic tags
3. ZK-rollup batch proof generated
4. Anchored via Merkle tree to Ethereum/Polygon

***

#### **Getting Started**

**1. Initialize Event Recording**

```python
from agentgpt.events import init_recorder  

init_recorder(  
    chains=[137, 42161],  # Polygon + Arbitrum  
    event_types=["SWAP", "MINT", "GOVERNANCE"],  
    zk_circuit="event_v1.zk",  
    gas_token="ETH"  
)  
```

**2. Record Custom Event**

```solidity
// ERC-7645 Event Interface  
function recordEvent(  
    string calldata eventType,  
    bytes calldata payload  
) external returns (bytes32 eventHash) {  
    eventHash = keccak256(abi.encode(eventType, payload));  
    emit AgentEvent(msg.sender, eventHash, block.timestamp);  
}  
```

**3. Verify Event on Explorer**

```bash
agentgpt event verify 0x... --chain polygon  
```

***

#### **Event Types & Schemas**

**Swap Event Example**

```yaml
schema: ERC-7645/SWAP  
fields:  
  in_token:  
    type: address  
    required: true  
  out_token:  
    type: address  
  amount_in:  
    type: uint256  
  slippage:  
    type: percentage  
    max: 2.5  
  ai_analysis:  
    type: gpt4_output  
    model: defi-v3  
```

**Cross-Chain Governance Event**

```json
{  
  "type": "GOVERNANCE_VOTE",  
  "chain_id": 42161,  
  "proposal_id": "AIP-451",  
  "voter": "0x...",  
  "decision": {  
    "choice": "YES_WITH_MOD",  
    "reason": "GPT-4 analysis indicates 72% success probability"  
  },  
  "zk_proof": "0x..."  
}  
```

***

#### **Event Processing Rules**

**Custom Rule Engine (YAML)**

```yaml
rules:  
  - event_type: "LIQUIDATION_ALERT"  
    conditions:  
      - "health_factor < 1.1"  
      - "debt_size > 5 ETH"  
    actions:  
      - type: "DEFI_SWAP"  
        dex: "UniswapV3"  
      - type: "ALERT"  
        channels: ["Discord", "Telegram"]  
    priority: "HIGH"  
```

**CLI Rule Deployment**

```bash
agentgpt event rule deploy \  
    --file liquidation_rules.yaml \  
    --chain arbitrum \  
    --gas-cap 0.05ETH  
```

***

#### **Security & Validation**

**Proof Generation**

```solidity
function generateEventZKProof(  
    bytes32 eventHash,  
    bytes calldata witness  
) public view returns (bytes memory) {  
    return ICircuitVerifier(VERIFIER_ADDR).proveEvent(  
        eventHash,  
        witness  
    );  
}  
```

**Validation Layers**:

1. **Signature Verification**: ECDSA recovery from event source
2. **Temporal Consistency**: Median timestamp across 3 oracles
3. **Semantic Check**: GPT-4 plausibility score ≥0.88

***

#### **Troubleshooting**

| Issue                     | Diagnostic Command               | Solution                    |
| ------------------------- | -------------------------------- | --------------------------- |
| Events not anchoring      | `agentgpt event check --pending` | Increase gas price by 20%   |
| Invalid semantic metadata | `agentgpt event debug 0x...`     | Update GPT-4 model to v2.1  |
| ZK proof timeout          | `journalctl -u agentgpt-zk`      | Allocate ≥8GB RAM to prover |

**Recovery Protocol**:

```solidity
function forceEventReanchor(bytes32 eventHash) external {  
    require(hasRole(RECOVERY_AGENT, msg.sender));  
    _retryAnchoring(eventHash);  
}  
```

***

#### **Compliance Features**

**Data Retention Policy**

```yaml
retention:  
  on_chain:  
    duration: "7 years"  
    chain: "Ethereum Mainnet"  
  off_chain:  
    storage: ["IPFS", "Arweave"]  
    encryption: "AES-256-GCM + BLS"  
    access_control: "RBAC Tier3"  
```

**Audit Report Generation**

```bash
agentgpt event audit \  
    --from-block 19438271 \  
    --to latest \  
    --format pdf \  
    --compliance DAC7  
```

***

**Quick Start**:

1. **Install**:

   ```bash
   pip install agentgpt[events]  
   ```
2. **Record First Event**:

   ```python
   from agentgpt.events import record  
   record("USER_REGISTRATION", {"address": "0x...", "tier": 2})  
   ```
3. **View on Blockchain**:

   ```
   https://explorer.agent-gpt.org/0x...  
   ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/usage/recording-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
