> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xmonaco.com/llms.txt
> Use this file to discover all available pages before exploring further.

# V0.5.2

# Monaco Protocol v0.5.2

## gRPC API Introduction

This release introduces the Monaco gRPC API, a high-performance alternative to our REST API designed for low-latency trading applications. The gRPC API provides the same functionality as the REST API with significantly reduced overhead and native streaming support.

### What's New

**gRPC API**

* **Full Trading Support**: Create, cancel, and replace orders via gRPC
* **Real-time Market Data**: Orderbook snapshots, recent trades, and OHLCV candles
* **Account Management**: Profile, balances, movements, and sub-account limits
* **Authentication**: Wallet-based (SIWE) and backend service authentication
* **Transfers**: Deposit and withdrawal signature generation

### gRPC Services Overview

The Monaco gRPC API exposes the following services:

| Service | Description | Auth Required |
| - | - | - |
| `AuthService` | Authentication (challenge, verify, refresh, revoke) | No |
| `OrdersService` | Order management (create, cancel, replace, list) | Yes (JWT) |
| `AccountsService` | Account info, balances, movements, sub-accounts | Yes (JWT) |
| `MarketDataService` | Trading pairs, orderbook, trades, candles | No |
| `FeesService` | Fee simulation for orders | Yes (JWT) |
| `ApplicationsService` | Backend-only app management | Yes (x-server-key) |
| `TransfersService` | Deposit/withdrawal signatures | Yes (JWT) |
| `FaucetService` | Testnet token minting | Yes (JWT) |
| `HealthService` | Service health checks | No |

### Connection Details

The gRPC API is exposed via path-based routing on the same ALB as the REST API:

```
Protocol: HTTP/2 with TLS (gRPC over HTTPS)
Package: public_api.v1

Environments:
  Staging:      staging.apimonaco.xyz

Routing on ALB:
  - REST API:    https://staging.apimonaco.xyz/       → api-gateway (port 8080)
  - WebSocket:   wss://staging.apimonaco.xyz/ws       → ws-api (port 8080)
  - gRPC:        https://staging.apimonaco.xyz        → grpc-api (port 50051)
```

The ALB routes requests based on path prefixes:

* `/ws/*` routes to the WebSocket service
* gRPC method paths such as `/monaco.api.*` route to the gRPC service with `protocolVersion: GRPC`
* All other paths route to the REST API

### Quick Start

**1. Generate client code from proto**

Download the proto file and generate client code for your language:

```bash theme={null}
# For Node.js/TypeScript (using gRPC-Web for ALB path-based routing)
npm install @grpc/grpc-js @grpc/proto-loader

# For Rust
# Add to Cargo.toml: tonic, prost
```

**2. Connecting to the gRPC API**

Since the gRPC API uses HTTP/2 method-path routing on the ALB, clients need to connect with the correct configuration:

```typescript theme={null}
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';

// Load proto definition
const packageDefinition = protoLoader.loadSync('public_api.proto');
const proto = grpc.loadPackageDefinition(packageDefinition);

// Environment configuration
const GRPC_HOST = 'staging.apimonaco.xyz';

// Create client - the ALB routes gRPC method paths to the gRPC service
const client = new proto.public_api.v1.AuthService(
  `${GRPC_HOST}:443`,
  grpc.credentials.createSsl()
);
```

**3. Authentication Flow**

```typescript theme={null}
// Step 1: Get challenge
const challenge = await new Promise((resolve, reject) => {
  client.Challenge({
    address: '0xYourWalletAddress',
    client_id: 'your-client-id' // optional
  }, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});

// Step 2: Sign message with wallet (using viem, ethers, etc.)
const signature = await wallet.signMessage(challenge.message);

// Step 3: Verify and get tokens
const tokens = await new Promise((resolve, reject) => {
  client.Verify({
    address: '0xYourWalletAddress',
    signature: signature,
    nonce: challenge.nonce
  }, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});

console.log('Access Token:', tokens.access_token);
console.log('Refresh Token:', tokens.refresh_token);
```

**4. Creating an Order**

```typescript theme={null}
// Create authenticated client with JWT
const metadata = new grpc.Metadata();
metadata.set('authorization', `Bearer ${tokens.access_token}`);

const ordersClient = new proto.public_api.v1.OrdersService(
  `${GRPC_HOST}:443`,
  grpc.credentials.createSsl()
);

const orderResponse = await new Promise((resolve, reject) => {
  ordersClient.CreateOrder({
    trading_pair_id: 'uuid-of-trading-pair',
    order_type: 'LIMIT',
    side: 'BUY',
    price: '50000.00',
    quantity: '0.1',
    time_in_force: 'GTC'
  }, metadata, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});

console.log('Order ID:', orderResponse.order_id);
console.log('Status:', orderResponse.status);
```

**5. Getting Market Data (No Auth Required)**

