Socket
Book a DemoInstallSign in
Socket

@0xmonaco/core

Package Overview
Dependencies
Maintainers
2
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@0xmonaco/core

⚠️ **EARLY DEVELOPMENT WARNING** ⚠️

latest
npmnpm
Version
0.1.5
Version published
Maintainers
2
Created
Source

Monaco Core SDK

⚠️ EARLY DEVELOPMENT WARNING ⚠️

This package is currently in early development (v0.1.0).

Breaking changes are expected and may occur without notice. This version is intended for:

  • Early adopters and testing
  • Development and experimentation
  • Feedback collection

Core SDK implementation for interacting with Monaco Protocol. This SDK provides a comprehensive implementation with Vault and Trading APIs, featuring EIP-712 intent signatures and secure API Gateway integration.

Installation

npm install @0xmonaco/core

Features

🏦 Vault Operations

  • Token Approvals: ERC20 token approvals for vault usage
  • Deposits: Secure token deposits with EIP-712 signatures
  • Withdrawals: Token withdrawals with cryptographic validation
  • Balance Queries: Real-time vault balance tracking
  • Allowance Management: Efficient approval checking and management

📈 Trading Operations

  • Order Types: Limit (with timeInForce: GTC/IOC/FOK), Market, Post-Only orders
  • Order Management: Place, replace (cancel + new), and cancel orders
  • Position Management: Close positions with slippage control
  • Order Queries: Open orders, order history, and individual order details
  • Real-time Updates: Live order status and execution tracking

🔐 Security Features

  • EIP-712 Signatures: Type-safe, structured data signing
  • Intent-Based Authorization: Every action explicitly authorized
  • API Gateway Integration: Secure communication with Monaco backend
  • Nonce Protection: Replay attack prevention
  • TLS Encryption: Secure API communications

Test Setup

Before running tests, ensure you have:

  • A running hardhat node with the Monaco Protocol contracts deployed:

    # In the contracts package
    cd ../contracts
    pnpm hardhat node  # Start a local hardhat node
    pnpm hardhat deploy --network localhost  # Deploy contracts
    
  • Create a .env.test file in the tests directory:

    # Create the file
    cd packages/core/src/tests
    touch .env.test
    
    # Add the following content to .env.test:
    echo 'TEST_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' > .env.test
    
  • Replace the example private key in .env.test with your actual test account private key:

    • The private key must be a 0x-prefixed 64-character hex string
    • The account must have enough ETH on the local hardhat network for transactions
    • Never commit real private keys to version control
  • Verify your setup:

    # Make sure you're in the core package directory
    cd packages/core
    
    # Check if .env.test exists and has the correct format
    cat src/tests/.env.test
    # Should show: TEST_PRIVATE_KEY=0x...
    
    # Run the tests
    pnpm test
    

If you see an error about TEST_PRIVATE_KEY not being set:

  • Double check that .env.test exists in packages/core/src/tests directory
  • Make sure the private key format is correct (0x-prefixed, 64 characters)
  • Try running the tests with the environment variable directly:
    TEST_PRIVATE_KEY=0x1234... pnpm test
    

Network Support

The SDK supports both Sei mainnet (pacific-1) and testnet (atlantic-2) networks. Network configurations are automatically handled through the NETWORK_ENDPOINTS constant:

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

// Access network configurations by network name
const mainnetConfig = NETWORK_ENDPOINTS.mainnet; // Pacific-1 mainnet
const testnetConfig = NETWORK_ENDPOINTS.testnet; // Atlantic-2 testnet

// Each network config includes:
// - rpcUrl: RPC endpoint for the network
// - apiUrl: API gateway endpoint for the network

Quick Start

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

// Initialize the SDK with private key
const monaco = new MonacoSDK({
  privateKey: "0x...", // Your private key
  network: "mainnet", // or "testnet"
});

// Vault Operations
async function vaultExample() {
  // Check vault balance
  const balance = await monaco.vault.getBalance("0x..."); // token address
  console.log("Vault balance:", balance.formatted, balance.symbol);

  // Check if approval is needed
  const needsApproval = await monaco.vault.needsApproval("0x...", parseEther("100"));
  if (needsApproval) {
    // Approve vault to spend tokens
    const approval = await monaco.vault.approve("0x...", parseEther("1000"));
    console.log("Approval transaction:", approval.hash);
  }

  // Deposit tokens
  const result = await monaco.vault.deposit("0x...", parseEther("100"));
  console.log("Deposit transaction:", result.hash);
}

