@0xmonaco/core

中文文档
1.1.8发布于 2026/11/06TypeScriptES Module近 30 天下载 8175

Core SDK implementation for interacting with Monaco Protocol. This SDK provides a comprehensive implementation with Authentication, Vault, Trading, Market, and Profile APIs, featuring noncustodial session-key authentication and secure API Gateway integrat

原始使用文档
文档目录32 节
  1. Installation
  2. Features
  3. 🔐 Authentication
  4. 🏦 Vault Operations
  5. 📈 Trading Operations
  6. 📊 Market Data
  7. 👤 Profile Management
  8. 🔐 Security Features
  9. Network Support
  10. Quick Start
  11. API Reference
  12. MonacoSDK
  13. Configuration
  14. Authentication & Session Management
  15. Vault API
  16. Trading API
  17. Market API
  18. WebSocket Authentication
  19. Error Handling
  20. Development
  21. Project Structure
  22. Development Setup
  23. Testing
  24. Code Style
  25. Security Features
  26. Session-key Authentication
  27. API Gateway Integration
  28. On-chain Security
  29. Performance Considerations
  30. Development Workflow
  31. License
  32. Support

Monaco Core SDK

Core SDK implementation for interacting with Monaco Protocol. This SDK provides a comprehensive implementation with Authentication, Vault, Trading, Market, and Profile APIs, featuring noncustodial session-key authentication and secure API Gateway integration.

Installation

npm install @0xmonaco/core

Required Peer Dependencies:

npm install viem@^2.31.7

Features

🔐 Authentication

  • Session-key Authentication: Noncustodial ed25519 session keys — the server never holds a credential that can impersonate you
  • Wallet Signature Verification: EIP-712 signature authorizes each session key
  • Session Refresh: Extend session expiry without re-prompting the wallet

🏦 Vault Operations

  • Token Approvals: ERC20 token approvals for vault usage
  • Deposits: Secure token deposits with signature validation
  • Withdrawals: Token withdrawals with cryptographic validation
  • Balance Queries: Real-time vault balance tracking

📈 Trading Operations

  • Order Types: Limit and Market orders
  • Order Management: Place, replace, and cancel orders
  • Order Queries: Paginated orders, order history, and individual order details
  • Real-time Updates: WebSocket support for live order updates

📊 Market Data

  • Trading Pairs: Complete trading pair metadata
  • Market Information: Fees, tick sizes, order limits
  • Pair Discovery: Search and filter available markets

👤 Profile Management

  • User Profiles: Account information and settings
  • Sub-accounts: Multi-account management
  • Balance Tracking: Cross-platform balance monitoring

🔐 Security Features

  • Session-key Signing: Every authenticated request is signed with a locally held ed25519 key
  • EIP-712 Signatures: Type-safe, structured data signing for session authorization
  • API Gateway Integration: Secure communication with Monaco backend
  • TLS Encryption: Secure API communications

Network Support