```typescript theme={null}
const marketClient = new proto.public_api.v1.MarketDataService(
  `${GRPC_HOST}:443`,
  grpc.credentials.createSsl()
);

// List trading pairs
const pairs = await new Promise((resolve, reject) => {
  marketClient.ListTradingPairs({
    is_active: true,
    limit: 10
  }, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});

// Get orderbook
const orderbook = await new Promise((resolve, reject) => {
  marketClient.GetOrderbook({
    trading_pair_id: 'uuid-of-trading-pair',
    levels: 20
  }, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});

// Get candles
const candles = await new Promise((resolve, reject) => {
  marketClient.GetCandles({
    trading_pair_id: 'uuid-of-trading-pair',
    interval: '1h',
    limit: 100
  }, (err, response) => {
    if (err) reject(err);
    else resolve(response);
  });
});
```

**Note on Path-Based Routing**

The ALB listener rule routes gRPC method paths such as `/monaco.api.*` and `/grpc.health.v1.*` to the gRPC service. Clients connect to the host on `443` and do not include a `/grpc` prefix.

### Service Reference

#### AuthService

| Method | Request | Response | Description |
| - | - | - | - |
| `Challenge` | `ChallengeRequest` | `ChallengeResponse` | Generate authentication challenge |
| `Verify` | `VerifyRequest` | `VerifyResponse` | Verify signature and get tokens |
| `Refresh` | `RefreshRequest` | `RefreshResponse` | Refresh access token |
| `Revoke` | `RevokeRequest` | `RevokeResponse` | Revoke current session |

#### OrdersService

| Method | Request | Response | Description |
| - | - | - | - |
| `CreateOrder` | `PublicCreateOrderRequest` | `PublicCreateOrderResponse` | Create a new order |
| `CancelOrder` | `PublicCancelOrderRequest` | `PublicCancelOrderResponse` | Cancel an existing order |
| `ReplaceOrder` | `PublicReplaceOrderRequest` | `PublicReplaceOrderResponse` | Replace an order (atomic cancel + create) |
| `GetOrder` | `GetOrderRequest` | `OrderResponse` | Get order by ID |
| `ListOrders` | `ListOrdersRequest` | `ListOrdersResponse` | List orders with pagination |

#### AccountsService

| Method | Request | Response | Description |
| - | - | - | - |
| `GetProfile` | `GetProfileRequest` | `UserProfile` | Get user profile with balances |
| `GetBalances` | `GetBalancesRequest` | `BalancesResponse` | Get paginated balances |
| `GetBalanceByAsset` | `GetBalanceByAssetRequest` | `AccountBalance` | Get balance for specific token |
| `GetMovements` | `GetMovementsRequest` | `MovementsResponse` | Get ledger movements |
| `ListSubAccounts` | `ListSubAccountsRequest` | `ListSubAccountsResponse` | List sub-accounts (master only) |
| `CreateLimit` | `CreateLimitRequest` | `SubAccountLimit` | Create sub-account limit |
| `UpdateLimit` | `UpdateLimitRequest` | `SubAccountLimit` | Update sub-account limit |
| `GetLimits` | `GetLimitsRequest` | `LimitsResponse` | Get sub-account limits |
| `DeleteLimit` | `DeleteLimitRequest` | `DeleteLimitResponse` | Delete sub-account limit |

#### MarketDataService (Public)

| Method | Request | Response | Description |
| - | - | - | - |
| `ListTradingPairs` | `ListTradingPairsRequest` | `ListTradingPairsResponse` | List trading pairs |
| `GetTradingPair` | `GetTradingPairRequest` | `TradingPairResponse` | Get trading pair by ID |
| `GetOrderbook` | `GetOrderbookRequest` | `OrderbookResponse` | Get orderbook snapshot |
| `GetTrades` | `GetTradesRequest` | `TradesResponse` | Get recent trades |
| `GetCandles` | `GetCandlesRequest` | `CandlesResponse` | Get OHLCV candles |

#### FeesService

| Method | Request | Response | Description |
| - | - | - | - |
| `SimulateFees` | `SimulateFeesRequest` | `SimulateFeesResponse` | Simulate fees for an order |

#### TransfersService

| Method | Request | Response | Description |
| - | - | - | - |
| `GetDepositSignature` | `DepositSignatureRequest` | `DepositSignatureResponse` | Generate deposit signature |
| `GetWithdrawSignature` | `WithdrawSignatureRequest` | `WithdrawSignatureResponse` | Generate withdrawal signature |

#### ApplicationsService (Backend Only)

| Method | Request | Response | Description |
| - | - | - | - |
| `GetConfig` | `GetConfigRequest` | `ApplicationConfig` | Get application configuration |
| `ListAppOrders` | `ListAppOrdersRequest` | `ListAppOrdersResponse` | List orders for app |
| `ListAppUsers` | `ListAppUsersRequest` | `ListAppUsersResponse` | List users for app |
| `ListAppMovements` | `ListAppMovementsRequest` | `ListAppMovementsResponse` | List movements for app |
| `ListAppBalances` | `ListAppBalancesRequest` | `ListAppBalancesResponse` | List balances for app |

#### FaucetService (Testnet Only)

| Method | Request | Response | Description |
| - | - | - | - |
| `MintTokens` | `MintTokensRequest` | `MintTokensResponse` | Mint all testnet tokens to user |

### Order Types and Time-in-Force

**Order Types:**

