DEV Community

kenneth okenwa
kenneth okenwa

Posted on

Building Autonomous AI Agents on Solana: A Hands-On Guide with Solana Agent Kit and LangChain

By Kenneth Okenwa (@symplyKen | GitHub: @anekenonso)


AI Agents

1. Why Solana is the Settlement Layer for the AI Agent Economy

As artificial intelligence shifts from passive conversational assistants to autonomous economic actors, agents require an underlying financial rail. They need to pay for compute APIs, purchase data datasets, rebalance liquidity pools, and tip other agents for micro-tasks.

Traditional payment rails (Stripe, bank wires, credit cards) fail completely for AI agents: they require identity KYC, manual human onboarding, and impose heavy minimum fee floors (e.g., $0.30 + 2.9%), making 5-cent agent-to-agent transactions economically unviable.

Ethereum and high-fee EVM networks also present severe roadblocks: unpredictable gas auction spikes and multi-second block confirmations break high-frequency reasoning loops.

Solana provides the ideal substrate for autonomous AI agents:

  • Sub-Second Finality: ~400ms block times ensure agents can act with real-time speed.
  • Micro-Cent Transaction Fees: Average transaction fees of <$0.001 allow agents to conduct thousands of autonomous micro-operations daily without balance depletion.
  • Parallelized SVM Execution: The Sealevel runtime processes non-overlapping transactions concurrently, preventing localized DeFi activity from freezing an agent's operations.
  • Rich Composable Ecosystem: Deep liquidity on Jupiter DEX, compressed NFTs (cNFTs) for low-cost metadata attestation, and established SPL token standards.

In this developer guide, we walk through building an autonomous AI agent capable of reasoning, inspecting on-chain state, and executing live Solana transactions using the Solana Agent Kit and LangChain.


2. Architecture: How On-Chain AI Agents Work

An on-chain AI agent combines a high-level cognitive engine with deterministic blockchain execution tools:

┌──────────────────────────────────────────────────────────────┐
│                   Human Operator / Prompt                    │
│      "Check my SOL balance and swap 0.1 SOL to USDC"         │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│            Cognitive Layer (LangChain / LLM)                 │
│   • Evaluates user intent                                    │
│   • Selects appropriate tool from tool registry              │
│   • Extracts arguments: { amount: 0.1, output: "USDC" }      │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│                  Solana Agent Kit Bridge                     │
│   • Formats on-chain instruction                             │
│   • Fetches optimal swap route via Jupiter API               │
│   • Builds and signs serialized VersionedTransaction         │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│                    Solana Network (SVM)                      │
│   • Atomic execution on Mainnet-Beta / Devnet                │
│   • Returns transaction signature to Agent                   │
└──────────────────────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

3. Setting Up the Development Workspace

Let's initialize a fresh TypeScript project with the necessary dependencies:

mkdir solana-ai-agent
cd solana-ai-agent
npm init -y
npm install typescript @types/node ts-node --save-dev
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Install the Solana Agent Kit, Solana Web3 SDK, and LangChain packages:

npm install solana-agent-kit @solana/web3.js @langchain/core @langchain/openai dotenv bs58
Enter fullscreen mode Exit fullscreen mode

Create a .env file to configure your credentials:

OPENAI_API_KEY=your_openai_api_key_here
SOLANA_PRIVATE_KEY=your_base58_encoded_private_key_here
RPC_URL=https://api.mainnet-beta.solana.com
Enter fullscreen mode Exit fullscreen mode

Security Tip: Never commit .env or raw private keys to source control. For development, use a dedicated keypair funded with Devnet SOL from solana airdrop 1.


4. Implementation: The Autonomous Solana Agent

Create agent.ts to implement the agent initialization and execution loop:

import { SolanaAgentKit, createSolanaTools } from "solana-agent-kit";
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import * as dotenv from "dotenv";

dotenv.config();

