Observed since 21 Oct, 09:09 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
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
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.
npm install @0xmonaco/core
Required Peer Dependencies:
npm install viem@^2.31.7
The SDK supports the following documented preset networks. Configure the network by providing the network and seiRpcUrl parameters:
Preset Networks:
"staging" - Staging environment (https://staging.apimonaco.xyz)"mainnet" - Production environment (https://apimonaco.xyz)WebSocket URLs are automatically resolved per network.
import { MonacoSDK } from "@0xmonaco/core";
// Staging configuration
const stagingSdk = new MonacoSDK({
walletClient,
network: "staging",
seiRpcUrl: "https://evm-rpc-testnet.sei-apis.com",
});
// Mainnet configuration
const mainnetSdk = new MonacoSDK({
walletClient,
network: "mainnet",
seiRpcUrl: "https://evm-rpc.sei-apis.com",
});
import { MonacoSDK } from "@0xmonaco/core";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
// Initialize the SDK with wallet client
const account = privateKeyToAccount("0x...");
const walletClient = createWalletClient({
account,
chain: sei, // or seiTestnet
transport: http("https://evm-rpc.sei-apis.com") // or https://evm-rpc-testnet.sei-apis.com for testnet
});
const monaco = new MonacoSDK({
walletClient,
network: "staging", // or "mainnet"
seiRpcUrl: "https://evm-rpc-testnet.sei-apis.com", // or https://evm-rpc.sei-apis.com for mainnet
});
// 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?.maker_fee_bps);
}
// 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);
}
The main SDK class that provides access to all protocol features.
interface SDKConfig {
/** Wallet client for signing operations (optional - can be set later via setWalletClient) */
walletClient?: WalletClient;
/** Use "staging" for public testnet or "mainnet" for production. */
network: Network;
/** RPC URL for Sei blockchain interactions */
seiRpcUrl: string;
}
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, callrefreshAuth()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 IDoptions.connectWebSocket: (optional) Auto-connect WebSocket after login (default: false)AuthState with the session keypair, expiration, and user infologout() - Revoke the session, disconnect WebSocket, and clear state
auth.revokeSession() internallyrefreshAuth() - Extend the current session's expiryisAuthenticated() - Check if a session is activegetAuthState() - Get current auth state with the session keypairsetAuthState(authState) - Set auth state directly (useful for sharing across SDK instances)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>;
}
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>;
}
The market API provides access to trading pair metadata:
interface MarketAPI extends BaseAPI {
// Market data
getTradingPairs(): Promise<TradingPair[]>;
getTradingPairBySymbol(symbol: string): Promise<TradingPair | undefined>;
}
The SDK provides three WebSocket clients with different authentication requirements:
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");
});
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:
connectWebSocket: true option automatically connects all authenticated WebSocket channels (currently Orders).connect() explicitly as they don't require authentication.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 errorsAPIError: API request failures and communication errorsContractError: Smart contract operation errorsInvalidConfigError: Configuration validation errorsInvalidStateError: Invalid state or operation errorspackages/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
Clone the repository:
git clone https://github.com/monaco-protocol/monaco-monorepo.git
cd monaco-monorepo
Install dependencies:
bun run install
Build the package:
bun run build --filter @0xmonaco/core
Run the test suite:
bun run test --filter @0xmonaco/core
The project uses ESLint and Prettier for code formatting. Run the linter:
bun run lint --filter @0xmonaco/core
This project is licensed under the MIT License.
For support, please:
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 1.0.65 | 23 Sept 2026 | 8 | |
| 1.0.64 | 22 Sept 2026 | 8 | |
| 1.0.62 | 18 Sept 2026 | 8 | |
| 1.0.61 | 16 Sept 2026 | 8 | |
| 1.0.60 | 16 Sept 2026 | 8 | |
| 1.0.59 | 15 Sept 2026 | 8 | |
| 1.0.58-develop.f12e78b | 13 Sept 2026 | 8 | |
| 1.0.58 | 13 Sept 2026 | 8 | |
| 1.0.57 | 12 Sept 2026 | 8 | |
| 1.0.56 | 11 Sept 2026 | 8 | |
| 1.0.55 | 10 Sept 2026 | 8 | |
| 1.0.54 | 9 Sept 2026 | 8 | |
| 1.0.53 | 7 Sept 2026 | 8 | |
| 1.0.51 | 6 Sept 2026 | 8 | |
| 1.0.50-develop.9c1b239 | 5 Sept 2026 | 8 | |
| 1.0.50 | 3 Sept 2026 | 8 | |
| 1.0.48 | 3 Sept 2026 | 8 | |
| 1.0.47 | 2 Sept 2026 | 8 | |
| 1.0.46 | 31 Aug 2026 | 8 | |
| 1.0.45 | 28 Aug 2026 | 8 |
This describes our collected data; it is not a security assessment.
Shared repository data · GitHub
Observed since 21 Oct, 09:09 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:8b17ee41b2def36c1d38c3bf2dddc0f9ef4fe37e6429c38d342e10c1c485c160