How to build onchain agents: wallets, payments, and real-time data
Author: Uttam Singh

Most "AI agent" tutorials stop at the LLM. The hard part starts when the agent needs a wallet, a way to pay for the services it calls, and a live view of the chain it's acting on.
To build onchain agents, give the agent three primitives: a scoped wallet for signing, a payment rail like x402, and a real-time data feed through webhooks, WebSockets, or gRPC. The model decides; these primitives let it act onchain.
An LLM that writes code is a copilot. An agent that holds money, signs transactions, and reacts to onchain events in real time is something else: a participant in the economy. The infrastructure exists, but it is scattered across wallet, payment, and real-time data primitives. This guide walks through the three you actually need and how to wire them together. The Alchemy CLI and our agentic products ship each as a primitive you can use directly.
What's different about building an onchain agent?
Most of a regular AI agent's stack still works onchain: the model, the framework, the tool-calling pattern, the orchestration loop, the eval harness, the prompt store. All of it transfers. If you've built a Slack bot, a coding agent, or a research agent, the upper half of the stack is already familiar.
Three things don't transfer: the wallet, the payment rail, and the real-time data feed. None of the three have a clean equivalent in the LLM tooling world, none are solved by picking a smarter model, and getting any of them wrong is the kind of mistake that drains a wallet or stalls an agent in production.
- Identity is a private key, not an email address. Whatever the agent can sign, it can spend. Key custody becomes a security model, not a config file.
- Payments happen at the protocol layer. Stripe doesn't accept "I'm an agent" as a payer. Crypto rails do, through standards like HTTP 402/x402.
- Real-time data is the default mode, not a feature. Block times are short and finality matters. Polling burns budget; the agent needs the chain to push state to it.
Each of the three building blocks below maps to one of these shifts.
What are the three building blocks of an onchain agent?
A production onchain agent usually needs three things:
- Wallet. The agent can sign with it, scoped so a compromised prompt can't drain it.
- Payment rail. The agent pays for offchain APIs and onchain gas without a human in the loop.
- Real-time data pipe. The agent reacts to new blocks, transactions, and contract events the instant they happen.
The rest of this guide is one section per building block, plus a final walkthrough that puts them together.
How do you give an agent a wallet without leaking your keys?
The naive pattern is the one everyone tries first: drop a private key in a .env file, load it with dotenv, sign transactions with it from inside the agent loop. It works on a local demo. It is one prompt injection away from a drained wallet in production.
Two patterns are emerging as the safer defaults.
The first pattern is embedded smart accounts (programmable wallet contracts, not raw private-key accounts) with delegated signing. The key lives inside a custody service (Privy, Turnkey, Coinbase MPC for multi-party computation). Your agent never sees it. It calls a signing API, the service verifies the request against a policy, and the signed transaction comes back. The agent can sign within rules you set (max value per tx, allowed contracts, daily limits) and nothing else.
The second pattern is session-scoped wallets approved from a developer surface. The agent gets a time-limited, revocable session bound to a specific wallet. You approve the session from a UI you control. Revocation is one click.
The newest take on pattern 2 is the agent wallet feature in the Alchemy CLI, which ships as part of the CLI itself:
# Install the latest Alchemy CLI
npm i -g @alchemy/cli@latest
# Authenticate your CLI session
alchemy auth
# Connect the wallet your agent will use
alchemy wallet connectalchemy wallet connect opens our dashboard in a browser. You pick the wallet you want the agent to use, approve the session, and from that point the CLI can sign on the agent's behalf. The private key stays with Privy. Every signing call goes through a two-step flow: our backend constructs the payload, the CLI signs locally, the request hits Privy. If the session has expired, been revoked, or fails binding checks, the request is rejected before it leaves our infrastructure.
The CLI was designed as a tool surface for agents, not just humans. Three commands matter:
# Run any command with structured output and no prompts
alchemy <command> --json --no-interactive
# Print the JSON manifest of every command and flag
alchemy agent-prompt
# Install Alchemy Skills for an agent client
alchemy install skills
# Install the Alchemy MCP server config
alchemy install mcpalchemy agent-prompt is the part that makes this agent-native. Instead of asking your LLM to memorize the CLI surface, you feed it the JSON manifest at session start and the model knows the full command space, error codes, and example invocations. That eliminates an entire category of "the agent hallucinated a flag that doesn't exist" failures.
How to choose between the two patterns:
Pattern | Best for | Trade-off |
|---|---|---|
Embedded smart account with delegated signing | Production agents acting on behalf of end users (consumer apps, agent commerce) | More setup, but per-user isolation and granular policy |
Session-scoped CLI wallet | Single-developer agents, automation, internal tools, prototypes | Faster to wire up, scoped per session, revocable from one dashboard |
Whichever you pick, the rule is the same: the agent never sees a raw private key. If your design has one in memory, you have built a vulnerability, not an agent.
How does an agent pay for the services it calls?
Once the agent has a wallet, it still has to pay for things. Two kinds of things:
- Onchain costs. Gas, swap fees, bridge fees, anything the chain charges for state changes.
- Offchain costs. RPC requests, indexed data APIs, inference, anything the agent needs from a server.
Onchain costs are solved by gas sponsorship. Many account-abstraction providers expose a paymaster API, where a paymaster is a contract that pays gas on someone else's behalf. The agent submits a user operation (ERC-4337's transaction-equivalent for smart accounts), the paymaster covers it, you reconcile usage on your side. This pattern is already common in smart-account systems.
Offchain costs are the harder problem, because the agent doesn't have a credit card on file and you don't want to provision API keys for every agent. The pattern converging across the ecosystem is x402: the HTTP 402 Payment Required status code, plus a small payload that tells the agent how to pay.
Here's the full flow:
- The agent makes an HTTP request to a service.
- The service replies
402 Payment Requiredwith a JSON body describing the price, the accepted token, and the chain. - The agent constructs a payment (USDC on Base is the common default), signs it with its wallet, and retries the original request with a payment proof in a header.
- The service verifies, settles, and returns the data.
We implement this end to end. An agent can hit our RPC API, Token API, Portfolio API, NFT API, and Prices API with no API key and no dashboard signup. The first request gets a 402; subsequent requests pay the endpoint's quoted amount in USDC on Base and return data. No human in the loop.
A minimal client-side handler looks like this:
async function paidFetch(url: string, wallet: AgentWallet) {
let res = await fetch(url);
if (res.status === 402) {
const requirement = await res.json();
const payment = await wallet.signX402Payment(requirement);
res = await fetch(url, {
headers: { "X-PAYMENT": payment },
});
}
return res.json();
}The agent retries the same URL with the signed payment header. The endpoint settles the payment onchain, hands back the data, and the agent moves on. The pattern composes across providers: any service that speaks x402 can take agent payments without writing custom auth.
How does the agent stay in sync with the chain?
Chains don't push to your app by default. If your agent polls eth_blockNumber every second to find out what's happening, you're paying for the poll and arriving late to every event you care about.
Three patterns cover almost every real-time use case. The full breakdown is in the webhooks vs WebSockets vs gRPC comparison, but here's the short version for agent builders:
Pattern | Use when |
|---|---|
Webhooks | The agent runs as a service with a public URL and wants the provider to push events (new transactions, mined blocks, address activity). Cheapest to operate at low-to-medium event volume. |
WebSockets | The agent runs a persistent process and needs sub-second pickup on logs and pending transactions. Best for in-process loops. |
The agent is throughput-bound on Solana or another high-TPS chain. Lowest latency, highest cost to integrate. |
For most agents, webhooks plus a few Data API calls (token balances, transaction history, portfolio) are enough. The webhook fires, the agent wakes up, queries enriched state, decides what to do, signs a transaction, and sleeps.
Wiring it together: a minimal onchain agent architecture
Here's a compact architecture sketch that combines all three building blocks. It watches its own wallet, queries a paid endpoint when something arrives, asks an LLM what to do, and signs a response transaction. Replace the x402 signing helper with your custody provider before running it in production.
import { createPublicClient, webSocket } from "viem";
import { base } from "viem/chains";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import OpenAI from "openai";
const run = promisify(execFile);
const openai = new OpenAI();
const agentWallet = process.env.AGENT_WALLET_ADDRESS!.toLowerCase();
const client = createPublicClient({
chain: base,
transport: webSocket(process.env.ALCHEMY_RPC_WSS!),
});
async function signX402Payment(requirement: unknown) {
// Plug in your x402 client and custody provider here.
// The signer should construct the payment payload and sign it with the agent wallet.
throw new Error("Implement x402 signing with your wallet provider");
}
// 1. Signing through the agent wallet session (no private key in process).
// `alchemy evm send` uses the session approved via `alchemy wallet connect`.
async function refund(to: string, amountEth: string) {
const { stdout } = await run("alchemy", [
"evm",
"send",
to,
amountEth,
"-n",
"base-mainnet",
"--json",
"--no-interactive",
]);
return JSON.parse(stdout);
}
// 2. Paid data fetch via x402 against an Alchemy endpoint.
async function paidFetch(url: string) {
let res = await fetch(url);
if (res.status === 402) {
const requirement = await res.json();
const payment = await signX402Payment(requirement);
res = await fetch(url, { headers: { "X-PAYMENT": payment } });
}
return res.json();
}
// 3. Real-time trigger: react to inbound transactions on the agent wallet.
client.watchBlocks({
includeTransactions: true,
onBlock: async (block) => {
for (const tx of block.transactions) {
if (tx.to?.toLowerCase() !== agentWallet) continue;
const portfolio = await paidFetch(
`https://api.g.alchemy.com/data/v1/portfolio/${tx.from}`
);
const decision = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{
role: "system",
content: "You are a treasury agent. Decide whether to refund.",
},
{
role: "user",
content: JSON.stringify({ tx, sender_portfolio: portfolio }),
},
],
});
const action = JSON.parse(decision.choices[0].message.content!);
if (action.refund) {
await refund(tx.from, action.amount);
}
}
},
});Three things are worth noting about this shape:
- No private key in the process. Every sign call goes through the CLI session, which talks to Privy. If this process is compromised, the attacker gets a revocable session, not a wallet.
- No API key for the data call.
paidFetchworks against any x402-speaking endpoint. The endpoint charges per request in USDC. - The LLM is the smallest piece. Most of the surface area is wallets, payments, and data plumbing. The model just decides.
That's the pattern. Swap the trigger (Discord message, cron, marketplace event), swap the action (swap, vote, bridge, mint), swap the model, and you have a different agent.
Build it with Claude
Or have Claude build it for you. First install our Skills and MCP server so Claude can discover our primitives:
alchemy install skills && alchemy install mcpThen paste this prompt into Claude Code:
Build a TypeScript onchain agent on Base that:
1. Watches a wallet address for incoming transactions in real time
2. When a transaction arrives, queries an x402-payable portfolio API for the sender's holdings
3. Asks an LLM whether to refund
4. Signs the refund without holding the private key in the process
Use production-grade primitives.The output mirrors the script above: a viem WebSocket against our RPC, our Portfolio API behind x402, and alchemy evm send for the refund. No private key in the process.
Which agent framework should you use?
Frameworks layer on top of the three primitives above. They handle the agent loop, tool registration, memory, and (for some) social platform clients. The right choice depends on whether you're optimizing for chain depth, multi-chain breadth, or a full runtime.
Framework | Best for | Chains | Notes |
|---|---|---|---|
LangChain / LangGraph | General-purpose orchestration with any model and any tool | Any (via tool wrappers) | Most flexible, least opinionated. You wire the wallet and RPC tools yourself. |
Multi-chain agents that need EVM and Solana under one API | EVM + Solana | Plugin model. Good fit when the agent crosses chains. | |
Social agents (Twitter, Discord, Farcaster) with character files | Any | Full runtime including memory and platform clients. Heavier than a library. | |
Deepest Solana protocol coverage (Jupiter, Raydium, Drift, etc.) | Solana only | Tool library, not a runtime. Bring your own loop. | |
Vercel AI SDK | Streaming agent responses to a web UI | Any (via tools) | Good fit for streaming agent responses to a browser UI. |
For a chain-native end-to-end build with wallet setup, RPC integration, and Jupiter swaps, see the Solana AI agent build guide. For a chain-agnostic provider comparison, see the best blockchain APIs for autonomous onchain agents.
The frameworks are interchangeable in a way the building blocks are not. You can swap LangChain for GOAT in an afternoon. Swapping how your agent signs is a security review.
What to build next
The three building blocks compose. Once you have an agent that holds a session-scoped wallet, pays for data with x402, and reacts to real-time events, the question stops being "can the agent do this" and starts being "what should the agent do?"
We ship each of the three building blocks as a primitive. Our CLI handles wallets through Privy-backed, revocable sessions. Our RPC, Token, Portfolio, NFT, and Prices APIs speak x402 directly. No API key, no dashboard signup, no contract. Webhooks, WebSocket subscriptions, and Solana gRPC streaming cover the real-time data feed.
Install Alchemy Skills and the MCP server once, and agent frameworks on top, including LangChain, GOAT, and ElizaOS, can discover and call those primitives with less custom integration. To start: npm i -g @alchemy/cli, then alchemy auth and alchemy wallet connect. Then connect a wallet and sign your first transaction through the CLI. Learn more about our agentic products.
Frequently asked questions
What is an onchain agent?
An onchain agent is an AI agent that can read blockchain state, hold or control a wallet, and sign transactions based on a policy or model decision. The model decides what to do; the wallet, payment rail, and data feed let it act.
How do you build an onchain agent?
Start with three primitives: a scoped wallet for signing, a payment rail such as x402 for paid API calls, and a real-time data feed through webhooks, WebSockets, or gRPC. Then connect those primitives to the agent framework or orchestration loop you already use.
What wallet should an AI agent use?
Use a wallet pattern that keeps raw private keys out of the agent process. Embedded smart accounts with delegated signing work well for user-facing apps, while session-scoped CLI wallets work well for developer agents, internal automation, and prototypes.
How do onchain agents pay for APIs?
They can use x402 payments. The agent makes a request, receives a 402 Payment Required response with payment details, signs the payment with its wallet, and retries the request with a payment proof.
Should onchain agents use webhooks, WebSockets, or gRPC?
Use webhooks when the agent runs as a service and can receive pushed events. Use WebSockets when the agent runs as a persistent process and needs low-latency logs or pending transactions. Use gRPC streaming for high-throughput Solana-style workloads where latency matters enough to justify more integration work.
What is the best framework for onchain agents?
The best framework depends on the loop you need. LangChain or LangGraph are flexible for general orchestration, GOAT is useful for multi-chain tool coverage, ElizaOS is built for social agents, Solana Agent Kit goes deep on Solana, and the Vercel AI SDK is a good fit for browser-facing agent UIs.
The core infrastructure is ready to build with. What you do with it is the part nobody else can write for you.
Alchemy Newsletter
Be the first to know about releases
Sign up for our newsletter
Get the latest product updates and resources from Alchemy
By entering your email address, you agree to receive our marketing communications and product updates. You acknowledge that Alchemy processes the information we receive in accordance with our Privacy Notice. You can unsubscribe anytime.
Related articles

How to build on UTXO chains: Bitcoin, Litecoin, Dogecoin, and Bitcoin Cash
UTXO chains for developers: how Bitcoin, Litecoin, Dogecoin, and Bitcoin Cash differ from EVM, what infrastructure you need, and how Alchemy delivers it.

Blockchain RPC infrastructure evaluation guide for enterprises
Choosing the wrong blockchain RPC provider can mean costly migrations and poor performance. Use this enterprise evaluation framework to ask the right questions before you commit.

Photon on Alchemy: compressed Solana data, standard RPC
Photon / ZK Compression read methods now run on Alchemy’s standard Solana RPC URL—one endpoint, production-scale latency, and a migration that is a URL change from other Photon-compatible providers.