# Monaco React SDK

React hooks and components for the Monaco Protocol. Build trading applications with React using type-safe hooks for authentication, trading, market data, and WebSocket connections.

## Installation

```bash
# Install the React SDK and its dependencies
npm install @0xmonaco/react react wagmi@^2.17.5 viem@^2.31.7

# Or with bun
bun add @0xmonaco/react react wagmi@^2.17.5 viem@^2.31.7

# Or with yarn
yarn add @0xmonaco/react react wagmi@^2.17.5 viem@^2.31.7
```

## Features

- 🎣 **React Hooks**: Type-safe hooks for all Monaco Protocol operations
- 🔐 **Authentication**: `useAuth` hook for wallet-based login and session management
- 📈 **Trading**: `useTrade` hook for placing and managing orders
- 📊 **Market Data**: `useMarket` hook for trading pairs and candlestick data
- 👤 **Profile**: `useProfile` hook for user account information
- 🔄 **WebSocket**: Real-time hooks for orders, OHLCV, and orderbook updates
- 💼 **Vault**: `useVault` hook for token deposits and withdrawals

## Quick Start

### 1. Setup the Monaco Provider

Wrap your application with the `MonacoProvider`:

```tsx
import { MonacoProvider } from "@0xmonaco/react";
import { WagmiProvider, createConfig, http } from "wagmi";
import { seiTestnet } from "wagmi/chains";

const wagmiConfig = createConfig({
  chains: [seiTestnet],
  transports: {
    [seiTestnet.id]: http("https://evm-rpc-testnet.sei-apis.com"),
  },
});

function App() {
  return (
    <WagmiProvider config={wagmiConfig}>
      <MonacoProvider
        network="staging"
        seiRpcUrl="https://evm-rpc-testnet.sei-apis.com"
      >
        <YourApp />
      </MonacoProvider>
    </WagmiProvider>
  );
}
```

### 2. Use Monaco Hooks

```tsx
import { useMonaco, useAuth, useTrade, useMarket } from "@0xmonaco/react";

function TradingComponent() {
  const sdk = useMonaco();
  const { login, logout, isAuthenticated } = useAuth();
  const { placeLimitOrder, placeMarketOrder } = useTrade();
  const { tradingPairs, getTradingPairBySymbol } = useMarket();

  // Login
  const handleLogin = async () => {
    await login("your-client-id", { connectWebSocket: true });
  };

  // Place an order
  const handlePlaceOrder = async () => {
    const order = await placeLimitOrder(
      "BTC/USDC",
      "BUY",
      "0.001",
      "50000"
    );
    console.log("Order placed:", order.order_id);
  };

  return (
    <div>
      <button onClick={handleLogin}>
        {isAuthenticated ? "Logout" : "Login"}
      </button>
      <button onClick={handlePlaceOrder}>Place Order</button>
    </div>
  );
}
```

## Available Hooks

### Core Hooks

#### `useMonaco()`
Access the Monaco SDK instance directly.

```tsx
const sdk = useMonaco();
const address = sdk.getAccountAddress();
```

#### `useAuth()`
Authentication and session management.

```tsx
const { login, logout, isAuthenticated, authState } = useAuth();

// Login with auto-connect WebSocket
await login(clientId, { connectWebSocket: true });

// Check authentication status
if (isAuthenticated) {
  console.log("User:", authState?.user);
}

// Logout
await logout();
```

### Trading Hooks

#### `useTrade()`
Place and manage orders.

```tsx
const {
  placeLimitOrder,
  placeMarketOrder,
  cancelOrder,
  replaceOrder,
  getOrder,
  getPaginatedOrders,
} = useTrade();

// Place a limit order
const order = await placeLimitOrder(
  "BTC/USDC",
  "BUY",
  "0.001",
  "50000",
  { timeInForce: "GTC" }
);

// Place a market order
const marketOrder = await placeMarketOrder(
  "BTC/USDC",
  "SELL",
  "0.001",
  { slippageTolerance: 0.01 } // 1%
);

// Cancel an order
await cancelOrder(orderId);

// Get orders
const { data: orders } = await getPaginatedOrders({
  status: "SUBMITTED",
  trading_pair: "BTC/USDC",
});
```

