npm package: @quantish/sdk
Description: Quantish SDK - AI-powered trading infrastructure for Polymarket prediction markets
Author: Quantish
Latest version: 1.5.0

# @quantish/sdk

Official SDK for **Quantish** - AI-powered trading infrastructure for Polymarket prediction markets.

[![npm version](https://badge.fury.io/js/%40quantish%2Fsdk.svg)](https://www.npmjs.com/package/@quantish/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔐 **Secure Wallet Infrastructure** - Gasless Safe wallet deployment on Polygon
- 📈 **Full Trading Capabilities** - Place, cancel, and manage orders
- 💰 **Position Management** - Track holdings, claim winnings
- 🔄 **Token Swaps** - Swap USDC, MATIC via LI.FI aggregator
- 🤖 **MCP Integration** - Works with Cursor IDE and Claude Desktop
- 🛡️ **HMAC Signing** - Optional request authentication

## Installation

```bash
npm install @quantish/sdk
```

## Quick Start

### Option 1: CLI Setup (Easiest)

```bash
npx @quantish/sdk setup
```

This interactive wizard will:
1. Ask for your access code (get one from [quantish.live](https://quantish.live))
2. Create your wallet  
3. Give you your API credentials
4. Show MCP config for Cursor/Claude

### Option 2: Programmatic Setup

```typescript
import { requestApiKey } from '@quantish/sdk';

const credentials = await requestApiKey({
  accessCode: 'QNT-XXXX-XXXX-XXXX', // From Quantish
  externalId: 'your-unique-user-id',
});

console.log('API Key:', credentials.apiKey);
console.log('API Secret:', credentials.apiSecret);
// SAVE THESE - they won't be shown again!
```

## CLI Commands

```bash
npx @quantish/sdk setup    # Interactive setup wizard
npx @quantish/sdk config   # Generate MCP config
npx @quantish/sdk test     # Test server connection
npx @quantish/sdk enable   # Auto-configure Cursor IDE
npx @quantish/sdk help     # Show help
```

## Using the SDK Client

```typescript
import QuantishClient from '@quantish/sdk';

const client = new QuantishClient({
  apiKey: 'pk_live_...',
  apiSecret: 'sk_live_...', // Optional but recommended for HMAC
});

// Setup wallet (do this once)
await client.setupWallet();

// Check balance
const balances = await client.getBalances();
console.log('USDC:', balances.safe?.usdc);

// Search markets
const markets = await client.searchMarkets('bitcoin', 5);

// Place an order
const order = await client.placeOrder({
  conditionId: '0x...',
  tokenId: '123...',
  side: 'BUY',
  price: 0.55,
  size: 10,
});

// Get positions
const positions = await client.getPositions();

// Claim winnings from resolved markets
const winnings = await client.claimWinnings();
```

---

## MCP Integration (Cursor IDE / Claude)

### Cursor IDE Setup

**Method 1: Auto-configure (Recommended)**
```bash
npx @quantish/sdk enable
```

**Method 2: Manual Setup**

1. Open your MCP config file: `~/.cursor/mcp.json`
2. Add this configuration:

```json
{
  "mcpServers": {
    "quantish": {
      "url": "https://quantish-sdk-production.up.railway.app/mcp",
      "headers": {
        "x-api-key": "YOUR_API_KEY_HERE"
      }
    }
  }
}
```

3. Restart Cursor IDE

### Claude Desktop Setup

Add to your Claude Desktop config (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "quantish": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-proxy", "https://quantish-sdk-production.up.railway.app/mcp"],
      "env": {
        "QUANTISH_API_KEY": "YOUR_API_KEY_HERE"
      }
    }
  }
}
```

---

## Complete MCP Tools Reference

### 🔐 Account & Wallet Management

| Tool | Description |
|------|-------------|
| `request_api_key` | Register and get API credentials (requires access code) |
| `setup_wallet` | Deploy Safe wallet, create CLOB credentials, approve contracts |
| `get_wallet_status` | Check wallet deployment and approval status |
| `get_balances` | Get USDC, Native USDC, MATIC, and WMATIC balances |
| `list_api_keys` | List all your API keys |
| `create_additional_api_key` | Create new API key for same account |
| `revoke_api_key` | Revoke an API key |
| `export_private_key` | Securely export encrypted private key backup |

### 📈 Market Data

| Tool | Description |
|------|-------------|
| `search_markets` | Search markets by keyword |
| `get_market` | Get detailed market info by conditionId |
| `get_active_markets` | List active prediction markets |
| `get_orderbook` | Get bids/asks for a token |
| `get_price` | Get current midpoint price |

### 💹 Trading

| Tool | Description |
|------|-------------|
| `place_order` | Place buy/sell orders (GTC, GTD, FOK, FAK types) |
| `cancel_order` | Cancel an existing order (supports local ID or CLOB ID) |
| `get_orders` | Get all your orders (optionally filter by status) |
| `sync_order_status` | Sync order status with Polymarket |

### 📊 Positions & Claims

| Tool | Description |
|------|-------------|
| `get_positions` | Get your share holdings |
| `sync_positions` | Sync positions with Polymarket |
| `get_claimable_winnings` | Check for winnings from resolved markets |
| `claim_winnings` | **Claim winnings from resolved markets** |
| `get_onchain_shares` | Get shares directly from blockchain (finds gifted/transferred shares) |
| `check_token_balance` | Check specific token balance on-chain |

### 💸 Transfers (All Gasless!)

| Tool | Description |
|------|-------------|
| `transfer_usdc` | Transfer bridged USDC.e |
| `transfer_native_usdc` | Transfer Circle's native USDC |
| `transfer_shares` | Transfer ERC-1155 prediction market shares |
| `transfer_matic` | ⚠️ Not supported (native MATIC can't use relayer) |

### 🔄 Token Swaps

| Tool | Description |
|------|-------------|
| `get_swap_quote` | Get swap quote via LI.FI aggregator |
| `swap_tokens` | Swap between MATIC, USDC, Native USDC (uses WMATIC for MATIC swaps) |

### 🔍 Research Tools

| Tool | Description |
|------|-------------|
| `scrapeURL` | Scrape content from any URL |
| `news_search` | Search for news articles |

---

## Example AI Prompts

After connecting MCP, try asking your AI assistant:

**Wallet & Balance:**
- "What's my wallet status?"
- "What are my balances?"
- "Setup my wallet"

**Market Research:**
- "Search for bitcoin prediction markets"
- "What are the most active markets right now?"
- "Get the order book for [market]"
- "What's the latest news about crypto regulations?"

**Trading:**
- "Place a $10 buy order on [market] at 55 cents"
- "What are my current orders?"
- "Cancel my order on [market]"
- "What positions do I have?"

**Winnings & Claims:**
- "Do I have any claimable winnings?"
- "Claim all my winnings"

**Transfers:**
- "Transfer 5 USDC to 0x..."
- "Send my shares of [market] to 0x..."

---

## API Reference

### Wallet Methods

```typescript
await client.setupWallet();           // Deploy Safe wallet
await client.getWalletStatus();       // Get deployment status
await client.getBalances();           // Get all balances
await client.exportPrivateKey(pass);  // Export encrypted backup
```

### Market Methods

```typescript
await client.searchMarkets(query, limit);  // Search markets
await client.getMarket(conditionId);       // Get market details
await client.getActiveMarkets(limit);      // List active markets
await client.getPrice(tokenId);            // Get current price
await client.getOrderbook(tokenId);        // Get order book
```

### Order Methods

```typescript
// Place order
await client.placeOrder({
  conditionId: '0x...',
  tokenId: '123...',
  side: 'BUY',        // or 'SELL'
  price: 0.55,        // 0.01 to 0.99
  size: 10,           // number of shares
  orderType: 'GTC',   // GTC, GTD, FOK, FAK
});

await client.cancelOrder(orderId);     // Cancel order
await client.getOrders(status?);       // Get orders
await client.syncOrderStatus(orderId); // Sync with Polymarket
```

### Position Methods

```typescript
await client.getPositions();           // Get positions
await client.syncPositions();          // Sync positions
await client.getOnchainShares();       // Get shares from blockchain
await client.checkTokenBalance(tokenId); // Check specific token
await client.getClaimableWinnings();   // Check claimable winnings
await client.claimWinnings(positionId?); // Claim winnings
```

### Transfer Methods

```typescript
await client.transferUsdc(toAddress, amount);
await client.transferNativeUsdc(toAddress, amount);
await client.transferShares(toAddress, tokenId, amount);
```

### Swap Methods

```typescript
await client.getSwapQuote(fromToken, toToken, amount);
await client.swapTokens(fromToken, toToken, amount);
// Tokens: 'USDC', 'NATIVE_USDC', 'MATIC' (uses WMATIC)
```

### Research Methods

```typescript
await client.searchNews(query, num?, timeRange?);
await client.scrapeUrl(url);
```

---

## Security

### Security Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    YOUR APPLICATION                          │
└─────────────────────────────────────────────────────────────┘
                           │
                           │ HTTPS + API Key + HMAC (optional)
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                  QUANTISH MCP SERVER                         │
│  ┌──────────┐  ┌──────────┐  ┌────────────────────────────┐ │
│  │Rate Limit│→ │Auth Layer│→ │ Tool Execution (User ID    │ │
│  │(60/min)  │  │(API Key) │  │ derived from header ONLY)  │ │
│  └──────────┘  └──────────┘  └────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
                           │
           ┌───────────────┼───────────────┐
           ▼               ▼               ▼
   ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
   │ PostgreSQL  │ │ Polymarket  │ │ Polygon RPC │
   │ (Encrypted) │ │ Relayer     │ │ (Fallback)  │
   └─────────────┘ └─────────────┘ └─────────────┘
```

### Key Security Principles

- ✅ **User isolation** - userId derived from API key header, NEVER from request body
- ✅ **Gasless transactions** - Private keys only decrypted momentarily for signing
- ✅ **Secure export** - Keys encrypted with user password before transmission
- ✅ **Access codes** - Registration requires admin-issued codes
- ✅ **Rate limiting** - 60 requests/minute per API key

### Encryption at Rest

| Data | Encryption | Algorithm |
|------|------------|-----------|
| Wallet Private Keys | ✅ Encrypted | AES-256-GCM (random IV) |
| CLOB API Credentials | ✅ Encrypted | AES-256-GCM (random IV) |
| User API Keys | ✅ Hashed | SHA-256 (one-way) |

<details>
<summary><strong>🔐 Authentication & HMAC Signing (Click to expand)</strong></summary>

#### API Key Authentication

Every request (except registration) requires a valid API key in the header:
```
x-api-key: pk_live_xxxxxxxxxxxxx
```

**API Key Properties:**
- 32-byte cryptographically random value
- Base64URL encoded with `pk_live_` prefix
- Stored as SHA-256 hash (never plaintext)
- One-way lookup: cannot be recovered

#### HMAC Request Signing (Optional but Recommended)

For enhanced security, provide your API secret:

```typescript
const client = new QuantishClient({
  apiKey: 'pk_live_...',
  apiSecret: 'sk_live_...', // Enables HMAC signing automatically
});
```

**Signature Calculation:**
```
message = timestamp + method + path + body
signature = HMAC-SHA256(message, apiSecret)
```

**Headers sent:**
```
x-api-key:   pk_live_xxxxx
x-timestamp: 1701234567890
x-signature: aBcDeFgHiJkLmNoPqRsTuVwXyZ==
```

**HMAC protects against:**
| Attack | Prevention |
|--------|------------|
| Request Tampering | Any change invalidates signature |
| Replay Attack | 30-second timestamp window |
| Timing Attack | Constant-time comparison |
| Man-in-the-Middle | Can't forge signature without secret |

</details>

<details>
<summary><strong>🔒 Encryption Architecture (Click to expand)</strong></summary>

#### V2 Encryption (AES-256-GCM)

All sensitive data uses authenticated encryption:

```
Algorithm: AES-256-GCM
Key Size:  256 bits (32 bytes)
IV:        128 bits - Random per encryption
Auth Tag:  128 bits - Tamper detection

Format: "v2:{iv}:{authTag}:{ciphertext}"
```

**Why GCM?**
- Provides confidentiality AND integrity
- Authentication tag prevents tampering
- Random IV = identical plaintexts produce different ciphertexts

#### Key Hierarchy

```
MASTER KEY (Environment Variable)
       │
       │ Encrypts
       ▼
USER WALLET PRIVATE KEY (Per-user, in database)
       │
       │ Derives
       ▼
EOA ADDRESS → Controls → SAFE WALLET (Smart Contract)
```

#### Secure Key Export

When exporting your private key:
1. You provide a strong password (min 12 chars)
2. Server derives key using PBKDF2 (100,000 iterations)
3. Private key encrypted with derived key
4. You decrypt LOCALLY with your password

**⚠️ Raw private key NEVER travels over network unencrypted!**

</details>

<details>
<summary><strong>💼 Wallet Security (Click to expand)</strong></summary>

#### Safe Wallet Architecture

Each user gets a Gnosis Safe (smart contract wallet):

```
USER'S SAFE (Smart Contract Wallet)
├── Address: 0x434313cb96d8280b2b1a08883fdbff1faa346fab
├── Type: Gnosis Safe Proxy
├── Owner: User's EOA (1-of-1 threshold)
├── Modules: None (no backdoors)
└── Approved Contracts:
    ├── USDC Token
    ├── CTF Exchange (Polymarket trading)
    ├── Neg Risk CTF Exchange
    └── Neg Risk Adapter
```

**Security Properties:**
- ✓ Only EOA owner can authorize transactions
- ✓ No modules = no backdoor access
- ✓ Battle-tested Gnosis Safe contracts
- ✓ Funds recoverable if service discontinued

#### Gasless Transaction Flow

```
1. You request action (e.g., transfer USDC)
2. Server decrypts private key (in memory only)
3. Transaction signed
4. Signature sent to Polymarket Relayer
5. Relayer submits to blockchain (PAYS GAS)
6. Private key cleared from memory
```

**Benefits:**
- You never need MATIC for gas
- Private key only in memory for milliseconds
- Signature proves authorization without exposing key

</details>

<details>
<summary><strong>🛡️ Rate Limiting & Protection (Click to expand)</strong></summary>

#### Multi-Tier Rate Limits

| Endpoint | Limit | Purpose |
|----------|-------|---------|
| `/mcp` (all tools) | 60/minute | Prevent trading abuse |
| `/api/*` (REST) | 100/15 min | General protection |
| Registration | 5/hour per IP | Prevent account spam |

#### Request Size Limits

```
JSON body: 1MB max (prevents DoS)
Strict mode: Only arrays/objects accepted
```

#### Security Headers (via Helmet)

- `X-Content-Type-Options: nosniff`
- `X-Frame-Options: DENY`
- `Strict-Transport-Security: max-age=31536000`
- `Content-Security-Policy: default-src 'self'`

</details>

<details>
<summary><strong>📋 Activity Logging (Click to expand)</strong></summary>

#### What We Log

```
✅ Tool execution attempts
✅ Authentication failures
✅ API key creation/revocation
✅ Wallet deployments
✅ Order placements/cancellations
✅ Transfer operations
```

#### What We DON'T Log

```
❌ Private keys (NEVER)
❌ API secrets
❌ CLOB credentials
❌ Decrypted data
❌ Passwords
```

</details>

### Access Code System

Access codes prevent unauthorized account creation:
- One-time or multi-use codes
- Expiration dates supported
- Tied to your developer account

---

## Server URLs

```typescript
import { QUANTISH_URLS } from '@quantish/sdk';

QUANTISH_URLS.mcp    // https://quantish-sdk-production.up.railway.app/mcp
QUANTISH_URLS.api    // https://quantish-sdk-production.up.railway.app
QUANTISH_URLS.health // https://quantish-sdk-production.up.railway.app/health
```

---

## Getting an Access Code

Access codes are required to create an account. Get yours at:
- 🌐 Website: [quantish.live](https://quantish.live)

---

## FAQ

**Q: What happens if I use the same external ID multiple times?**
A: You'll create new API keys for the **same wallet**. All keys are valid and access the same account.

**Q: Can I have multiple API keys?**
A: Yes! Use `create_additional_api_key` or request new keys with the same external ID.

**Q: Are transactions gasless?**
A: Yes! All transactions use Polymarket's relayer - no MATIC required for gas.

**Q: What if I receive gifted shares?**
A: Use `get_onchain_shares` to find shares transferred directly to your wallet.

---

## Support

- 📖 GitHub: [Issues](https://github.com/boshjerns/polymarket-mcp-server/issues)
- 🌐 Website: [quantish.live](https://quantish.live)

## License

MIT © [Quantish](https://quantish.live)