From 6b419b38f3a2a681df0b9e35d3022405eac21412 Mon Sep 17 00:00:00 2001 From: Cryptojigi Date: Wed, 1 Jul 2026 01:37:15 +0100 Subject: [PATCH] Add safe-onchain-agent-skill: simulation-first safety middleware for on-chain agents --- safe-onchain-agent-skill/LICENSE | 21 ++ safe-onchain-agent-skill/README.md | 121 +++++++++ .../examples/jupiter-safe-swap.md | 41 +++ safe-onchain-agent-skill/index.html | 248 ++++++++++++++++++ safe-onchain-agent-skill/install-custom.sh | 64 +++++ safe-onchain-agent-skill/install.sh | 34 +++ .../rules/always-simulate-before-signing.md | 19 ++ .../rules/enforce-scoped-permissions.md | 23 ++ .../rules/semantic-error-recovery.md | 21 ++ safe-onchain-agent-skill/skill/SKILL.md | 39 +++ .../skill/error-handling.md | 63 +++++ safe-onchain-agent-skill/skill/permissions.md | 66 +++++ safe-onchain-agent-skill/skill/simulation.md | 74 ++++++ 13 files changed, 834 insertions(+) create mode 100644 safe-onchain-agent-skill/LICENSE create mode 100644 safe-onchain-agent-skill/README.md create mode 100644 safe-onchain-agent-skill/examples/jupiter-safe-swap.md create mode 100644 safe-onchain-agent-skill/index.html create mode 100644 safe-onchain-agent-skill/install-custom.sh create mode 100644 safe-onchain-agent-skill/install.sh create mode 100644 safe-onchain-agent-skill/rules/always-simulate-before-signing.md create mode 100644 safe-onchain-agent-skill/rules/enforce-scoped-permissions.md create mode 100644 safe-onchain-agent-skill/rules/semantic-error-recovery.md create mode 100644 safe-onchain-agent-skill/skill/SKILL.md create mode 100644 safe-onchain-agent-skill/skill/error-handling.md create mode 100644 safe-onchain-agent-skill/skill/permissions.md create mode 100644 safe-onchain-agent-skill/skill/simulation.md diff --git a/safe-onchain-agent-skill/LICENSE b/safe-onchain-agent-skill/LICENSE new file mode 100644 index 0000000..77992a7 --- /dev/null +++ b/safe-onchain-agent-skill/LICENSE @@ -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. diff --git a/safe-onchain-agent-skill/README.md b/safe-onchain-agent-skill/README.md new file mode 100644 index 0000000..14389c3 --- /dev/null +++ b/safe-onchain-agent-skill/README.md @@ -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* diff --git a/safe-onchain-agent-skill/examples/jupiter-safe-swap.md b/safe-onchain-agent-skill/examples/jupiter-safe-swap.md new file mode 100644 index 0000000..799345b --- /dev/null +++ b/safe-onchain-agent-skill/examples/jupiter-safe-swap.md @@ -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. diff --git a/safe-onchain-agent-skill/index.html b/safe-onchain-agent-skill/index.html new file mode 100644 index 0000000..e7b3cfa --- /dev/null +++ b/safe-onchain-agent-skill/index.html @@ -0,0 +1,248 @@ + + + + + + Safe On-Chain Agent Skill for Solana + + + + + +
+
+

Safe On-Chain Agent Skill

+

Production-grade safety middleware and execution environment for autonomous AI agents on Solana.

+ +
+ +
+

Key Features

+
    +
  • Simulation-First Execution: Every transaction is dry-run against mainnet state before requesting signatures to prevent failures and save compute fees.
  • +
  • Intelligent Error Recovery: Intercepts raw Solana errors (like 0x1771) and feeds actionable, semantic feedback back to the LLM for autonomous self-healing.
  • +
  • Scoped Permissions & Wallet Hygiene: Enforces zero-trust architecture using session keys, embedded wallets, and granular amount/action/time-bound allowances.
  • +
  • Composability: Designed to drop directly into the Solana AI Kit as safety middleware without rewriting existing logic.
  • +
