Non-Custodial Architecture: How Spellbook Deploys AI Agents Without Key Risk
How to decouple LangGraph reasoning loops from transaction signing using Safe multisig, scoped session keys, and RPC fork simulations.
- AI agents must operate as advisory engines rather than keyholders. Large language model reasoning loops running on LangGraph state machines and vector databases are treated as untrusted compute that emit raw, unsigned calldata proposals.
- Execution and signing must be strictly air-gapped from LLM memory. Private keys are never stored in server environment variables or agent containers.
- Every proposed transaction undergoes pre-execution simulation on a local fork via Tenderly or RPC static calls to inspect asset transfer deltas and parameter sanity before signing.
- High-value transactions route to Safe multisig human councils, while routine autonomous actions execute via scoped session keys bounded by on-chain Zodiac Roles policies with hard spend ceilings.
Every demo video of a Web3 AI agent on Twitter follows the exact same script. Someone feeds an OpenAI API key into a terminal, connects an Ethereum wallet with twenty dollars of testnet ETH, and watches the bot execute a Uniswap swap. Everyone claps. The comments call it the future of autonomous finance.
I call it a catastrophe waiting to happen.
If you give an autonomous agent an unrestricted private key to an externally owned account, you are effectively handing a stranger the physical master key to your house. You might trust the delivery driver to drop off a package on your porch. You do not hand them the keys to your bedroom and your safe. Yet in Web3, teams build bots that hold raw private keys in plaintext environment variables, run them inside docker containers, and pray that an unexpected prompt injection does not wipe their entire treasury.
When we architect AI agents at Spellbook, our first rule is simple: the intelligence layer must never hold the keys to the kingdom.
The Web3 AI Security Paradox
The fundamental problem with large language models in Web3 is the conflict between probabilistic reasoning and deterministic finality.
Neural networks are probabilistic engines. They predict the next most likely token based on statistical weights. They make mistakes. They misinterpret ambiguous sentences. They get tricked by adversarial context.
Public blockchains are the exact opposite. Every transaction is binary. It either reverts or it executes with cryptographic finality. Once state changes persist on Ethereum, Arbitrum, or Solana, no rollbacks exist. No support team can hit undo.
- On-Chain Prompt Injection: An attacker deposits an ERC-20 token where the name string contains a malicious system prompt instruction. When your monitoring agent inspects the transaction log, the untrusted string overrides your system instructions.
- Parameter Hallucination: During high volatility, a model calculates token swap slippage incorrectly or misinterprets an address checksum, sending funds to a burned contract.
- Secret Exposure: Storing an unencrypted private key in runtime memory or server environments leaves funds vulnerable to simple supply-chain dependency attacks or container breakout vulnerabilities.
You cannot patch these problems with a better system prompt. Prompts are not security boundaries. You need architectural firewalls.
Decoupling Reasoning from Signing
The core rule of our architecture is strict separation: the Decision Engine is completely decoupled from the Execution Interface.
Think of it like an air-gapped system inside an enterprise bank. The analysts who review credit applications do not print the physical cash or open the vault doors. They stamp an approval packet and slide it through a secure window.
In our stack, the agent runs as a state graph using LangGraph. It maintains long-term memory via Supabase pgvector and queries blockchain state through read-only RPCs. The agent can ingest Discord messages, crawl governance forums, analyze Dune dashboards, and parse transaction logs.
Crucially, the agent runtime has zero cryptographic signing capabilities. It does not import private keys. It cannot sign a transaction hash. When the agent decides an action is required, its only output is a structured JSON proposal containing the target contract, raw hexadecimal calldata, and mathematical justification.
The Technical Blueprint
When an agent builds a transaction, it encodes standard ABI function calls using Viem. Notice in the implementation below that no signing keys are referenced.
import { encodeFunctionData, parseUnits, isAddress } from "viem";
const VAULT_ABI = [
{
type: "function",
name: "rebalancePool",
inputs: [
{ name: "targetPool", type: "address" },
{ name: "amount", type: "uint256" },
{ name: "minReturn", type: "uint256" },
],
outputs: [{ name: "success", type: "bool" }],
stateMutability: "nonpayable",
},
] as const;
export interface TransactionProposal {
target: `0x${string}`;
data: `0x${string}`;
value: bigint;
description: string;
maxSlippageBps: number;
}
export function buildRebalanceProposal(
vaultAddress: `0x${string}`,
poolAddress: `0x${string}`,
amountUsdc: string,
minReturnUsdc: string
): TransactionProposal {
if (!isAddress(vaultAddress) || !isAddress(poolAddress)) {
throw new Error("Invalid address provided to proposal builder");
}
const calldata = encodeFunctionData({
abi: VAULT_ABI,
functionName: "rebalancePool",
args: [poolAddress, parseUnits(amountUsdc, 6), parseUnits(minReturnUsdc, 6)],
});
return {
target: vaultAddress,
data: calldata,
value: 0n,
description: "Automated pool rebalance generated by liquidity monitoring agent",
maxSlippageBps: 50,
};
}Before the proposal can be presented to signers or an automated relayer, our verification worker executes an eth_call or a Tenderly fork simulation.
The simulation runs against the exact pending state of the blockchain. It inspects the post-state trace to confirm that the call succeeds, that token balance changes match expected bounds, and that no unexpected delegatecalls were attempted. If any check fails, the transaction is dropped instantly.
Comparing Key Architectures
| Dimension | Full Key Access (EOA Bot) | Delegated Session Keys | Spellbook Non-Custodial Runtime |
|---|---|---|---|
| Key Storage | Server memory / .env file | Browser storage / KMS signer | Zero keys in agent memory. Hardware multisig or KMS |
| Blast Radius on Injection | Total account drain. 100% loss | Capped by session expiration and spend limit | Zero direct execution. MultiSendCallOnly or human quorum |
| Spend Ceiling | Unlimited balance access | Hard daily limit enforced by smart account | Strictly bound by Safe multisig threshold or Zodiac policy |
| Asset Risk | Catastrophic | Low to Moderate | Mathematically bounded |
| Setup Overhead | Fast but irresponsible | Moderate (requires account abstraction) | Turnkey deployment with complete client sovereignty |
| Client Control | Trust-based promise | Token allowance management | Instant kill-switch via multisig module revocation |
Production Handoff & Client Sovereignty
A common concern founders have when working with external developers is vendor lock-in. Who actually controls the infrastructure?
With Spellbook, you retain absolute sovereignty over your keys from day zero.
- Non-Custodial Handoff: We provide the compiled agent runtime and environment configs. You deploy the smart account modules through your Safe signers.
- Root Authority: Your multisig council remains the sole owner of the contract. You can disable our agent's execution module with a single transaction directly from the official Safe web app.
- Bounded Relayers: If your workflow requires autonomous micro-transactions (such as gas refuels or oracle heartbeat syncs), we configure a Cloudflare KMS or AWS KMS relayer wrapped in a Zodiac Roles modifier. The relayer can only execute approved function selectors up to a hard daily gas cap.
- Transparent Runbooks: Every client receives complete source code, deployment scripts, and operational runbooks. We do not run black boxes.
The Verdict
Autonomous agents will run Web3 operations. They will manage liquidity, monitor bridges, triage vulnerabilities, and automate payroll.
But the teams that survive and scale will not be the ones that recklessly attach private keys to language model loops. They will be the teams that treat AI as an advisory engine, enforcing hard cryptographic boundaries between thought and action.
That is how we build software at Spellbook. If you are ready to automate your protocol workflows without putting your treasury at risk, explore our live catalogue or talk to us about a custom deployment sprint.
Deploy Production Web3 AI Agents in 48 Hours
Need an autonomous multisig sentinel, anti-phishing moderation bot, or custom on-chain telemetry agent for your protocol? We build, test, and hand over production agents with zero private keys.
Related Engineering Blueprints
View AllSeparating Intelligence from Execution: Building Web3 Agents with Bounded Autonomy and Human-in-the-Loop Approval
Why giving an LLM an unrestricted private key is an existential threat to protocol treasuries. Explore the three tiers of agent autonomy, on-chain policy constraints with Zodiac Roles, prompt injection defenses in transaction calldata, and cryptographically verified approval quorums.
Why Crypto Teams Need a Dedicated AI Agent Security Budget
Web3 protocols spend millions on smart contract audits but assign zero budget to autonomous AI agents. Learn why DIY bots lead to prompt injection drainers and why an AI security budget is mandatory.