> ## 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.6

# Monaco Protocol SDK v0.5.6

## Real-Time Balance Updates & API Improvements

This release introduces real-time balance tracking via WebSocket, refines the batch cancel API with two dedicated methods for clearer usage, and improves error handling for vault operations.

***

## New Features

### Real-Time Balance Updates via WebSocket

Track your account balances in real-time with the new WebSocket balance channel and React hook.

**Core SDK:**

* **New Method**: `sdk.ws.balances()` for subscribing to live balance changes
* **Authenticated Channel**: Requires valid JWT token (user-specific updates)
* **Detailed Events**: Includes available, locked, and total balances (both normalized and raw values)
* **Update Reasons**: Know why balances changed (lock, unlock, deposit, withdrawal, trade)

**React SDK:**

* **New Hook**: `useUserBalances()` for real-time balance tracking
* **Hybrid Approach**: Fetches initial balances via REST, then subscribes to WebSocket for live updates
* **Manual Refresh**: Built-in `refresh()` function for on-demand balance reload
* **Connection Status**: Track if WebSocket subscription is active

**Use Cases:**

* Display live balance updates during trading
* Show real-time locked balance as orders execute
* Monitor deposits and withdrawals instantly
* Track fee deductions from trades
* Update balance UI without polling

**Example: WebSocket Balance Subscription**

```typescript theme={null}
import { MonacoSDK } from "@0xmonaco/core";

// Authenticate first
await sdk.login('your-client-id');

// Subscribe to balance updates
const unsubscribe = sdk.ws.balances((event) => {
  console.log('Balance updated:', event.data.reason);
  console.log('Token:', event.data.tokenSymbol);
  console.log('Available:', event.data.available);
  console.log('Locked:', event.data.locked);
  console.log('Total:', event.data.total);

  // Update UI with new balances
  updateBalanceDisplay(event.data);
});

// Later, to unsubscribe:
unsubscribe();
```

**Example: React Hook**

```tsx theme={null}
import { useUserBalances } from "@0xmonaco/react";

function BalanceDashboard() {
  const { balances, loading, subscribed, error, refresh } = useUserBalances();

  if (loading) return <div>Loading balances...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <div className="header">
        <h2>Your Balances</h2>
        {subscribed && <span className="live-badge">● Live</span>}
        <button onClick={refresh}>Refresh</button>
      </div>

      {balances.map(balance => (
        <div key={balance.asset_id} className="balance-row">
          <span>{balance.symbol}</span>
          <div>
            <div>Available: {balance.available_balance}</div>
            <div>Locked: {balance.locked_balance}</div>
            <div>Total: {balance.total_balance}</div>
          </div>
        </div>
      ))}
    </div>
  );
}
```

**Event Structure:**

```typescript theme={null}
interface UserBalanceEvent {
  eventType: "balance_update";
  userId: string;
  data: {
    tokenAddress: string;           // Token contract address
    tokenSymbol: string | null;     // Token symbol (e.g., "USDC")
    available: string;              // Available balance (normalized)
    availableRaw: string;           // Available balance (raw/wei)
    locked: string;                 // Locked in orders (normalized)
    lockedRaw: string;              // Locked in orders (raw/wei)
    total: string;                  // Total balance (normalized)
    totalRaw: string;               // Total balance (raw/wei)
    reason: "lock" | "unlock" | "deposit" | "withdrawal" | "trade";
    referenceId: string | null;     // Related order/movement ID
    updatedAt: string;              // ISO 8601 timestamp
  };
}
```

[Learn more about WebSocket API →](/websocket)

***

### Batch Cancel API Split

The `batchCancelOrders()` method has been split into two dedicated methods for clearer intent and simpler usage.

**What Changed:**

```typescript theme={null}
// Before (v0.5.5)
// Cancel specific orders
await sdk.trading.batchCancelOrders({
  orderIds: ['order-1', 'order-2', 'order-3']
});

// Cancel all orders
await sdk.trading.batchCancelOrders({ cancelAll: true });

// After (v0.5.6)
// Cancel specific orders - dedicated method
await sdk.trading.batchCancel(['order-1', 'order-2', 'order-3']);

// Cancel all orders - dedicated method
await sdk.trading.batchCancelAll();

// NEW: Cancel all orders for a specific trading pair
await sdk.trading.batchCancelAll(tradingPairId);
```

**Core SDK:**

* **New Method**: `batchCancel(orderIds: string[])` - Cancel specific orders by ID
* **New Method**: `batchCancelAll(tradingPairId?: string)` - Cancel all active orders, optionally filtered by trading pair
* **Clearer Intent**: Method names explicitly indicate what they do
* **Simpler Parameters**: No more object wrappers - just pass the array or trading pair ID

