npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sample-agent

v0.1.3

Published

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

Readme

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:

  1. Agent Backend: A running instance of your agent backend API
  2. API URL: The URL of your agent backend (e.g., https://your-agent-backend.com)
  3. 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

  1. Fork the repository
  2. Create your feature branch
  3. Add comprehensive tests
  4. Update documentation
  5. Submit a pull request

📄 License

MIT License - see LICENSE file for details


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