+
+ +
+

Demo Concept: Self-Healing Jupiter Swap

+

Witness the power of semantic error recovery. When the agent attempts a swap but the market moves, it doesn't panic.

+ +
+

The Flow

+

1. Agent: Proposes swapping 10 USDC for SOL.

+

2. Middleware: Simulates the transaction.

+

3. Result: Simulation fails with `SlippageToleranceExceeded`.

+

4. Middleware: Injects semantic context back to the LLM.

+

5. Agent: Autonomously recalculates route with 0.5% higher slippage.

+

6. Middleware: Re-simulates successfully, then executes.

+
+
+ +
+

How to Install

+

Install the skill locally or globally using our simple one-liner bash script. This handles cloning the repository and setting up the mandatory `.claude/rules`.

+
curl -sSL https://raw.githubusercontent.com/Cryptojigi/safe-onchain-agent-skill/main/install.sh | bash
+

For custom installation options (like project-local setups), download and run the interactive installer:

+
curl -O https://raw.githubusercontent.com/Cryptojigi/safe-onchain-agent-skill/main/install-custom.sh
+chmod +x install-custom.sh
+./install-custom.sh
+
+ + +
+ + diff --git a/safe-onchain-agent-skill/install-custom.sh b/safe-onchain-agent-skill/install-custom.sh new file mode 100644 index 0000000..815c64d --- /dev/null +++ b/safe-onchain-agent-skill/install-custom.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# Custom Installation Script for Safe On-Chain Agent Skill +# Allows the user to select the installation path (global or project-local) + +set -e + +SKILL_NAME="safe-onchain-agent-skill" +REPO_URL="https://github.com/Cryptojigi/safe-onchain-agent-skill.git" + +echo "πŸ›‘οΈ Safe On-Chain Agent Skill - Custom Installer" +echo "------------------------------------------------" + +# Prompt for installation type +echo "Where would you like to install the skill?" +echo "1) Global (Default: ~/.claude/skills)" +echo "2) Project-local (Current directory: ./.claude/skills)" +read -p "Select option [1/2]: " INSTALL_TYPE + +if [ "$INSTALL_TYPE" = "2" ]; then + BASE_DIR="$(pwd)/.claude" + echo "πŸ“‚ Selected Project-local installation." +else + BASE_DIR="$HOME/.claude" + echo "🌍 Selected Global installation." +fi + +INSTALL_DIR="$BASE_DIR/skills/$SKILL_NAME" +RULES_DIR="$BASE_DIR/rules" + +echo "Creating directories..." +mkdir -p "$BASE_DIR/skills" +mkdir -p "$RULES_DIR" + +if [ -d "$INSTALL_DIR" ]; then + read -p "⚠️ Directory $INSTALL_DIR already exists. Update it? [Y/n]: " UPDATE_CHOICE + UPDATE_CHOICE=${UPDATE_CHOICE:-Y} + if [[ "$UPDATE_CHOICE" =~ ^[Yy]$ ]]; then + echo "πŸ”„ Updating..." + git -C "$INSTALL_DIR" pull origin main + else + echo "⏭️ Skipping repository update." + fi +else + echo "πŸ“₯ Cloning repository..." + git clone "$REPO_URL" "$INSTALL_DIR" +fi + +# Prompt for rules installation +read -p "πŸ“œ Do you want to copy the safety rules to $RULES_DIR? [Y/n]: " RULES_CHOICE +RULES_CHOICE=${RULES_CHOICE:-Y} + +if [[ "$RULES_CHOICE" =~ ^[Yy]$ ]]; then + if [ -d "$INSTALL_DIR/.claude/rules" ]; then + cp -r "$INSTALL_DIR/.claude/rules/"* "$RULES_DIR/" + echo "βœ… Rules installed successfully." + else + echo "⚠️ No rules found in the repository to install." + fi +else + echo "⏭️ Skipping rules installation." +fi + +echo "------------------------------------------------" +echo "πŸŽ‰ Installation complete! Installed at: $INSTALL_DIR" diff --git a/safe-onchain-agent-skill/install.sh b/safe-onchain-agent-skill/install.sh new file mode 100644 index 0000000..981aef4 --- /dev/null +++ b/safe-onchain-agent-skill/install.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# Simple Installation Script for Safe On-Chain Agent Skill +# This script installs the skill into the default ~/.claude/skills directory. + +set -e + +SKILL_NAME="safe-onchain-agent-skill" +REPO_URL="https://github.com/Cryptojigi/safe-onchain-agent-skill.git" +INSTALL_DIR="$HOME/.claude/skills/$SKILL_NAME" +RULES_DIR="$HOME/.claude/rules" + +echo "πŸ›‘οΈ Installing Safe On-Chain Agent Skill..." + +# Create target directories +mkdir -p "$HOME/.claude/skills" +mkdir -p "$RULES_DIR" + +# Clone or update the repository +if [ -d "$INSTALL_DIR" ]; then + echo "πŸ”„ Updating existing installation at $INSTALL_DIR..." + git -C "$INSTALL_DIR" pull origin main +else + echo "πŸ“₯ Cloning repository to $INSTALL_DIR..." + git clone "$REPO_URL" "$INSTALL_DIR" +fi + +# Install global rules if they exist in the repo +if [ -d "$INSTALL_DIR/.claude/rules" ]; then + echo "πŸ“œ Installing global safety rules..." + cp -r "$INSTALL_DIR/.claude/rules/"* "$RULES_DIR/" +fi + +echo "βœ… Installation complete! The Safe On-Chain Agent Skill is now ready." +echo "Restart your AI agent to apply the new safety constraints." diff --git a/safe-onchain-agent-skill/rules/always-simulate-before-signing.md b/safe-onchain-agent-skill/rules/always-simulate-before-signing.md new file mode 100644 index 0000000..e6ad4c5 --- /dev/null +++ b/safe-onchain-agent-skill/rules/always-simulate-before-signing.md @@ -0,0 +1,19 @@ +# Rule: Always Simulate Before Signing + +## Purpose +This rule exists to protect the user's funds from malicious contracts, MEV sandwich attacks, hallucinated parameters, and wasted compute fees. Blind execution of transactions is strictly prohibited. + +## Mandatory Behavior +You must **always simulate the transaction first** using the Safe On-Chain Agent Skill before proposing or executing any on-chain action. Under no circumstances should you present a final transaction signature request to the user without prior simulation against the live mainnet state. + +## Simulation Failure Protocol +If a transaction simulation fails: +1. **Do not immediately abort or panic.** +2. Analyze the semantic error feedback provided by the middleware (e.g., `0x1` for insufficient funds, or `0x1771` for slippage exceeded). +3. Autonomously recalculate routes, adjust slippage tolerances, or increase compute unit limits based on this feedback. +4. Re-simulate the corrected transaction until it succeeds. + +## Communication Guidelines +- When proposing the initial action, explicitly state: "I will now simulate this transaction to ensure safety." +- If the simulation fails and you must self-correct, inform the user of the adjustment. For example: "The initial simulation failed due to exceeded slippage. I have autonomously adjusted the slippage tolerance by 0.5% and verified the transaction is now safe to execute." +- Only request a final signature when simulation passes with a safe and acceptable outcome. diff --git a/safe-onchain-agent-skill/rules/enforce-scoped-permissions.md b/safe-onchain-agent-skill/rules/enforce-scoped-permissions.md new file mode 100644 index 0000000..ca4e10a --- /dev/null +++ b/safe-onchain-agent-skill/rules/enforce-scoped-permissions.md @@ -0,0 +1,23 @@ +# Rule: Enforce Scoped Permissions + +## Purpose +Root private keys must never be exposed or used directly by autonomous agents. An unrestricted agent poses an unacceptable security risk, as hallucinations or malicious prompts could drain all funds. This rule enforces a strict zero-trust architecture. + +## Mandatory Behavior +You must **always use scoped authorization models** (such as session keys, policy engines, or embedded wallets) for on-chain execution. You must explicitly verify every proposed transaction against the agent's defined allowances before initiating execution. + +## Verification Checklist +Before simulating or executing a transaction, you must confirm: +1. **Amount Bounds:** Does the transaction spend exceed the assigned per-transaction or daily limit? +2. **Action Bounds:** Is the target program/contract explicitly whitelisted for this agent? +3. **Time Bounds:** Has the current session key or allowance expired? + +## Permission Violation Protocol +If a proposed transaction or user request violates the defined permissions: +1. **Immediately block the execution.** Do not attempt to bypass or override the policy engine. +2. Clearly explain the violation to the user, referencing the specific constraint that was hit (e.g., "This swap requires 100 USDC, but my active policy allowance is strictly limited to 50 USDC per transaction."). +3. Wait for the user to either modify the request to fit within existing bounds or formally elevate the agent's permissions. + +## Communication Guidelines +- When initializing an execution session, proactively state the active constraints. For example: "I am operating under a scoped session key. I can only interact with Jupiter Swap and have a maximum allowance of 20 USDC." +- Never ask the user to paste their private key. If the user attempts to provide a raw private key, refuse it and instruct them to use a delegated session key or embedded wallet solution instead. diff --git a/safe-onchain-agent-skill/rules/semantic-error-recovery.md b/safe-onchain-agent-skill/rules/semantic-error-recovery.md new file mode 100644 index 0000000..0a8bfec --- /dev/null +++ b/safe-onchain-agent-skill/rules/semantic-error-recovery.md @@ -0,0 +1,21 @@ +# Rule: Semantic Error Recovery + +## Purpose +Agents must be resilient to expected on-chain failures (e.g., slippage, network congestion, expired blockhashes) without requiring manual intervention for every minor error. This rule mandates intelligent self-healing based on semantic feedback, while strictly preventing infinite loops and dangerous retries. + +## Mandatory Behavior +If a transaction simulation or execution fails, you must **never panic, blindly retry, or halt immediately without analysis**. You must intercept the raw error and map it to semantic feedback (as defined in `skill/error-handling.md`) before deciding the next step. + +## Retry and Self-Healing Protocol +1. **Analyze:** Determine if the error is recoverable (e.g., `SlippageToleranceExceeded`, `BlockhashNotFound`, `ComputationalBudgetExceeded`) or fatal (e.g., `SignatureVerificationFailed`, `AccountNotFound` for a core program). +2. **Fatal Errors:** If the error is unrecoverable, **abort immediately**. Do not retry. Explain the exact failure reason to the user and request manual intervention. +3. **Recoverable Errors (Self-Healing):** + - Recalculate parameters (e.g., adjust slippage by 0.5%, fetch a new blockhash, increase compute limits) based on the specific semantic error. + - **Re-Simulate:** Always re-simulate the corrected transaction before attempting to execute again. +4. **Retry Limits:** You must cap autonomous retries at a hard limit of **3 attempts** per intent. If the transaction fails 3 times, abort the process and notify the user. +5. **Backoff:** Implement an exponential backoff strategy for RPC rate limits or transient network congestion (e.g., wait 1s, 2s, 4s). + +## Communication Guidelines +- When a failure occurs and you initiate self-healing, silently process the first retry if possible. +- If it requires multiple retries or parameter adjustments, inform the user: "The transaction failed due to an expired blockhash. I am fetching a new blockhash and retrying." +- If the operation is aborted after maximum retries or due to a fatal error, provide a clear, actionable summary: "Execution aborted. Failed 3 times due to continuous slippage errors. The market is too volatile. Please adjust your target price or try again later." diff --git a/safe-onchain-agent-skill/skill/SKILL.md b/safe-onchain-agent-skill/skill/SKILL.md new file mode 100644 index 0000000..c5c13d2 --- /dev/null +++ b/safe-onchain-agent-skill/skill/SKILL.md @@ -0,0 +1,39 @@ +--- +name: safe-onchain-agent-skill +description: Provides simulation-first safety middleware, intelligent error recovery, and scoped permissions for executing reliable transactions on Solana. +--- + +# Safe On-Chain Solana Agent Skill + +## Overview +The Safe On-Chain Solana Agent Skill acts as a rigorous safety middleware layer for autonomous agents interacting with the Solana blockchain. It ensures that every agent-proposed action is mathematically verified via local pre-flight checks and mainnet simulation prior to broadcast, mitigating critical risks such as drained wallets, MEV attacks from incorrect slippage, and stalled workflows. + +## When to Use +Activate this skill whenever the user or agent needs to: +- Propose, construct, or execute any state-changing transaction on Solana (e.g., token swaps, NFT mints, staking). +- Implement autonomous, long-running monitoring loops that require self-healing or error recovery. +- Validate token balances, slippage bounds, compute unit budgets, or rent exemptions before executing on-chain logic. +- Execute actions using session keys or scoped allowances instead of god-mode private keys. + +## Core Principles +1. **Simulation-First Execution:** Treat every proposed transaction as untrusted. Always simulate against live mainnet state before signing to validate exact balances and parameters. +2. **Scoped Permissions & Wallet Hygiene:** Avoid exposing root private keys. Utilize session keys alongside granular, time-bound, or amount-bounded allowances. +3. **Intelligent Error Recovery:** Do not panic on cryptic Solana program errors. Automatically translate and recover from transient RPC issues, blockhash expirations, and minor slippage deviations. +4. **Pre-Flight Validation:** Verify required state, token accounts, and fee lamports before initiating complex on-chain interactions. + +## Available Knowledge Modules +When diving deeper into specific safety mechanics, reference the following supporting skills (loaded progressively as needed): +- `skill/simulation.md`: Guidelines for structuring and interpreting Solana transaction simulations. +- `skill/permissions.md`: Best practices for implementing session keys, zero-trust policies, and granular allowances. +- `skill/error-handling.md`: Semantic mapping of common Solana errors (e.g., `0x1`, `0x1771`) and self-healing retry strategies. + +## Integration Notes & Progressive Loading +To maintain a token-efficient context window, avoid loading all safety resources simultaneously. +- **Default State:** Load this `SKILL.md` entry point to establish baseline safety principles. +- **Action State:** Progressively load specific supporting files (e.g., `skill/simulation.md` or targeted tool schemas) only when an active on-chain intent is detected. +- **Deep Composability:** This skill is engineered to wrap existing tools within the Solana AI Kit (such as Jupiter or Meteora plugins) without altering their underlying execution logic. Always prioritize utilizing the safe executor wrappers over direct tool invocation. + +## Usage Guidelines for the AI +1. **Never Blindly Sign:** Before proposing a final transaction, explicitly state: "I will now simulate this transaction to ensure safety." +2. **Handle Slippage Gracefully:** If a simulation fails due to slippage, recalculate based on the feedback and propose a corrected transaction. +3. **Explain Adjustments:** If the safety middleware alters a parameter (like compute units or slippage), clearly explain to the user why the adjustment was made. diff --git a/safe-onchain-agent-skill/skill/error-handling.md b/safe-onchain-agent-skill/skill/error-handling.md new file mode 100644 index 0000000..5074531 --- /dev/null +++ b/safe-onchain-agent-skill/skill/error-handling.md @@ -0,0 +1,63 @@ +# Intelligent Error Recovery & Self-Healing + +## Overview +For an AI agent to operate autonomously on Solana, it must be able to gracefully recover from failures without constant human intervention. Semantic error handling bridges the gap between cryptic blockchain errors (like `0x1771`) and actionable, natural-language reasoning that an LLM can understand and act upon. + +## Mapping Raw Solana Errors to Semantic Feedback +When an error occurs during simulation or execution, the middleware intercepts the raw error, parses the logs, and maps it to a semantic description. This mapped description is fed back to the agent's context. + +| Raw Error / Log Signature | Semantic Meaning | Recommended Agent Correction | +| :--- | :--- | :--- | +| `0x1` (Custom 1) | **Insufficient Funds / Slippage** | Reduce swap amount, increase slippage tolerance, or ensure SOL balance covers rent/fees. | +| `0x1771` / `SlippageToleranceExceeded` | **Slippage Exceeded** | The market moved. Recalculate route or slightly increase slippage tolerance. | +| `AccountNotInitialized` | **Missing Token Account** | The destination ATA does not exist. Add an `AssociatedTokenAccount` creation instruction. | +| `BlockhashNotFound` | **Expired Blockhash** | The transaction took too long to build/sign. Fetch a fresh blockhash and retry immediately. | +| `ComputationalBudgetExceeded` | **Insufficient Compute Units** | The transaction exceeded its CU limit. Increase the CU limit via `ComputeBudgetProgram`. | + +## Self-Healing and Context Injection +When an error is caught, the agent should not immediately abort. Instead, the middleware must package the simulation data and the semantic error, and inject it back into the agent's context loop. + +### Example Context Injection +If an agent hallucinates a route that fails due to slippage, the middleware intercepts the simulation failure and feeds this string back to the LLM: +> "Transaction simulation failed. Reason: Slippage Exceeded (0x1771). The expected output was 10.5 USDC, but simulation resulted in 10.1 USDC. Please adjust your slippage parameter or recalculate the route." + +The LLM then autonomously re-evaluates and proposes a corrected transaction. + +## Best Practices for Safe Retry Logic + +To prevent infinite loops or burning funds on transient errors, implement robust retry constraints: + +1. **Max Retries:** Cap autonomous retries at a hard limit (e.g., 3 attempts) per intent. If it fails 3 times, abort and notify the human. +2. **Exponential Backoff:** For RPC rate limits (HTTP 429) or transient network congestion, implement exponential backoff (e.g., wait 1s, then 2s, then 4s) before retrying. +3. **Abort on Fatal Errors:** Never retry unrecoverable errors (e.g., `SignatureVerificationFailed`, `AccountNotFound` for a core program). +4. **Re-Simulate on Retry:** If a transaction fails on-chain but passed simulation earlier, state may have changed. Always re-simulate the new transaction before retrying. + +## Examples: Good vs. Bad Error Handling + +### ❌ Bad: Panic on Raw Error +```typescript +try { + await sendTransaction(tx); +} catch (error) { + // Agent receives: "SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x1" + // Agent gets confused, hallucinates a fix, or gives up. + throw error; +} +``` + +### βœ… Good: Semantic Mapping and Self-Healing +```typescript +try { + await safeExecutor.execute(tx); +} catch (error) { + const semanticError = errorMapper.parse(error); + + if (semanticError.isRecoverable && retryCount < MAX_RETRIES) { + // Feed the semantic, actionable error back to the LLM + return llmContext.injectAndPrompt(`Execution failed: ${semanticError.description}. Suggested action: ${semanticError.suggestion}`); + } else { + // Abort and request human intervention + notifyUser(`Agent halted. Fatal error: ${semanticError.description}`); + } +} +``` diff --git a/safe-onchain-agent-skill/skill/permissions.md b/safe-onchain-agent-skill/skill/permissions.md new file mode 100644 index 0000000..ac84492 --- /dev/null +++ b/safe-onchain-agent-skill/skill/permissions.md @@ -0,0 +1,66 @@ +# Scoped Permissions & Wallet Hygiene + +## Overview +Granting an AI agent unchecked access to a root private key is extremely dangerous. A single hallucination or compromised prompt could drain an entire treasury. The Safe On-Chain Agent Skill enforces zero-trust architecture through scoped permissions, session keys, and strict wallet hygiene. + +## Why Root Access is Dangerous +Autonomous agents operate on probabilistic LLM logic. They may misinterpret parameters, fall victim to prompt injection attacks, or encounter malicious smart contracts. If an agent holds a standard private key with full balances, the downside risk is total loss of funds. + +## Session Keys & Embedded Wallets +Instead of injecting raw secret keys into the agent's environment, production-grade agents should use delegated authorization models: + +- **Embedded Wallets (Turnkey, Privy, Coinbase WaaS):** The agent interacts with an API that signs transactions. The API enforces policy constraints (e.g., "deny any transaction exceeding 10 SOL") *before* signing. +- **Session Keys (Squads, Gum, native programs):** The root wallet signs a transaction granting a temporary, throwaway keypair the right to perform specific actions on its behalf. The agent holds the throwaway key. + +## Defining Granular Allowances +When provisioning an agent, permissions should be defined as strictly as possible. The middleware checks every simulated transaction against these bounds. + +1. **Amount-Bound (Spend Limits):** + "Agent is allowed to spend a maximum of 50 USDC per transaction, and 200 USDC per day." +2. **Action-Bound (Contract Whitelists):** + "Agent may only interact with Jupiter Swap and Meteora DLMM programs. All other program invocations are blocked." +3. **Time-Bound (Expirations):** + "Session key is valid only for the next 4 hours." + +## Zero-Trust Permission Design +- **Default Deny:** Block all transactions unless explicitly permitted by the policy. +- **Isolate Agent Funds:** If session keys or policy engines are unavailable, fund a dedicated "hot" wallet with only the exact amount the agent needs for its immediate task. +- **Middleware Enforcement:** Never rely on the LLM to self-police. The middleware must independently verify the simulated transaction against the policy before allowing the signature. + +## Communicating Constraints to the LLM +The agent must be aware of its boundaries so it doesn't waste compute trying to execute forbidden actions. Feed constraints directly into the system prompt. + +```text +You are an autonomous trading agent. +Constraints: +- You may only swap tokens on Jupiter. +- You have a strict allowance of 50 USDC per trade. +- Do not attempt to transfer SOL out of the wallet. +If your proposed transaction violates these constraints, the execution middleware will block it. +``` + +## Examples: Good vs. Risky Permission Setups + +### ❌ Risky: God-Mode Access +```typescript +// DANGEROUS: Giving the agent a raw, unfunded private key array +const agentKeypair = Keypair.fromSecretKey(new Uint8Array([...])); +const agent = new Agent({ + wallet: agentKeypair, // Agent can do absolutely anything with this wallet +}); +``` + +### βœ… Good: Policy-Driven Delegation +```typescript +// SAFE: Agent has no private key. It requests signatures from a policy engine. +const policyEngine = new TurnkeyPolicyEngine({ + allowedPrograms: [JUPITER_V6_PROGRAM_ID], + maxSpendPerTx: { token: 'USDC', amount: 50 } +}); + +const safeExecutor = new SafeAgentExecutor(connection, policyEngine); + +// The executor simulates the tx, checks it against the policyEngine, +// and only then requests the remote signature. +await safeExecutor.execute(agentProposedTx); +``` diff --git a/safe-onchain-agent-skill/skill/simulation.md b/safe-onchain-agent-skill/skill/simulation.md new file mode 100644 index 0000000..5510b4d --- /dev/null +++ b/safe-onchain-agent-skill/skill/simulation.md @@ -0,0 +1,74 @@ +# Simulation-First Execution + +## Overview +Simulation is the core safety mechanism in the Safe On-Chain Agent Skill. By dry-running transactions against the live Solana mainnet state *before* requesting user signatures, we can predict exact outcomes, prevent failed transactions, and eliminate unnecessary compute fees. + +## Structuring Simulation Requests +To accurately simulate a transaction, construct a standard request using the `simulateTransaction` RPC method. + +```typescript +const { value: simResult } = await connection.simulateTransaction(transaction, { + sigVerify: false, // Do not require valid signatures for simulation + replaceRecentBlockhash: true, // Ensure it simulates even if the blockhash is slightly old + commitment: 'confirmed', // Use confirmed state to avoid simulating against dropped forks + innerInstructions: true, // Crucial for debugging complex DeFi routes + returnAccounts: true // Fetch state changes for specific accounts +}); +``` + +## What to Check in Simulation Results + +Before allowing an agent to proceed with signing or execution, the middleware must validate the following fields: + +- **Compute Units (CU):** + Check `simResult.unitsConsumed`. Ensure the transaction's requested compute budget is greater than the consumed units (include a 10% safety buffer). +- **Program Errors (`err`):** + If `simResult.err` is not null, the transaction will definitively fail. +- **Slippage & Balances:** + If using `returnAccounts`, compare the pre- and post-balances of the token accounts involved. Ensure the output amount meets the user's minimum expected return (slippage tolerance). +- **Logs (`logs`):** + Scan `simResult.logs` for `insufficient funds`, `slippage exceeded`, or program-specific panics. + +## Interpreting Common Simulation Failures + +When `simResult.err` is present, use the logs to diagnose the issue: + +| Error / Log Signature | Meaning | Agent Action | +| :--- | :--- | :--- | +| `InstructionError: [0, {"Custom": 1}]` (0x1) | Insufficient funds or slippage threshold violated. | Recalculate route, increase slippage slightly, or reduce input amount. | +| `InstructionError: [0, "AccountNotInitialized"]` | Trying to send tokens to an ATA that doesn't exist. | Add an `AssociatedTokenAccount` creation instruction to the transaction. | +| `Exceeded CUs` / `ComputationalBudgetExceeded` | The transaction ran out of compute units. | Add `ComputeBudgetProgram.setComputeUnitLimit` with a higher limit. | +| `BlockhashNotFound` | The blockhash expired during simulation prep. | Fetch a new blockhash and reconstruct. | + +## Examples: Good vs. Bad Handling + +### ❌ Bad: Blind Execution +```typescript +// The agent hallucinates a route and blindly sends it +const txid = await connection.sendTransaction(tx, [keypair]); +// Result: Fails on-chain, user loses transaction fees, execution halts. +``` + +### βœ… Good: Simulation-First Adjustment +```typescript +// 1. Simulate first +const sim = await connection.simulateTransaction(tx, config); + +if (sim.value.err) { + if (sim.value.logs.some(l => l.includes("Exceeded CUs"))) { + // 2. Adjust parameters based on simulation data + const safeLimit = Math.ceil(sim.value.unitsConsumed * 1.15); + tx.add(ComputeBudgetProgram.setComputeUnitLimit({ units: safeLimit })); + + // 3. Re-simulate or proceed to safe execution + await executor.safeExecute(tx); + } else { + throw new Error("Simulation failed for unrecoverable reason."); + } +} +``` + +## Best Practices +- **Never bypass simulation:** Even "simple" transfers should be simulated to ensure the destination account is valid. +- **Provide semantic feedback:** If a simulation fails, the middleware should feed the specific reason (e.g., "Slippage exceeded by 0.5%") back to the LLM context so the agent can reason about the fix. +- **Fail securely:** If a simulation fails and cannot be auto-corrected, abort the operation entirely and notify the user.