# AI Agents & Realms

## AI Agents and Realms

AI agents can be powerful participants in DAO governance. They can monitor proposals, analyze voting patterns, automate routine governance tasks, and even act as delegates. This guide covers how to integrate AI agents into Realms-based DAOs.

### Use Cases

#### 1. Proposal Monitoring and Analysis

An AI agent can watch for new proposals and provide automated analysis:

* Summarize proposal content and linked discussions
* Assess risk of proposed on-chain transactions
* Flag proposals that modify critical parameters
* Alert stakeholders about upcoming vote deadlines

#### 2. Automated Voting (Delegate Agent)

SPL Governance supports delegation. A token owner can delegate their voting power to another address, which can be controlled by an AI agent:

```typescript
import { withSetGovernanceDelegate } from '@realms-today/spl-governance';
import { TransactionInstruction } from '@solana/web3.js';

// Delegate voting power to the agent's wallet
const instructions: TransactionInstruction[] = [];

await withSetGovernanceDelegate(
  instructions,
  programId,
  programVersion,           // e.g. 3
  realmAddress,
  governingTokenMint,
  tokenOwnerWallet,         // token owner
  tokenOwnerWallet,         // governance authority (current authority)
  agentWalletAddress,       // the AI agent's wallet
);
```

Once delegated, the agent can cast votes on behalf of the token owner:

```typescript
import { withCastVote, Vote, YesNoVote } from '@realms-today/spl-governance';

const voteIxs: TransactionInstruction[] = [];

await withCastVote(
  voteIxs,
  programId,
  programVersion,
  realmAddress,
  governanceAddress,
  proposalAddress,
  proposalOwnerRecordAddress,
  delegatorTokenOwnerRecordAddress,
  agentWalletAddress,       // agent signs as delegate
  governingTokenMint,
  Vote.fromYesNoVote(YesNoVote.Yes),
  agentWalletAddress,       // payer
  voterWeightRecord,
  maxVoterWeightRecord,
);
```

#### 3. Proposal Creation Agent

An agent can create proposals programmatically based on triggers:

* Scheduled treasury distributions
* Automated parameter adjustments based on on-chain metrics
* Emergency proposals when security thresholds are breached

#### 4. Transaction Execution Bot

After a proposal passes and the hold-up time elapses, execution is permissionless. An AI agent can monitor for executable proposals and trigger them:

```typescript
import { withExecuteTransaction } from '@realms-today/spl-governance';

// Anyone can execute - no special permissions needed
const executeIxs: TransactionInstruction[] = [];

await withExecuteTransaction(
  executeIxs,
  programId,
  programVersion,
  governanceAddress,
  proposalAddress,
  proposalTransactionAddress,
  transactionInstructions,  // InstructionData[] from the ProposalTransaction
);
```

#### 5. Governance Analytics Agent

Build an agent that provides ongoing governance health metrics:

* Voter participation rates
* Proposal success/failure ratios
* Treasury balance monitoring
* Token holder concentration analysis

### Architecture Pattern

A typical AI agent integration follows this pattern:

```
┌─────────────────────┐
│   AI Agent Service   │
│  (Off-chain server)  │
├─────────────────────┤
│  - LLM for analysis │
│  - Decision logic    │
│  - Scheduling        │
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│   Agent Wallet       │
│  (Solana Keypair)    │
├─────────────────────┤
│  - Signs transactions│
│  - Holds SOL for fees│
│  - Delegated voting  │
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│  SPL Governance      │
│  (On-chain program)  │
├─────────────────────┤
│  - Cast votes        │
│  - Create proposals  │
│  - Execute txs       │
└─────────────────────┘
```

### Implementation Guide

#### 1. Set Up the Agent Wallet

```typescript
import { Keypair, Connection } from '@solana/web3.js';

// Generate or load the agent's keypair
const agentKeypair = Keypair.fromSecretKey(
  Buffer.from(process.env.AGENT_PRIVATE_KEY, 'base64')
);

const connection = new Connection(process.env.RPC_URL);
```

#### 2. Monitor Proposals

Poll for new proposals or use WebSocket subscriptions:

```typescript
import { getAllProposals, ProposalState } from '@realms-today/spl-governance';

async function monitorProposals(governanceAddress: PublicKey) {
  const proposals = await getAllProposals(
    connection,
    programId,
    governanceAddress,
  );

  const activeProposals = proposals.flat().filter(
    p => p.account.state === ProposalState.Voting
  );

  for (const proposal of activeProposals) {
    await analyzeAndVote(proposal);
  }
}
```

#### 3. Analyze and Decide

Feed proposal data to your AI model for analysis:

```typescript
async function analyzeAndVote(proposal) {
  // Fetch proposal details and description
  const description = await fetchProposalDescription(proposal.account.descriptionLink);

  // Fetch proposed transactions
  const transactions = await getProposalTransactions(proposal.pubkey);

  // AI analysis
  const analysis = await aiModel.analyze({
    name: proposal.account.name,
    description,
    transactions: transactions.map(formatTransaction),
    governanceConfig: await getGovernanceConfig(proposal.account.governance),
  });

  // Decision
  if (analysis.shouldVote) {
    await submitVote(proposal, analysis.vote);
  }
}
```

#### 4. Submit Votes

```typescript
async function submitVote(proposal, voteDecision: Vote) {
  const instructions: TransactionInstruction[] = [];

  await withCastVote(
    instructions,
    programId,
    programVersion,
    realmAddress,
    proposal.account.governance,
    proposal.pubkey,
    proposalOwnerRecord,
    agentTokenOwnerRecord,
    agentKeypair.publicKey,
    governingTokenMint,
    voteDecision,
    agentKeypair.publicKey,
  );

  const tx = new Transaction().add(...instructions);
  await sendAndConfirmTransaction(connection, tx, [agentKeypair]);
}
```

### Security Considerations

* **Key Management**: Store agent private keys securely (HSM, KMS, or encrypted vault). Never hardcode keys.
* **Spending Limits**: Use a dedicated wallet with limited SOL for fees. The agent should not hold governance tokens directly - use delegation instead.
* **Delegation Revocation**: Token owners can revoke delegation at any time by calling `setGovernanceDelegate` with `None`.
* **Audit Trail**: Log all agent decisions and the reasoning behind them for transparency.
* **Rate Limiting**: Implement rate limits to prevent the agent from taking too many actions in a short period.
* **Human Override**: Always maintain the ability for human governance participants to override agent decisions through delegation revocation.

### Existing Integrations

AI agents can be combined with existing governance plugins:

* **VSR + AI Agent**: Agent votes with time-locked token power
* **NFT Voter + AI Agent**: Agent manages NFT-based governance participation
* **Sowellian + AI Agent**: Agent participates in prediction market governance bets

The delegation mechanism is the key enabler. Since any wallet can be a delegate, AI agents naturally fit into the existing governance model without requiring any protocol changes.


---

# 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://docs.realms.today/developer-resources/ai-agents-and-realms.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.