// Trading Operations
async function tradingExample() {
  // Place a limit order
  const order = await monaco.trading.placeLimitOrder(
    "ETH-USDC", // market
    "buy", // side
    parseEther("1.0"), // size (1 ETH)
    parseUnits("2000", 6) // price (2000 USDC)
  );
  console.log("Order placed:", order.orderId);

  // Place a market order with slippage protection
  const marketOrder = await monaco.trading.placeMarketOrder(
    "ETH-USDC",
    "sell",
    parseEther("0.5"),
    { slippageToleranceBps: 50 } // 0.5% max slippage (50 basis points)
  );
  console.log("Market order placed:", marketOrder.orderId);

  // Place a limit order with IOC time in force
  const iocOrder = await monaco.trading.placeLimitOrder(
    "ETH-USDC",
    "buy",
    parseEther("1.0"),
    parseUnits("2000", 6),
    { timeInForce: "IOC" } // Immediate-or-Cancel
  );
  console.log("IOC order placed:", iocOrder.orderId);

  // Get open orders
  const openOrders = await monaco.trading.getOpenOrders({ market: "ETH-USDC" });
  console.log("Open orders:", openOrders.length);

  // Replace an order (cancel + new)
  const replaceResult = await monaco.trading.replaceOrder("order-id", {
    market: "ETH-USDC",
    side: "buy",
    size: parseEther("2.0"),
    price: parseUnits("2100", 6),
    type: "limit",
    timeInForce: "FOK" // Fill-or-Kill
  });
  console.log("Order replaced:", replaceResult.orderId);

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

API Reference

MonacoSDK

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

class MonacoSDK {
  readonly vault: VaultAPI;
  readonly trading: TradingAPI;
  readonly walletClient: WalletClient;
  readonly publicClient: PublicClient;

  constructor(config: SDKConfig);
}

Configuration

interface SDKConfig {
  /** Private key as hex string (0x-prefixed) */
  privateKey?: Hex;
  
  /** Viem Account for advanced account management */
  signer?: PrivateKeyAccount;
  
  /** Custom Account implementation (overrides privateKey/signer) */
  account?: Account;
  
  /** Optional network override (defaults to 'mainnet') */
  network?: Network;
}

Vault API

The vault API provides secure token management operations:

interface VaultAPI {
  // Token approvals
  approve(token: string, amount: bigint): Promise<TransactionResult>;
  
  // Deposit and withdrawal
  deposit(token: string, amount: bigint): Promise<TransactionResult>;
  withdraw(token: string, amount: bigint): Promise<TransactionResult>;
  
  // Balance and allowance queries
  getBalance(token: string): Promise<Balance>;
  getAllowance(token: string): Promise<bigint>;
  needsApproval(token: string, amount: bigint): Promise<boolean>;
}

Trading API

The trading API provides comprehensive order management with support for different execution policies:

Order Types and Execution Policies

  • Limit Orders: Standard limit orders with optional timeInForce parameter

    • GTC (Good Till Cancelled): Default behavior, order stays active until filled or cancelled
    • IOC (Immediate or Cancel): Order fills what it can immediately, then cancels the rest
    • FOK (Fill or Kill): Order must fill completely or not at all
  • Market Orders: Immediate execution with optional slippage protection

  • Post-Only Orders: Limit orders that never execute immediately, only add liquidity

Order Management

  • Replace Orders: Cancel existing order and place a new one (atomic operation)
  • Cancel Orders: Cancel any open order by ID
interface TradingAPI {
  // Order placement
  placeLimitOrder(market: string, side: OrderSide, size: bigint, price: bigint, options?: { timeInForce?: TimeInForce }): Promise<OrderResponse>;
  placeMarketOrder(market: string, side: OrderSide, size: bigint, options?: { slippageToleranceBps?: number }): Promise<OrderResponse>;
  placePostOnlyOrder(market: string, side: OrderSide, size: bigint, price: bigint): Promise<OrderResponse>;
  
  // Order management
  replaceOrder(originalOrderId: string, newOrder: { market: string; side: OrderSide; size: bigint; price?: bigint; type: OrderType; timeInForce?: TimeInForce }): Promise<OrderResponse>;
  cancelOrder(orderId: string): Promise<CancelOrderResponse>;
  
  // Position management
  closePosition(market: string, options?: { maxSlippage?: number }): Promise<ClosePositionResponse>;
  
  // Order queries
  getOrder(orderId: string): Promise<Order>;
  getOpenOrders(params?: GetOpenOrdersParams): Promise<Order[]>;
  getOrderHistory(params: OrderHistoryParams): Promise<PaginatedOrders>;
}

Error Handling

The SDK uses structured error classes for comprehensive error handling:

import { APIError, ContractError, TransactionError, OrderError } 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);
  } else if (error instanceof TransactionError) {
    console.error("Transaction error:", error.message);
  } else if (error instanceof OrderError) {
    console.error("Order error:", error.message);
    console.error("Market:", error.market);
  }
}

Error Types:

  • APIError: API request failures and communication errors
  • ContractError: Smart contract operation errors
  • TransactionError: Blockchain transaction errors
  • OrderError: Trading order specific errors
  • InvalidConfigError: Configuration validation errors

Development

Project Structure

packages/core/
├── src/                   # Source code
│   ├── api/               # API implementations
│   │   ├── vault/         # Vault operations API
│   │   │   └── api.ts     # Vault API implementation with comprehensive docs
│   │   └── trading/       # Trading operations API
│   │       └── api.ts     # Trading API implementation with comprehensive docs
│   ├── chains.ts          # Chain definitions (Sei mainnet/testnet)
│   ├── 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

  • Clone the repository:
git clone https://github.com/monaco-protocol/monaco-monorepo.git
cd monaco-monorepo
  • Install dependencies:
pnpm install
  • Build the package:
pnpm build --filter @0xmonaco/core

Testing

Run the test suite:

pnpm test --filter @0xmonaco/core

Code Style

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

pnpm lint --filter @0xmonaco/core

Security Features

EIP-712 Intent Signatures

  • Type-safe signing: Structured data with domain separation
  • Intent-based authorization: Every action explicitly authorized
  • Nonce protection: Prevents replay attacks
  • Domain validation: Ensures signatures are valid for specific contracts

API Gateway Integration

  • Secure communication: TLS encryption for all API calls
  • Signature validation: Backend validates all signed intents
  • Rate limiting: Protection against abuse
  • Audit logging: Complete transaction history

On-chain Security

  • Smart contract validation: All operations validated on-chain
  • Multi-signature support: Advanced security for institutional users
  • Emergency stops: Circuit breakers for critical situations

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

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  • Fork the repository
  • Create a feature branch
  • Make your changes
  • Add tests for new functionality
  • Ensure all tests pass
  • Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support, please:

FAQs

Package last updated on 08 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.