**React SDK:**

* Both methods available in `useTrade()` hook
* Same signatures as Core SDK

**Example:**

```typescript theme={null}
// Cancel specific orders
const result = await sdk.trading.batchCancel([
  'order-id-1',
  'order-id-2',
  'order-id-3'
]);

console.log(`Cancelled: ${result.total_cancelled}/${result.total_requested}`);

// Check individual results
result.results.forEach(r => {
  if (r.success) {
    console.log(`Order ${r.order_id} cancelled`);
  } else {
    console.log(`Order ${r.order_id} failed: ${r.error.message}`);
  }
});

// Cancel ALL active orders globally
const allResult = await sdk.trading.batchCancelAll();
console.log(`Emergency exit: cancelled ${allResult.total_cancelled} orders`);

// Cancel all orders for a specific trading pair
const pair = await sdk.market.getTradingPairBySymbol('ETH/USDC');
const pairResult = await sdk.trading.batchCancelAll(pair.id);
console.log(`Cancelled ${pairResult.total_cancelled} ETH/USDC orders`);
```

**Migration Guide:**

Replace `batchCancelOrders()` calls with the appropriate new method:

```typescript theme={null}
// Old: Cancel specific orders
await sdk.trading.batchCancelOrders({ orderIds: [id1, id2, id3] });

// New: Use batchCancel with direct array
await sdk.trading.batchCancel([id1, id2, id3]);

// Old: Cancel all orders
await sdk.trading.batchCancelOrders({ cancelAll: true });

// New: Use batchCancelAll (no parameters)
await sdk.trading.batchCancelAll();
```

**Why this change:**

* **Clearer API**: Method names explicitly describe the action
* **Simpler Usage**: No need to wrap parameters in objects
* **Better TypeScript**: Type inference works better with direct parameters
* **Trading Pair Filter**: New capability to cancel all orders for a specific pair

[Learn more about trading API →](/sdk/typescript/trades)

***

## Technical Updates

### viem Peer Dependency

The `viem` package has been moved from a direct dependency to a peer dependency (version `^2.45.2`) in both `@0xmonaco/core` and `@0xmonaco/types` packages.

**What this means:**

* Your application must now install `viem` directly
* Prevents type duplication issues when consuming the SDK
* Ensures consistent `viem` version across your entire application

**Installation:**

```bash theme={null}
# Install viem alongside Monaco SDK
npm install @0xmonaco/core@0.5.6 viem@^2.45.2

# Or for React
npm install @0xmonaco/react@0.5.6 @0xmonaco/core@0.5.6 viem@^2.45.2
```

### React Hook Count Correction

Monaco Protocol React SDK now has **14 hooks** (not 13 as previously documented):

1. `useAuth` - Authentication
2. `useFees` - Fee simulation
3. `useMarket` - Market data
4. `useMonacoSDK` - SDK instance access
5. `useOHLCV` - Real-time candlesticks
6. `useOrderbook` - Real-time orderbook
7. `useProfile` - User profile
8. `useTokenLifecycle` - Token management
9. `useTrade` - Trading operations
10. `useTradeFeed` - Real-time trades
11. **`useUserBalances`** - Real-time balances (NEW in v0.5.6)
12. `useUserMovements` - Account movements
13. `useUserOrders` - Real-time orders
14. `useVault` - Vault operations

***

## Bug Fixes

### Proto-Generated API Contract Alignment

This release also fixes several mismatches between the proto-generated API surface and the live service behavior.

**What Changed:**

* Implemented gRPC market metadata so the published contract no longer points to an unimplemented endpoint
* Defined gRPC batch order operations for batch create, batch replace, batch cancel, and cancel-all flows in the published contract; server-side handlers remain stubbed and return `UNIMPLEMENTED` in this release
* Aligned gRPC market pair filtering with the HTTP API by treating `base_token` and `quote_token` as token symbols instead of contract addresses
* Removed transport-only `source` fields from account balance and movement responses so generated contracts match the HTTP API
* Relaxed generated order `status` query constraints so comma-separated filters like `FILLED,PARTIALLY_FILLED` remain valid
* Replaced a panic path in `get_balance_by_asset` with proper `invalid_argument` validation for malformed asset UUIDs

### Vault Operations: Clear Error When No Account Available

Vault operations now throw a clear `InvalidConfigError` when the wallet client has no account connected, instead of failing with an unclear error message later in the transaction flow.

**What Changed:**

Previously, if you initialized the SDK with a wallet client but no account was connected, vault operations would fail with unclear errors during transaction execution. Now, you'll receive an immediate, actionable error.