async function bootstrapSolanaAgent() {
  console.log("==================================================");
  console.log("   BOOTSTRAPPING AUTONOMOUS SOLANA AGENT");
  console.log("==================================================");

  const privateKey = process.env.SOLANA_PRIVATE_KEY;
  const rpcUrl = process.env.RPC_URL || "https://api.devnet.solana.com";
  const openAIApiKey = process.env.OPENAI_API_KEY;

  if (!privateKey || !openAIApiKey) {
    throw new Error("Missing required environment variables in .env");
  }

  // 1. Initialize SolanaAgentKit instance
  const agentKit = new SolanaAgentKit(
    privateKey,
    rpcUrl,
    openAIApiKey
  );

  console.log(`Agent Wallet Address: ${agentKit.wallet_address.toBase58()}`);

  // 2. Wrap Solana Agent Kit actions into LangChain structured tools
  const tools = createSolanaTools(agentKit);
  console.log(`Loaded ${tools.length} on-chain tools (Jupiter, Pyth, SPL, Transfers)...`);

  // 3. Initialize the Cognitive LLM model
  const llm = new ChatOpenAI({
    model: "gpt-4o",
    temperature: 0.1, // Low temperature for deterministic financial decisions
  });

  // 4. Create the LangGraph ReAct execution agent
  const agent = createReactAgent({
    llm,
    tools,
  });

  return agent;
}

// 5. Interactive Execution Loop
async function runAgentTask(promptText: string) {
  const agent = await bootstrapSolanaAgent();

  console.log(`\n[Prompt]: "${promptText}"`);
  console.log("Agent is reasoning and selecting on-chain tools...\n");

  const stream = await agent.stream(
    {
      messages: [{ role: "user", content: promptText }],
    },
    { streamMode: "values" }
  );

  for await (const chunk of stream) {
    const lastMessage = chunk.messages[chunk.messages.length - 1];
    if (lastMessage.role === "assistant" && lastMessage.content) {
      console.log(`[Agent Response]:\n${lastMessage.content}\n`);
    }
  }
}

// Execute sample task
runAgentTask("Check my wallet's SOL balance, and tell me current network TPS.");
Enter fullscreen mode Exit fullscreen mode

5. What Actions Can the Agent Execute?

Thanks to the Solana Agent Kit's modular plugin ecosystem, your agent automatically inherits high-level capabilities without requiring manual instruction encoding:

  1. Token Swaps via Jupiter:
    • Prompt: "Swap 0.05 SOL to USDC with 1% slippage tolerance"
    • Action: Queries Jupiter aggregator for the best routing path, checks token decimals, builds the transaction, and executes it.
  2. Transferring SPL Tokens:
    • Prompt: "Send 5 USDC to 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
    • Action: Creates or resolves the recipient's Associated Token Account (ATA) and executes the SPL transfer.
  3. DeFi Staking & Lending:
    • Prompt: "Stake 1 SOL with Jito to get JitoSOL"
    • Action: Deposits SOL into the stake pool and receives liquid staking tokens.
  4. Compressed NFTs (cNFTs) via Bubblegum:
    • Prompt: "Mint an identity credential cNFT with metadata title 'IdentityForge Attestation'"
    • Action: Mints into a Merkle tree at a fraction of a cent per mint.

6. Critical Security Safeguards for Production Agents

Giving an autonomous LLM write access to a blockchain keypair requires strict defense-in-depth:

  1. Transaction Velocity & Caps: Wrap the agent runner with a maximum spend envelope (e.g., maximum 0.5 SOL per single transaction, max $200 per 24 hours).
  2. Session Key Delegation: Instead of funding the agent with the master treasury key, use delegated session keypairs that only have permissions for designated programs (e.g., only Jupiter and SPL transfers, with zero permission to drain stake accounts).
  3. Prompt Injection Sanitization: Never feed untrusted third-party Web2 data (e.g., raw tweets, unmoderated Discord messages) directly into the agent's system prompt without validating parameter schema boundaries.

7. The Frontier: What this Means for Builders in Nigeria & Africa

In emerging markets like Nigeria, access to global payment infrastructure has historically been plagued by card limits, FX restrictions, and high cross-border wire friction.

Autonomous on-chain agents on Solana unlock transformative micro-economic utilities:

  • Autonomous Remittance Agents: Bots that automatically convert global freelance earnings into stablecoins and rebalance to hedge currency volatility.
  • Agentic Micro-Bounties: Autonomous bots that review pull requests, verify bug fixes, and pay out 10–50 USDC bounties instantly without human administrative overhead.
  • Decentralized AI Workforces: Local developers can build agents that operate worldwide 24/7, earning revenue directly on Solana.

8. Conclusion & Getting Started

Autonomous AI agents will be the highest-volume transactors on public blockchains within the next 3 years. Solana's speed, micro-penny transaction costs, and mature developer tooling make it the natural home for this new paradigm.

To explore further:

Top comments (0)