* `LIMIT` - Limit order (price required)
* `MARKET` - Market order (no price, uses slippage tolerance)

**Time-in-Force Options:**

* `GTC` - Good Till Cancelled (default)
* `IOC` - Immediate or Cancel
* `FOK` - Fill or Kill
* `GTD` - Good Till Date (requires `expiration_date`)

### Error Handling

gRPC uses standard status codes. Common codes:

| Code | Description |
| - | - |
| `OK` | Success |
| `INVALID_ARGUMENT` | Invalid request parameters |
| `NOT_FOUND` | Resource not found |
| `UNAUTHENTICATED` | Missing or invalid authentication |
| `PERMISSION_DENIED` | Insufficient permissions |
| `FAILED_PRECONDITION` | Operation cannot be performed in current state |
| `UNAVAILABLE` | Service temporarily unavailable |

### Proto File

The complete proto definition is available at:

* **GitHub**: `protos/*`

### Technical Details

**Server Implementation**

* Built with Tonic (Rust gRPC framework)
* HTTP/2 multiplexing for concurrent requests
* Standard gRPC health checks (`grpc.health.v1.Health`)
* OpenTelemetry integration for distributed tracing

**Performance Benefits over REST**

* Binary Protocol Buffers serialization (smaller payloads)
* HTTP/2 connection multiplexing (no head-of-line blocking)
* Native streaming support (future: real-time orderbook updates)
* Strong typing with code generation

### Current Limitations

Please note:

* **Stability**: API may change before stable release
* **Streaming**: Server-side streaming not yet implemented
* **Rate Limits**: Same limits as REST API apply
* **Documentation**: Proto file is the source of truth

### Migration from REST

The gRPC API provides equivalent functionality to all REST endpoints. Key differences:

| REST | gRPC |
| - | - |
| `POST /auth/challenge` | `AuthService.Challenge` |
| `POST /auth/verify` | `AuthService.Verify` |
| `POST /orders` | `OrdersService.CreateOrder` |
| `DELETE /orders/:id` | `OrdersService.CancelOrder` |
| `GET /market/trading-pairs` | `MarketDataService.ListTradingPairs` |
| `GET /orderbook/:id` | `MarketDataService.GetOrderbook` |

### Feedback

We welcome feedback on:

* API design and ergonomics
* Missing functionality
* Performance issues
* Documentation clarity

Please share your feedback with the Monaco team.

***

## Testnet Faucet & New Assets

### New Testnet Assets

This release includes a migration that resets testnet assets with the following tokens:

| Token | Contract Address | Decimals |
| - | - | - |
| WBTC | `0xF117edeAf9F3eBBd4F32029297FB6b9fCCF190E3` | 8 |
| WETH | `0x56B49bF1d089B1d8f95B9Be6Ae3aA071593c0C00` | 18 |
| WSOL | `0x410CC773b96a5dA34776Efa93A278acac0A70A7B` | 9 |
| WSEI | `0x298b267Dd31eE390DC5a9291216423f4cFa03F66` | 18 |
| USDC | `0x23E459c24C4925BA89205c400dcECa7aBC11723d` | 6 |
| SPX | `0xFdFd38E526cDdf6Ab76E87d656fd896b6f45D2AC` | 8 |
| AMZN | `0x8977fe7E64cb358174f906D9691915299355C7b1` | 8 |
| GOOG | `0x56e350af4b6C14D7Af40e496230D64c43122814E` | 8 |
| META | `0x9D1a2eaaD89F77B97749326463F921A28D010a18` | 8 |
| NVDA | `0x8eED6535E1A806aadbBc478F915d64D70d531D39` | 8 |
| TSLA | `0xFd27738B096AB3c2947dC31d9B3af2c572C35c91` | 8 |

### Trading Pairs

All tokens are paired against USDC:

* WBTC/USDC, WETH/USDC, WSOL/USDC, WSEI/USDC
* SPX/USDC, AMZN/USDC, GOOG/USDC, META/USDC, NVDA/USDC, TSLA/USDC

### Faucet Endpoint

A new faucet endpoint allows authenticated users to mint all testnet tokens at once.

**Endpoint:** `POST /api/v1/faucet/mint`

**Authentication:** Required (JWT Bearer token)

**Rate Limit:** Configurable via `faucet_daily_limit` feature flag (default: 1 request per 24 hours)

**Response:**

```json theme={null}
{
  "success": true,
  "minted": [
    {
      "asset_id": "uuid",
      "symbol": "WBTC",
      "amount": "5",
      "tx_hash": "0x..."
    },
    {
      "asset_id": "uuid",
      "symbol": "WETH",
      "amount": "100",
      "tx_hash": "0x..."
    }
  ],
  "failed": [],
  "remaining_requests_24h": 0
}
```

**Faucet Amounts per Token:**

| Token | Amount |
| - | - |
| WBTC | 5 |
| WETH | 100 |
| WSOL | 100 |
| WSEI | 1,000 |
| USDC | 10,000 |
| SPX, AMZN, GOOG, META, NVDA, TSLA | 50 each |

***

*Note: The REST API remains fully supported.*


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.