Skip to content

Commit

Permalink
Refactor NEAR integration and token transfer plugin
Browse files Browse the repository at this point in the history
- Updated default node URL in NEARConnection to point to the official testnet.
- Added async context manager support in NEARConnection for better resource management.
- Enhanced TokenTransferPlugin initialization to create NEAR connection and market data manager only if they don't already exist.
- Improved error handling during plugin initialization and cleanup processes.
- Updated quickstart.sh script to use the Python module for plugin management and execution commands, enhancing usability.
  • Loading branch information
jbarnes850 committed Jan 21, 2025
1 parent ee0189f commit 0b47a90
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 28 deletions.
10 changes: 9 additions & 1 deletion near_swarm/core/near_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self,
self.network = network.lower()
self.account_id = account_id
self.private_key = private_key
self.node_url = node_url or "https://test.rpc.fastnear.com"
self.node_url = node_url or "https://rpc.testnet.near.org"
self.use_backup = use_backup

try:
Expand All @@ -71,6 +71,14 @@ def __init__(self,
logger.error(f"Failed to initialize NEAR connection: {str(e)}")
raise NEARConnectionError(f"Failed to initialize connection: {str(e)}")

async def __aenter__(self):
"""Async context manager entry."""
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.close()

async def check_account(self, account_id: str) -> bool:
"""Check if account exists."""
try:
Expand Down
62 changes: 44 additions & 18 deletions plugins/token-transfer/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,10 @@

import asyncio
import logging
import os
from typing import Dict, Any, Optional
from near_swarm.plugins.base import AgentPlugin
from near_swarm.core.exceptions import AgentError, NEARError, LLMError
from near_swarm.core.market_data import MarketDataManager
from near_swarm.core.near_integration import NEARConnection

# Configure logging
logger = logging.getLogger(__name__)
Expand All @@ -69,26 +67,26 @@ class TokenTransferPlugin(AgentPlugin):
"""Plugin for secure NEAR token transfers with LLM validation."""

async def initialize(self) -> None:
"""Initialize plugin."""
"""Initialize plugin resources."""
try:
# Initialize LLM provider
if not hasattr(self, 'llm_provider'):
self.llm_provider = await self._create_llm_provider()

# Initialize NEAR connection
self.near = await NEARConnection.create(
account_id=os.getenv('NEAR_ACCOUNT_ID'),
private_key=os.getenv('NEAR_PRIVATE_KEY'),
network="testnet"
)
if not hasattr(self, 'near'):
self.near = await self._create_near_connection()

# Initialize market data manager
if not hasattr(self, 'market_data'):
self.market_data = MarketDataManager()
await self.market_data._ensure_session()

logger.info("TokenTransferPlugin initialized successfully")
except Exception as e:
logger.error(f"Initialization failed: {str(e)}")
raise

async def cleanup(self) -> None:
"""Cleanup plugin resources."""
if hasattr(self, 'near'):
try:
await self.near.close()
except Exception as e:
logger.warning(f"Error closing NEAR connection: {str(e)}")
except Exception as e:
logger.error(f"Initialization failed: {e}")
raise AgentError(f"Failed to initialize plugin: {e}")

async def _create_llm_provider(self):
"""Create LLM provider from configuration."""
Expand All @@ -107,6 +105,22 @@ async def _create_llm_provider(self):

return create_llm_provider(config)

async def _create_near_connection(self):
"""Create NEAR connection from configuration."""
from near_swarm.core.near_integration import create_near_connection, NEARConfig
from dotenv import load_dotenv
import os

load_dotenv()

config = NEARConfig(
network=os.getenv('NEAR_NETWORK', 'testnet'),
account_id=os.getenv('NEAR_ACCOUNT_ID'),
private_key=os.getenv('NEAR_PRIVATE_KEY')
)

return await create_near_connection(config)

async def execute(self, operation: Optional[str] = None, **kwargs) -> Any:
"""Execute plugin operations."""
if not operation:
Expand Down Expand Up @@ -229,6 +243,18 @@ async def _validate_transfer(
logger.error(f"LLM validation failed: {e}")
raise

async def cleanup(self) -> None:
"""Clean up plugin resources."""
try:
if hasattr(self, 'near'):
await self.near.close()
if hasattr(self, 'market_data'):
await self.market_data.close()
logger.info("TokenTransferPlugin cleaned up successfully")
except Exception as e:
logger.error(f"Cleanup failed: {e}")
raise AgentError(f"Failed to cleanup plugin: {e}")

async def main():
"""Run the token transfer example."""
from near_swarm.plugins import PluginLoader
Expand Down
18 changes: 9 additions & 9 deletions scripts/quickstart.sh
Original file line number Diff line number Diff line change
Expand Up @@ -166,21 +166,21 @@ section_header "🚀 Setting Up Agent Plugins"

# Install example plugins
show_progress "Installing token transfer plugin"
near-swarm plugins install near_swarm/examples/token_transfer_strategy.py --name token-transfer
python -m near_swarm.cli.main plugins install near_swarm/examples/token_transfer_strategy.py --name token-transfer

show_progress "Installing arbitrage plugin"
near-swarm plugins install near_swarm/examples/arbitrage_strategy.py --name arbitrage-agent
python -m near_swarm.cli.main plugins install near_swarm/examples/arbitrage_strategy.py --name arbitrage-agent

# List installed plugins
echo -e "\n${CYAN}Installed Plugins:${NC}"
near-swarm plugins list
python -m near_swarm.cli.main plugins list

# Initialize demo
section_header "📈 Running Demo"

# Run the token transfer demo
show_progress "Running token transfer demo"
near-swarm execute token-transfer --operation balance
python -m near_swarm.cli.main execute token-transfer --operation balance

# After setup, show status
section_header "📊 System Status"
Expand Down Expand Up @@ -212,13 +212,13 @@ section_header "💬 Starting Interactive Chat"
echo -e "Tip: Type ${CYAN}/help${NC} to see available commands"
echo -e " Type ${CYAN}/exit${NC} to quit at any time\n"

near-swarm chat --tutorial create-first-agent
python -m near_swarm.cli.main chat --tutorial create-first-agent

echo -e "\n${CYAN}Next steps:${NC}"
echo "1. Explore more agent templates: near-swarm plugins list"
echo "2. Create custom agents: near-swarm create agent my-agent"
echo "1. Explore more agent templates: python -m near_swarm.cli.main plugins list"
echo "2. Create custom agents: python -m near_swarm.cli.main create agent my-agent"
echo "3. Run advanced demos:"
echo " • Multi-agent trading: near-swarm demo trading"
echo " • Portfolio management: near-swarm demo portfolio"
echo " • Multi-agent trading: python -m near_swarm.cli.main demo trading"
echo " • Portfolio management: python -m near_swarm.cli.main demo portfolio"
echo ""
echo -e "${BLUE}Documentation: https://github.com/jbarnes850/near-ai-agent-studio${NC}"

0 comments on commit 0b47a90

Please sign in to comment.