A Python implementation for interacting with NEAR using intents for multichain transactions. This implementation provides an AI Agent that automates token swaps and other operations on the NEAR mainnet.
graph TD
A([User]) --> B[AI Agent]
B --> C[Intent Contract]
C --> D[Intent Request]
D --> E[Solver Bus]
E --> F[Solvers Pool]
F --> E
E --> D
D --> G[Signed Intent]
G --> H[Verifier Contract]
H --> I[State Change]
style A fill:#f9f9f9
style B fill:#d4edda
style C fill:#cce5ff
style D fill:#cce5ff
style E fill:#fff3cd
style F fill:#fff3cd
style G fill:#e2e3e5
style H fill:#f8d7da
style I fill:#f8d7da
-
Initialization:
- User initializes AI Agent with credentials
- Agent deposits NEAR tokens for operations
-
Quote Process:
- Create intent request for token swap
- Query Solver Bus for quotes
- Solvers provide best execution options
- Best quote is selected
-
Execution:
- Sign the selected quote
- Submit to Verifier Contract
- Execute state changes on-chain
- AI Agent (
ai_agent.py
): High-level interface for users - NEAR Intents (
near_intents.py
): Core protocol interactions - Solver Bus: Off-chain quote aggregation
- Verifier Contract: On-chain execution and settlement
NEAR Intents is a system for executing multichain transactions. An intent represents a user's desired state change (e.g., "I want to swap X NEAR for Y USDC") rather than a specific execution path. This allows for more flexible and efficient execution of financial operations.
NEAR Intents
├── Intent Settlement
│ ├── Solver Bus (off-chain message bus)
│ └── Verifier (on-chain smart contract)
└── Entities
├── Distribution Channels
└── Solvers
Our implementation maps to the protocol components as follows:
near-intents-ai-agent/
├── src/near_intents/
│ ├── near_intents.py # Core protocol interactions
│ │ ├── IntentRequest # Creates intent requests
│ │ ├── Quote # Handles quote creation/signing
│ │ └── ASSET_MAP # Supported tokens configuration
│ │
│ └── ai_agent.py # High-level interface
│ └── AIAgent # Manages the full swap flow
│
├── examples/ # Usage examples
│ └── basic_swap.py # Basic NEAR to USDC swap
│
└── tests/ # Test coverage
└── test_ai_agent.py
-
Solver Bus Integration (
near_intents.py
):- Communicates with the off-chain Solver Bus
- Fetches trading options and quotes
- Publishes signed intents
-
Intent Creation & Verification (
near_intents.py
):- Creates and signs token diff intents
- Interacts with the on-chain verifier contract
- Handles token deposits and withdrawals
-
AI Agent Interface (
ai_agent.py
):- Provides high-level swap operations
- Manages account setup and registration
- Handles token storage and deposits
-
Intent Settlement:
- Solver Bus: An off-chain message bus for communication between users and solvers
- Verifier: Smart contract on NEAR that verifies and executes signed intents
-
Key Players:
- Users: Participants who issue intents (e.g., "swap NEAR for USDC")
- Solvers: Market participants who fulfill user intents
- Distribution Channels: Applications connecting users with the intent system
The AI Agent serves as a high-level interface for executing intents on NEAR mainnet. It handles:
-
Account Management:
- Loading NEAR accounts from key files
- Registering public keys for intent operations
- Managing token storage registration
-
Core Operations:
- NEAR deposits for intent operations
- Token swaps using the intent system
- Error handling and logging
The core library implementing the NEAR Intents protocol:
-
Asset Management:
- Token mappings and identifiers
- Decimal precision handling
- Storage registration
-
Intent Operations:
- Quote creation and signing
- Intent submission and execution
- Solver bus interaction
User Request → AI Agent → NEAR Intents Library → Solver Bus → NEAR Blockchain
↑ ↓
└──────────────── Response/Result ────────────┘
# The complete flow from user request to execution:
# 1. Initialize AI Agent with account
agent = AIAgent("./account_file.json")
# - Loads NEAR account
# - Registers public key with intents contract
# - Verifies account state and balance
# 2. Deposit NEAR if needed
agent.deposit_near(1.0)
# - Checks current balance
# - Registers token storage
# - Deposits NEAR to intents contract
# 3. Execute a swap
result = agent.swap_near_to_token("USDC", 1.0)
# - Creates intent request
# - Fetches quotes from Solver Bus
# - Selects best quote
# - Signs and submits intent
# - Returns execution result
The swap process involves several steps:
-
Quote Creation:
# Create intent request request = IntentRequest() .set_asset_in("NEAR", amount_in) .set_asset_out("USDC") # Get quotes from Solver Bus options = fetch_options(request) best_option = select_best_option(options)
-
Intent Execution:
# Create and sign quote quote = create_token_diff_quote( account, "NEAR", amount_in, "USDC", best_option['amount_out'] ) # Submit to Solver Bus response = publish_intent(quote)
- Python 3.8+
- NEAR account with sufficient balance
- Account credentials in JSON format
NEAR_ACCOUNT_FILE=./account_file.json
NEAR_DEPOSIT_AMOUNT=1.0
TARGET_TOKEN=USDC
SWAP_AMOUNT=1.0
{
"account_id": "your-account.near",
"private_key": "ed25519:..."
}
Run our interactive setup script:
chmod +x setup_and_run.sh
./setup_and_run.sh
This script will:
- Check and install prerequisites
- Guide you through NEAR wallet creation
- Set up your development environment
- Configure your account and environment
- Execute your first swap
If you prefer to set things up manually:
- Clone the repository
git clone https://github.com/jbarnes850/near-intents-example
cd near-intents-example
- Set up your Python environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
- Configure your environment
cp .env.example .env
cp account_file.example.json account_file.json
- Set up your NEAR account
- Create a NEAR account (here's a wallet portal if you don't have one)
- Export your private key from the NEAR wallet
- Update
account_file.json
with your account details:- Replace
your-account.near
with your actual account ID - Replace
your-private-key-here
with your actual private key
- Replace
- Configure your environment variables
Edit .env
file and adjust the values according to your needs:
NEAR_DEPOSIT_AMOUNT=1.0 # Amount you want to deposit
SWAP_AMOUNT=1.0 # Amount you want to swap
- Run your first swap
python intents/ai_agent.py
from ai_agent import AIAgent
# Initialize agent
agent = AIAgent("./account_file.json")
# Deposit NEAR for operations
agent.deposit_near(1.0)
# Swap NEAR to USDC
result = agent.swap_near_to_token("USDC", 1.0)
try:
agent = AIAgent("./account_file.json")
# Check account state
account_state = agent.account.state()
balance_near = float(account_state['amount']) / 10**24
if balance_near > 1.0:
# Deposit and swap
agent.deposit_near(1.0)
result = agent.swap_near_to_token("USDC", 0.5)
print(f"Swap completed: {result}")
except Exception as e:
print(f"Error: {str(e)}")
Currently supported tokens in this demo:
- NEAR (Native token)
- USDC (a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.factory.bridge.near)
The implementation includes comprehensive error handling for:
- Insufficient balances
- Storage registration issues
- Network communication errors
- Invalid responses from solver bus
- Transaction execution failures
- Always check balances before operations
- Register storage for new tokens
- Use appropriate gas limits for transactions
- Handle errors gracefully
- Monitor solver bus responses for best execution
-
Private Key Management:
- Store private keys securely
- Use environment variables for sensitive data
- Never commit credentials to version control
-
Transaction Safety:
- Verify transaction amounts
- Check recipient addresses
- Monitor execution status
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.