Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions safe-onchain-agent-skill/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Alex_Uche

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
121 changes: 121 additions & 0 deletions safe-onchain-agent-skill/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Safe On-Chain Solana Agent Skill

**Production-grade safety middleware for autonomous AI agents on Solana.**

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Framework: Solana AI Kit](https://img.shields.io/badge/Framework-Solana_AI_Kit-purple.svg)](https://github.com/solanabr/solana-ai-kit)
[![Version: 1.0.0](https://img.shields.io/badge/Version-1.0.0-green.svg)]()

---

## 🛑 The Problem: Agentic Trust on Solana

As AI agents transition from read-only observers to active on-chain participants, the risks increase dramatically. Standard tooling often leads to hallucinated transaction parameters, incorrect slippage causing MEV attacks, drained wallets, or stalled workflows due to transient RPC errors and expired blockhashes.

An agent cannot operate truly autonomously if a human must constantly monitor execution, manually adjust parameters, or intervene after every failure.

## 🛡️ The Solution: Simulation-First Safety Middleware

The **Safe On-Chain Solana Agent Skill** provides a rigorous safety layer for the [Solana AI Kit](https://github.com/solanabr/solana-ai-kit). It treats every agent-proposed action as untrusted until verified through pre-flight checks and mainnet simulation.

By combining **scoped permissions**, **intelligent error recovery**, and **self-healing patterns**, this skill enables agents to execute reliably and autonomously — even under volatile conditions.

---

## ✨ Key Features

- **Simulation-First Execution** — Every transaction is simulated against live mainnet state before signing. This validates exact balances, slippage, compute units, and account states.
- **Scoped Permissions & Wallet Hygiene** — Supports session keys and granular, time-bound allowances instead of exposing full private keys.
- **Intelligent Error Parsing + Autonomous Retry** — Translates raw Solana program errors into meaningful feedback. Automatically recovers from transient RPC issues, blockhash expirations, and minor slippage failures.
- **Pre-Flight Validation** — Checks token accounts, rent exemptions, fee lamports, and required state before any on-chain action.
- **Progressive / Token-Efficient Loading** — Only relevant knowledge and schemas are loaded into context when needed, reducing token usage and hallucination risk.
- **Deep Composability** — Works as a safety wrapper around existing tools (Jupiter, Meteora, etc.) without requiring changes to the underlying skills.

---

## 🏗️ Architecture Overview

The skill acts as an intelligent safety layer between the agent's reasoning and the Solana network.

```mermaid
graph TD
A[Agent Intent / LLM] -->|Proposes Action| B(Safety Middleware)
B --> C{Pre-flight Checks}
C -- Pass --> D[Transaction Simulation]
C -- Fail --> E[Self-Healing & Feedback]
D -- Success --> F[Scoped On-Chain Execution]
D -- Error / Slippage --> E
F --> G[State Validation & Receipt]
E -.->|Context Update| A

classDef secure fill:#e6f3ff,stroke:#0066cc,stroke-width:2px;
classDef execute fill:#e6ffe6,stroke:#00cc00,stroke-width:2px;
classDef error fill:#ffe6e6,stroke:#cc0000,stroke-width:2px;

class B,C,D secure;
class F,G execute;
class E error;
```

## 📦 Installation

### Add to Solana AI Kit (Recommended)

Clone the skill and add it to your project following the standard pattern used by other skills in the kit:

```bash
git clone https://github.com/Cryptojigi/safe-onchain-agent-skill.git
cd safe-onchain-agent-skill

# Run the installer (follow prompts)
./install.sh
```

Or manually add it as a git submodule / skill in your `.claude/skills/` directory for progressive loading.

### Source / Development

```bash
git clone https://github.com/Cryptojigi/safe-onchain-agent-skill.git
cd safe-onchain-agent-skill
```

## 🚀 Usage Examples

### 1. Safer Jupiter Swap (Prompt Example)

When the skill is loaded, Claude will automatically:
- Simulate the swap before suggesting any transaction
- Validate slippage against current market conditions
- Suggest corrected parameters or retry logic if simulation fails
- Provide clear reasoning for any adjustments

**Example prompt you can use:**
> “Perform a Jupiter swap of 25 USDC to SOL with 0.5% slippage. Use safe execution.”

Claude will now simulate first, check for realistic slippage, and only then provide the final transaction instructions.

### 2. Autonomous Position Monitoring with Self-Healing

The skill enables agents to run monitoring loops that recover gracefully from common failures (expired blockhash, RPC issues, minor price movements). Claude can now suggest safe rebalancing logic with built-in simulation and error recovery patterns.

### 3. Progressive Loading in the Solana AI Kit

The skill is designed for efficient context usage. Safety modules (simulation rules, error maps, permission patterns) are loaded only when the conversation involves on-chain actions.

## 🤝 Contributing

Contributions that improve on-chain agent safety are welcome.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Open a Pull Request

Please keep changes focused, well-documented, and aligned with production-grade standards.

---

**Safe On-Chain Solana Agent Skill** is built to help the Solana ecosystem move toward trustworthy autonomous agents.

*MIT License © 2026*
41 changes: 41 additions & 0 deletions safe-onchain-agent-skill/examples/jupiter-safe-swap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Example: Self-Healing Jupiter Swap

This example demonstrates how an AI agent equipped with the **Safe On-Chain Agent Skill** handles a typical token swap, specifically showcasing the middleware's ability to intercept failures and the agent's ability to self-correct.

## 1. The User Prompt
> **User:** "Swap 10 USDC for SOL on Jupiter using my active session key."

## 2. Agent Execution Flow

### Step 1: Pre-Flight Validation & Routing
The agent determines the current USDC balance and fetches a route from the Jupiter API for exactly 10 USDC to SOL, applying a default 0.1% slippage.

### Step 2: Simulation-First Execution (Failure)
Following the `.claude/rules/always-simulate-before-signing.md` rule, the agent proposes the transaction to the middleware for simulation against live mainnet state.

**Agent Action:**
> "I have calculated the route for 10 USDC to SOL. I will now simulate this transaction to ensure safety."

**Middleware Result:**
> ❌ **Simulation Failed:** `SlippageToleranceExceeded` (0x1771). The market moved during route calculation. Expected minimum out was 0.065 SOL, but the simulation yielded 0.0648 SOL.

### Step 3: Semantic Error Recovery (Self-Healing)
Instead of aborting or blindly retrying, the middleware maps the raw `0x1771` error into semantic context and injects it back into the LLM.

**Agent Self-Correction:**
> "The initial simulation failed because the slippage tolerance was exceeded. I have autonomously adjusted the slippage tolerance from 0.1% to 0.5% and fetched a new route."

### Step 4: Re-Simulation & Safe Execution
The agent submits the revised transaction.

**Middleware Result:**
> ✅ **Simulation Passed:** Transaction requires 55,000 Compute Units. No program errors. Slippage parameters are within bounds.

**Agent Action:**
> "The revised simulation was successful. Executing the safe transaction now..."
> *(Transaction is signed using the scoped session key and broadcasted to mainnet).*

## Key Safety Steps Taken
- **No Blind Signing:** The initial route would have failed on-chain, costing the user transaction fees. Simulation prevented this.
- **Zero-Trust Policy:** The agent used a scoped session key rather than holding a root private key.
- **Intelligent Error Recovery:** The agent used semantic feedback to adjust parameters, resolving a transient issue without bothering the user for manual intervention.
Loading