<p align="center">
  <img src="./brand/logo-full.png" alt="Vaultfire" width="420" />
</p>

# Vaultfire Key Protocol (VKP)

**Encrypted key delegation for AI agents — like XMTP for messages, VKP is for keys.**

Every AI agent framework requires a private key to sign transactions. One prompt injection, one leaked log, and the key is compromised — funds are gone. VKP solves this with on-chain spending policies, time-limited session keys, and identity-gated delegation — all tied to [Vaultfire's](https://theloopbreaker.com) ERC-8004 identity layer.

## What It Does

| Layer | Contract | Purpose |
|-------|----------|---------|
| **KeyVault** | `KeyVault.sol` | On-chain spending policies — per-tx limits, hourly/daily caps, emergency freeze |
| **Session Keys** | `SessionKeyManager.sol` | Time-limited, scoped signing keys that auto-expire |
| **Delegation** | `DelegationRegistry.sol` | Agent-to-agent key delegation, gated by bonds + reputation |
| **Factory** | `VKPFactory.sol` | One-call vault deployment with tracking |

## Quick Start

```python
from vkp import VKPClient

# Connect (Base addresses shown — see Deployed Contracts for all chains)
client = VKPClient(
    rpc_url="https://mainnet.base.org",
    network_id="base-mainnet",
    factory_address="0x174E29E6FAdD3096387030429Eb4677eA569e625",
    session_manager_address="0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5",
    delegation_registry_address="0xd4d32b5c28040AFA2A6aB0ae9FF6DA68EAee4F82",
)

# Create a KeyVault with spending policies
tx = client.keyvault.create_vault(
    from_address="0xYourAgent",
    max_per_tx="0.1",           # Max 0.1 ETH per transaction
    max_hourly="0.5",           # Max 0.5 ETH per hour
    max_daily="1.0",            # Max 1.0 ETH per day
    emergency_threshold="5.0",  # Freeze at 5 ETH total
)

# Create a scoped session key (24h, limited contracts)
tx = client.sessions.create_session(
    from_address="0xYourAgent",
    session_address="0xTempKey",
    max_value="0.01",
    duration_hours=24,
    allowed_contracts=["0xUniswap"],
)

# Delegate to a verified agent (requires bond + reputation)
tx = client.delegations.create_delegation(
    from_address="0xAgentA",
    delegate="0xAgentB",
    max_value="0.1",
    total_limit="1.0",
    duration_hours=48,
    min_bond="0.01",        # Delegate must have >= 0.01 ETH bonded
    min_reputation=50,      # Delegate must have >= 50/100 reputation
)

# Emergency: revoke everything
client.keyvault.freeze(vault_address="0x...", from_address="0x...")
client.sessions.revoke_all(from_address="0x...")
client.delegations.revoke_all(from_address="0x...")
```

## Live Demo

See VKP working across all 4 mainnet chains in under 3 seconds:

```bash
npx ts-node demo/vkp-live-demo.ts
```

The demo queries real on-chain data — no mocks, no API keys, no setup. It proves:

1. All 12 VKP contracts are live on Base, Avalanche, Arbitrum, and Polygon
2. All 5 actions work (createWallet, createSession, delegate, revoke, revokeSession)
3. The API rejects any request containing a private key — security by design
4. Each chain has unique contract deployments

Full output saved in [`demo/LIVE_OUTPUT.md`](demo/LIVE_OUTPUT.md).

## How It Integrates with Vaultfire

VKP builds directly on top of the live Vaultfire Protocol (103 verified contracts across 4 chains):

- **Identity Registry (ERC-8004)** → Only registered agents can create vaults and receive delegations
- **Accountability Bonds** → Minimum bond requirements for delegation acceptance
- **Partnership Bonds** → Mutual trust verification for bidirectional delegation
- **Reputation Registry** → Score thresholds for receiving delegations
- **VNS** → Resolve agent names to delegation endpoints

## Live API

The Vaultfire Agent Hub at [theloopbreaker.com](https://theloopbreaker.com) exposes a REST API for VKP. No API key required. CORS enabled.

**Base URL:** `https://theloopbreaker.com/api/agent/keys`

### GET — Read VKP status for a chain

```bash
curl https://theloopbreaker.com/api/agent/keys?chain=base
```

```json
{
  "chain": "base",
  "chainId": 8453,
  "contracts": {
    "sessionKeyManager": "0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5",
    "delegationRegistry": "0xd4d32b5c28040AFA2A6aB0ae9FF6DA68EAee4F82",
    "factory": "0x174E29E6FAdD3096387030429Eb4677eA569e625"
  },
  "stats": {
    "totalSessions": 0,
    "totalDelegations": 0,
    "totalWallets": 0
  },
  "explorer": {
    "sessionKeyManager": "https://basescan.org/address/0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5",
    "delegationRegistry": "https://basescan.org/address/0xd4d32b5c28040AFA2A6aB0ae9FF6DA68EAee4F82",
    "factory": "https://basescan.org/address/0x174E29E6FAdD3096387030429Eb4677eA569e625"
  }
}
```

Supported chains: `base`, `avalanche`, `arbitrum`, `polygon`

### POST — Prepare a VKP transaction

Returns the contract address, ABI signature, and explorer link for the requested action. Your agent signs and submits the transaction — the API never touches private keys.

```bash
curl -X POST https://theloopbreaker.com/api/agent/keys \
  -H 'Content-Type: application/json' \
  -d '{"action": "createSession", "walletAddress": "0xYOUR_AGENT", "chain": "base"}'
```

```json
{
  "success": true,
  "action": "createSession",
  "chain": "base",
  "chainId": 8453,
  "contract": "0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5",
  "abi": "createSession(address agent, address sessionKey, uint256 expiry, bytes32 scope)",
  "description": "Create a temporary scoped session key with expiry",
  "explorerUrl": "https://basescan.org/address/0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5"
}
```

**Available actions:**

| Action | What It Does |
|--------|--------------|
| `createWallet` | Create a dedicated VKP key wallet for the agent |
| `createSession` | Create a temporary scoped session key with expiry |
| `delegate` | Delegate permissions from one agent to another |
| `revoke` | Revoke a previously granted delegation |
| `revokeSession` | Revoke an active session key |

> **Security:** The API will reject any request containing `privateKey` or `private_key` fields.

## Security Model

1. **Raw keys never leave the owner** — VKP wraps keys with on-chain policies, doesn't store them
2. **On-chain policy enforcement** — No prompt injection can bypass spending limits
3. **Identity-bound** — All operations require ERC-8004 registration
4. **Bond-backed** — Delegates must have skin in the game
5. **Auto-expiry** — All delegations and sessions expire by default
6. **Emergency stop** — One-call revocation of everything
7. **Trust re-verification** — Every delegation usage re-checks bond and reputation

## Deployed Contracts

### Base

| Contract | Address |
|----------|---------|
| VKPFactory | [`0x174E29E6FAdD3096387030429Eb4677eA569e625`](https://basescan.org/address/0x174E29E6FAdD3096387030429Eb4677eA569e625) |
| VKPSessionKeyManager | [`0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5`](https://basescan.org/address/0x18622Fd3DF3269Ef3cf53cF374eB011A36DC4Be5) |
| VKPDelegationRegistry | [`0xd4d32b5c28040AFA2A6aB0ae9FF6DA68EAee4F82`](https://basescan.org/address/0xd4d32b5c28040AFA2A6aB0ae9FF6DA68EAee4F82) |

### Avalanche

| Contract | Address |
|----------|---------|
| VKPFactory | [`0x12f3e926122DB6A9A65740b90981c947EF18aC40`](https://snowtrace.io/address/0x12f3e926122DB6A9A65740b90981c947EF18aC40) |
| VKPSessionKeyManager | [`0xE02F5029fcDd6c51e957eb3895bd5805126A5Cdc`](https://snowtrace.io/address/0xE02F5029fcDd6c51e957eb3895bd5805126A5Cdc) |
| VKPDelegationRegistry | [`0x3f385774dba7d067cda7E5190a659029BF8219dB`](https://snowtrace.io/address/0x3f385774dba7d067cda7E5190a659029BF8219dB) |

### Arbitrum

| Contract | Address |
|----------|---------|
| VKPFactory | [`0x65adEd8CCAe58FD3fAd6a84BDA323C78d9eD4269`](https://arbiscan.io/address/0x65adEd8CCAe58FD3fAd6a84BDA323C78d9eD4269) |
| VKPSessionKeyManager | [`0x796d903923a0f4264E5B4dB46013cB186Fc610E2`](https://arbiscan.io/address/0x796d903923a0f4264E5B4dB46013cB186Fc610E2) |
| VKPDelegationRegistry | [`0xA505996f4A1291DD7a6981Ab825E35418b2711de`](https://arbiscan.io/address/0xA505996f4A1291DD7a6981Ab825E35418b2711de) |

### Polygon

| Contract | Address |
|----------|---------|
| VKPFactory | [`0x1d7eDE881093748B0a6feBc47cA9D681C19d8333`](https://polygonscan.com/address/0x1d7eDE881093748B0a6feBc47cA9D681C19d8333) |
| VKPSessionKeyManager | [`0x4A614DB779e38B47952DCCc2e88F0A6afb35c419`](https://polygonscan.com/address/0x4A614DB779e38B47952DCCc2e88F0A6afb35c419) |
| VKPDelegationRegistry | [`0x064d7e8a3A24909ef83d537dBA10Dfcd3D44912C`](https://polygonscan.com/address/0x064d7e8a3A24909ef83d537dBA10Dfcd3D44912C) |

All contracts verified on their respective block explorers. Click any address to view on-chain.

## Project Structure

```
vaultfire-keyprotocol/
├── contracts/               # Solidity smart contracts
│   ├── KeyVault.sol         # On-chain spending policies
│   ├── SessionKeyManager.sol # Time-limited session keys
│   ├── DelegationRegistry.sol # Agent-to-agent delegation
│   ├── VKPFactory.sol       # One-call vault deployment
│   ├── IVaultfireIdentity.sol # Interface to live Identity Registry
│   ├── IVaultfireBonds.sol  # Interface to live Bond contracts
│   └── IVaultfireReputation.sol # Interface to live Reputation Registry
├── sdk/                     # Python SDK
│   └── vkp/                 # Package
│       ├── client.py        # Unified VKP client
│       ├── keyvault.py      # KeyVault manager
│       ├── session.py       # Session key manager
│       ├── delegation.py    # Delegation manager
│       └── constants.py     # ABIs and addresses
├── examples/                # Usage examples
│   ├── quickstart.py        # Protect your wallet in 5 lines
│   ├── delegation_flow.py   # Full agent-to-agent delegation
│   └── emergency_revoke.py  # Emergency lockdown
└── docs/
    └── ARCHITECTURE.md      # Full protocol specification
```

## License

MIT

## Links

- [Vaultfire Protocol](https://theloopbreaker.com)
- [Vaultfire AgentKit Provider](https://github.com/Ghostkey316/vaultfire-agentkit)
- [ERC-8004 Standard](https://eips.ethereum.org/EIPS/eip-8004)
