git clone https://github.com/solana-labs/solana-agent-kit.git
cd solana-agent-kit
yarn install
Once installed, build and deploy the agent runtime using:
solana program deploy target/deploy/agent_program.so --url https://api.devnet.solana.com
This deploys the core program enabling agent logic on Solana. For quick testing, you can run sample scripts in examples/ like hello_agent.ts to confirm your environment.
In my experience, setting up wallet permissions and RPC endpoints correctly here saves hours of frustration later — triple-check the cluster URL and wallet keypair path.
Creating Your First On-Chain AI Agent
The Solana Agent Kit is designed with modularity — you write agent logic mostly in Rust on-chain, then interact via off-chain SDKs (TypeScript/Python).
Here’s a minimal agent example in Rust running simple event handlers:
#[program]
pub mod simple_agent {
use super::*;
pub fn handle_action(ctx: Context<ActionContext>, input: u64) -> ProgramResult {
msg!("Agent received input: {}", input);
// Example: call other programs here or update state
Ok(())
}
}
This barebones setup listens for transactions targeting your program with serialized input. On the off-chain side, your TypeScript client sends a transaction like this:
import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';
async function sendAgentAction(connection: Connection, payerKeypair: Keypair, agentProgramId: PublicKey, input: number) {
const instruction = new TransactionInstruction({
keys: [],
programId: agentProgramId,
data: Buffer.from(Uint8Array.of(input)), // simplistic input
});
const tx = new Transaction().add(instruction);
await connection.sendTransaction(tx, [payerKeypair]);
console.log('Sent agent action with input:', input);
}
For a real agent, you’d extend data layouts, use PDAs for state, and call other Solana programs (like Serum or Orca).
Integrating Solana Agent Kit with Langchain
Langchain excels at chaining LLM prompts with external actions; integrating it with Solana Agent Kit lets you translate AI decisions to on-chain agent calls.
The main idea: run your AI workflows off-chain with Langchain, but invoke Solana agent instructions as side effects.
Here’s a simplified snippet:
import { SolanaAgent } from 'solana-agent-kit';
import { Chain } from 'langchain';
class SolanaAgentChain extends Chain {
constructor() {
super();
this.agent = new SolanaAgent({ connection, programId, payerKeypair });
}
async _call(input: string) {
const aiDecision = await someLLMcall(input); // e.g., OpenAI
// send AI output to Solana agent contract
const txSig = await this.agent.sendAction(parseInt(aiDecision));
return `Tx sent: ${txSig}`;
}
}
What I’ve found is that handling rate limits and batching in Langchain before sending transactions reduces RPC failures with Solana’s rate-limited nodes.
Linking Langchain’s prompt chains to on-chain Solana actions bridges AI reasoning to real DeFi or agent-controlled flows.
LangGraph Example: Visual Workflow for Agents
LangGraph offers a visual node-based editor for AI workflows, which can integrate Solana Agent Kit steps.
Example use case: user inputs -> LLM analysis -> condition nodes -> agent transaction dispatch.
Pseudo-code for a LangGraph node that sends agent actions:
class AgentTransactionNode {
execute(context) {
const input = context.get('agentInput');
return solanaAgent.sendAction(input).then(txSig => {
context.set('txSignature', txSig);
return txSig;
});
}
}
These visual tools ease debugging complex AI + blockchain pipelines without writing all boilerplate.
Implementing DeFi Actions on Solana
Automated DeFi requires your AI agent to interact with SPL token swaps, liquidity pools, or lending protocols.
A practical example: swapping tokens on Serum Dex programmatically.
Here’s how your Solana agent script calls Serum swap instructions:
import { Market, OpenOrders } from '@project-serum/serum';
async function performSwap(connection, wallet, marketAddress, amount) {
const market = await Market.load(connection, marketAddress, {}, SERUM_DEX_PID);
const payer = wallet.publicKey;
const openOrders = await OpenOrders.findForOwner(connection, payer, marketAddress, SERUM_DEX_PID);
// Compose and send a swap order (simplified)
const orderTx = market.makePlaceOrderTransaction(connection, {
owner: wallet.publicKey,
payer: payer,
side: 'buy',
price: 1,
size: amount,
orderType: 'limit',
});
await connection.sendTransaction(orderTx, [wallet]);
console.log('Swap order submitted');
}
In production, I'd recommend building this in agent Rust program with PDA-managed state and secure price oracles (see FAQ for oracle integration tips).
Agent Payment Protocols and MCP Integration
Handling micro-payments for AI agent services on-chain follows agent payment protocol patterns, often integrating with blockchain MCP servers.
The Solana Agent Kit supports payment flow hooks to authorize transactions only after off-chain payment confirmations.
Here’s a usage pattern:
const paymentConfirmed = await mcpServer.confirmPayment(agentId, userWallet);
if (!paymentConfirmed) throw new Error('Payment required');
await solanaAgent.sendAction(myActionData);
Caution: trust boundaries here matter. MCP servers can be untrusted—use signed receipts and verify payment conditions strictly on-chain to prevent freeloading.
If you want an example integrating MCP with Solana Agent Kit, see mcp-server-integration.
Security Considerations When Using Solana Agent Kit
From my time shipping agents, here are points to watch:
- Session keys & spending limits: Always scope agent wallets with limited authority to mitigate risks of funds draining.
- Unlimited approvals: Avoid infinite token approvals; establish on-demand allowances.
- Untrusted MCP servers: Validate all off-chain payment signals on-chain.
- Mainnet vs testnet: Extensively test on devnet before mainnet deployment; bugs in Rust agent logic can cost real funds.
- Audit integration: Use Slither or Aderyn (where applicable) for static analysis, though Solana Rust differs from EVM Solidity—consider Rust linters and fuzzing.
Troubleshooting Common Issues
Error: Transaction failed with instruction error 0x1
Often the agent encountered unauthorized account access or invalid PDA. Check your account seeds and wallet keypair.
RPC rate limits causing send failures
Batch or throttle transactions, or deploy your own RPC node.
Agent state not updating
Verify on-chain PDA addresses and that your transaction includes the necessary account metas.
For more in-depth debugging, see agent-wallet-security and trading-bot-development.
Summary and Next Steps
This tutorial walked through setting up Solana Agent Kit, creating a basic on-chain AI agent, and integrating with Langchain and LangGraph. We touched on implementing DeFi actions and securing agent payments with MCP protocols. I hope the practical code and candid notes on gotchas help you build robust decentralized AI agents.
From here, experiment with:
- Extending Rust agent logic with custom PDAs
- Tight integration with oracle feeds for DeFi automation
- More advanced Langchain prompt sequencing tied to agent state
- Full audit pipelines integrating static analysis tools plus runtime monitoring
If you want to explore related agent frameworks or account abstraction, the following pages may help:
Ready to ship your first AI-powered Solana agent? Start small, test on devnet, and iterate with secure wallet handling. And remember — the edge cases tend to appear once agents start handling money autonomously.
Happy building!
Related: Rig Rust AI Agent Framework