plugin-moralis-v2
v2.0.0
Published
Moralis DeFi plugin for ElizaOS - provides real-time Solana blockchain data
Maintainers
Readme
plugin-moralis-v2
A Moralis DeFi plugin for ElizaOS that provides real-time Solana blockchain data including token prices, trading pairs, statistics, OHLCV data, and token metadata via the Moralis API. Built with multi-chain architecture supporting Solana (currently implemented) with extensibility for Ethereum and other chains.
Features
Current Implementation (Solana)
- Token Trading Pairs: Retrieve all trading pairs for specific Solana tokens across DEXes (Raydium, Orca, etc.)
- Pair Statistics: Detailed trading pair statistics including price changes, liquidity, volume, buys/sells across multiple timeframes (5m, 1h, 4h, 24h)
- Token Statistics: Aggregated statistics across all pairs for a token including total liquidity, active pairs, active DEXes, and trading volumes
- OHLCV Data: Historical candlestick price data with support for multiple timeframes (1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w)
- Token Prices: Current token prices with USD and native SOL pricing from primary liquidity sources
- Token Metadata: Comprehensive token information including name, symbol, decimals, supply, Metaplex metadata, social links, and spam detection
Architecture
- Multi-chain Ready: Built with chain-agnostic API client supporting multiple blockchain networks
- Service-based Design: Clean separation between API client, service layer, and actions
- Type-safe: Full TypeScript support with comprehensive type definitions
- Extensible: Easy to add support for additional chains (Ethereum infrastructure already in place)
Installation
# Install dependencies
bun install
# Build the plugin
bun run buildConfiguration
Environment Variables
Add the following to your .env file:
# Required
MORALIS_API_KEY=your_moralis_api_key_hereThe plugin uses chain-specific base URLs automatically:
- Solana:
https://solana-gateway.moralis.io - Ethereum:
https://deep-index.moralis.io/api/v2.2(infrastructure ready)
Get a Moralis API Key
- Visit Moralis.io
- Sign up for a free account
- Navigate to your dashboard
- Create a new API key
- Copy the key to your
.envfile
Character Configuration
Add the plugin to your character configuration file:
import { moralisPlugin } from './plugin-moralis-v2';
export const character = {
name: 'Your Agent',
plugins: [
moralisPlugin,
// ... other plugins
],
settings: {
secrets: {
MORALIS_API_KEY: process.env.MORALIS_API_KEY,
},
},
};Or use it programmatically:
import { moralisPlugin, MoralisService } from './plugin-moralis-v2';
// Initialize plugin
await moralisPlugin.init({
MORALIS_API_KEY: 'your-api-key',
});Available Actions
All actions support natural language queries and automatically extract Solana token/pair addresses from user messages.
1. GET_SOLANA_TOKEN_PAIRS
Retrieves all trading pairs for a specific Solana token across all DEXes.
Response Data:
- Exchange name and address
- Pair address and label
- USD and native price with 24h changes
- Trading volume (24h in USD and native)
- Liquidity in USD
- Base and quote token information
- Pair status (active/inactive)
Example:
User: "Show me all trading pairs for Solana token So11111111111111111111111111111111111111112"
Agent: Returns paginated list of trading pairs with comprehensive market dataSimiles: FETCH_SOLANA_TOKEN_PAIRS, CHECK_SOLANA_TOKEN_PAIRS, SHOW_SOLANA_TOKEN_PAIRS
2. GET_SOLANA_PAIR_STATS
Fetches detailed statistics for a specific trading pair with time-based analytics.
Response Data:
- Current USD and native prices
- Total liquidity in USD
- Price and liquidity percentage changes across timeframes (5m, 1h, 4h, 24h)
- Buy/sell counts and volumes per timeframe
- Unique buyers and sellers per timeframe
- Exchange information with logos and URLs
- Pair creation date and labels
Example:
User: "Get statistics for Solana pair 4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"
Agent: Returns comprehensive pair statistics with multi-timeframe analysisSimiles: FETCH_SOLANA_PAIR_STATS, CHECK_SOLANA_PAIR_STATS, SHOW_SOLANA_PAIR_STATS
3. GET_SOLANA_TOKEN_STATS
Aggregates statistics across all trading pairs for a token to provide holistic market overview.
Response Data:
- Total liquidity in USD across all pairs
- Total number of active trading pairs
- Total number of active DEXes
- Total swaps per timeframe (5m, 1h, 4h, 24h)
- Total trading volumes (total, buy, sell) per timeframe
- Unique buyers and sellers counts per timeframe
Example:
User: "Show me overall statistics for token So11111111111111111111111111111111111111112"
Agent: Returns aggregated market data across all DEXes and pairsSimiles: FETCH_SOLANA_TOKEN_STATS, CHECK_SOLANA_TOKEN_STATS, SHOW_SOLANA_TOKEN_STATS
4. GET_SOLANA_PAIR_OHLCV
Retrieves OHLCV (Open, High, Low, Close, Volume) candlestick price history data for technical analysis and charting.
Response Data:
- Timestamp for each candle
- Open, High, Low, Close prices
- Trading volume
- Number of trades
- Timeframe and currency information
- Pagination support with cursor
Supported Timeframes: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w
Example:
User: "Get price history for pair 4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R with 1h timeframe"
Agent: Returns array of OHLCV candles for the specified timeframeSimiles: FETCH_SOLANA_PAIR_OHLCV, GET_SOLANA_OHLCV, SHOW_SOLANA_PAIR_OHLCV
5. GET_SOLANA_TOKEN_PRICE
Fetches the current price of a Solana token from its primary liquidity source.
Response Data:
- USD price
- Native price (value, symbol, name, decimals)
- Exchange name and address
- Primary liquidity source information
Example:
User: "What is the price of token So11111111111111111111111111111111111111112?"
Agent: Returns current price in USD and SOL with exchange detailsSimiles: FETCH_SOLANA_TOKEN_PRICE, CHECK_SOLANA_TOKEN_PRICE, SHOW_SOLANA_TOKEN_PRICE
6. GET_SOLANA_TOKEN_METADATA
Retrieves comprehensive metadata and on-chain information for a Solana token.
Response Data:
- Token mint address
- Name, symbol, and logo
- Decimals and token standard
- Total supply (raw and formatted)
- Fully diluted valuation
- Metaplex metadata (URI, mutability, sale info, royalties, update authority)
- Social links (Twitter, Discord, Website, Medium, Reddit)
- Description
- Verification status
- Spam detection flag
Example:
User: "Show me information about token So11111111111111111111111111111111111111112"
Agent: Returns comprehensive token metadata including supply, social links, and Metaplex dataSimiles: FETCH_SOLANA_TOKEN_METADATA, GET_SOLANA_TOKEN_INFO, SHOW_SOLANA_TOKEN_METADATA
Usage Examples
Natural Language Queries
The plugin automatically extracts token/pair addresses from natural language:
User: "What's the current price of SOL token So11111111111111111111111111111111111111112?"
Agent: "Current price for token So11111111111111111111111111111111111111112:
USD Price: $204.65
Native Price: 1.000000 SOL
Exchange: Orca Whirlpool (whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc)"User: "Show me trading pairs for USDC EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
Agent: Returns all trading pairs with prices, volumes, and liquidity dataProgrammatic Usage
import { moralisPlugin, MoralisService } from './plugin-moralis-v2';
import { MoralisChain } from './plugin-moralis-v2/types/moralis';
// Access the service from runtime
const service = runtime.getService(MoralisService.serviceType) as MoralisService;
const apiClient = service.getApiClient();
// Get token pairs (multi-chain support)
const pairsResult = await apiClient.getTokenPairs(
MoralisChain.SOLANA,
'So11111111111111111111111111111111111111112'
);
// Get current token price
const priceResult = await apiClient.getTokenPrice(
MoralisChain.SOLANA,
'So11111111111111111111111111111111111111112'
);
// Get pair statistics
const statsResult = await apiClient.getPairStats(
MoralisChain.SOLANA,
'4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R'
);
// Get OHLCV data
const ohlcvResult = await apiClient.getPairOHLCV(
MoralisChain.SOLANA,
'4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R',
'1h',
Date.now() - 86400000, // from 24h ago
Date.now() // to now
);API Reference
MoralisService
The core service that manages the Moralis API client and lifecycle.
class MoralisService extends Service {
static serviceType = 'moralis';
capabilityDescription: string;
getApiClient(): MoralisApiClient;
static start(runtime: IAgentRuntime): Promise<Service>;
static stop(runtime: IAgentRuntime): Promise<void>;
}MoralisApiClient
Multi-chain API client for direct Moralis API access.
class MoralisApiClient {
constructor(config: MoralisConfig);
// Multi-chain methods (all require MoralisChain parameter)
async getTokenPairs(chain: MoralisChain, tokenAddress: string): Promise<MoralisApiResponse<TokenPairsResponse>>;
async getPairStats(chain: MoralisChain, pairAddress: string): Promise<MoralisApiResponse<PairStats>>;
async getTokenStats(chain: MoralisChain, tokenAddress: string): Promise<MoralisApiResponse<TokenStats>>;
async getPairOHLCV(chain: MoralisChain, pairAddress: string, timeframe: string, fromDate: number, toDate: number): Promise<MoralisApiResponse<OHLCVResponse>>;
async getTokenPrice(chain: MoralisChain, tokenAddress: string): Promise<MoralisApiResponse<TokenPrice>>;
async getTokenMetadata(chain: MoralisChain, tokenAddress: string): Promise<MoralisApiResponse<TokenMetadata>>;
}Type Definitions
enum MoralisChain {
SOLANA = 'solana',
ETHEREUM = 'ethereum',
}
interface MoralisConfig {
apiKey: string;
timeout?: number; // default: 20000ms
}
interface MoralisApiResponse<T> {
success: boolean;
data?: T;
error?: string;
}Development
Setup
# Install dependencies
bun install
# Build the plugin
bun run build
# Build with watch mode
bun run build:watch
# Development mode with hot reload
bun run dev
# Run tests
bun test
# Format code
bun run formatProject Structure
plugin-moralis-v2/
├── src/
│ ├── actions/ # All 6 Solana DeFi actions
│ │ ├── getSolanaTokenPairs.ts
│ │ ├── getSolanaPairStats.ts
│ │ ├── getSolanaTokenStats.ts
│ │ ├── getSolanaPairOHLCV.ts
│ │ ├── getSolanaTokenPrice.ts
│ │ ├── getSolanaTokenMetadata.ts
│ │ └── index.ts
│ ├── providers/ # Context providers
│ │ └── moralisDataProvider.ts
│ ├── services/ # Core services
│ │ └── moralisService.ts
│ ├── templates/ # LLM prompt templates
│ │ ├── tokenPairs.ts
│ │ ├── pairStats.ts
│ │ ├── tokenStats.ts
│ │ ├── pairOHLCV.ts
│ │ ├── tokenPrice.ts
│ │ └── tokenMetadata.ts
│ ├── types/ # TypeScript type definitions
│ │ ├── moralis.ts # Core Moralis types
│ │ └── solana.ts # Solana-specific types
│ ├── utils/ # Utilities
│ │ ├── api.ts # Multi-chain API client
│ │ └── actionHelper.ts # Action execution helper
│ ├── __tests__/ # Test suites
│ │ ├── plugin.test.ts
│ │ ├── actions.test.ts
│ │ ├── test-utils.ts
│ │ └── e2e/
│ │ └── plugin-moralis.e2e.ts
│ ├── plugin.ts # Main plugin configuration
│ └── index.ts # Entry point
├── dist/ # Compiled output
├── package.json
├── tsconfig.json
├── build.ts
└── README.mdTesting
The plugin includes comprehensive test coverage:
# Run all tests
bun test
# Run specific test file
bun test src/__tests__/plugin.test.ts
# Run E2E tests
bun test src/__tests__/e2e/plugin-moralis.e2e.ts
# Watch mode
bun test --watchTest Structure:
- Unit tests for service initialization and configuration
- Action validation tests
- E2E tests for full plugin integration
- Mock runtime utilities for testing
API Health Check
The plugin provides a health check endpoint:
GET /api/moralis/statusResponse:
{
"status": "configured",
"plugin": "plugin-moralis",
"version": "2.0.0",
"apiKeyConfigured": true,
"supportedChains": ["Solana"],
"availableActions": [
"GET_SOLANA_TOKEN_PAIRS",
"GET_SOLANA_PAIR_STATS",
"GET_SOLANA_TOKEN_STATS",
"GET_SOLANA_PAIR_OHLCV",
"GET_SOLANA_TOKEN_PRICE",
"GET_SOLANA_TOKEN_METADATA"
],
"timestamp": "2025-01-11T10:30:00.000Z"
}Error Handling
The plugin includes comprehensive error handling at multiple layers:
Configuration Validation
- Schema Validation: Uses Zod to validate configuration on initialization
- API Key Validation: Ensures MORALIS_API_KEY is provided and non-empty
- Timeout Validation: Validates timeout values are positive and finite
Runtime Error Handling
- Chain Validation: Validates supported chains before making API requests
- API Errors: Gracefully handles network failures, timeouts, and invalid responses
- Service Errors: Handles service unavailability with clear error messages
- Type Safety: TypeScript ensures type correctness throughout the stack
Logging
All errors and important events are logged using ElizaOS logger:
logger.info()- Initialization and normal operationslogger.success()- Successful operationslogger.warn()- Non-critical issueslogger.error()- Errors with full context for debugginglogger.debug()- Detailed debugging information
Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests (
bun test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see LICENSE file for details
Support
- Documentation: ElizaOS Documentation
- Discord: ElizaOS Community
- Issues: GitHub Issues
- Moralis Docs: Moralis Documentation
Technical Features
Multi-Chain Architecture
The plugin is built with extensibility in mind:
- Chain-agnostic API client with
MoralisChainenum - Separate base URLs per chain (Solana, Ethereum)
- Easy to add new chains by extending the
MoralisChainenum
LLM Integration
- Smart Templates: Each action has a dedicated prompt template for address extraction
- Natural Language Processing: Automatically parses token/pair addresses from conversational input
- Context Awareness: Only processes the most recent message to avoid confusion
- Chain Detection: Templates can detect and reject requests for unsupported chains
ElizaOS Plugin System
- Service Pattern: MoralisService extends ElizaOS Service class
- Action System: All 6 actions follow ElizaOS Action interface
- Provider Integration: moralisDataProvider supplies context to agents
- Route Support: HTTP endpoints for health checks and status
- Test Integration: E2E test suite included in plugin definition
Changelog
v2.0.0 (Current)
Architecture:
- Multi-chain API client supporting Solana and Ethereum (infrastructure)
- Service-based architecture with proper lifecycle management
- Comprehensive TypeScript type definitions for all API responses
- Dedicated LLM prompt templates for natural language processing
Features:
- 6 Solana DeFi actions (pairs, stats, OHLCV, price, metadata)
- Real-time data from Moralis API with automatic chain routing
- Health check HTTP endpoint
- Data provider for agent context
Quality:
- Zod schema validation for configuration
- Comprehensive error handling and logging
- Full test coverage (unit, integration, E2E)
- Code formatting with Prettier
Documentation:
- Detailed API reference
- Usage examples (conversational and programmatic)
- Complete type definitions
- Architecture documentation
Credits
Built with ElizaOS and powered by Moralis API.
