Skip to content

Monaco-Research/monaco-sdk

Repository files navigation

Monaco SDK

A TypeScript SDK providing secure access to Monaco's hybrid trading architecture. The SDK implements a comprehensive interface for vault operations and trading functionalities with a strong focus on security through EIP-712 signatures and comprehensive documentation.

Features

  • Vault Operations: Token deposits, withdrawals, and approvals with EIP-712 signatures
  • Trading API: Complete order placement and management with comprehensive documentation
  • Network Support: Sei mainnet and testnet with automatic configuration
  • Authentication: JWT-based authentication with EIP-712 signatures, WebSocket support
  • WebSocket Clients: Real-time order events, OHLCV data, and orderbook updates
  • Documentation: Comprehensive JSDoc documentation for all API methods
  • Error Handling: Structured error types with detailed error information
  • Type Safety: Full TypeScript support with strict mode compatibility

Installation

# Install the core SDK
npm install @0xmonaco/core

# Or with bun
bun add @0xmonaco/core

# Or with yarn
yarn add @0xmonaco/core

Required Peer Dependencies:

npm install viem@^2.31.7

For React integration:

npm install @0xmonaco/react react wagmi@^2.17.5 viem@^2.31.7

Quick Start

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

// Initialize SDK with wallet client
const account = privateKeyToAccount("0x...");
const walletClient = createWalletClient({
  account,
  chain: seiTestnet,
  transport: http()
});

const sdk = new MonacoSDK({
  walletClient,
  network: 'testnet' // 'mainnet' | 'testnet'
});

// Authentication (required for authenticated APIs)
// Option 1: Login and auto-connect WebSocket
const authState = await sdk.login("your-client-id", { connectWebSocket: true });

// Option 2: Login only, connect WebSocket manually later
// const authState = await sdk.login("your-client-id");
// await sdk.ws.connect();

// Vault Operations
async function vaultExample() {
  // Get asset ID from trading pair
  const pair = await sdk.market.getTradingPairBySymbol("USDC/USDT");
  const assetId = pair.base_asset_id; // Asset ID (UUID)
  
  // Check balance
  const balance = await sdk.profile.getUserBalanceByAssetId(assetId);
  console.log(`Balance: ${balance.total_balance} ${balance.symbol}`);
  
  // Deposit tokens
  const result = await sdk.vault.deposit(assetId, parseEther("100"));
  console.log(`Deposit transaction: ${result.hash}`);
}

// Trading Operations
async function tradingExample() {
  // Place a limit order
  const order = await sdk.trading.placeLimitOrder(
    "BTC/USDC",
    "BUY",
    "0.001",
    "50000"
  );
  console.log(`Order placed: ${order.order_id}`);

  // Place a market order
  const marketOrder = await sdk.trading.placeMarketOrder(
    "BTC/USDC",
    "SELL",
    "0.001"
  );
  console.log(`Market order placed: ${marketOrder.order_id}`);

  // Get paginated orders
  const orders = await sdk.trading.getPaginatedOrders({
    status: "SUBMITTED",
    trading_pair: "BTC/USDC"
  });
  console.log(`Orders: ${orders.data.length}`);

  // Cancel an order
  const cancelResult = await sdk.trading.cancelOrder("order-id");
  console.log(`Order cancelled: ${cancelResult.status}`);
}

Configuration

The SDK requires a viem WalletClient for signing operations:

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

// For testnet
const account = privateKeyToAccount("0x...");
const walletClient = createWalletClient({
  account,
  chain: seiTestnet,
  transport: http()
});

const sdk = new MonacoSDK({
  walletClient,
  network: 'testnet' // Optional: defaults to 'testnet'
});

// For mainnet
const mainnetWalletClient = createWalletClient({
  account,
  chain: sei,
  transport: http()
});

const mainnetSdk = new MonacoSDK({
  walletClient: mainnetWalletClient,
  network: 'mainnet'
});

Configuration Options:

  • walletClient (required): Viem WalletClient for signing operations
  • network (optional): Network to connect to ('mainnet' | 'testnet'), defaults to 'testnet'
  • transport (optional): Custom transport for the public client

Note: The wallet client's chain must match the selected network.

Architecture

The Monaco SDK implements a hybrid trading architecture that combines on-chain security with off-chain performance:

graph TB
    Client["Client Application"]
    SDK["Monaco SDK"]
    API["API Gateway"]
    Chain["Blockchain"]
    Sequencer["Trading Sequencer"]
    
    subgraph "Monaco SDK Components"
        VaultAPI["Vault API"]
        TradingAPI["Trading API"]
        Utils["Utils"]
        Auth["Auth Manager"]
    end
    
    Client --> SDK
    SDK --> VaultAPI & TradingAPI & Utils
    VaultAPI & TradingAPI --> Auth
    Auth --> API
    API --> Chain
    API --> Sequencer
