# Guide

## Limit Order API Integration Documentation

### Overview

This document provides comprehensive integration guidelines for the OpenOcean Limit Order API, based on the implementation in `LimitOrder.js`. The API allows users to create, manage, and cancel limit orders for token trading on supported blockchain networks.

{% embed url="<https://github.com/openocean-finance/OpenOcean-API-Examples/blob/main/frontend/src/pages/LimitOrder.js>" %}

### API Base Information

#### Base URL

```
https://open-api.openocean.finance
```

#### View the current supported chains [here](https://apis.openocean.finance/developer/apis/supported-chains#limit-order-api-supported-chains).

### Token Configuration

#### Token Approval

Before creating a limit order, users must approve the contract to spend their tokens:

```javascript
// Check current allowance
const currentAllowance = await tokenContract.allowance(account, contractAddress);

// Approve if needed
if (currentAllowance < requiredAmount) {
  const tx = await tokenContract.approve(contractAddress, ethers.MaxUint256);
  await tx.wait();
}
```

### API Endpoints

#### 1. Create Limit Order

**Endpoint:** `POST /v2/{chainId}/limit-order`

**URL Parameters:**

* `chainId`: The blockchain network ID (e.g., 8453 for Base)

**Request Body:**

```json
{
  "makerAsset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "takerAsset": "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2",
  "makerAmount": "1000000",
  "takerAmount": "2000000",
  "expireTime": 1704067200000,
  "signature": "0x...",
  "orderMaker": "0x..."
}
```

**Field Descriptions:**

* `makerAsset`: Address of the token being sold
* `takerAsset`: Address of the token being bought
* `makerAmount`: Amount of maker token (in smallest units)
* `takerAmount`: Amount of taker token (in smallest units)
* `expireTime`: Order expiration timestamp (milliseconds)
* `signature`: signMessage
* `orderMaker`: User's wallet address

**Response:**

```json
{
  "success": true,
  "data": {
    "orderHash": "0x...",
    "status": "pending"
  }
}
```

#### 2. Cancel Limit Order

**Endpoint:** `POST /v2/{chainId}/limit-order/cancelLimitOrder`

**Request Body:**

```json
{
  "orderHash": "0x...",
  "signature": "0x..."
}
```

**Field Descriptions:**

* `orderHash`: Hash of the order to cancel
* `signature`: signMessage

**Response:**

```json
{
  "success": true,
  "data": {
    "status": "cancelled"
  }
}
```

#### 3. Get User Orders

**Endpoint:** `GET /v2/{chainId}/limit-order/address/{address}`

**URL Parameters:**

* `chainId`: The blockchain network ID
* `address`: User's wallet address

**Query Parameters:**

* `page`: Page number (default: 1)
* `limit`: Number of orders per page (default: 100)
* `statuses`: Array of order statuses to filter \[1,2,5]
* `sortBy`: Sort field (default: createDateTime)
* `exclude`: Exclude certain orders (default: 0)

**Example URL:**

```
/v2/8453/limit-order/address/0x1234...?page=1&limit=100&statuses=[1,2,5]&sortBy=createDateTime&exclude=0
```

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "123",
      "orderHash": "0x...",
      "makerAsset": "0x...",
      "takerAsset": "0x...",
      "makerAmount": "1000000",
      "takerAmount": "2000000",
      "createDateTime": "2024-01-01T00:00:00Z",
      "statuses": 2,
      "expireTime": 1704067200000
    }
  ]
}
```

### Request/Response Formats

#### Order Status Codes

| Code | Status    | Description                       |
| ---- | --------- | --------------------------------- |
| 1    | Pending   | Order is pending execution        |
| 2    | Active    | Order is active and can be filled |
| 3    | Filled    | Order has been completely filled  |
| 4    | Cancelled | Order has been cancelled          |
| 5    | Expired   | Order has expired                 |

#### Message Signing Format

**For Order Creation:**

```
makerAsset:
{makerAssetAddress}
takerAsset:
{takerAssetAddress}
makerAmount:
{makerAmount}
takerAmount:
{takerAmount}
expireTime:
{expireTime}
```

**For Order Cancellation:**

```
orderHash:
{orderHash}
```

#### Signature Generation

```javascript
const message = `makerAsset:\n${makerAsset}\ntakerAsset:\n${takerAsset}\nmakerAmount:\n${makerAmount}\ntakerAmount:\n${takerAmount}\nexpireTime:\n${expireTime}`;
const signature = await signer.signMessage(message);
```

### Integration Examples

#### Complete Order Creation Flow

```javascript
async function createLimitOrder(makerAmount, takerAmount, expireTime) {
  try {
    // 1. Validate inputs
    if (!makerAmount || !takerAmount || makerAmount <= 0 || takerAmount <= 0) {
      throw new Error('Invalid parameters');
    }

    // 2. Check wallet connection
    if (!isWalletConnected) {
      throw new Error('Wallet not connected');
    }

    // 3. Get contract address
    const contractAddress = getLimitContractAddress(chainName);

    // 4. Check and approve token if needed
    if (!isNativeToken(inToken.address)) {
      const approvalAmount = makerAmount * (10 ** inToken.decimals);
      await checkTokenApproval(inToken.address, contractAddress, approvalAmount, walletAccount, provider);
    }

    // 5. Prepare order parameters
    const messageParams = {
      makerAsset: inToken.address,
      takerAsset: outToken.address,
      makerAmount: (makerAmount * (10 ** inToken.decimals)).toString(),
      takerAmount: (takerAmount * (10 ** outToken.decimals)).toString(),
      expireTime: expireTime,
    };

    // 6. Create and sign message
    const message = `makerAsset:\n${messageParams.makerAsset}\ntakerAsset:\n${messageParams.takerAsset}\nmakerAmount:\n${messageParams.makerAmount}\ntakerAmount:\n${messageParams.takerAmount}\nexpireTime:\n${messageParams.expireTime}`;
    const signer = await provider.getSigner();
    const signature = await signer.signMessage(message);

    // 7. Submit order
    const order = {
      ...messageParams,
      signature,
      orderMaker: walletAccount,
    };

    const response = await axios.post(
      `https://open-api.openocean.finance/v2/8453/limit-order`,
      order,
      { headers: { 'Content-Type': 'application/json' } }
    );

    return response.data;
  } catch (error) {
    console.error('Error creating limit order:', error);
    throw error;
  }
}
```

#### Order Management

```javascript
// Get user orders
const orders = await getLimitOrders(walletAddress);
const { orderHash } = orders[0];
const message = 'orderHash:\n' + orderHash;
const signer = await state.provider.getSigner();
const signature = await signer.signMessage(message);

await axios.post(
        `https://open-api.openocean.finance/v2/8453/limit-order/cancelLimitOrder`,
        { orderHash, signature }
      );
```

### Support

For technical support or questions about the API:

* Check the [OpenOcean Documentation](https://docs.openocean.finance)
* Contact the development team
* Review error logs and API responses
