# Smart Contract Interaction

The 21X SDK enables seamless interaction with the platform's smart contracts deployed on the Polygon network. The provided `OrderBook` class allows users to manage their trading activity directly on the blockchain, including setting token allowances, creating and canceling orders, and retrieving balances.

***

### Initializing the `OrderBook` Class

The `OrderBook` class is designed to interact with the 21X platform's smart contract on the Polygon network. It requires signing transactions, and the SDK provides a configurable middleware for transaction management.

#### Configuration

Currently, the `OrderBook` class utilizes the [Web3.py](https://web3py.readthedocs.io/) library to sign and send transactions. This requires the user's private key during initialization. However, the middleware layer for transaction handling is designed to be flexible, allowing for integration with alternative mechanisms in the future (e.g., secure APIs or third-party signing services).

#### Constructor Parameters:

* `rpc_url` (`str`): The RPC URL of the Polygon node.
* `private_key` (`str`): The private key for signing transactions.\
  \&#xNAN;*(This is optional if an external middleware is used to handle transaction signing.)*
* `contract_address` (`str`): The address of the `OrderBook` smart contract.

#### Example:

```python
from x21_sdk import OrderBook

# Initialize the OrderBook class
order_book = OrderBook(
  private_key="your_private_key",
  orderbook_addr="0xOrderBookAddress",
  rpc_url="https://polygon-mainnet.g.alchemy.com/v2/YOUR_API_KEY",
)
```

#### Middleware for Transactions

The SDK's design abstracts transaction signing and sending through a middleware layer. This allows the implementation to be swapped or extended with minimal changes to your codebase. For instance:

* You can integrate a custom API for signing and broadcasting transactions.
* Security policies or hardware modules can be incorporated into the middleware.

In future releases, the SDK will provide a streamlined way to configure alternative transaction handlers.

***

### Overview of Contract Methods

The following methods are available for interacting with the smart contract through the `OrderBook` class:

#### Key Methods:

* **`get_balance`**: Fetches the current balance of base and quote tokens.
* **`get_allowance`**: Fetches the current allowance of base and quote tokens.
* **`set_base_allowance`**: Sets the allowance for the base token.
* **`set_quote_allowance`**: Sets the allowance for the quote token.
* **`create_buy_order`**: Creates a buy order for a trading pair.
* **`create_sell_order`**: Creates a sell order for a trading pair.
* **`cancel_buy_order`**: Cancels an existing buy order.
* **`cancel_sell_order`**: Cancels an existing sell order.

Refer to the detailed method documentation below for usage examples and parameters.

***

### `get_balance`

Fetches the current balance of the base and quote tokens for the specified trading pair.

#### Returns:

* `Pair`: An object containing:
  * `base` (`Decimal`): Balance of the base token.
  * `quote` (`Decimal`): Balance of the quote token.

#### Example:

```python
balance = order_book.get_balance()
print(f"Base Token Balance: {balance.base}")
print(f"Quote Token Balance: {balance.quote}")
```

***

### `get_allowance`

Fetches the current allowance of the base and quote tokens for the specified trading pair.

#### Returns:

* `Pair`: An object containing:
  * `base` (`Decimal`): Allowance of the base token.
  * `quote` (`Decimal`): Allowance of the quote token.

#### Example:

```python
allowance = order_book.get_allowance()
print(f"Base Token Allowance: {allowance.base}")
print(f"Quote Token Allowance: {allowance.quote}")
```

***

### `set_base_allowance`

Sets the spending allowance for the base token. This allowance is required for creating sell orders.\
The amount specified will be approved for use by the smart contract.

#### Parameters:

* `amount` (`Decimal`): The amount of the base token to approve.

#### Example:

```python
order_book.set_base_allowance(amount=Decimal('1000'))
```

***

### `set_quote_allowance`

Sets the spending allowance for the quote token. This allowance is required for creating buy orders.\
The amount specified will be approved for use by the smart contract.

#### Parameters:

* `amount` (`Decimal`): The amount of the quote token to approve.

#### Example:

```python
order_book.set_quote_allowance(amount=Decimal('1000'))
```

***

### `create_buy_order`

Creates a buy order for the specified quantity and price.\
Optionally, the method can automatically set the required allowance if `allowance=True`.

#### Parameters:

* `quantity` (`Decimal`): The amount of the base token to buy.
* `price` (`Decimal`): The price per unit of the base token in terms of the quote token.
* `auto_allowance` (`bool`, optional): Automatically sets the required allowance for the quote token. Defaults to `True`.

#### Example:

```python
order_book.create_buy_order(quantity=Decimal('10'), price=Decimal('1.5'), auto_allowance=True)
```

***

### `create_sell_order`

Creates a sell order for the specified quantity and price.\
Optionally, the method can automatically set the required allowance if `allowance=True`.

#### Parameters:

* `quantity` (`Decimal`): The amount of the base token to sell.
* `price` (`Decimal`): The price per unit of the base token in terms of the quote token.
* `auto_allowance` (`bool`, optional): Automatically sets the required allowance for the base token. Defaults to `True`.

#### Example:

```python
order_book.create_sell_order(quantity=Decimal('5'), price=Decimal('2.0'), auto_allowance=True)
```

***

### `cancel_buy_order`

Cancels an existing buy order using its unique order ID.

#### Parameters:

* `order_id` (`int`): The ID of the buy order to cancel.

#### Example:

```python
order_book.cancel_buy_order(order_id=1234)
```

***

### `cancel_sell_order`

Cancels an existing sell order using its unique order ID.

#### Parameters:

* `order_id` (`int`): The ID of the sell order to cancel.

#### Example:

```python
order_book.cancel_sell_order(order_id=5678)
```

***

### Notes on Usage

1. **Allowances**:\
   Before creating buy or sell orders, ensure sufficient allowances are set for the respective tokens. If `auto_allowance=True` is passed during order creation, the SDK will handle this step automatically.
2. **Balances**:\
   Always check your token balances using `get_balance()` to ensure you have sufficient funds to place orders.
3. **Order Cancellation**:\
   Use the respective `cancel_buy_order` or `cancel_sell_order` methods to cancel pending orders. Ensure the correct order ID is provided.
4. **Error Handling**:\
   All methods interact with the blockchain. Ensure your wallet is funded with sufficient MATIC to cover gas fees for these transactions.


---

# Agent Instructions: 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:

```
GET https://docs.21x.eu/sdk/04-contract.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