```typescript theme={null}
import { MonacoSDK, InvalidConfigError } from "@0xmonaco/core";
import { createWalletClient, http } from "viem";
import { seiTestnet } from "viem/chains";

// Wallet client without account
const walletClient = createWalletClient({
  chain: seiTestnet,
  transport: http()
  // No account specified
});

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

try {
  // v0.5.6+: Clear error immediately
  await sdk.vault.deposit(assetId, 1000000000n);
} catch (error) {
  if (error instanceof InvalidConfigError && error.field === "account") {
    console.error("No account available in wallet client");
    console.error("Suggestion:", error.suggestion);
    // Handle: prompt user to connect wallet or provide account
  }
}
```

**When This Error Occurs:**

This error is thrown when calling any vault operation if:

* Wallet client is provided to SDK but `account` property is `undefined` or `null`
* User has disconnected their wallet after SDK initialization
* Wallet client was created without specifying an account

**Affected Operations:**

* `sdk.vault.deposit()`
* `sdk.vault.withdraw()`
* `sdk.vault.approve()`
* `sdk.vault.getAllowance()`
* `sdk.vault.needsApproval()`

**Error Details:**

```typescript theme={null}
InvalidConfigError: "No account available in wallet client"
  field: "account"
  code: "INVALID_CONFIG"
  suggestion: "Ensure wallet is connected and account is available"
```

**Why This Change:**

* **Earlier Detection**: Catch configuration issues before attempting blockchain transactions
* **Clearer Errors**: Specific error message indicates exactly what's wrong
* **Better DX**: Developers can handle this case explicitly and provide better UX
* **Actionable Suggestions**: Error includes suggestion on how to fix the issue

**Error Handling Example:**

```typescript theme={null}
try {
  await sdk.vault.deposit(assetId, amount);
} catch (error) {
  if (error instanceof InvalidConfigError) {
    // New in v0.5.6: Handle wallet configuration errors
    if (error.field === "account") {
      alert("Please connect your wallet to continue");
    }
  } else if (error instanceof APIError) {
    // Existing error handling
    console.error("API error:", error.message);
  }
}
```

***

## Internal Improvements

This release includes internal code quality improvements:

* Added TypeScript `override` keywords to error class methods for better type safety
* Improved null safety checks in React hooks (`useOHLCV`, `useUserOrders`, `useUserBalances`)
* Simplified network URL resolution logic
* Updated build tooling and linting configuration

These changes have no impact on the public API or usage patterns.

***

## Upgrade Instructions

### Install New Versions

```bash theme={null}
# NPM
npm install @0xmonaco/core@0.5.6 @0xmonaco/types@0.5.6 @0xmonaco/react@0.5.6 viem@^2.45.2

# Bun
bun add @0xmonaco/core@0.5.6 @0xmonaco/types@0.5.6 @0xmonaco/react@0.5.6 viem@^2.45.2
```

### Migration Steps

#### 1. Ensure viem is installed

```bash theme={null}
# Check if viem is already installed
npm list viem

# If not, install it
npm install viem@^2.45.2
```

#### 2. Update batch cancel calls

Find all occurrences of `batchCancelOrders()` and replace with the appropriate method:

```typescript theme={null}
// Replace specific order cancellations
- await sdk.trading.batchCancelOrders({ orderIds: [id1, id2] });
+ await sdk.trading.batchCancel([id1, id2]);

// Replace cancel-all calls
- await sdk.trading.batchCancelOrders({ cancelAll: true });
+ await sdk.trading.batchCancelAll();
```

#### 3. (Optional) Add balance tracking

Take advantage of the new real-time balance updates:

```typescript theme={null}
// TypeScript SDK
const unsubscribe = sdk.ws.balances((event) => {
  updateBalanceUI(event.data);
});

// React SDK
import { useUserBalances } from "@0xmonaco/react";

function Component() {
  const { balances, subscribed } = useUserBalances();
  // Your component logic
}
```

#### 4. (Optional) Improve vault error handling

Add explicit error handling for vault operations:

```typescript theme={null}
import { InvalidConfigError } from "@0xmonaco/core";

try {
  await sdk.vault.deposit(assetId, amount);
} catch (error) {
  if (error instanceof InvalidConfigError && error.field === "account") {
    // Prompt user to connect wallet
    alert("Please connect your wallet to continue");
  }
}
```

### Testing Recommendations

1. **Test batch cancel migrations**: Verify updated calls work correctly
2. **Test viem dependency**: Ensure your app builds with the peer dependency
3. **Test balance updates**: Verify WebSocket balance subscriptions work in your environment
4. **Test vault error handling**: Confirm improved error messages display correctly

***

*For complete documentation, see the [WebSocket API guide](/websocket), [Trading guide](/sdk/typescript/trades), [Vault Operations guide](/sdk/typescript/vault), and [Error Handling guide](/sdk/typescript/error-handling).*


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