Near Intents SDK Tutorial and Cross-Chain Examples
Introduction
If you’re building crypto×AI software that involves cross-chain DeFi interactions, the Near Intents SDK offers a unique approach for intent-based, programmable swaps and agent workflows. In this tutorial, I’ll walk you through setting up the SDK, exploring its solver architecture, and delivering a practical cross-chain swap example. We’ll also touch on integrating DefAI agents for AI-driven trading on Near, and compare the Near Intents SDK with the Li.Fi SDK—another popular tooling for cross-chain swaps.
The goal here isn’t theory but shipping working code and understanding the trade-offs these tools introduce. Many early adopters hit edge cases, so expect some honest insights from hands-on experience.
Setting Up Near Intents SDK
Prerequisites
- Node.js 18+
- npm or yarn
- Access to RPC endpoints for Near and your target EVM-compatible chains
- Basic familiarity with TypeScript and Near Protocol contracts
Installation
Near Intents SDK is distributed as an npm package offering APIs for intent creation, submission, and solver interaction. Here’s how to get going:
npm install near-intents-sdk
## or
yarn add near-intents-sdk
After installation, you can initialize the SDK in TypeScript:
import { NearIntentsClient } from "near-intents-sdk";
const client = new NearIntentsClient({
network: "testnet", // or 'mainnet'
rpcUrl: "https://rpc.testnet.near.org",
solverRpcUrl: "https://solvers.testnet.near-intents.io",
// Add wallet/publicKey config as needed
});
A quick note: The SDK at v0.3.x is evolving rapidly, so keep an eye on the official changelog for breaking changes.
Understanding Near Intents Solver Architecture
Near Intents works by having agents submit high-level "intents" rather than explicit swaps. The solver component listens for these intents and creates optimized transaction plans. This is slightly different from traditional DEX aggregators that immediately quote and route swaps on-chain or off-chain.
Key pieces explained:
| Component |
Role |
| Near Intents SDK |
Constructs and signs intents; submits to solver RPC |
| Solver RPC |
Matches intents, builds execution plans across chains |
| On-chain contracts |
Execute finalized swap plans atomically |
The solver aggregates intents on a batching window, optimizing gas and routing multi-hop swaps, even across chains like NEAR, Aurora (EVM), and others supporting relevant bridges.
Think of the solver as an orchestrator that interprets developer-signed intents into low-level swaps.
Building Your First Near Intents Agent
A minimal agent will create a simple cross-chain swap intent. Here’s a stripped-down example to build and submit an intent:
import { NearIntentsClient, Intent } from "near-intents-sdk";
const client = new NearIntentsClient({ network: "testnet" });
async function createIntent() {
const intent: Intent = {
fromChain: "aurora-testnet",
toChain: "near-testnet",
fromToken: "0x...WETH", // Aurora token address
toToken: "wrap.near",
amount: "1000000000000000000", // 1 WETH in wei
slippage: 0.005, // 0.5%
recipient: "your-near-wallet.testnet",
};
try {
const signedIntent = await client.signIntent(intent);
const txHash = await client.submitIntent(signedIntent);
console.log(`Submitted intent with TX: ${txHash}`);
} catch (e) {
console.error("Failed to submit intent", e);
}
}
createIntent();
Why intents?
This separates intent declaration from execution, which allows more efficient batch solving and cross-chain gas optimization. Plus, you don’t need to hardcode bridges or pair routes in your agent.
Cross-Chain Swap Example Using Near Intents
One practical use case is performing atomic swaps across Aurora and Near with minimal upfront complexity. The Near Intents solver will find the best bridge and route.
Walkthrough:
- Create intent parameters: Specify source chain/token, destination chain/token, amount, and recipient address.
- Submit intent through SDK: The intent is signed cryptographically, ensuring agent wallet control.
- Wait for Solver Execution: The batch solver picks up the intent, builds and submits composite on-chain transactions.
- Confirm Final Swap: After execution, confirm tokens arrive in recipient wallet.
While the SDK abstracts much of this, you will need to monitor events and confirmations off-chain using RPC and indexer queries.
This cross-chain swap approach differs from traditional DEX aggregators by using an intent-based, solver-mediated pipeline.
Integrating DefAI Agent for Intent-Based Trading on Near
DefAI agents add an AI layer on top of intent workflows. They analyze market data to generate intents reflecting trading strategies.
Simple DefAI integration:
- Use Near Intents SDK in combination with DefAI SDK to automate intent creation.
- Train your agent model off-chain (Python or Rust ML stack).
- Push intent creation commands based on signal thresholds and order book states.
Here’s a pseudo snippet demonstrating how your DefAI logic wraps the intent call:
import { DefAI } from "defai-sdk";
import { NearIntentsClient } from "near-intents-sdk";
const aiAgent = new DefAI(...);
const intentsClient = new NearIntentsClient({ network: "mainnet" });
async function tradeLoop() {
const decision = aiAgent.decideTrade();
if (decision.shouldTrade) {
const intent = aiAgent.buildIntent(decision);
await intentsClient.submitIntent(intent);
}
}
In my experience, tuning the AI thresholds to avoid spamming intents saved gas and improved success rate.
Comparing Near Intents with Li.Fi SDK for Cross-Chain Swaps
Li.Fi is another go-to for cross-chain swaps with a straightforward quote-based API. Here’s a feature breakdown:
| Feature |
Near Intents SDK |
Li.Fi SDK |
| Approach |
Intent-based with batch solver |
Quote & route with immediate exec |
| Chains supported |
NEAR, Aurora, multi EVM, evolving |
Multi EVM + select L1/L2 & Near |
| API surface |
Intent creation, signing, submit |
Quote, route, execute swap |
| Language |
TypeScript |
TypeScript |
| License |
Open-source (check repo) |
Open-source (check repo) |
| Security considerations |
Permissions around intents, replay |
Approval management, infinite approvals risk |
Using Li.Fi SDK for a cross-chain swap
Example snippet:
import { LiFi } from "lifi-sdk";
const lifi = new LiFi();
async function swap() {
const routes = await lifi.getRoutes({
fromChainId: 42161, // Arbitrum
toChainId: 137, // Polygon
fromTokenAddress: '0x...',
toTokenAddress: '0x...',
amount: '1000000000000000000'
});
console.log(routes[0]);
// proceed with execution
}
The trade-off boils down to declarative intent + batch optimization on Near Intents vs explicit quoting and on-demand execution with Li.Fi.
Security Best Practices and Common Gotchas
When wiring up agents with Near Intents SDK or integrating DefAI, keep these in mind:
- Never store private keys insecurely. Use hardware wallets or ephemeral session keys with spending limits.
- Avoid unlimited token approvals. Both the Near Intents and Li.Fi flows involve token transfers — restricting allowance reduces drainage risk.
- Validate solver RPC endpoints. Using untrusted solvers could risk frontrunning or intent censorship.
- Implement retry and monitoring loops. Network hiccups or chain reorganizations may cause intent failures.
- Test extensively on testnets. Network and contract versions may cause incompatibilities.
One gotcha I ran into was versioning mismatches between the SDK and deployed on-chain solver contracts. Make sure SDK version aligns with your target environment.
Conclusion and Next Steps
Getting started with the Near Intents SDK unlocks a novel way to build cross-chain DeAI agents and intent-based DeFi workflows. The batch solver architecture brings flexibility but also requires rigorous testing and security awareness.
For developers targeting multi-chain DEX aggregation or AI agent deployments, I recommend:
- Experimenting with the sample agent and cross-chain swap example here
- Combining Near Intents with DefAI for algorithmic trading on Near
- Comparing your use case against Li.Fi’s quote-and-route model
- Building comprehensive audit pipelines to secure your agent's approvals and private keys
To keep pushing your AI-driven trading or MCP tooling projects, also check out related content on agent-payment-protocols-x402, ai-smart-contract-security, and mev-bot-development for tighter integration with contract security and MEV strategies.
Happy building!