Loading

Security Model

The SDK uses EIP-712 signatures for secure, intent-based authorization:

  • No Sessions Required: Every action is individually authorized
  • EIP-712 Signatures: Type-safe, structured data signing
  • Nonce Protection: Prevents replay attacks
  • TLS Encryption: Secure API communications
  • Request Signing: MITM attack prevention

Packages

  • @0xmonaco/core: Main SDK implementation with comprehensive documentation
  • @0xmonaco/types: TypeScript interfaces and type definitions
  • @0xmonaco/contracts: Smart contract ABIs and addresses
  • @0xmonaco/react: React hooks and components [Coming Soon]
  • @0xmonaco/mcp-server: Documentation and development server

Key Features

  • 🏦 Vault Operations: Secure deposit/withdrawal with EIP-712 signatures
  • 🔐 Intent-Based Authorization: Every action explicitly authorized
  • 📱 Trading Operations: Complete order management with EIP-712 intent signatures
  • 🛡️ Security-First Design: No sessions required - all actions individually authorized
  • 🧰 Comprehensive Error Handling: Structured error types for better DX
  • 📚 TypeScript Ready: Full type safety and IntelliSense support
  • 📖 Full Documentation: Comprehensive JSDoc documentation for all methods
  • 🚀 Performance Optimized: Efficient API calls and connection management

Operation Flows

Vault Operations

sequenceDiagram
    participant User
    participant SDK
    participant API
    participant Chain
    
    User->>SDK: deposit(token, amount)
    SDK->>SDK: Check approval status
    SDK->>API: Get deposit signature
    API->>SDK: Return seed + signature
    SDK->>Chain: Execute deposit transaction
    Chain-->>SDK: Transaction result
    SDK-->>User: Transaction receipt
Loading

Trading Operations

sequenceDiagram
    participant User
    participant SDK
    participant API
    participant Sequencer
    
    User->>SDK: placeLimitOrder(...)
    SDK->>SDK: Generate order intent
    SDK->>SDK: Sign with EIP-712
    SDK->>API: Submit signed order
    API->>Sequencer: Process order
    Sequencer-->>API: Order status
    API-->>SDK: Order confirmation
    SDK-->>User: Order result
Loading

API Reference

Vault Operations

// Get asset IDs from trading pairs
const pair = await sdk.market.getTradingPairBySymbol("USDC/USDT");
const baseAssetId = pair.base_asset_id;
const quoteAssetId = pair.quote_asset_id;

// Check balance and allowance
const balance = await sdk.profile.getUserBalanceByAssetId(baseAssetId);
const allowance = await sdk.vault.getAllowance(baseAssetId);
const needsApproval = await sdk.vault.needsApproval(baseAssetId, amount);

// Approve and deposit
await sdk.vault.approve(baseAssetId, amount);
await sdk.vault.deposit(baseAssetId, amount);
await sdk.vault.withdraw(baseAssetId, amount);

Getting Asset IDs

// Get asset IDs from trading pairs
const pair = await sdk.market.getTradingPairBySymbol("USDC/USDT");
console.log("Base asset ID:", pair.base_asset_id);   // UUID
console.log("Quote asset ID:", pair.quote_asset_id); // UUID
console.log("Base token address:", pair.base_asset_address);   // 0x...
console.log("Quote token address:", pair.quote_asset_address); // 0x...

// Use asset IDs for balance queries
const usdcBalance = await sdk.profile.getUserBalanceByAssetId(pair.base_asset_id);
const usdtBalance = await sdk.profile.getUserBalanceByAssetId(pair.quote_asset_id);

Trading Operations

// Place orders
await sdk.trading.placeLimitOrder(
  "BTC/USDC", 
  "BUY", 
  "0.001", 
  "50000", 
  { timeInForce: "GTC" } // GTC, IOC, or FOK
);
await sdk.trading.placeMarketOrder(
  "BTC/USDC", 
  "SELL", 
  "0.001",
  { slippageTolerance: 50 } // 50 = 0.5%
);

// Manage orders
await sdk.trading.replaceOrder("order-id", {
  price: "51000",
  quantity: "0.002"
});
await sdk.trading.cancelOrder("order-id");

// Query orders
const order = await sdk.trading.getOrder("order-id");
const orders = await sdk.trading.getPaginatedOrders({
  status: "SUBMITTED",
  trading_pair: "BTC/USDC",
  page: 1,
  page_size: 10
});

Account Management

