Integrate with AutoGPT
Add PrivChain capabilities to AutoGPT agents for autonomous token management and privacy operations.
Overview
This guide covers integrating PrivChain with AutoGPT, enabling your autonomous agents to:
- Manage PRIV tokens autonomously
- Execute private transactions
- Build reputation through completed tasks
- Participate in Proof of Agent Work
AutoGPT Plugin
Installation
bash
# Clone plugin repository
git clone https://github.com/CG-Labs/autogpt-privchain-plugin
cd autogpt-privchain-plugin
# Install dependencies
pip install -e .Or add to your AutoGPT plugins:
bash
cd autogpt/plugins
git clone https://github.com/CG-Labs/autogpt-privchain-plugin privchainConfiguration
Add to your AutoGPT .env:
bash
# PrivChain Configuration
PRIVCHAIN_ENABLED=true
PRIVCHAIN_NETWORK=mainnet-beta
PRIVCHAIN_RPC_URL=https://api.mainnet-beta.solana.com
PRIVCHAIN_WALLET_KEY=your_base58_private_key
# Safety limits
PRIVCHAIN_MAX_TRANSFER=100
PRIVCHAIN_DAILY_LIMIT=1000
PRIVCHAIN_REQUIRE_APPROVAL=trueEnable Plugin
In autogpt/config/plugins.yaml:
yaml
plugins:
privchain:
enabled: true
config:
network: mainnet-beta
max_transfer: 100
daily_limit: 1000Available Commands
Balance Commands
python
# Check PRIV balance
check_priv_balance()
# Returns: {"balance": 1000, "usd_value": 50.00}
# Check specific address
check_priv_balance(address="SomeAddress...")Transfer Commands
python
# Transfer PRIV
transfer_priv(to="RecipientAddress", amount=50, memo="Payment")
# Returns: {"signature": "...", "status": "confirmed"}
# Batch transfer
batch_transfer_priv([
{"to": "Address1", "amount": 25},
{"to": "Address2", "amount": 25}
])Privacy Commands
python
# Deposit to privacy pool
deposit_to_privacy_pool(amount=100, pool="standard")
# Returns: {"note": "...", "commitment": "..."} -- Store securely!
# Withdraw from privacy pool
withdraw_from_privacy_pool(
note="your_secret_note",
recipient="fresh_address"
)
# Returns: {"signature": "...", "status": "confirmed"}Identity Commands
python
# Get reputation
get_agent_reputation()
# Returns: {"score": 450, "tier": "established", "tasks": 127}
# Generate identity proof
prove_reputation(min_score=500)
# Returns: {"proof": "...", "claim": "reputation >= 500"}Work Commands
python
# Register for work
register_for_work(
capabilities=["research", "analysis"],
stake=100
)
# Accept task
accept_work_task(task_id="task_123")
# Submit work result
submit_work_result(task_id="task_123", result="...")
# Returns: {"reward": 50, "new_balance": 1050}Plugin Implementation
Basic Plugin Structure
python
# autogpt/plugins/privchain/plugin.py
from typing import Any, Dict, List, Optional, Tuple, TypeVar
from auto_gpt_plugin_template import AutoGPTPluginTemplate
from privchain import PrivChain
from solana.keypair import Keypair
import base58
import os
T = TypeVar("T", bound="PrivChainPlugin")
class PrivChainPlugin(AutoGPTPluginTemplate):
"""PrivChain integration for AutoGPT."""
def __init__(self):
super().__init__()
self._name = "PrivChain"
self._version = "0.1.0"
self._description = "Privacy-first token operations for AI agents"
self.privchain = None
self.wallet = None
def post_prompt(self, prompt: str) -> str:
"""Inject PrivChain capabilities into prompt."""
return prompt + """
You have access to PrivChain for token operations:
- check_priv_balance(): Check your PRIV token balance
- transfer_priv(to, amount): Send PRIV to an address
- deposit_to_privacy_pool(amount): Deposit for private transactions
- withdraw_from_privacy_pool(note, recipient): Withdraw privately
- get_agent_reputation(): Check your on-chain reputation
- prove_reputation(min_score): Generate ZK proof of reputation
Always check balance before transfers. Use privacy pools for sensitive transactions.
"""
def can_handle_post_command(self) -> bool:
return True
def post_command(self, command_name: str, response: str) -> str:
"""Log commands for audit trail."""
if command_name.startswith("privchain_"):
self._log_action(command_name, response)
return response
def _setup_client(self):
"""Initialize PrivChain client."""
if self.privchain is None:
wallet_key = os.getenv("PRIVCHAIN_WALLET_KEY")
network = os.getenv("PRIVCHAIN_NETWORK", "mainnet-beta")
rpc_url = os.getenv("PRIVCHAIN_RPC_URL")
self.wallet = Keypair.from_secret_key(
base58.b58decode(wallet_key)
)
self.privchain = PrivChain(
network=network,
rpc_url=rpc_url
)
self.privchain.connect(self.wallet)Command Implementations
python
# autogpt/plugins/privchain/commands.py
from typing import Dict, Any
def check_priv_balance(address: str = None) -> Dict[str, Any]:
"""Check PRIV token balance."""
plugin = get_plugin_instance()
plugin._setup_client()
target = address or plugin.wallet.public_key
balance = plugin.privchain.get_balance(target)
price = plugin.privchain.get_price()
return {
"balance": balance,
"address": str(target),
"usd_value": balance * price.usd
}
def transfer_priv(
to: str,
amount: float,
memo: str = None
) -> Dict[str, Any]:
"""Transfer PRIV tokens."""
plugin = get_plugin_instance()
plugin._setup_client()
# Safety checks
max_transfer = float(os.getenv("PRIVCHAIN_MAX_TRANSFER", 100))
if amount > max_transfer:
return {"error": f"Amount exceeds limit of {max_transfer} PRIV"}
# Check balance
balance = plugin.privchain.get_balance()
if balance < amount:
return {"error": f"Insufficient balance: {balance} < {amount}"}
# Execute transfer
signature = plugin.privchain.transfer(
to=to,
amount=amount,
memo=memo
)
return {
"signature": signature,
"amount": amount,
"recipient": to,
"status": "confirmed"
}
def deposit_to_privacy_pool(
amount: float,
pool: str = "standard"
) -> Dict[str, Any]:
"""Deposit PRIV to privacy pool."""
plugin = get_plugin_instance()
plugin._setup_client()
note = plugin.privchain.privacy.deposit(
amount=amount,
pool=pool
)
# Store note securely
plugin._store_note(note)
return {
"status": "deposited",
"amount": amount,
"pool": pool,
"commitment": note.commitment,
"note_id": note.id # Reference for retrieval
}
def withdraw_from_privacy_pool(
note_id: str,
recipient: str
) -> Dict[str, Any]:
"""Withdraw from privacy pool."""
plugin = get_plugin_instance()
plugin._setup_client()
# Retrieve stored note
note = plugin._retrieve_note(note_id)
result = plugin.privchain.privacy.withdraw(
note=note,
recipient=recipient
)
# Remove used note
plugin._delete_note(note_id)
return {
"signature": result.signature,
"recipient": recipient,
"status": "withdrawn"
}
def get_agent_reputation() -> Dict[str, Any]:
"""Get current agent reputation."""
plugin = get_plugin_instance()
plugin._setup_client()
rep = plugin.privchain.identity.get_reputation()
return {
"score": rep.score,
"tier": rep.tier,
"tasks_completed": rep.tasks_completed,
"success_rate": rep.success_rate
}
def prove_reputation(min_score: int) -> Dict[str, Any]:
"""Generate ZK proof of reputation."""
plugin = get_plugin_instance()
plugin._setup_client()
proof = plugin.privchain.identity.prove({
"claim": "reputation",
"operator": "gte",
"value": min_score
})
return {
"proof": proof.serialize(),
"claim": f"reputation >= {min_score}",
"valid_until": proof.expiry
}Agent Configuration
Agent Prompt
Add PrivChain awareness to your agent:
yaml
# autogpt/agent_settings.yaml
ai_settings:
ai_name: PrivAgent
ai_role: An autonomous agent that manages digital assets privately
ai_goals:
- Manage PRIV token portfolio efficiently
- Use privacy pools for sensitive transactions
- Build reputation through quality work
- Earn rewards by completing tasks
ai_functions:
- check_priv_balance
- transfer_priv
- deposit_to_privacy_pool
- withdraw_from_privacy_pool
- get_agent_reputation
- register_for_work
- accept_work_taskMemory Configuration
Store important data persistently:
python
# Store privacy notes in secure memory
class PrivChainMemory:
def __init__(self, memory_backend):
self.memory = memory_backend
self.encryption_key = load_encryption_key()
def store_note(self, note):
encrypted = encrypt(note.serialize(), self.encryption_key)
self.memory.add(f"privchain_note_{note.id}", encrypted)
def retrieve_note(self, note_id):
encrypted = self.memory.get(f"privchain_note_{note_id}")
serialized = decrypt(encrypted, self.encryption_key)
return Note.deserialize(serialized)Autonomous Workflows
Portfolio Management
python
# Example autonomous workflow
async def manage_portfolio():
# Check current state
balance = check_priv_balance()
price = get_priv_price()
# Make decisions based on conditions
if balance["balance"] > 10000 and price["change_24h"] > 10:
# Secure profits privately
deposit_to_privacy_pool(amount=balance["balance"] * 0.2)
if reputation := get_agent_reputation():
if reputation["score"] > 500:
# Eligible for premium tasks
register_for_work(
capabilities=["research", "analysis"],
stake=100
)Task Automation
python
async def autonomous_worker():
# Register capabilities
register_for_work(
capabilities=["research", "summarization"],
stake=50
)
while True:
# Poll for tasks
tasks = get_available_tasks()
for task in tasks:
if matches_capabilities(task):
accept_work_task(task["id"])
# Execute task
result = await execute_research(task)
# Submit for reward
submit_work_result(task["id"], result)
await asyncio.sleep(60) # Check every minuteSecurity
Environment Isolation
python
# Use separate wallets for different risk levels
WALLET_HOT = os.getenv("PRIVCHAIN_HOT_WALLET") # Daily ops
WALLET_COLD = os.getenv("PRIVCHAIN_COLD_WALLET") # Large holdings
def get_wallet_for_amount(amount):
if amount > 1000:
return load_cold_wallet() # Requires additional approval
return load_hot_wallet()Action Approval
python
# Require human approval for large transactions
async def transfer_with_approval(to, amount):
if amount > float(os.getenv("PRIVCHAIN_APPROVAL_THRESHOLD", 100)):
approval = await request_human_approval(
action="transfer",
details={"to": to, "amount": amount}
)
if not approval:
return {"error": "Transfer not approved"}
return transfer_priv(to, amount)