NEAR Protocol AI Agents Developer Guide 2026 — The Anti-Loss Protocol for Building Autonomous On-Chain Agents
Published on 2026-05-30
Why NEAR Protocol Is Betting Big on AI Agents
The convergence of AI and blockchain is no longer theoretical. In 2026, autonomous AI agents — programs that can analyze data, make decisions, and execute transactions without human intervention — are live on multiple blockchains. But one chain has made AI agents its core strategic bet: NEAR Protocol.
NEAR isn't just adding AI features as an afterthought. The protocol's architecture — sharded consensus, human-readable account names, chain abstraction, and the BOS (Blockchain Operating System) — was designed from the ground up to support autonomous agents that interact with DeFi, social protocols, and cross-chain infrastructure. The NEAR Foundation has committed over $150 million in grants and ecosystem funding specifically for AI agent development through 2026 and beyond.
For developers, this means an unprecedented opportunity. The tooling is mature, the funding is available, and the user base is growing. But building AI agents that handle real money requires more than clever prompts — it requires the Anti-Loss Protocol for agent security, because a compromised agent doesn't just leak data, it drains wallets.
What Is an AI Agent on NEAR?
An AI agent on NEAR is an autonomous program (smart contract or off-chain service) that:
- Monitors on-chain data — prices, liquidity, governance proposals, social signals.
- Makes decisions — using LLMs, rule-based logic, or ML models.
- Executes transactions — swaps, stakes, votes, bridges, or any on-chain action.
- Manages its own account — NEAR accounts can hold tokens, deploy contracts, and interact with any dApp on the network.
Unlike simple bots, NEAR AI agents can maintain persistent state, hold funds, and interact with other agents. They can be user-owned (you control the agent's account) or protocol-owned (the agent operates as part of a DeFi protocol's infrastructure).
NEAR AI Agent Architecture Overview
Building on NEAR involves several layers that work together:
| Layer | Component | Purpose | Developer Tools |
|---|---|---|---|
| AI/LLM Layer | Language model (GPT-4, Claude, Llama, etc.) | Decision-making, natural language understanding | OpenAI API, Anthropic API, self-hosted models |
| Agent Framework | Agent runtime and logic | Orchestrates data → decision → action pipeline | NEAR AI Agent Kit, ElizaOS, Rig |
| Chain Interaction | NEAR SDK and RPC | Submit transactions, read on-chain state | near-api-js, near-rs (Rust SDK), near-cli |
| Account Layer | NEAR account (human-readable) | Holds funds, signs transactions, deploys contracts | wallet-selector, key storage (local or MPC) |
| Smart Contract | Rust or AssemblyScript contracts | On-chain logic the agent interacts with | near-sdk-rs, near-sdk-as |
| Cross-Chain | Chain abstraction / IBC / Rainbow Bridge | Interact with Ethereum, Solana, Cosmos, etc. | NEAR IBC, Omnia, Chain Signatures |
Getting Started: Your First NEAR AI Agent
Step 1: Set Up the Development Environment
You'll need Node.js 18+ and a NEAR testnet account to start:
# Install NEAR CLI
npm install -g near-cli
# Create a testnet account
near create-account my-agent.testnet --useFaucet
# Install the JavaScript SDK
npm install near-api-js
# For AI agent development, install the agent kit
npm install @near-ai/agent-kit
Step 2: Create the Agent Account
Every NEAR agent needs its own account. Unlike Ethereum where bots use EOA or multisig wallets, NEAR accounts are human-readable and can have multiple access keys with different permissions:
import { connect, keyStores, KeyPair } from 'near-api-js';
// Create a key pair for the agent
const keyStore = new keyStores.InMemoryKeyStore();
const agentAccountId = 'my-ai-agent.testnet';
const privateKey = 'ed25519:...'; // Generate with near-cli
await keyStore.setKey('testnet', agentAccountId, KeyPair.fromString(privateKey));
const near = await connect({
networkId: 'testnet',
keyStore,
nodeUrl: 'https://rpc.testnet.near.org',
});
Critical security note: The agent's private key is its identity. If an attacker obtains it, they own the agent and all its funds. Use limited access keys that can only call specific contracts — never give an agent a full-access key unless absolutely necessary.
Step 3: Connect the AI Layer
The agent's "brain" is an LLM that processes data and decides on actions. Here's a minimal pattern:
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function decideAction(marketData) {
const response = await openai.chat.completions.create({
model: 'gpt-4-turbo',
messages: [
{ role: 'system', content: 'You are a DeFi trading agent on NEAR. Respond with JSON: {action: "swap"|"stake"|"hold", token: string, amount: number, reason: string}' },
{ role: 'user', content: 'Current market data: ' + JSON.stringify(marketData) }
],
response_format: { type: 'json_object' }
});
return JSON.parse(response.choices[0].message.content);
}
Step 4: Execute On-Chain Actions
Once the AI decides on an action, the agent executes it via the NEAR SDK:
const account = await near.account(agentAccountId);
// Execute a token swap via a DEX on NEAR (e.g., Ref Finance)
const result = await account.functionCall({
contractId: 'v2.ref-finance.near',
methodName: 'swap',
args: { actions: [{ pool_id: 1559, token_in: 'wrap.near', amount_in: '1000000000000000000000000', token_out: 'usdt.tether-token.near', min_amount_out: '0' }] },
attachedDeposit: 1, // 1 yoctoNEAR (required)
gas: '300000000000000', // 300 TGas
});
NEAR AI Agent Frameworks Compared
| Framework | Language | Best For | Key Features | Maturity |
|---|---|---|---|---|
| NEAR AI Agent Kit | TypeScript | NEAR-native agents | Built-in NEAR SDK, wallet management, BOS integration | Beta (2026) |
| ElizaOS | TypeScript | Multi-chain social agents | Plugin architecture, Discord/Telegram integration, memory | Production |
| Rig | Rust | High-performance agents | Type-safe, async, LLM-agnostic | Beta |
| LangChain + NEAR | Python/TypeScript | Complex reasoning chains | Tool composition, RAG, agent memory | Production |
| Autonolas | Python | Autonomous services | Agent registry, staking for accountability | Production |
| Fetch.ai | Python | Agent-to-agent communication | Agent marketplace, decentralized agent economy | Production |
The Anti-Loss Protocol for NEAR AI Agents
An AI agent that controls funds is a high-value target. The Anti-Loss Protocol for NEAR agents has seven non-negotiable rules:
Rule 1: Use Limited Access Keys
NEAR supports two types of access keys: FullAccess (can do anything) and FunctionCall (can only call specific methods on specific contracts). Never give an agent a FullAccess key. Create a FunctionCall key that can only interact with the contracts it needs:
// Add a limited key — can only call 'swap' on Ref Finance
const newKey = KeyPair.fromString(privateKey);
await account.addKey(
newKey.getPublicKey(),
'v2.ref-finance.near', // contract
'swap', // allowed method
'50000000000000' // allowance in gas (50 TGas)
);
Rule 2: Set Spending Limits
Even with limited keys, an agent could drain its NEAR balance through repeated transactions. Implement a daily spending cap in your agent's logic:
- Track total spending per day in a database or on-chain.
- Hard-stop the agent when the cap is reached.
- Alert the owner (email, Telegram, Discord) when 80% of the cap is used.
Rule 3: Validate AI Outputs Before Execution
LLMs can hallucinate, be prompt-injected, or produce unexpected outputs. Never pass LLM output directly to a transaction. Always validate:
- Is the target contract address in the allowed list?
- Is the amount within expected bounds?
- Is the token address legitimate (check against a whitelist)?
- Does the transaction make economic sense (e.g., not selling at 90% below market)?
Rule 4: Use a Kill Switch
Every agent must have a mechanism for the owner to immediately halt all activity. On NEAR, this can be:
- An on-chain flag the agent checks before each action.
- A separate "owner" key that can revoke the agent's access keys.
- An off-chain circuit breaker that stops the agent process.
Rule 5: Isolate Agent Funds
Don't let an agent control your entire portfolio. Create a dedicated agent account with only the funds it needs. If the agent is compromised, the attacker gets $500 — not $500,000.
Rule 6: Audit the Contracts Your Agent Interacts With
Your agent is only as safe as the contracts it calls. Before adding a DEX, lending protocol, or bridge to your agent's whitelist:
- Check if the contract has been audited (look for audit reports from OtterSec, Zellic, or Trail of Bits).
- Verify the contract address on the protocol's official documentation.
- Check the contract's age and transaction history on NEAR Blocks.
Rule 7: Monitor and Log Everything
Every action your agent takes should be logged — both for debugging and for security forensics. Log:
- The input data the AI received.
- The AI's decision (raw output).
- The validated transaction parameters.
- The transaction hash and result.
Store logs off-chain (database, S3, or IPFS) and set up alerts for anomalous behavior — unusually large trades, failed transactions, or activity outside expected hours.
NEAR Chain Signatures: Cross-Chain AI Agents
One of NEAR's most powerful features for AI agents is Chain Signatures — the ability to sign transactions for other blockchains (Ethereum, Bitcoin, Solana, Cosmos) directly from a NEAR smart contract. This means a single NEAR-based agent can manage assets across multiple chains without holding keys on each chain.
The security implications are significant: the agent's cross-chain signing capability is governed by NEAR's MPC network, not by a single private key. This is more secure than traditional cross-chain bridges and eliminates the bridge hack risk that has cost users billions. For cross-chain agent operations, always verify the destination chain and contract using Crypto Network Guide before the agent executes.
Real-World NEAR AI Agent Use Cases in 2026
| Use Case | What the Agent Does | Risk Level | Anti-Loss Requirement |
|---|---|---|---|
| DeFi Yield Optimization | Moves funds between lending protocols to maximize APY | Medium | Spending caps, contract whitelist |
| Governance Participation | Votes on DAO proposals based on owner's preferences | Low | Limited key, vote preview before execution |
| Portfolio Rebalancing | Sells/buys tokens to maintain target allocation | Medium | Slippage limits, daily cap |
| Cross-Chain Arbitrage | Exploits price differences across chains | High | Small capital allocation, kill switch |
| Social Trading | Mirrors trades of selected wallets | Medium | Max position size, stop-loss rules |
| NFT Sniping | Buys undervalued NFTs based on floor price analysis | Medium | Budget cap, contract verification |
| Liquidity Management | Adds/removes liquidity based on volatility | Medium | Impermanent loss thresholds |
Funding and Grants for NEAR AI Agents
If you're building an AI agent on NEAR, several funding sources are available in 2026:
- NEAR Foundation Grants: Up to $250,000 for AI agent projects. Apply at near.org/grants.
- Proximity Labs: Research grants for agent-to-agent communication and DeFi automation.
- NEAR Horizon: Accelerator program for early-stage projects. Includes mentorship and up to $50,000 in funding.
- Octopus Network: Grants for agents operating on appchains within the NEAR ecosystem.
Bottom Line
NEAR Protocol has built the most developer-friendly environment for AI agents in the blockchain space. The combination of human-readable accounts, limited access keys, chain signatures for cross-chain operations, and a mature TypeScript/Rust SDK makes it the natural choice for developers building autonomous on-chain agents.
But with great autonomy comes great responsibility. The Anti-Loss Protocol is not optional — it's the difference between an agent that earns yield and one that gets drained by an exploit. Use limited access keys, set spending caps, validate every AI output, implement a kill switch, isolate agent funds, audit contracts, and log everything.
Start on testnet, deploy with small amounts, and scale only after your security model is battle-tested. For cross-chain agent operations, verify every destination at Crypto Network Guide — because the best AI agent is one that never sends funds to the wrong chain.