### Market Data Hooks

#### `useMarket()`
Access trading pair metadata and market data.

```tsx
const { tradingPairs, getTradingPairBySymbol, getCandlestickData } = useMarket();

// Get all trading pairs
const pairs = await tradingPairs();

// Get specific pair
const btcPair = await getTradingPairBySymbol("BTC/USDC");

// Get candlestick data
const candles = await getCandlestickData(
  "BTC/USDC",
  "1h",
  Date.now() - 86400000, // 24h ago
  Date.now()
);
```

#### `useTradeFeed()`
Get recent trades for a trading pair.

```tsx
const { getTradeFeed } = useTradeFeed();

const trades = await getTradeFeed("BTC/USDC", { limit: 50 });
```

### Vault Hooks

#### `useVault()`
Manage token deposits and withdrawals using asset IDs.

```tsx
const { deposit, withdraw, approve, needsApproval } = useVault();
const { getUserBalanceByAssetId } = useProfile();

// Get asset ID from trading pair
const pair = await getTradingPairBySymbol("USDC/USDT");
const assetId = pair.base_asset_id;

// Check balance
const balance = await getUserBalanceByAssetId(assetId);
console.log(`Balance: ${balance.total_balance} ${balance.symbol}`);

// Check if approval is needed
if (await needsApproval(assetId, amount)) {
  await approve(assetId, amount);
}

// Deposit tokens
await deposit(assetId, amount);

// Withdraw tokens
await withdraw(assetId, amount);
```

### Profile Hooks

#### `useProfile()`
Access user profile and account information.

```tsx
const { getProfile, getUserBalances, getUserMovements } = useProfile();

// Get profile
const profile = await getProfile();

// Get balances
const balances = await getUserBalances({
  page: 1,
  page_size: 10,
});

// Get movements (transaction history)
const movements = await getUserMovements({
  page: 1,
  page_size: 20,
});
```

### WebSocket Hooks

#### `useOrderWebSocket()`
Subscribe to real-time order updates.

```tsx
const { subscribe, unsubscribe, connect, disconnect } = useOrderWebSocket();

useEffect(() => {
  // Connect and subscribe
  await connect();
  
  subscribe("BTC/USDC", "SPOT", (event) => {
    console.log("Order event:", event.eventType);
    if (event.eventType === "ORDER_FILLED") {
      console.log("Order filled:", event.order);
    }
  });

  return () => {
    unsubscribe("BTC/USDC", "SPOT");
    disconnect();
  };
}, []);
```

#### `useOHLCVWebSocket()`
Subscribe to real-time candlestick data.

```tsx
const { subscribe, unsubscribe, connect, disconnect } = useOHLCVWebSocket();

useEffect(() => {
  await connect();
  
  subscribe("BTC/USDC", "SPOT", "1m", (event) => {
    console.log("New candle:", event.candlestick);
  });

  return () => {
    unsubscribe("BTC/USDC", "SPOT", "1m");
    disconnect();
  };
}, []);
```

#### `useOrderbook()`
Subscribe to real-time orderbook updates.

```tsx
const { subscribe, unsubscribe, connect, disconnect } = useOrderbook();

useEffect(() => {
  await connect();
  
  subscribe("BTC/USDC", "SPOT", (event) => {
    console.log("Orderbook:", {
      bids: event.bids.length,
      asks: event.asks.length,
    });
  });

  return () => {
    unsubscribe("BTC/USDC", "SPOT");
    disconnect();
  };
}, []);
```

## TypeScript Configuration

For optimal type inference, use these TypeScript settings:

```json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}
```

## Development

### Build

```bash
bun run build
```

### Watch Mode

```bash
bun run dev
```

### Lint

```bash
bun run lint
```


## License

This project is licensed under the MIT License.

## Support

For support, please:

- Open an issue on GitHub
- Join our [Discord community](https://discord.gg/monaco)
- Visit our [documentation site](https://docs.monaco.xyz)
- Check our [API documentation](https://docs.0xmonaco.com)