// Get account info
sdk.getAccountAddress();
sdk.getNetwork(); // 'mainnet' | 'testnet'
sdk.getChainId();
sdk.isAuthenticated();
sdk.isConnected();

// Get auth state
const authState = sdk.getAuthState();

Development

Setup

bun run install
bun run setup:hooks
bun run build

bun run setup:hooks configures Git to use the repository's .githooks/ directory, including the pre-push hook that runs: bun run test, bun run check, bun run format, bun run lint, and bun run build.

Testing

# Run all tests
bun run test

# Run specific package tests
bun run --filter @0xmonaco/core test

Test Status: Core functionality tested and working on testnet

Build

bun run build        # Build all packages
bun run -r dev      # Watch mode for development
bun run clean        # Clean build artifacts

Publishing Develop Releases

To publish a snapshot release under the @develop npm tag for testing:

# 1. Make sure all changes are committed first
git add -A && git commit -m "your changes"

# 2. Build and publish snapshot
bun run build
bun run release:develop

# 3. Reset your branch to restore changesets and package.json versions
git reset --hard HEAD

This publishes versions like 0.0.0-develop-20260120180031 to npm with the @develop tag.

Important: The release:develop script consumes changesets and modifies package.json versions locally. The git reset --hard HEAD step restores your working directory to match the last commit, preserving your changesets for the real release.

Installing develop versions:

npm install @0xmonaco/core@develop

Architecture

monaco-monorepo/
├── packages/
│   ├── core/        # Main SDK implementation with comprehensive docs
│   ├── types/       # TypeScript interfaces and types
│   ├── contracts/   # Contract ABIs and addresses
│   ├── utils/       # Utility functions
│   ├── react/       # React integration [Coming Soon]
│   └── mcp-server/  # Documentation and development server
├── docs/            # Documentation and guides
└── README.md        # This file

Error Handling

The SDK provides comprehensive error handling with structured error types:

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);
    console.error("URL:", error.url);
  }
}

Error Types:

  • APIError: API request failures and communication errors
  • ContractError: Smart contract operation errors
  • InvalidConfigError: Configuration validation errors

Technical Implementation

Core Components

  1. MonacoSDK Class

    • Main entry point for all SDK operations
    • Handles network configuration and authentication
    • Manages signature flows internally
  2. VaultAPI Interface

    • ERC20 token approvals with comprehensive documentation
    • Deposit/withdrawal operations with EIP-712 signatures
    • Balance management and allowance checks
    • Secure API Gateway integration
  3. TradingAPI Interface

    • Complete order management with full documentation
    • Limit/Market/IOC/FOK/Post-Only order placement
    • Order modification, replacement, and cancellation
    • Position management with slippage control
    • Real-time order status tracking
  4. Security Implementation

    • EIP-712 signature integration with domain separation
    • Nonce-based replay protection
    • TLS encryption for API communications
    • Request signing for MITM prevention

Current Status

Complete:

  • SDK initialization and configuration
  • Vault operations (deposits, withdrawals, approvals) with EIP-712 signatures
  • Trading API interfaces and order placement with comprehensive documentation
  • Order querying (open orders, order history, individual orders)
  • Network support (mainnet/testnet) with automatic configuration
  • Comprehensive error handling with structured error types
  • Full JSDoc documentation for all public methods
  • Security features (EIP-712, nonce protection, TLS encryption)

🔄 In Progress:

  • Trading backend integration (order placement ready, backend endpoints needed)
  • Enhanced error messages and user feedback

📋 Roadmap:

  • Real-time order book updates via WebSocket
  • Advanced order types and strategies
  • React hooks and components
  • Mobile SDK support
  • Institutional features (multi-sig, compliance)

Dependencies

  • TypeScript 5.9+: Full type safety and IntelliSense support
  • viem 2.31+: Modern Ethereum library for blockchain interactions
  • EIP-712: Type-safe, structured data signing for security

TypeScript Configuration

For optimal type inference and IntelliSense support, use the following TypeScript configuration:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

Security Considerations

  • Private keys never leave local environment: All signing happens locally
  • Each operation requires explicit authorization: No sessions or persistent auth
  • Nonce tracking prevents replay attacks: Unique nonce for each operation
  • All API communications use TLS: Encrypted in transit
  • Request signing prevents MITM attacks: Additional layer of security
  • Domain separation in signatures: Prevents cross-contract attacks

Performance Features

  • Efficient API calls: Optimized request patterns and connection management
  • Smart caching: Intelligent caching of frequently accessed data
  • Batch operations: Support for multiple operations in single requests
  • Async operations: Non-blocking operations for better user experience
  • Connection pooling: Optimized API connections and reuse

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages