> For the complete documentation index, see [llms.txt](https://docs.opinion.trade/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.opinion.trade/developer-guide/opinion-clob-typescript-sdk/api-references/models.md).

# Models

This page documents the enums, data types, response structures, and exception types used in the TypeScript SDK (`@opinion-labs/opinion-clob-sdk` v0.5.2).

***

## Enums

### TopicType

Market type for filtering.

```typescript
import { TopicType } from '@opinion-labs/opinion-clob-sdk';
```

| Value                   | Numeric | Description                            |
| ----------------------- | ------- | -------------------------------------- |
| `TopicType.BINARY`      | 0       | Binary (Yes/No) markets                |
| `TopicType.CATEGORICAL` | 1       | Categorical (multiple outcome) markets |
| `TopicType.ALL`         | 2       | All market types                       |

### TopicStatus

Market lifecycle status.

```typescript
import { TopicStatus } from '@opinion-labs/opinion-clob-sdk';
```

| Value                   | Numeric | Description                                   |
| ----------------------- | ------- | --------------------------------------------- |
| `TopicStatus.CREATED`   | 1       | Market has been created but is not yet active |
| `TopicStatus.ACTIVATED` | 2       | Market is active and open for trading         |
| `TopicStatus.RESOLVING` | 3       | Market is in the resolution process           |
| `TopicStatus.RESOLVED`  | 4       | Market has been resolved with a final outcome |
| `TopicStatus.FAILED`    | 5       | Market creation or resolution failed          |
| `TopicStatus.DELETED`   | 6       | Market has been deleted                       |

### TopicStatusFilter

Status filter for querying markets via `getMarkets()`.

```typescript
import { TopicStatusFilter } from '@opinion-labs/opinion-clob-sdk';
```

| Value                         | String        | Description                             |
| ----------------------------- | ------------- | --------------------------------------- |
| `TopicStatusFilter.ALL`       | `""`          | Return all markets regardless of status |
| `TopicStatusFilter.ACTIVATED` | `"activated"` | Only active/tradable markets            |
| `TopicStatusFilter.RESOLVED`  | `"resolved"`  | Only resolved markets                   |

### TopicSortType

Sorting options for market listings.

```typescript
import { TopicSortType } from '@opinion-labs/opinion-clob-sdk';
```

| Value                              | Numeric | Description                          |
| ---------------------------------- | ------- | ------------------------------------ |
| `TopicSortType.BY_TIME_DESC`       | 1       | Sort by creation time (newest first) |
| `TopicSortType.BY_CUTOFF_TIME_ASC` | 2       | Sort by cutoff time (soonest first)  |
| `TopicSortType.BY_VOLUME_DESC`     | 3       | Sort by total volume (highest first) |
| `TopicSortType.BY_VOLUME_ASC`      | 4       | Sort by total volume (lowest first)  |
| `TopicSortType.BY_VOLUME_24H_DESC` | 5       | Sort by 24h volume (highest first)   |
| `TopicSortType.BY_VOLUME_24H_ASC`  | 6       | Sort by 24h volume (lowest first)    |
| `TopicSortType.BY_VOLUME_7D_DESC`  | 7       | Sort by 7d volume (highest first)    |
| `TopicSortType.BY_VOLUME_7D_ASC`   | 8       | Sort by 7d volume (lowest first)     |

### OrderSide

Order direction.

```typescript
import { OrderSide } from '@opinion-labs/opinion-clob-sdk';
```

| Value            | Numeric | Description |
| ---------------- | ------- | ----------- |
| `OrderSide.BUY`  | 0       | Buy order   |
| `OrderSide.SELL` | 1       | Sell order  |

### OrderType

Order execution type.

```typescript
import { OrderType } from '@opinion-labs/opinion-clob-sdk';
```

| Value                    | Numeric | Description                                         |
| ------------------------ | ------- | --------------------------------------------------- |
| `OrderType.MARKET_ORDER` | 1       | Market order (executed at best available price)     |
| `OrderType.LIMIT_ORDER`  | 2       | Limit order (executed at specified price or better) |

***

## Data Types

### PlaceOrderDataInput

The input type used when placing orders via `placeOrder()` or `placeOrdersBatch()`.

```typescript
import type { PlaceOrderDataInput } from '@opinion-labs/opinion-clob-sdk';
import { OrderSide, OrderType } from '@opinion-labs/opinion-clob-sdk';

const orderData: PlaceOrderDataInput = {
  marketId: 57,
  tokenId: 'YOUR_TOKEN_ID',
  side: OrderSide.BUY,
  orderType: OrderType.LIMIT_ORDER,
  price: '0.6',
  makerAmountInQuoteToken: '100',  // 100 USDT
};
```

| Field                     | Type      | Required | Description                                                                                                          |
| ------------------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| `marketId`                | number    | Yes      | Market ID / Topic ID                                                                                                 |
| `tokenId`                 | string    | Yes      | Token ID of the CTF ERC1155 asset (e.g., Yes token ID)                                                               |
| `side`                    | OrderSide | Yes      | `OrderSide.BUY` or `OrderSide.SELL`                                                                                  |
| `orderType`               | OrderType | Yes      | `OrderType.MARKET_ORDER` or `OrderType.LIMIT_ORDER`                                                                  |
| `price`                   | string    | Yes      | Price per outcome token (e.g., `"0.5"` for 50 cents). Required for limit orders; set to any value for market orders. |
| `makerAmountInQuoteToken` | string    | No       | Amount in quote token (e.g., `"100"` USDC). Use for buy orders or when specifying by dollar value.                   |
| `makerAmountInBaseToken`  | string    | No       | Amount in outcome tokens (e.g., `"50"` Yes tokens). Use for sell orders or when specifying by share count.           |

Amount rules:

* You must provide exactly one of `makerAmountInQuoteToken` or `makerAmountInBaseToken`.
* For **market buy** orders: only `makerAmountInQuoteToken` is allowed.
* For **market sell** orders: only `makerAmountInBaseToken` is allowed.
* For **limit** orders: either field is accepted.

### ClientConfig

Configuration options for initializing the `Client`.

```typescript
import { Client, CHAIN_ID_BNB_MAINNET, DEFAULT_API_HOST } from '@opinion-labs/opinion-clob-sdk';

const client = new Client({
  host: DEFAULT_API_HOST,
  apiKey: 'YOUR_API_KEY',
  chainId: CHAIN_ID_BNB_MAINNET,
  rpcUrl: 'YOUR_RPC_URL',
  privateKey: '0xYOUR_PRIVATE_KEY',
  multiSigAddress: '0xYOUR_MULTI_SIG_ADDRESS',
});
```

| Field                        | Type    | Required | Description                                                    |
| ---------------------------- | ------- | -------- | -------------------------------------------------------------- |
| `host`                       | string  | Yes      | API host URL                                                   |
| `apiKey`                     | string  | Yes      | API authentication key                                         |
| `chainId`                    | number  | Yes      | Blockchain chain ID (56 for BNB Chain)                         |
| `rpcUrl`                     | string  | Yes      | RPC endpoint URL                                               |
| `privateKey`                 | Hex     | Yes      | Private key for signing transactions                           |
| `multiSigAddress`            | Address | Yes      | Multi-signature wallet address                                 |
| `conditionalTokensAddress`   | Address | No       | Conditional tokens contract address                            |
| `multiSendAddress`           | Address | No       | MultiSend contract address                                     |
| `feeManagerAddress`          | Address | No       | FeeManager contract address                                    |
| `ctfExchangeAddress`         | Address | No       | CTF Exchange contract address (overrides API-provided)         |
| `enableTradingCheckInterval` | number  | No       | Cache TTL for enable trading checks in seconds (default: 3600) |
| `quoteTokensCacheTtl`        | number  | No       | Cache TTL for quote tokens in seconds (default: 3600)          |
| `marketCacheTtl`             | number  | No       | Cache TTL for market data in seconds (default: 300)            |
| `proxyUrl`                   | string  | No       | HTTP proxy URL for API requests                                |

### TransactionResult

Returned by blockchain operations (`enableTrading`, `split`, `merge`, `redeem`).

```typescript
interface TransactionResult {
  txHash?: string;  // Transaction hash (undefined if no on-chain tx was needed)
  success: boolean;
}
```

***

## Response Structure

All API methods return responses in a consistent wrapper format:

```typescript
interface ApiResponse<T> {
  errno: number;   // 0 = success, non-zero = error
  errmsg: string;  // Error message (empty on success)
  result: T;       // Response payload
}
```

### Example: Successful response

```json
{
  "errno": 0,
  "errmsg": "",
  "result": {
    "total": 10,
    "list": [
      {
        "marketId": 5,
        "marketTitle": "Example Market",
        "status": 2,
        "statusEnum": "activated",
        "yesTokenId": "101128430008250248394161770787866737734499464157137890629662678617009651760181",
        "noTokenId": "60119751433323231793441870248949152266777555824072219518426778460783591201702",
        "yesLabel": "Yes",
        "noLabel": "No",
        "quoteToken": "0x5Fd47a476d9c8309dF84D50cfAa0AB576c28DF0D",
        "volume": "2.000000000000000000",
        "conditionId": "...",
        "cutoffAt": 1734537600,
        "createdAt": 1734515671,
        "rules": ""
      }
    ]
  }
}
```

### Example: Error response

```json
{
  "errno": 500,
  "errmsg": "error message",
  "result": null
}
```

### Common errno Values

| errno | Description              |
| ----- | ------------------------ |
| 0     | Success                  |
| 1     | Internal error           |
| 2     | Invalid parameter        |
| 100   | Invalid API key          |
| 200   | Market not found         |
| 300   | Order not found          |
| 301   | Order cannot be canceled |
| 303   | Insufficient balance     |
| 304   | Price out of range       |
| 305   | Amount too small         |
| 429   | Rate limit exceeded      |
| 500   | Internal server error    |

***

## Exception Types

The SDK defines custom exception classes for different error scenarios. All exceptions extend the base `SdkError` class.

```typescript
import {
  SdkError,
  InvalidParamError,
  OpenApiError,
  BalanceNotEnough,
  NoPositionsToRedeem,
  InsufficientGasBalance,
  ValidationException,
} from '@opinion-labs/opinion-clob-sdk';
```

| Exception                | When Thrown                                                                                                       |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `SdkError`               | Base class for all SDK errors. Not thrown directly.                                                               |
| `InvalidParamError`      | Invalid parameters passed to SDK methods (e.g., invalid `marketId`, missing required fields, price out of range). |
| `OpenApiError`           | API call failures (e.g., network errors, unexpected API responses, chain mismatch).                               |
| `BalanceNotEnough`       | Insufficient token balance for an operation.                                                                      |
| `NoPositionsToRedeem`    | Attempting to redeem from a market with no redeemable positions.                                                  |
| `InsufficientGasBalance` | Signer wallet does not have enough gas (BNB) for a blockchain transaction.                                        |
| `ValidationException`    | Order validation failed during the order building process.                                                        |

### Error Handling Example

```typescript
import {
  Client,
  InvalidParamError,
  OpenApiError,
  BalanceNotEnough,
} from '@opinion-labs/opinion-clob-sdk';

try {
  const result = await client.placeOrder(orderData);
} catch (error) {
  if (error instanceof InvalidParamError) {
    console.error('Invalid parameter:', error.message);
  } else if (error instanceof BalanceNotEnough) {
    console.error('Insufficient balance:', error.message);
  } else if (error instanceof OpenApiError) {
    console.error('API error:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.opinion.trade/developer-guide/opinion-clob-typescript-sdk/api-references/models.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
