@moonx-farm/shared

v1.0.2

Published

Shared utilities and types for MoonX Farm ecosystem

Readme

@moonx-farm/shared

Shared utilities and types for MoonX Farm ecosystem.

Overview

This package provides standardized JSON-RPC 2.0 types, interfaces, and utilities for WebSocket communication between client and server components in the MoonX Farm ecosystem. It also includes comprehensive market data types and validation schemas for DEX trading data.

Features

  • JSON-RPC 2.0 Compliance: Full implementation of JSON-RPC 2.0 specification
  • Market Data Types: Complete TypeScript types and Zod schemas for DEX protocols, trading pairs, OHLCV candles
  • WebSocket Messages: Standardized message schemas for real-time market data streaming
  • TypeScript Support: Complete type definitions and type safety
  • Message Builders: Convenient utilities for creating standardized messages
  • Validation: Built-in message validation utilities with Zod
  • Shared: Common types and utilities for MoonX Farm ecosystem

Installation

npm install @moonx-farm/shared

Usage

Basic Types

import { 
  JsonRpcRequest, 
  JsonRpcNotification, 
  JsonRpcResponse,
  JsonRpcErrorResponse,
  JsonRpcErrorCodes 
} from '@moonx-farm/shared';

// Create a request
const request: JsonRpcRequest = {
  jsonrpc: "2.0",
  method: "your_method",
  params: { key: "value" },
  id: "req_123"
};

Message Builder

import { JsonRpcMessageHelper } from '@moonx-farm/shared';

// Create a request
const request = JsonRpcMessageHelper.createRequest("your_method", { key: "value" });

// Create a notification
const notification = JsonRpcMessageHelper.createNotification("event", { data: "value" });

// Create error response
const errorResponse = JsonRpcMessageHelper.createMethodNotFoundError("unknown_method", "req_123");

Message Validation

import { JsonRpcValidator } from '@moonx-farm/shared';

const message = JSON.parse(rawMessage);

if (JsonRpcValidator.isValidMessage(message)) {
  if (JsonRpcValidator.isRequest(message)) {
    // Handle request
  } else if (JsonRpcValidator.isNotification(message)) {
    // Handle notification
  }
}

Message Parsing

import { JsonRpcMessageHelper } from '@moonx-farm/shared';

// Parse incoming message
const message = JsonRpcMessageHelper.parseMessage(rawMessage);

if (message) {
  // Valid JSON-RPC message
  console.log(message);
}

// Serialize message
const serialized = JsonRpcMessageHelper.serializeMessage(message);

Market Data Types

import { 
  DexProtocolSchema,
  TradingPairSchema, 
  OhlcvCandleSchema,
  WebSocketMessageSchema,
  MarketDataSubscriptionSchema,
  TimeframeSchema,
  type Timeframe,
  type OhlcvCandle,
  type TradingPair
} from '@moonx-farm/shared';

// Create OHLCV subscription
const subscription = MarketDataSubscriptionSchema.parse({
  pairs: ["ETH-USDC", "BTC-USDT"],
  timeframes: ["1m", "5m", "1h"],
  chain_ids: [1, 56, 8453]
});

// Validate WebSocket message
const wsMessage = {
  type: "subscribe",
  payload: subscription
};

const validatedMessage = WebSocketMessageSchema.parse(wsMessage);

// Work with validated data
const candle: OhlcvCandle = {
  id: 1,
  trading_pair_id: 123,
  timeframe: "1h",
  timestamp_bucket: "2024-12-19T10:00:00.000Z",
  open_price: "2000.50",
  high_price: "2010.75", 
  low_price: "1995.25",
  close_price: "2005.00",
  volume_usd: "150000.50",
  // ... other fields
};

Utility Functions

import { 
  timeframeToMs,
  getTimestampBucket,
  generatePairSymbol,
  parsePairSymbol,
  isValidAddress,
  getChainName
} from '@moonx-farm/shared';

// Convert timeframe to milliseconds
const duration = timeframeToMs("1h"); // 3600000

// Get timestamp bucket
const bucket = getTimestampBucket(Date.now(), "1h");

// Generate pair symbol
const symbol = generatePairSymbol("ETH", "USDC"); // "ETH-USDC"

// Parse pair symbol
const tokens = parsePairSymbol("ETH-USDC"); // { token0: "ETH", token1: "USDC" }

// Validate address
const isValid = isValidAddress("0x742d35Cc6635C0532925a3b8D82A9e87aa5E82f0");

// Get chain name
const chainName = getChainName(1); // "Ethereum"

JSON-RPC 2.0 Message Types

Request

A request message that expects a response:

{
  "jsonrpc": "2.0",
  "method": "method_name",
  "params": { "key": "value" },
  "id": "request_id"
}

Notification

A request message that doesn't expect a response:

{
  "jsonrpc": "2.0",
  "method": "method_name",
  "params": { "key": "value" }
}

Response (Success)

A successful response to a request:

{
  "jsonrpc": "2.0",
  "result": { "data": "value" },
  "id": "request_id"
}

Response (Error)

An error response to a request:

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32601,
    "message": "Method not found",
    "data": { "method": "unknown_method" }
  },
  "id": "request_id"
}

Standard Error Codes

JSON-RPC 2.0 defines the following error codes:

  • -32700 Parse error - Invalid JSON was received
  • -32600 Invalid Request - The JSON sent is not a valid Request object
  • -32601 Method not found - The method does not exist / is not available
  • -32602 Invalid params - Invalid method parameter(s)
  • -32603 Internal error - Internal JSON-RPC error
  • -32000 to -32099 Server error - Reserved for implementation-defined server-errors

Development

# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Run linter
npm run lint

License

MIT