Configure the network by providing the network and seiRpcUrl parameters. Use the "mainnet" preset, which connects to Sei mainnet and the production API (https://apimonaco.xyz). WebSocket URLs are resolved automatically.

import { MonacoSDK } from "@0xmonaco/core";

const sdk = new MonacoSDK({
  walletClient,
  network: "mainnet",
  seiRpcUrl: "https://evm-rpc.sei-apis.com",
});

Quick Start

import { MonacoSDK } from "@0xmonaco/core";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { sei } from "viem/chains";

// Initialize the SDK with wallet client
const account = privateKeyToAccount("0x...");
const walletClient = createWalletClient({
  account,
  chain: sei,
  transport: http("https://evm-rpc.sei-apis.com")
});

const monaco = new MonacoSDK({
  walletClient,
  network: "mainnet",
  seiRpcUrl: "https://evm-rpc.sei-apis.com", // public RPC; use a dedicated provider in production
});

// Authentication
async function authExample() {
  // Login with client ID and auto-connect authenticated WebSocket channels (Orders)
  const authState = await monaco.login("your-client-id", { connectWebSocket: true });
  console.log("Authenticated:", authState.user);
  console.log("Session:", {
    sessionPublicKey: authState.sessionPublicKey,
    expiresAt: authState.expiresAt,
  });
  
  // Authenticated WebSocket channels are now connected - start receiving real-time updates
  // Currently this includes: Orders (personal order updates)
  monaco.websocket.orders.subscribeToOrderEvents("BTC/USDC", "SPOT", (event) => {
    console.log("Order event:", event.eventType);
  });
  
  // Check authentication status
  console.log("Is authenticated:", monaco.isAuthenticated());
  
  // Logout (revokes the session and disconnects authenticated WebSockets)
  await monaco.logout();
  
  // Or manually revoke the session
  await monaco.auth.revokeSession();
}

// Market Data
async function marketExample() {
  // Get all trading pairs
  const pairs = await monaco.market.getTradingPairs();
  console.log("Available pairs:", pairs.length);
  
  // Get specific trading pair
  const btcPair = await monaco.market.getTradingPairBySymbol("BTC/USDC");
  console.log("BTC pair:", btcPair?.symbol, btcPair?.tickSize);

  // Fee rates are tiered: read the pair's schedule (public) or your own tier
  if (btcPair) {
    const { feeSchedule } = await monaco.fees.getFeeSchedule(btcPair.id);
    console.log("Tier 1 taker fee (bps):", feeSchedule[0]?.takerFeeBps);
  }
}

// Vault Operations
async function vaultExample() {
  // Get asset ID from trading pair
  const pair = await monaco.market.getTradingPairBySymbol("USDC/USDT");
  const assetId = pair.base_asset_id; // Asset ID (UUID)
  
  // Check vault balance
  const balance = await monaco.profile.getUserBalanceByAssetId(assetId);
  console.log("Vault balance:", balance.total_balance, balance.symbol);

  // Approve vault to spend tokens
  const approval = await monaco.vault.approve(assetId, parseEther("1000"));
  console.log("Approval transaction:", approval.hash);

  // Deposit tokens
  const result = await monaco.vault.deposit(assetId, parseEther("100"));
  console.log("Deposit transaction:", result.hash);
  
  // Withdraw tokens
  const withdrawal = await monaco.vault.withdraw(assetId, parseEther("50"));
  console.log("Withdrawal transaction:", withdrawal.hash);
}

// Trading Operations
async function tradingExample() {
  // Look up the trading pair UUID first
  const pair = await monaco.market.getTradingPairBySymbol("BTC/USDC");
  const tradingPairId = pair.id; // UUID

  // Place a limit order
  const order = await monaco.trading.placeLimitOrder(
    tradingPairId, // trading pair UUID
    "BUY", // side
    "0.001", // quantity
    "50000" // price
  );
  console.log("Order placed:", order.order_id);

  // Place a limit order with IOC (Immediate or Cancel)
  const iocOrder = await monaco.trading.placeLimitOrder(
    tradingPairId,
    "BUY",
    "0.001",
    "50000",
    { timeInForce: "IOC" } // Execute immediately or cancel
  );
  console.log("IOC order placed:", iocOrder.order_id);

  // Place a market order
  const marketOrder = await monaco.trading.placeMarketOrder(
    tradingPairId,
    "SELL",
    "0.001"
  );
  console.log("Market order placed:", marketOrder.order_id);

  // Get paginated orders
  const orders = await monaco.trading.getPaginatedOrders({
    status: "SUBMITTED",
    trading_pair: "BTC/USDC",
    page: 1,
    page_size: 10
  });
  console.log("Orders:", orders.data.length);

  // Replace an order
  const replaceResult = await monaco.trading.replaceOrder("order-id", {
    quantity: "0.002",
    price: "51000"
  });
  console.log("Order replaced:", replaceResult.order_id);

  // Cancel an order
  const cancelResult = await monaco.trading.cancelOrder("order-id");
  console.log("Order cancelled:", cancelResult.status);
  
  // Get specific order
  const orderDetails = await monaco.trading.getOrder("order-id");
  console.log("Order details:", orderDetails.order);
}

API Reference

MonacoSDK

The main SDK class that provides access to all protocol features.

Configuration

interface SDKConfig {
  /** Wallet client for signing operations (optional - can be set later via setWalletClient) */
  walletClient?: WalletClient;
  
  /** Use "mainnet" (Sei mainnet, production API). */
  network: Network;
  
  /** RPC URL for Sei blockchain interactions */
  seiRpcUrl: string;
}

Authentication & Session Management

The SDK uses a noncustodial session-key scheme. On login it generates an ed25519 keypair locally, has your wallet authorize it via an EIP-712 signature, and signs every subsequent request with the private key — the server never holds a credential that can impersonate you.

// After login, you receive an AuthState object
const authState = await sdk.login(clientId);

// AuthState structure:
interface AuthState {
  sessionPublicKey: string;   // ed25519 public key registered with the server
  sessionPrivateKey: string;  // ed25519 private key used to sign requests (the long-lived credential)
  expiresAt: number;          // Unix timestamp (seconds) when the session expires
  user: User;                 // User information
}

The private key is the long-lived credential. Persist it (e.g. localStorage, same risk profile as a JWT) to survive page reloads without re-prompting the wallet. When the session expires, call refreshAuth() or re-login().

// Revoke the current session
await sdk.auth.revokeSession();

// 💡 TIP: Use the built-in logout method
await sdk.logout(); // Automatically calls revokeSession internally

Session Management Methods:

  • login(clientId, options?) - Authorize a session key and authenticate
    • clientId: Your application's client ID
    • options.connectWebSocket: (optional) Auto-connect WebSocket after login (default: false)
    • Returns AuthState with the session keypair, expiration, and user info
  • logout() - Revoke the session, disconnect WebSocket, and clear state
    • Calls auth.revokeSession() internally
    • Disconnects authenticated WebSocket channels
    • Clears local auth state
  • refreshAuth() - Extend the current session's expiry
  • isAuthenticated() - Check if a session is active
  • getAuthState() - Get current auth state with the session keypair
  • setAuthState(authState) - Set auth state directly (useful for sharing across SDK instances)

Vault API

The vault API provides secure token management operations:

interface VaultAPI extends BaseAPI {
  // Vault address management
  setVaultAddress(vaultAddress: Address): void;
  getVaultAddress(): Address | undefined;
  
  // Token operations
  approve(token: string, amount: bigint, autoWait?: boolean): Promise<TransactionResult>;
  deposit(token: string, amount: bigint, autoWait?: boolean): Promise<TransactionResult>;
  withdraw(token: string, amount: bigint, autoWait?: boolean): Promise<TransactionResult>;
  
}

Trading API

The trading API provides comprehensive order management:

interface TradingAPI extends BaseAPI {
  // Order placement
  placeLimitOrder(
    tradingPairId: string, 
    side: OrderSide, 
    quantity: string, 
    price: string, 
    options?: {
      tradingMode?: TradingMode;
      useMasterBalance?: boolean;
      expirationDate?: string;
      timeInForce?: TimeInForce;
    }
  ): Promise<CreateOrderResponse>;
  
  placeMarketOrder(
    tradingPairId: string, 
    side: OrderSide, 
    quantity: string, 
    options?: {
      tradingMode?: TradingMode;
      slippageTolerance?: number;
    }
  ): Promise<CreateOrderResponse>;
  
  // Order management
  cancelOrder(orderId: string): Promise<CancelOrderResponse>;
  replaceOrder(
    orderId: string, 
    newOrder: {
      price?: string;
      quantity: string;
      useMasterBalance?: boolean;
    }
  ): Promise<ReplaceOrderResponse>;
  
  // Order queries
  getPaginatedOrders(params?: GetPaginatedOrdersParams): Promise<GetPaginatedOrdersResponse>;
  getOrder(orderId: string): Promise<GetOrderResponse>;
}

Market API

The market API provides access to trading pair metadata:

interface MarketAPI extends BaseAPI {
  // Market data
  getTradingPairs(): Promise<TradingPair[]>;
  getTradingPairBySymbol(symbol: string): Promise<TradingPair | undefined>;
}

WebSocket Authentication

The SDK provides three WebSocket clients with different authentication requirements:

Public WebSockets (OHLCV and Orderbook)

No authentication required. Provide public market data. You always connect manually:

// Step 1: Establish WebSocket connection (no authentication needed)
await monaco.websocket.ohlcv.connect();
await monaco.websocket.orderbook.connect();

// Step 2: Subscribe to public market data
monaco.websocket.ohlcv.subscribeToOHLCV("BTC/USDC", "SPOT", "1m", (event) => {
  console.log("OHLCV data:", event.candlestick);
});

monaco.websocket.orderbook.subscribeToOrderbookEvents("BTC/USDC", "SPOT", (event) => {
  console.log("Orderbook update:", event.bids.length, "bids");
});

Authenticated WebSockets (Orders)

Requires an authenticated session for personal order updates. You can either auto-connect during login or connect manually:

Option 1: Auto-connect (recommended for authenticated channels)

// Login and auto-connect all authenticated WebSocket channels
// Currently includes: Orders (personal order updates)
await monaco.login(clientId, { connectWebSocket: true });

// Subscribe to personal order events (already connected)
monaco.websocket.orders.subscribeToOrderEvents("BTC/USDC", "SPOT", (event) => {
  console.log("Personal order event:", event.eventType);
});

Option 2: Manual connection (required for public channels, optional for authenticated)

// Public channels like OHLCV always require manual connection (no auth needed)
await monaco.websocket.ohlcv.connect();

monaco.websocket.ohlcv.subscribeToOHLCV("BTC/USDC", "SPOT", "1m", (event) => {
  console.log("OHLCV data:", event.candlestick);
});

// For authenticated channels, you can also connect manually for more control
await monaco.login(clientId);
await monaco.websocket.orders.connect();
monaco.websocket.orders.subscribeToOrderEvents("BTC/USDC", "SPOT", (event) => {
  console.log("Personal order event:", event.eventType);
});

Note:

  • The connectWebSocket: true option automatically connects all authenticated WebSocket channels (currently Orders).
  • Public WebSocket clients (OHLCV, Orderbook) always require calling connect() explicitly as they don't require authentication.

Error Handling

The SDK uses structured error classes for comprehensive error handling:

import { APIError, ContractError } from "@0xmonaco/core";

try {
  await sdk.vault.deposit(token, amount);
} catch (error) {
  if (error instanceof ContractError) {
    console.error("Contract error:", error.message);
    console.error("Error code:", error.code);
  } else if (error instanceof APIError) {
    console.error("API error:", error.message);
    console.error("Status:", error.status);
  }
}

Error Types:

  • MonacoCoreError: Base error class for all SDK errors
  • APIError: API request failures and communication errors
  • ContractError: Smart contract operation errors
  • InvalidConfigError: Configuration validation errors
  • InvalidStateError: Invalid state or operation errors

Development

Project Structure

packages/core/
├── src/                   # Source code
│   ├── api/               # API implementations
│   │   ├── applications/  # Applications API
│   │   ├── auth/          # Authentication API
│   │   ├── base.ts        # Base API class
│   │   ├── market/        # Market data API
│   │   ├── profile/       # Profile management API
│   │   ├── trading/       # Trading operations API
│   │   ├── vault/         # Vault operations API
│   │   ├── websocket/     # WebSocket client
│   │   └── index.ts       # API exports
│   ├── constants/         # Constants and configurations
│   ├── errors.ts          # Error classes and codes
│   ├── networks.ts        # Network endpoint configurations
│   ├── sdk.ts             # Main SDK implementation
│   └── index.ts           # Public API exports
├── tests/                 # Test suite
├── dist/                  # Compiled output
├── package.json           # Package configuration
└── tsconfig.json          # TypeScript configuration

Development Setup

  1. Clone the repository:

    git clone https://github.com/monaco-protocol/monaco-monorepo.git
    cd monaco-monorepo
    
  2. Install dependencies:

    bun run install
    
  3. Build the package:

    bun run build --filter @0xmonaco/core
    

Testing

Run the test suite:

bun run test --filter @0xmonaco/core

Code Style

The project uses ESLint and Prettier for code formatting. Run the linter:

bun run lint --filter @0xmonaco/core

Security Features

Session-key Authentication

  • Noncustodial: ed25519 session keys are generated locally; the server never holds a credential that can impersonate you
  • EIP-712 login: Wallet signature authorizes each session key
  • Session refresh: Extend expiry without re-prompting the wallet

API Gateway Integration

  • Secure communication: TLS encryption for all API calls
  • Request signing: Backend verifies the session signature on every authenticated request
  • Rate limiting: Protection against abuse
  • Audit logging: Complete transaction history

On-chain Security

  • Smart contract validation: All operations validated on-chain
  • Signature verification: EIP-712 signatures for authentication
  • Multi-signature support: Advanced security for institutional users

Performance Considerations

  • Batch operations: Efficient handling of multiple operations
  • Connection pooling: Optimized API connections
  • Caching: Smart caching of frequently accessed data
  • Async operations: Non-blocking operations for better UX

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License.

Support

For support, please:

版本与发布记录

@0xmonaco/core 共发布 197 个版本,首次发布于 2025/08/28;过去 12 个月发布了 173 个版本。

版本发布日期距今
1.1.8latest2026/11/061 天前
1.1.72026/11/052 天前
1.1.62026/11/053 天前
1.1.5-prerelease.de852e2prerelease-1.1.62026/11/044 天前
1.1.5-develop.129b2c6develop2026/11/044 天前
1.1.52026/11/034 天前

其他发布通道:prerelease-1.0.40 → 1.0.39-prerelease.19d492d,develop → 1.1.5-develop.129b2c6,prerelease-1.1.6 → 1.1.5-prerelease.de852e2。

关于 @0xmonaco/core 的常见问题

@0xmonaco/core 是什么?

Core SDK implementation for interacting with Monaco Protocol. This SDK provides a comprehensive implementation with Authentication, Vault, Trading, Market, and Profile APIs, featuring noncustodial session-key authentication and secure API Gateway integrat

如何安装 @0xmonaco/core?

在项目目录运行 npm install @0xmonaco/core,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:viem(^2.45.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@0xmonaco/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@0xmonaco/core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@0xmonaco/core 可以商用吗?

@0xmonaco/core 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@0xmonaco/core 的下载量有多少?

根据 npm 官方下载统计,@0xmonaco/core 在 2026/10/04 – 2026/11/02 这 30 天内被下载 8,175 次,日均约 273 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@0xmonaco/core 还在维护吗?

最新版本 1.1.8 发布于 2026/11/06(1 天前);至今共发布 197 个版本,其中过去 12 个月发布了 173 个;首次发布于 2025/08/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。