New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

sample-agent

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sample-agent

Abstraxn Agent SDK for zero-code web3 multi-agent service integration with chat, authentication, transactions, and real-time features

latest
npmnpm
Version
0.1.3
Version published
Maintainers
1
Created
Source

Abstraxn Agent SDK

Web3 AI Agent SDK for chat, authentication, and agent backend integration.

The Abstraxn Agent SDK provides a simple interface to integrate with your agent backend API, enabling AI-powered Web3 interactions with minimal code.

🚀 Quick Start

npm install @abstraxn/agent

📋 Prerequisites

Before using the SDK, you need:

  • Agent Backend: A running instance of your agent backend API
  • API URL: The URL of your agent backend (e.g., https://your-agent-backend.com)
  • Wallet: Any wallet provider (ethers.js, Web3Auth, WalletConnect, MetaMask, etc.)
import { Agent } from '@abstraxn/agent';
import { ethers } from 'ethers';

// Initialize the agent with your backend API
const agent = new Agent({
  apiUrl: "https://your-agent-backend.com", // Your agent backend URL
  chainId: 1, // Ethereum mainnet
  signer: new ethers.Wallet("your-private-key"), // Any wallet provider
  autoConnect: true,
});

// Initialize and authenticate
await agent.init();
await agent.login({ address: "0x..." });

// Chat with AI agent
const response = await agent.ask("What's my ETH balance?");

// Get session history
const history = await agent.chat.getCurrentHistory();
console.log("Chat history:", history.data);

🔌 API Integration

The SDK provides complete integration with your agent backend API. All API endpoints are automatically handled with proper error handling and response conversion.

🔐 Authentication APIs

// Login with wallet signature
await agent.login({ address: "0x..." });

// Get current user info
const user = await agent.getCurrentUser();

// Logout
await agent.logout();

💬 Chat APIs

// Send a message
const response = await agent.chat.send("What's my ETH balance?");

// Get user sessions
const sessions = await agent.chat.getSessions();

// Get session messages
const messages = await agent.chat.getHistory(sessionId);

🏥 System APIs

// Check system health
const health = await agent.getHealth();

🎯 Key Features

🔐 Smart Authentication

  • Automatic wallet authentication with message signing
  • JWT token management with auto-refresh
  • Session persistence across browser restarts
  • Background health monitoring

💬 AI Chat Integration

  • Context-aware conversations with wallet and chain data
  • Streaming responses for real-time interaction
  • Session management with history persistence
  • Real-time API integration with your agent backend

🌐 Backend API Integration

  • Complete API coverage for all agent backend endpoints
  • Authentication APIs (login, refresh, logout, user info)
  • Chat APIs (send messages, get sessions, session messages)
  • System APIs (health check)
  • Automatic error handling and response conversion

🏗️ Production Ready

  • Zero configuration - works out of the box
  • Full TypeScript support with comprehensive types
  • Error handling with automatic retry logic
  • Storage management with localStorage/sessionStorage

📖 Detailed Usage

Authentication

// Wallet-based authentication (automatic)
await agent.login({ address: wallet.address });

// Check authentication status
const isAuth = agent.auth.isAuthenticated();
const user = await agent.auth.getCurrentUser();

// Handle auth events
agent.auth.onAuthChange((isAuthenticated, user) => {
  console.log('Auth status:', isAuthenticated, user);
});

Chat Operations

// Send a message
const response = await agent.chat.send("What's my balance?", {
  context: { 
    chain_ids: [137], 
    wallet_address: address 
  }
});

// Streaming chat
for await (const chunk of agent.chat.sendStream("Explain DeFi")) {
  console.log(chunk.content);
}

// Session management
const session = await agent.chat.createSession({ title: "DeFi Discussion" });
const history = await agent.chat.getHistory(session.id);

Advanced Features

// Error handling
agent.on('onError', (error) => {
  console.error('Agent error:', error);
});

// Health monitoring
const health = await agent.getHealth();
console.log('Service status:', health);

// Storage management
await agent.clearAllData(); // Clear all cached data

🔧 Configuration

const agent = new Agent({
  // Required
  apiUrl: "http://localhost:8000", 
  chainId: 137, // Polygon
  signer: wallet, // Any wallet provider
  
  // Optional
  autoConnect: true,
  
  // Storage configuration
  storage: {
    type: "localStorage", // or "sessionStorage" or "custom"
    prefix: "abstraxn_agent_"
  },
  
  // WebSocket configuration
  webSocket: {
    enabled: true,
    autoConnect: true,
    reconnection: true
  }
});

🔗 Wallet Provider Support

The SDK supports any wallet provider that implements the WalletSigner interface:

Ethers.js Wallet

import { ethers } from 'ethers';

const wallet = new ethers.Wallet("private-key");
const agent = new Agent({
  apiUrl: "https://your-backend.com",
  chainId: 1,
  signer: wallet, // ethers.Signer
});

Web3Auth

const web3AuthSigner = {
  async getAddress(): Promise<string> {
    return await web3Auth.getUserInfo().then(user => user.address);
  },
  async signMessage(message: string): Promise<string> {
    return await web3Auth.signMessage(message);
  }
};

const agent = new Agent({
  apiUrl: "https://your-backend.com",
  chainId: 1,
  signer: web3AuthSigner, // Generic WalletSigner
});

WalletConnect

const walletConnectSigner = {
  async getAddress(): Promise<string> {
    return await walletConnect.getAccounts()[0];
  },
  async signMessage(message: string): Promise<string> {
    return await walletConnect.signMessage(message);
  }
};

const agent = new Agent({
  apiUrl: "https://your-backend.com",
  chainId: 1,
  signer: walletConnectSigner, // Generic WalletSigner
});

MetaMask

const metaMaskSigner = {
  async getAddress(): Promise<string> {
    const accounts = await window.ethereum.request({ method: 'eth_accounts' });
    return accounts[0];
  },
  async signMessage(message: string): Promise<string> {
    const accounts = await window.ethereum.request({ method: 'eth_accounts' });
    return await window.ethereum.request({
      method: 'personal_sign',
      params: [message, accounts[0]]
    });
  }
};

const agent = new Agent({
  apiUrl: "https://your-backend.com",
  chainId: 1,
  signer: metaMaskSigner, // Generic WalletSigner
});

Custom Wallet Provider

class CustomWallet {
  async getAddress(): Promise<string> {
    // Your custom logic
    return "0x...";
  }
  
  async signMessage(message: string): Promise<string> {
    // Your custom signing logic
    return "0x...";
  }
}

const agent = new Agent({
  apiUrl: "https://your-backend.com",
  chainId: 1,
  signer: new CustomWallet(), // Custom WalletSigner
});

🎯 Real-World Examples

DeFi Portfolio Manager

const agent = new Agent({ /* config */ });
await agent.init();

// Ask about portfolio
const portfolio = await agent.ask("Show my DeFi portfolio across all chains");

// Get AI suggestions
const suggestions = await agent.ask("What are the best DeFi strategies for my portfolio?");

AI Trading Assistant

const agent = new Agent({ /* config */ });

// Get market analysis
const analysis = await agent.ask("Analyze current market conditions and suggest trading opportunities");

// Get specific token information
const tokenInfo = await agent.ask("What's the current price and analysis for ETH?");

NFT Collection Assistant

// Get NFT collection analysis
const collection = await agent.ask("Analyze my NFT collection and suggest which ones to sell");

// Get floor price information
const floorPrices = await agent.ask("What are the current floor prices for Bored Apes?");

🔗 Direct API Integration

The Agent SDK integrates directly with your backend APIs for maximum simplicity:

const agent = new Agent({
  apiUrl: "http://localhost:8000", // Your backend API
  chainId: 137, // Polygon
  signer: wallet,
  // All blockchain operations handled by your backend
});

🛡️ Security & Best Practices

  • Never expose private keys in client-side code
  • Implement proper error handling for production use
  • Use session management for better UX
  • Validate all responses from the agent backend
  • Handle network errors gracefully

📚 API Reference

Agent Class

  • init() - Initialize the agent
  • login(credentials) - Authenticate user
  • ask(message, sessionId?) - Send chat message
  • getHealth() - Check service health
  • getCurrentUser() - Get current user
  • logout() - Logout user

Auth Manager

  • isAuthenticated() - Check auth status
  • refreshToken() - Refresh access token
  • getCurrentUser() - Get user profile
  • clearTokens() - Clear stored tokens

Chat Manager

  • send(message, options) - Send message
  • sendStream(message) - Streaming chat
  • createSession() - Create new session
  • getSessions() - Get all sessions
  • getHistory(sessionId) - Get chat history
  • getCurrentHistory() - Get current session history

🔄 Migration from Direct API Usage

Before (Manual Implementation):

// Complex setup + manual API calls
const response = await fetch('/api/v1/chat/', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}` },
  body: JSON.stringify({ message, session_id, context })
});
const data = await response.json();

After (Agent SDK):

// Simple solution
const response = await agent.ask(message);

📈 Performance Benefits

  • 90% less code compared to direct API integration
  • Built-in caching for better performance
  • Background processing for seamless UX
  • Error recovery with automatic retry logic
  • TypeScript support for better development experience

🤝 Contributing

  • Fork the repository
  • Create your feature branch
  • Add comprehensive tests
  • Update documentation
  • Submit a pull request

📄 License

MIT License - see LICENSE file for details

Built with ❤️ by the Abstraxn team for the Web3 developer community.

Keywords

Web3

FAQs

Package last updated on 09 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts