> For the complete documentation index, see [llms.txt](https://docs.21x.eu/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.21x.eu/integration-guide/21x-integration-guide.md).

# 21X Integration Guide

A reference for partners connecting to 21X.

## 1. Introduction <a href="#id-1-introduction" id="id-1-introduction"></a>

21X is a multi-chain regulated exchange. Secondary-market trading is executed on a smart-contract orderbook, with each trading pair pinned to a specific blockchain. Two chains are exposed in the proof-of-concept (POC) environment:

* **Polygon Amoy** - EVM orderbook contract, ERC-20 token approvals, EVM transactions.
* **Stellar Testnet** - Soroban orderbook contract, Soroban token approvals, Soroban contract invocations.

The 21X REST API (Market View) is the single source for trading-pair discovery across both chains. It returns the target chain, the orderbook and token contract addresses, the scaling factors used to encode orders, the trading status, and public market data.

> Order placement and cancellation are not REST operations. Both chains require the trading wallet to sign and submit a blockchain transaction directly to the active orderbook contract. REST is used for discovery and market visibility only.

## 2. Getting started <a href="#id-2-getting-started" id="id-2-getting-started"></a>

Before integrating, complete the following:

1. Confirm which chains and trading pairs your integration will cover. Each pair is bound to either Polygon Amoy or Stellar Testnet; you must support the chain associated with each pair you trade.
2. Prepare a scripting language of your choice (Python, TypeScript, Java, Go).
3. Prepare a REST API client such as Postman to test market-data calls and inspect responses.
4. For Polygon: prepare an EVM wallet on Polygon Amoy with POL test gas, and an EVM library such as ethers.js, web3.js, viem, or web3.py.
5. For Stellar: install the Stellar CLI or a Soroban-capable SDK, and prepare a funded testnet account.
6. Coordinate with 21X to obtain whitelist/client authorization on the target orderbooks and beneficiary or trustline authorization on the relevant tokens.
7. Verify the discovered `orderBookVersion` and load the matching canonical contract ABI. This guide supports EVM orderbook `1.2.0` and Stellar orderbook `1.2.0`; fail closed on an unsupported version.
8. Record the exact versions of every tool and SDK your integration is validated against (Stellar CLI, ethers.js, web3 library, language runtime) and pin them in your build. CLI output formats and SDK APIs change between versions; an integration validated against one version is not automatically valid against another. The JavaScript examples in this guide use the **ethers v6** API (`ethers.JsonRpcProvider`, `AbiCoder.defaultAbiCoder()`); they do not run unmodified on ethers v5.

> **Production note.** Production REST URLs, contract addresses, custody and signing requirements, and authentication and onboarding details must be obtained from 21X before go-live. Do not hardcode POC contract addresses in production systems.

## 3. How to connect <a href="#id-3-how-to-connect" id="id-3-how-to-connect"></a>

21X exposes two integration surfaces relevant to this guide:

1. **REST API.** Provides access to structured market data, including instrument metadata, contract addresses, scales, public orderbook snapshots, price levels, reference prices, and trade information.
2. **Smart contract interface.** Used for direct on-chain interactions, particularly for executing secondary-market orders and cancellations.

The high-level integration flow is the same for both chains:

```
Discover the pair via REST
  -> read chain, contract addresses, scales, limits, status, and fees
  -> prepare wallet/account and permissions on the target chain
  -> verify the orderbook version and load its canonical ABI/interface
  -> fund native fees and trading-token balances
  -> approve the orderbook to transfer or lock the relevant tokens
  -> encode the order using the target chain's expected format
  -> simulate or dry-run the transaction
  -> submit the blockchain transaction
  -> monitor events, balances, REST market data, and order history
  -> cancel pending orders when needed
```

### 3.1 REST environment <a href="#id-31-rest-environment" id="id-31-rest-environment"></a>

```
POC REST base URL
https://ex.str2.poc.21x.eu/api/v1/

Primary pair discovery
GET https://ex.str2.poc.21x.eu/api/v1/tradingpairs
```

### 3.2 Polygon Amoy environment <a href="#id-32-polygon-amoy-environment" id="id-32-polygon-amoy-environment"></a>

```
Network:           Polygon Amoy testnet
Chain ID:          80002
Native gas token:  POL / MATIC test token
RPC URL:           https://rpc-amoy.polygon.technology
POC pair:          USMO / 21XUSDQ
```

### 3.3 Stellar Testnet environment <a href="#id-33-stellar-testnet-environment" id="id-33-stellar-testnet-environment"></a>

```
Network:             Stellar Testnet
Network passphrase:  Test SDF Network ; September 2015
RPC URL:             https://soroban-testnet.stellar.org
POC pair:            XAMA1 / XUSDT
```

## 4. Market View (REST) <a href="#id-4-market-view-rest" id="id-4-market-view-rest"></a>

Use the REST API to discover active instruments, target chains, orderbook contracts, token contracts, scales, limits, fees, market status, and public orderbook state. The `blockChain` field on each pair determines whether the order is executed on Polygon or Stellar.

> **Units in REST responses.** All prices, order values, and reference prices in REST responses are **human-readable decimal strings** - for example `"100.00"`, `"10000000.00"` - not scaled integers. Scale factors themselves are returned as strings (for example `"1000"`). Scaled integers appear only in on-chain order encoding (§5.5) and in on-chain events. Do not apply the internal scales to REST values.

### 4.1 Discovering pairs <a href="#id-41-discovering-pairs" id="id-41-discovering-pairs"></a>

```
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs" | jq .
```

The response is an object, not a top-level array:

```
{
  "items": [ /* one entry per active trading pair */ ],
  "total_count": <integer>
}
```

Iterate over `.items[]` in every example below. A snippet that treats the response as a top-level array (`jq '.[]'`) will return nothing.

### 4.2 Trading pair fields <a href="#id-42-trading-pair-fields" id="id-42-trading-pair-fields"></a>

| Field                                                           | Purpose                                                                                                   |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `id`                                                            | REST trading pair identifier.                                                                             |
| `blockChain`                                                    | Target execution chain, for example `POLYGON_AMOY` or `STELLAR_TESTNET`.                                  |
| `baseTokenData.symbol`                                          | Base asset display symbol.                                                                                |
| `baseTokenData.isin` / `baseTokenData.dti`                      | Instrument identifiers (ISIN, Digital Token Identifier) of the base asset.                                |
| `quoteTokenSymbol`                                              | Quote asset display symbol.                                                                               |
| `quoteTokenEquivalentCurrency`                                  | Fiat currency the quote token represents, for example `USD`.                                              |
| `smartContractOrderBook`                                        | Blockchain address of the orderbook contract. Orders must be sent to this address.                        |
| `smartContractBase`                                             | Blockchain address of the base (financial instrument) token contract.                                     |
| `smartContractQuote`                                            | Blockchain address of the quote (e-money) token contract.                                                 |
| `baseTokenInternalScale`                                        | Scale used for base quantity in order encoding.                                                           |
| `quoteTokenInternalScale`                                       | Scale used for quote price in order encoding.                                                             |
| `baseTokenNativeScale`                                          | Native scale used for base token balances and transfers.                                                  |
| `quoteTokenNativeScale`                                         | Native scale used for quote token balances and transfers.                                                 |
| `minimumOrderValue` / `maximumOrderValue`                       | Pre-trade order value limits.                                                                             |
| `makerCommission` / `takerCommission` / `marketMakerCommission` | Commission parameters. Read per pair - rates differ between pairs and between maker and taker (see §6.5). |
| `tickSizeMode`                                                  | Tick-size regime applied by pre-trade controls, for example `REGULATORY` or `GRANULAR`. See §5.5.         |
| `maximumMatches`                                                | Maximum number of matches a single incoming order may generate (see `MaxMatches` rejection, §7.10).       |
| `liquidityBand`                                                 | Liquidity band used by tick-size and volatility controls.                                                 |
| `staticReferencePrice`                                          | Reference price used by market controls.                                                                  |
| `staticThreshold` / `dynamicThreshold`                          | Volatility-management thresholds.                                                                         |
| `priceCollarFactor`                                             | Pre-trade control parameter.                                                                              |
| `tradingStatus`                                                 | Current trading status. Submit orders only when the market is open or in continuous trading.              |
| `statusChangeReason`                                            | Reason for the last trading-status change, for example `START_OF_TRADING_DAY`.                            |
| `orderBookVersion`                                              | Version of the deployed orderbook contract.                                                               |

**Trading statuses**

`tradingStatus` follows the venue's trading phase lifecycle. The full status set:

| Lifecycle status       | Meaning                                                                             |
| ---------------------- | ----------------------------------------------------------------------------------- |
| Created                | Pair and orderbook deployed but inactive; activated manually by the venue.          |
| Out of Trading         | Active pair outside trading hours.                                                  |
| Continuous Trading     | Market open; the only status in which orders are accepted.                          |
| Automatic Trading Halt | Volatility-triggered halt; resumes automatically (see trading hours below).         |
| Manual Trading Halt    | Halt initiated via the venue's Service Portal (regulatory, technical, capacity, …). |
| Disabled               | Pair deactivated.                                                                   |
| Permanently Deleted    | Terminal state; the pair is offboarded.                                             |

REST renders statuses in upper snake case such as `CONTINUOUS_TRADING`; expect the same convention for the others (for example `OUT_OF_TRADING`). Pairs in `Created`, `Disabled`, or `Permanently Deleted` states are hidden from the venue's trading front end; the REST list contains one entry per **active** pair. Gate order submission on `CONTINUOUS_TRADING` exactly and treat every other value as not-open.

`statusChangeReason` reports why the status last changed, from a fixed list: Start of Trading Day, Manual Market Open, End of Trading Day, Manual Market Close, Regulator/Participant/Venue/Capacity Initiated Halt, Volatility Halt, Technical Halt, Trading Pair Activated/Deactivated/Offboarded, Trading Pair Creation, Automatic Resume. (REST renders these in upper snake case as well - `START_OF_TRADING_DAY` is confirmed live.)

**Trading hours and halts**

* Trading days open at **08:00 CET** and close at **17:00 CET**, observing German daylight-saving time. Pairs do not open on non-working days (weekends, holidays, and venue-defined dates).
* At opening time, pairs in `Out of Trading` or `Automatic Trading Halt` move to `Continuous Trading` and the daily halt counter resets. At closing time, pairs move to `Out of Trading` and the static reference price is set to the last execution price.
* Automatic (volatility) trading halts resume automatically: roughly **5-6 minutes** after the first halt of the day and **15-16 minutes** after the second, provided the halt occurred more than 30 minutes before close. The `tradingHaltCounter` field in `tradeinfo` counts that day's automatic halts.
* **About 5 minutes after closing time, expired orders are cleared** - see §5.4 for how this surfaces on chain.

### 4.3 Selecting the right pair <a href="#id-43-selecting-the-right-pair" id="id-43-selecting-the-right-pair"></a>

There are two ways to resolve a pair, depending on what you already know.

**If the trading pair id is known**, call the single-resource endpoint directly. There is no need to list every pair and filter client-side just to find an id you already have:

```
PAIR_ID="<TRADING_PAIR_ID>"
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs/$PAIR_ID" | jq .
```

**If you are discovering by attributes**, list the pairs and filter by `blockChain`, `baseTokenData.symbol`, and `quoteTokenSymbol` - but do **not** filter by `id` (you do not have one yet):

```

# Discover by chain + exact symbols (no id filter)
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs" | jq '
  .items[]
  | select(.blockChain == "POLYGON_AMOY")
  | select(.baseTokenData.symbol == "USMO")
  | select(.quoteTokenSymbol == "21XUSDQ")
'
```

The POC environment exposes several active pairs across both chains, including pairs whose symbols differ by a single prefix (for example `AMA1/XUSDT` and `XAMA1/XUSDT` are both Stellar Testnet pairs). When discovering by attributes, match all three of `blockChain`, `baseTokenData.symbol`, and `quoteTokenSymbol`. Do not rely on a partial symbol match alone.

> **Read this before hardcoding.** Symbols are not unique across pairs. Once you have resolved a pair, drive the trading flow by its `id`, and treat the addresses returned alongside the id as the source of truth for that environment.

### 4.4 Public market endpoints <a href="#id-44-public-market-endpoints" id="id-44-public-market-endpoints"></a>

```
PAIR_ID="<TRADING_PAIR_ID>"

curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs/$PAIR_ID" | jq .
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs/$PAIR_ID/orderbook?limit=5" | jq .
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs/$PAIR_ID/pricelevels?limit=5" | jq .
curl -s "https://ex.str2.poc.21x.eu/api/v1/tradingpairs/$PAIR_ID/tradeinfo" | jq .
```

**Sample responses**

`orderbook` and `pricelevels` share the same envelope: the pair id plus a `buy` array and a `sell` array. An empty book returns empty arrays (this is the normal state of a quiet POC pair, not an error):

```
{
  "tradingPairId": "<TRADING_PAIR_ID>",
  "buy": [],
  "sell": []
}
```

The entries inside `buy` / `sell` carry price and quantity as human-readable decimal strings, consistent with the units rule at the top of §4. Inspect a live populated response for the exact per-entry field names before writing your parser - place a resting order on your own sandbox pair if every public book is empty.

`tradeinfo` returns last price, reference price, 24-hour change and volume, and trading status:

```
{
  "lastPrice": "100.00",
  "referencePrice": "100.00",
  "priceChange24h": "0.000000",
  "tradeVolume24h": "0",
  "liquidityBand": 5,
  "tradingStatus": "CONTINUOUS_TRADING",
  "statusChangeReason": "START_OF_TRADING_DAY",
  "tradingHaltCounter": 0
}
```

All prices here are human decimals (`"100.00"`), not scaled integers. `tradingHaltCounter` counts the day's automatic trading halts and resets at market open (see §4.2); `statusChangeReason` follows the enum in §4.2.

### 4.5 Pagination and rate limits <a href="#id-45-pagination-and-rate-limits" id="id-45-pagination-and-rate-limits"></a>

The collection response carries a `total_count` field, which implies the endpoint is designed to page. As of this writing, however, the POC `/tradingpairs` endpoint **ignores `limit` and `offset` query parameters** and always returns every active pair in a single page (verified against the live POC: `?limit=1` still returns all items). The `limit` parameter **is** honoured on the `orderbook` and `pricelevels` endpoints, where it bounds the number of levels returned per side.

Code defensively against this changing:

* After fetching `/tradingpairs`, compare `.items | length` against `.total_count`. If they differ, the endpoint has started paging - implement the paging parameters before trusting the list to be complete.
* Do not build logic that depends on receiving all pairs in one response.

Rate limits for the POC REST API are not published. Apply standard client-side discipline: cache pair metadata rather than re-fetching it on every order, throttle polling loops, and back off exponentially on HTTP `429` or `5xx` responses. Confirm production rate limits with 21X before go-live.

### 4.6 POC pairs <a href="#id-46-poc-pairs" id="id-46-poc-pairs"></a>

| Chain             | Pair             | Trading pair id       | Orderbook             |
| ----------------- | ---------------- | --------------------- | --------------------- |
| `POLYGON_AMOY`    | `USMO / 21XUSDQ` | Discover through REST | Discover through REST |
| `STELLAR_TESTNET` | `XAMA1 / XUSDT`  | Discover through REST | Discover through REST |

> **These are examples, not stable identifiers.** Trading pair ids, orderbook addresses, and token contract addresses can change at any time. Deploying or restoring an orderbook can produce a new trading pair id and new contract addresses; token contract addresses change less often, but can also change. Always discover the active values through the REST API for the target environment immediately before trading, and never hardcode the values above into a production system.

### 4.7 REST authentication <a href="#id-47-rest-authentication" id="id-47-rest-authentication"></a>

Public market endpoints - `/tradingpairs`, `/tradingpairs/{id}`, `/orderbook`, `/pricelevels`, `/tradeinfo` - do not require authentication. Participant-scoped endpoints for wallet, order, and trade history require a bearer token issued by 21X to your sandbox account; calls without it return HTTP `401`. Request credentials when you request your sandbox.

> Authenticated history endpoints are out of scope for this guide. On-chain events emitted by the orderbook contract (§6.8 and §7.10) are the primary on-chain observation mechanism for order-state changes, but interpreting them correctly requires the ABI/interface matching the discovered contract version, complete event ingestion, deduplication, and chain-finality handling. Reconcile those events with transaction receipts, balances, and authenticated venue order/trade history when available; do not treat an isolated or unconfirmed event as sufficient evidence of final state.

## 5. Order model <a href="#id-5-order-model" id="id-5-order-model"></a>

### 5.1 Buy and sell <a href="#id-51-buy-and-sell" id="id-51-buy-and-sell"></a>

* **Buy order.** The participant buys the base asset and pays the quote asset. The orderbook may pre-fund or transfer the quote token.
* **Sell order.** The participant sells the base asset and receives the quote asset. The orderbook may lock or transfer the base token, depending on configuration.

When the `side` value appears in events or struct fields, it uses the same enum on both chains:

| Value | Side |
| ----- | ---- |
| `1`   | Buy  |
| `2`   | Sell |

### 5.2 Limit vs market <a href="#id-52-limit-vs-market" id="id-52-limit-vs-market"></a>

<table><thead><tr><th width="88.54547119140625">Value</th><th width="125.42706298828125">Type</th><th>Behaviour</th></tr></thead><tbody><tr><td><code>0</code></td><td>Limit</td><td>The order has a specified price. Any unmatched remainder may rest on the book, depending on the execution condition.</td></tr><tr><td><code>1</code></td><td>Market</td><td>The order executes immediately against available liquidity and does not rest on the book.</td></tr></tbody></table>

> **Market order execution.** Market orders are treated as Immediate or Cancel (IOC) by default: any quantity that cannot be filled immediately is cancelled. If Fill or Kill (FOK) is selected, the market order must execute in full immediately or be rejected.

### 5.3 Execution conditions <a href="#id-53-execution-conditions" id="id-53-execution-conditions"></a>

<table><thead><tr><th width="88.51336669921875">Value</th><th>Name</th><th>Behaviour</th><th>Typical use</th></tr></thead><tbody><tr><td><code>0</code></td><td>Standard</td><td>Match where possible; any unmatched limit remainder rests on the book.</td><td>Normal limit orders.</td></tr><tr><td><code>1</code></td><td>Immediate or Cancel (IOC)</td><td>Match what is immediately available; cancel any unfilled remainder.</td><td>Default condition for market orders; take available liquidity only.</td></tr><tr><td><code>2</code></td><td>Book or Cancel (BOC)</td><td>Rest on the book only if the order would not immediately match. Reject if it would cross.</td><td>Post-only / maker-only orders.</td></tr><tr><td><code>3</code></td><td>Fill or Kill (FOK)</td><td>Execute the full quantity immediately or reject the entire order. No partial fill.</td><td>All-or-nothing immediate execution.</td></tr></tbody></table>

An IOC or FOK order submitted against an empty or non-crossing book is rejected. The transaction itself succeeds and emits an `OrderRejected` event with a `quantity_not_executed` equal to the original quantity.

### 5.4 Validity constraints <a href="#id-54-validity-constraints" id="id-54-validity-constraints"></a>

<table><thead><tr><th width="117.26202392578125">Value</th><th>Name</th><th>Meaning</th></tr></thead><tbody><tr><td><code>0</code></td><td>Good For Day (GFD)</td><td>Default validity for limit orders.</td></tr><tr><td><code>1</code></td><td>Good Till Date (GTD)</td><td>Valid for the number of days specified in the <code>lifetime</code> field.</td></tr></tbody></table>

Rules for `lifetime`:

* Expressed in days. Valid range is **0 to 90**.
* `lifetime = 0` is accepted and behaves as a Good For Day order.
* `lifetime > 90` is invalid and should be rejected by client-side validation before submission.
* The field is only meaningful for limit orders that set `validityConstraints = 1` (GTD).

**How expiry is surfaced.** A GFD or GTD order that reaches its expiry is removed by the venue, not by the participant. Expired orders are cleared by an off-chain venue process **about 5 minutes after the 17:00 CET close** on trading days (§4.2). On chain this appears as an administrative cancellation in a transaction sent by the venue: a `CancelOrder` event with `cancellationType = 1` (`ByAdmin`), returning any pre-funded tokens per the pair configuration. This is distinct from `ByContract` (`2`), which is used when a non-pre-funded order fails its balance/allowance check at matching time (§8.1). Reconciliation logic must therefore treat `CancelOrder` events it did not initiate as a normal terminal state, not as an anomaly - and must not assume every cancellation maps to one of its own `cancel*Order` transactions.

### 5.5 Scaling <a href="#id-55-scaling" id="id-55-scaling"></a>

Orders are encoded with integer values derived from the internal scales returned by REST. Convert human values to scaled integers before encoding:

```
quantityRaw = humanBaseQuantity * baseTokenInternalScale
priceRaw    = humanQuotePrice   * quoteTokenInternalScale
```

Use decimal-safe arithmetic. Do not use binary floating point. Examples:

```
USMO / 21XUSDQ on Polygon Amoy
  baseTokenInternalScale  = 1000
  quoteTokenInternalScale = 100
  1.000 USMO @ 100.00 21XUSDQ
    quantityRaw = 1.000 * 1000 = 1000
    priceRaw    = 100.00 * 100 = 10000

XAMA1 / XUSDT on Stellar Testnet
  baseTokenInternalScale  = 10,000,000
  quoteTokenInternalScale = 10,000,000
  100 XAMA1 @ 1.05 XUSDT
    quantityRaw = 100 * 10,000,000  = 1,000,000,000
    priceRaw    = 1.05 * 10,000,000 = 10,500,000
```

**Exactness, rounding, and tick sizes**

The scaling formulas above only produce valid encodings when the product is an **exact integer**. A price of `1.234` against a quote internal scale of `100` yields `123.4`, which cannot be encoded. Client-side validation must **reject** such inputs rather than silently round or truncate them: a silently rounded price is a different order from the one the user asked for, and a truncated quantity changes the order value checked by pre-trade controls.

```
from decimal import Decimal

def scale_exact(value: str, scale: str) -> int:
    scaled = Decimal(value) * Decimal(scale)
    if scaled != scaled.to_integral_value():
        raise ValueError(f"{value} is not representable at scale {scale}")
    return int(scaled)
```

The internal scale defines the finest representable increment, but the venue may enforce a **coarser tick size** on top of it: each pair carries a `tickSizeMode` (`REGULATORY` or `GRANULAR` in the POC) and a `liquidityBand`, which together determine the price increments pre-trade controls accept. An exactly-scaled price can therefore still be rejected for being off-tick. Request the tick-size table for your pairs from 21X, validate against it client-side, and treat a pre-trade price rejection (§9.4) as the venue-side enforcement of the same rule.

**Internal vs native scales**

A pair carries **two** scale systems and they are not interchangeable:

* **Internal scales** (`baseTokenInternalScale`, `quoteTokenInternalScale`) encode `quantityRaw` and `priceRaw` inside `orderData`. They appear in orderbook events.
* **Native scales** (`baseTokenNativeScale`, `quoteTokenNativeScale`) denominate actual token balances, transfers, approvals, and `Transfer` events.

On some pairs they coincide (XAMA1/XUSDT: both 10,000,000). On others they do not - on USMO/21XUSDQ the quote internal scale is `100` but the quote native scale is `1,000,000`, a factor of 10⁴ apart. A `priceRaw` of `10000` therefore has no direct relationship to the `100,000,000` raw units that move when the trade settles. Use internal scales only for order encoding, native scales for everything that touches balances - including the approval amounts computed in §6.5.

### 5.6 Order lifecycle <a href="#id-56-order-lifecycle" id="id-56-order-lifecycle"></a>

1. Pending orders may lock or transfer the relevant token into the orderbook, depending on the pair configuration.
2. Some pairs do not pre-fund the base token, the quote token, or both. In those configurations, no token is transferred when the order becomes pending.
3. Matching orders settle base and quote token movements on chain. If a pending order is not pre-funded and the required balance is no longer available at matching time, the pending order is cancelled.
4. Cancellation removes the order from the book. Any tokens that were locked or transferred are returned according to the pair configuration.
5. Order ids are emitted by the orderbook in `OrderReceived`, `NewBuyOrder`, and `NewSellOrder` events. Persist them for cancellation and reconciliation.

Matching follows price-time priority: buys are considered from highest price to lowest, sells from lowest price to highest, and orders at the same price are processed FIFO. Market orders match immediately and never become resting orders; any unmatched remainder is rejected.

## 6. Polygon Amoy execution <a href="#id-6-polygon-amoy-execution" id="id-6-polygon-amoy-execution"></a>

Polygon execution uses an EVM orderbook contract. Trading wallets must be whitelisted by 21X for buy, sell, and cancel; restricted tokens additionally require beneficiary status on the receiving wallet.

### 6.1 USMO / 21XUSDQ pair <a href="#id-61-usmo--21xusdq-pair" id="id-61-usmo--21xusdq-pair"></a>

| Field                             | Required value                                            |
| --------------------------------- | --------------------------------------------------------- |
| Trading pair id                   | Read `id` from REST                                       |
| Blockchain                        | `POLYGON_AMOY`                                            |
| Base / quote symbols              | `USMO` / `21XUSDQ`                                        |
| Orderbook                         | Read `smartContractOrderBook` from REST                   |
| Base / quote tokens               | Read `smartContractBase` / `smartContractQuote` from REST |
| Internal and native scales        | Read all four scale fields from REST                      |
| Limits, controls, and commissions | Read the active pair values from REST and `getConfig()`   |
| Orderbook version                 | `1.2.0`                                                   |

> **Discover immediately before trading.** The EVM v1.2 orderbook is non-upgradeable after initialization. Functional changes require a new deployment and controlled migration, which changes the orderbook address and normally the trading pair id. Treat REST discovery as the source of truth and reject an EVM pair whose `orderBookVersion` is not the version your integration supports.

### 6.2 Prerequisites <a href="#id-62-prerequisites" id="id-62-prerequisites"></a>

| Requirement              | What it controls                                                        | Failure mode                                               |
| ------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------- |
| 21X whitelist            | Whether the wallet is allowed to buy, sell, or cancel on the orderbook. | `OrderBook_NotAllowedToBuy` / `OrderBook_NotAllowedToSell` |
| Token beneficiary status | Whether the wallet can receive a restricted token.                      | `Receiver must be a beneficiary`                           |
| ERC-20 allowance         | Whether the orderbook can transfer or lock tokens from the wallet.      | `ERC20InsufficientAllowance`                               |
| Token balance            | Whether the wallet has sufficient base or quote balance for the order.  | `ERC20InsufficientBalance` or simulation revert            |
| Native gas               | POL / MATIC test gas to pay transaction fees.                           | Transaction will not be mined.                             |

For a matched trade, both sides must be authorised to receive the asset they will get on settlement: a buyer must be able to receive the base token, a seller must be able to receive the quote token.

### 6.3 Reading contract state <a href="#id-63-reading-contract-state" id="id-63-reading-contract-state"></a>

Read on-chain configuration and orderbook state with any EVM library. The example below uses ethers.js.

```
import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider("https://rpc-amoy.polygon.technology");
const orderbook = discoveredPair.smartContractOrderBook;
const orderbookAbi = orderBookV1_2Abi; // canonical compiled v1.2 ABI supplied by 21X

const ob = new ethers.Contract(orderbook, orderbookAbi, provider);
console.log(await ob.getOrderBookPhase()); // 1 = open for trading
console.log(await ob.countBuyOrders());
console.log(await ob.countSellOrders());
console.log(await ob.bestBidOffer());
```

The read API also exposes `bestBidOffer`, `bestFiftyOffers`, the static reference price, and the current pre-trade and volatility-management configuration. Use the canonical compiled v1.2 ABI for their exact return structures rather than maintaining handwritten fragments. Treat detailed per-order inspection as a privileged operation: participant reconciliation should use lifecycle events and authenticated history endpoints rather than depend on `getOrderDetails` access.

The Polygon orderbook returns the phase as a `uint8`. Value `1` corresponds to the open / continuous trading state, which is exposed by the REST `tradingStatus` field as `CONTINUOUS_TRADING`. Submit orders only when the contract phase is `1` and the REST status is `CONTINUOUS_TRADING`.

> **Other phase values.** The orderbook contract has four phases, which map onto the venue trading statuses (§4.2): **Open for Trading** (= Continuous Trading), **Closed for Trading** (= Out of Trading and the inactive statuses), **Manual Halt**, and **Automatic Halt**. `1` (Open for Trading) is the only numeric value documented for the POC; gate on `phase === 1` exactly and treat any other value as not-open rather than guessing its numeric meaning.

### 6.4 Order encoding <a href="#id-64-order-encoding" id="id-64-order-encoding"></a>

The EVM v1.2 orderbook accepts between two and six standard ABI slots. Optional fields must be appended in order; they cannot be skipped.

| Position | Field                 | ABI type | Required |
| -------- | --------------------- | -------- | -------- |
| 1        | `quantity`            | `uint64` | Yes      |
| 2        | `price`               | `uint64` | Yes      |
| 3        | `orderType`           | `uint8`  | No       |
| 4        | `executionCondition`  | `uint8`  | No       |
| 5        | `validityConstraints` | `uint8`  | No       |
| 6        | `lifetime`            | `uint8`  | No       |

Accepted encoded lengths are exactly **64, 96, 128, 160, or 192 bytes**. Use `abi.encode`, not `solidityPacked` or manually concatenated compact integers.

Defaulting depends on the number of supplied slots:

<table><thead><tr><th width="206.8536376953125">Slots</th><th>Behaviour</th></tr></thead><tbody><tr><td>2</td><td>Limit, Standard, GFD, lifetime <code>0</code></td></tr><tr><td>3</td><td>Parse <code>orderType</code>; default to IOC for Market and Standard for Limit</td></tr><tr><td>4</td><td>Parse and validate the execution condition</td></tr><tr><td>5</td><td>Parse the validity constraint</td></tr><tr><td>6</td><td>Parse lifetime; require Limit + GTD</td></tr></tbody></table>

Client-side validation must enforce these contract rules:

* `quantity` must be greater than zero.
* A Limit order must have `price > 0`; a Market order may use `price = 0`.
* Market orders permit only IOC or FOK and cannot be GTD.
* A supplied lifetime requires a Limit + GTD order and must be between `0` and `90` days.

Examples:

```
const coder = ethers.AbiCoder.defaultAbiCoder();

// Minimal Standard Limit order.
const limitOrderData = coder.encode(
  ["uint64", "uint64"],
  [quantityRaw, priceRaw]
);

// Explicit IOC Market order. A market price may be zero.
const marketIocOrderData = coder.encode(
  ["uint64", "uint64", "uint8", "uint8"],
  [quantityRaw, 0n, 1, 1]
);

// GTD Limit order with a 30-day lifetime.
const gtdOrderData = coder.encode(
  ["uint64", "uint64", "uint8", "uint8", "uint8", "uint8"],
  [quantityRaw, priceRaw, 0, 0, 1, 30]
);
```

`crossIdentifier` is a separate raw `bytes` argument. It must be either empty (`0x`, interpreted as zero) or exactly four big-endian bytes. Do **not** use `abi.encode(["uint32"], [0])`, which produces a 32-byte value.

```
const crossIdentifier = "0x00000000"; // exactly four bytes
const reportingData = participantReportingData; // bytes format agreed with 21X
```

`crossIdentifier` is an optional client correlation field, not an exchange-side sequence number. Use a non-zero value only when your integration has a defined reconciliation scheme. `reportingData` is also a separate opaque `bytes` argument and is emitted with lifecycle events; use only the participant-specific reporting format agreed with 21X. Do not carry forward an encoding convention from an older SDK without validating it against the current SDK and deployed v1.2 ABI.

### 6.5 Approving tokens <a href="#id-65-approving-tokens" id="id-65-approving-tokens"></a>

Approve the orderbook as ERC-20 spender for each token the wallet must transfer. The buy side approves the quote token; the sell side approves the base token.

**Computing the required amounts**

The sell side is simple: the orderbook pulls the scaled base quantity in **native** units.

```
requiredBaseNative = humanBaseQuantity * baseTokenNativeScale
```

The buy side must cover the order notional **plus commission**, both in **native quote units** - not in the internal units used by `priceRaw`:

```
notionalQuoteNative  = humanBaseQuantity * humanQuotePrice * quoteTokenNativeScale
commissionQuoteNative = notionalQuoteNative * commissionRate        (round UP)
requiredQuoteNative  = notionalQuoteNative + commissionQuoteNative
```

In the POC configuration the commission values returned by REST (`makerCommission`, `takerCommission`) are expressed in **basis points** (1 bp = 0.01%), so `commissionRate = commission / 10000` and the POC value `10` means 0.10%. Confirm the unit and the venue's rounding rules with 21X before go-live - this guide derives the unit from the POC configuration, and a wrong unit makes every approval wrong.

Worked example - buy `1.000 USMO @ 100.00 21XUSDQ` (quote native scale `1,000,000`, taker commission `10` bp):

```
notionalQuoteNative   = 1.000 * 100.00 * 1,000,000          = 100,000,000
commissionQuoteNative = 100,000,000 * 10 / 10000 (round up) =     100,000
requiredQuoteNative   = 100,000,000 + 100,000               = 100,100,000
```

Two practical rules:

* **Do not derive the approval from `priceRaw`.** `priceRaw` uses the quote *internal* scale (`100` on this pair); transfers use the *native* scale (`1,000,000`). On USMO/21XUSDQ they differ by 10⁴ - see §5.5. Compute the approval from human values and the native scale.
* **Size for the worst-case commission.** Which rate applies depends on how the order executes: the portion that matches immediately pays the **taker** rate (the buyer's wallet is debited `rounded(P × Q) × (1 + takerCommission)`), while a remainder that rests on the book is pre-funded at the **maker** rate (`limitPrice × Q × (1 + makerCommission)`). A single order can do both, and rates can differ on the same pair (a live POC pair charges maker `10` / taker `30`) - so use `max(makerCommission, takerCommission)` when sizing approvals. Wallets designated as market makers pay `marketMakerCommission` in both roles instead.

Two settlement details worth knowing (they explain "unexpected" transfer amounts during reconciliation): a pre-funded resting buy that executes below its limit is reimbursed the difference `(limit − executionPrice) × Q × (1 + makerCommission)` from the orderbook, and the venue generally aims to round settlement amounts in the participant's favour. That outcome cannot be guaranteed for every participant in every settlement, so integrations must reconcile the actual token transfers rather than infer them from an assumed rounding direction.

```
import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider("https://rpc-amoy.polygon.technology");
const orderbook = discoveredPair.smartContractOrderBook;
const baseAddress  = discoveredPair.smartContractBase;
const quoteAddress = discoveredPair.smartContractQuote;

const erc20Abi = [
  "function approve(address spender,uint256 amount) returns (bool)",
  "function allowance(address owner,address spender) view returns (uint256)",
  "function balanceOf(address owner) view returns (uint256)",
];

// Signers must be configured through local keys or the partner custody stack.
const buyer  = new ethers.Wallet("<BUYER_PRIVATE_KEY>",  provider);
const seller = new ethers.Wallet("<SELLER_PRIVATE_KEY>", provider);

const quote = new ethers.Contract(quoteAddress, erc20Abi, buyer);
const base  = new ethers.Contract(baseAddress,  erc20Abi, seller);

// Buy 1.000 USMO @ 100.00 21XUSDQ: notional + commission, computed as above.
// The commission rate comes from the pair's makerCommission / takerCommission
// via REST - never a hardcoded constant.
await quote.approve(orderbook, 100_100_000n);

// Sell 1.000 USMO requires 1.000 base = 1000 raw units.
await base.approve(orderbook, 1000n);
```

Approve enough quote balance to cover both the order notional and the commission charged by the orderbook. Approving only the notional results in `ERC20InsufficientAllowance` when the trade settles.

> **Do not hardcode the commission.** The commission applied at settlement comes from the trading pair / orderbook configuration (`makerCommission` / `takerCommission`, exposed via REST and `getConfig`), not from a fixed constant. Any numeric commission shown in this guide is an example only. Read the live rate for the pair when computing the amount to approve - a stale or wrong rate leaves the approval too low (causing `ERC20InsufficientAllowance` at settlement) or unnecessarily high.

### 6.6 Submitting orders <a href="#id-66-submitting-orders" id="id-66-submitting-orders"></a>

Always dry-run with `staticCall` before broadcasting:

```
const orderbookAbi = orderBookV1_2Abi;

const obAsBuyer  = new ethers.Contract(orderbook, orderbookAbi, buyer);
const obAsSeller = new ethers.Contract(orderbook, orderbookAbi, seller);

await obAsBuyer.newBuyOrder.staticCall(limitOrderData, reportingData, crossIdentifier);
await obAsSeller.newSellOrder.staticCall(limitOrderData, reportingData, crossIdentifier);

const buyTx = await obAsBuyer.newBuyOrder(limitOrderData, reportingData, crossIdentifier);
await buyTx.wait();

const sellTx = await obAsSeller.newSellOrder(limitOrderData, reportingData, crossIdentifier);
await sellTx.wait();
```

When a buy rests on the book, quote tokens are transferred or locked. When a matching sell arrives, the trade settles and, on full match, the book returns to empty for that order.

> **Nonce management for sequential orders.** EVM transactions from one wallet execute in strict nonce order. The simple pattern above (`await tx.wait()` between submissions) is safe but serial. If you submit several orders from the same wallet without waiting, assign nonces explicitly (`provider.getTransactionCount(address, "pending")` as the starting point) and remember that one stuck underpriced transaction blocks every transaction behind it - replacing it requires re-sending the same nonce with a higher gas price. For higher throughput, prefer separate wallets per strategy over deep nonce pipelines.

### 6.7 Cancelling orders <a href="#id-67-cancelling-orders" id="id-67-cancelling-orders"></a>

Cancellation is signed by the order owner and submitted as an EVM transaction. `orderId` is read from `OrderReceived`, `NewBuyOrder`, or `NewSellOrder` events emitted when the order was created.

```
const ob = new ethers.Contract(orderbook, orderbookAbi, wallet);

await ob.cancelBuyOrder(59n);
await ob.cancelSellOrder(62n);
```

Only the owning wallet can cancel its own order, and only while the order is still resting on the book. If the order has already been partially matched, cancellation removes only its unfilled resting remainder; quantities already executed are unaffected. Participant cancellation is permitted while the orderbook is open or halted, but not after it has moved to a closed phase. A wallet must also retain its `canCancel` whitelist permission.

### 6.8 Events <a href="#id-68-events" id="id-68-events"></a>

Event declarations, indexed parameters, and data layouts are part of the EVM v1.2 ABI. Load the canonical compiled ABI supplied by 21X and use its `Interface.parseLog` result; do not reconstruct event declarations from an older orderbook or assume an order id occupies a fixed topic position without checking that ABI.

The v1.2 topic-0 hashes are:

| Event                   | Topic-0                                                              |
| ----------------------- | -------------------------------------------------------------------- |
| `OrderRejected`         | `0xfcd67a70002bb36185e01e77ee187a2706e52b209633586cf1b69f48f4ac9e76` |
| `OrderReceived`         | `0xef879ba5489cfede1af80093037c6f791adf833eeaf2906ba0246c2b8471bdb6` |
| `NewBuyOrder`           | `0x8b5f9c7ac27d14b4e56f3c87b39a77847c558bc660e652707b3d0b23596014ac` |
| `NewSellOrder`          | `0x76637075c686328c46606fceeeb7b12e992fcaef62b8ffc59a52f9a66a387bc1` |
| `NewBuyInitiatedTrade`  | `0xc229a3724c975962a62cc8314ab9661c634d2470934872a0ccaa326db36d245a` |
| `NewSellInitiatedTrade` | `0x129eff071abb78edc82828874c6f83f62039874da53a1db79f26d99f796d8d8a` |
| `CancelOrder`           | `0x6a8723de0691c41ddcbfef9ff9b48fdea2bf4203c1cc65d84a0a7ef89563ccae` |

Use these hashes for coarse log filtering and the canonical ABI for decoding. Keeping the ABI artifact with the integration source ensures that event declarations and topics advance together.

Lifecycle:

* `OrderReceived` is emitted when the orderbook accepts the submission for processing. The `side` field follows the enum in §5.1 (`1 = Buy`, `2 = Sell`).
* `OrderRejected` is emitted when submission processing succeeds on chain but matching rules, market controls, or the requested execution condition reject the order or its remainder. Decode the rejection reason and unexecuted quantity from the v1.2 ABI.
* `NewBuyInitiatedTrade` / `NewSellInitiatedTrade` is emitted when an incoming order matches resting liquidity, for the matched quantity. A **fully-matched** incoming order emits `OrderReceived`, the trade-initiated event, and the base/quote token `Transfer` and commission events, but **no** `NewBuyOrder` / `NewSellOrder` - nothing rests on the book.
* `NewBuyOrder` / `NewSellOrder` is emitted when the (remaining) order rests on the book. A **partial match** emits the trade-initiated event for the matched quantity and `NewBuyOrder` / `NewSellOrder` for the residual that rests.
* `CancelOrder` is emitted when an order is removed; `token` and `toAddress` identify the asset returned and the receiving wallet.
* Token `Transfer` events from the base or quote ERC-20 contract are emitted alongside lifecycle events and reflect the actual balance movements.

> **Execution price vs limit price.** The matching engine uses **single-price execution**: however many resting orders an incoming order matches, the entire execution happens at one price. That price is the **last execution price, clamped into the range the participating orders' limits allow** - for an incoming buy, between the highest collected sell limit (lower bound) and the incoming buy's own limit (upper bound); mirrored for an incoming sell. The venue picks the price that moves the market as little as possible, so the fill price is frequently *neither* side's limit price (an incoming buy at 101 against a resting sell at 99 executes at the last execution price if it lies between 99 and 101). Never assume your limit price is the fill price. Reconcile actual execution economics against the token `Transfer` amounts in the same transaction: the venue computes the rounded order value `rounded(P × Q)` plus commission and generally aims to round in the participant's favour, but that direction is not guaranteed for every participant in every settlement.

**Monitoring events in production**

The examples in this guide read events from the transaction receipt of the participant's own submission. That covers self-initiated actions only. Resting orders also change state through **other parties' transactions** - a fill arrives in the counterparty's transaction, an expiry in a venue transaction - so a production integration must watch the orderbook contract itself:

* **Polling:** `eth_getLogs` over bounded block ranges with `address = orderbook` and the v1.2 event topic-0 values above. Decode with the canonical ABI, then filter for the participant address and order ids. Add an indexed participant topic filter only if the canonical ABI confirms its position. Persist the last processed block number and resume from it.
* **Streaming:** a WebSocket subscription (`contract.on(...)` over a `WebSocketProvider`) for low latency, always backed by an `eth_getLogs` catch-up on reconnect - subscriptions drop silently.
* **Reorg safety:** Polygon Amoy can reorganise recent blocks. Treat events as tentative until a confirmation depth your risk tolerance accepts, and key your event store by `(transactionHash, logIndex)` so replayed logs deduplicate.

### 6.9 Allowance behaviour <a href="#id-69-allowance-behaviour" id="id-69-allowance-behaviour"></a>

EVM v1.2 supports pre-funded and no-prefund configurations. Read `getConfig()` for the active deployment and treat `staticCall` as the authoritative preflight check; do not infer funding behavior from the chain.

In pre-funded mode, the orderbook calls `transferFrom` when an order rests: a sell moves base tokens and a buy moves quote tokens plus the applicable commission. The ERC-20 allowance is consumed. Cancellation returns locked tokens but does **not** restore that allowance, so re-approve or maintain sufficient standing approval for expected churn.

In no-prefund mode, an order may rest without moving tokens. Balance and allowance must still be available when matching occurs. If they are insufficient, the order may be cancelled by the contract while matching continues with other eligible liquidity. See §8.1.

## 7. Stellar Testnet execution <a href="#id-7-stellar-testnet-execution" id="id-7-stellar-testnet-execution"></a>

Stellar execution uses a Soroban orderbook contract. Compared to the Polygon flow, Stellar additionally requires trustlines for non-native assets and uses an `expiration_ledger` on token approvals.

### 7.1 XAMA1 / XUSDT pair <a href="#id-71-xama1--xusdt-pair" id="id-71-xama1--xusdt-pair"></a>

| Field                         | Value                                                      |
| ----------------------------- | ---------------------------------------------------------- |
| Trading pair id               | `50a1b1ec-b46a-459e-9359-57412351e45f`                     |
| Blockchain                    | `STELLAR_TESTNET`                                          |
| Orderbook                     | `CCGMSRH63Z7SAQVRH3O4VHOXMLWJZ2MOYWHWMQF7RKUJCBUYWWBQ35RQ` |
| Base token                    | `CCAVB4PVYQED74TETVAPWS3MIRSITNKQFVB7Q6WPTSTMJF3WFATTRHO3` |
| Quote token                   | `CBU53REE7UH7DHI2DEZXTRXMTJJS5FODBDMO7M7H6EGVUXEG5ZJSARKK` |
| Base symbol                   | `XAMA1`                                                    |
| Quote symbol                  | `XUSDT`                                                    |
| Base internal / native scale  | `10,000,000` / `10,000,000`                                |
| Quote internal / native scale | `10,000,000` / `10,000,000`                                |
| Minimum order value           | `20.0000000`                                               |
| Maximum order value           | `1000000000.0000000`                                       |
| Maker / taker commission      | `10` / `30`                                                |
| Trading status                | `CONTINUOUS_TRADING`                                       |
| Orderbook version             | `1.2.0`                                                    |

> **These are examples, not stable identifiers.** The trading pair id and the orderbook, base, and quote contract addresses above can change at any time - a redeployed orderbook produces a new trading pair id and new contract addresses. Discover the active values through the REST API (§4.3) immediately before trading; do not hardcode them.

### 7.2 Stellar CLI setup <a href="#id-72-stellar-cli-setup" id="id-72-stellar-cli-setup"></a>

Install the Stellar CLI and confirm the version:

```
stellar --version
```

> **Pin the CLI version.** Record the exact CLI version your integration is validated against and pin it in your tooling. The CLI's human-readable output (ledger headers, event rendering, simulation summaries) is not a stable interface and changes between releases - anything that parses CLI output (§7.4, §7.10) is sensitive to upgrades. Re-validate output parsing whenever you bump the CLI.

Configure the testnet network:

```
stellar network add testnet \
  --rpc-url "https://soroban-testnet.stellar.org" \
  --network-passphrase "Test SDF Network ; September 2015"
```

Import or generate a local signing identity:

```

# Existing secret key
printf '%s' '<STELLAR_SECRET_KEY>' | stellar keys add my-test-account --secret-key --overwrite


# Or generate and fund a new test account
stellar keys generate my-test-account --network testnet --fund
```

The local alias (for example `my-test-account`) is used as the `--source-account` on every contract invocation.

**`--source-account` vs `--user`**

The orderbook methods take an explicit `user: Address` parameter. The CLI also takes a `--source-account` flag for the local signing identity. The two must be reconciled:

* **`--source-account`** is the local alias that signs and broadcasts the transaction. The corresponding account pays the network fee.
* **`--user`** is the on-chain Stellar address whose action this is. The orderbook resolves the participant against its client registry using this value, and the contract calls `require_auth(user)`.

For a self-trading flow, set `--source-account` and `--user` to the same identity; the source signature satisfies `require_auth(user)` and the orderbook reads the participant's client info for the same address. For a custodial flow where the trading account is signed for by a different submitter, the `user` must additionally provide a Soroban authorization entry for the call. The participant whitelist applies to `--user`, not to `--source-account`.

### 7.3 Trustlines and authorization <a href="#id-73-trustlines-and-authorization" id="id-73-trustlines-and-authorization"></a>

Trustlines and allowances are independent prerequisites:

| Requirement       | What it does                                                                                | Why it matters                                                 |
| ----------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| Trustline         | Allows the Stellar account to hold a non-native asset.                                      | Required before the account can receive or hold the asset.     |
| 21X authorization | Issuer / whitelist permission for the participant.                                          | Required before the orderbook accepts orders from the account. |
| Allowance         | Permits the orderbook to transfer the participant's token balance up to an approved amount. | Required before the orderbook can lock or pre-fund tokens.     |

The orderbook participant interface uses a `ClientInformation` structure for permissioning:

```
pub struct ClientInformation {
    pub can_buy: bool,
    pub can_cancel: bool,
    pub can_sell: bool,
    pub can_transfer: bool,
    pub client: Address,
    pub id: u64,
    pub is_market_maker: bool,
}
```

If the participant is not registered or lacks a permission, order placement fails with `ClientNotFound`, `NotAllowedToBuy`, `NotAllowedToSell`, or `NotAllowedToCancel`.

Create trustlines and check authorization and balances:

```
USER="<USER_G_ADDRESS>"
ORDERBOOK="<smartContractOrderBook>"
BASE="<smartContractBase>"
QUOTE="<smartContractQuote>"
ALIAS="<LOCAL_SIGNING_ALIAS>"


# Trustlines are safe to repeat.
stellar contract invoke --network testnet --id "$BASE" \
  --source-account "$ALIAS" --send=yes -- trust --addr "$USER"
stellar contract invoke --network testnet --id "$QUOTE" \
  --source-account "$ALIAS" --send=yes -- trust --addr "$USER"


# Confirm token authorization and balances.
stellar contract invoke --network testnet --id "$BASE" \
  --source-account "$ALIAS" --send=no -- authorized --id "$USER"
stellar contract invoke --network testnet --id "$QUOTE" \
  --source-account "$ALIAS" --send=no -- authorized --id "$USER"

stellar contract invoke --network testnet --id "$BASE" \
  --source-account "$ALIAS" --send=no -- balance --id "$USER"
stellar contract invoke --network testnet --id "$QUOTE" \
  --source-account "$ALIAS" --send=no -- balance --id "$USER"
```

### 7.4 Allowances <a href="#id-74-allowances" id="id-74-allowances"></a>

Soroban approvals carry an `expiration_ledger`. Read the latest testnet ledger and pick a future ledger high enough for the intended trading window:

```
CURRENT_LEDGER="$(stellar ledger latest --network testnet | awk '/Sequence:/ {print $2}')"
EXPIRATION_LEDGER="$((CURRENT_LEDGER + 100000))"
ALLOWANCE="1000000000000"

stellar contract invoke --network testnet --id "$BASE" \
  --source-account "$ALIAS" --send=yes -- approve \
  --from "$USER" --spender "$ORDERBOOK" \
  --amount "$ALLOWANCE" \
  --expiration_ledger "$EXPIRATION_LEDGER"

stellar contract invoke --network testnet --id "$QUOTE" \
  --source-account "$ALIAS" --send=yes -- approve \
  --from "$USER" --spender "$ORDERBOOK" \
  --amount "$ALLOWANCE" \
  --expiration_ledger "$EXPIRATION_LEDGER"

stellar contract invoke --network testnet --id "$BASE" \
  --source-account "$ALIAS" --send=no -- allowance \
  --from "$USER" --spender "$ORDERBOOK"
stellar contract invoke --network testnet --id "$QUOTE" \
  --source-account "$ALIAS" --send=no -- allowance \
  --from "$USER" --spender "$ORDERBOOK"
```

> The `awk '/Sequence:/'` extraction above parses the CLI's human-readable output, which is not a stable interface (see §7.2). If your CLI version offers a JSON output mode for ledger queries, prefer it; in SDK-based integrations, read the latest ledger from the Soroban RPC (`getLatestLedger`) instead of shelling out to the CLI.

Approve **both** the base token (used by sell-side flows) and the quote token (used by buy-side flows). Refresh allowances before they expire or run out.

The CLI returns the allowance as a single numeric amount (for example `"10000000000"`). The associated `expiration_ledger` is internal state and is not echoed back; track it locally when you set the allowance.

> **Pre-fund configuration.** Whether an order is pre-funded at placement or only at matching is determined by the orderbook's pre-funding configuration (`no_prefund_config` in `get_config`), not by the chain. Where the active configuration permits it, a sell order can be accepted without an immediate base-token transfer. Do not rely on any single behaviour globally - always read `get_config` and treat the simulation result as authoritative for the current orderbook deployment. See §8.1 for the full set of pre-funding options.

### 7.5 Inspecting the orderbook <a href="#id-75-inspecting-the-orderbook" id="id-75-inspecting-the-orderbook"></a>

Participant-facing orderbook methods:

```
fn new_buy_order  (user: Address, order_data: Bytes, cross_identifier: Bytes, reporting_data: Bytes);
fn new_sell_order (user: Address, order_data: Bytes, cross_identifier: Bytes, reporting_data: Bytes);
fn cancel_buy_order  (user: Address, order_id: u64);
fn cancel_sell_order (user: Address, order_id: u64);
```

View / configuration methods:

```
fn get_config()           -> OrderBookConfigData;
fn get_order_book_phase() -> OrderBookPhase;     // string enum, e.g. "OpenForTrading"
fn count_buy_orders()     -> u64;
fn count_sell_orders()    -> u64;
fn best_bid_offer()       -> U256;
fn best_fifty_offers()    -> (Vec<U256>, Vec<U256>);
```

The CLI renders `get_order_book_phase` as a quoted string (for example `"OpenForTrading"`), not as the integer used by the Polygon orderbook. Compare against the string symbol when gating order placement. The contract phase model is the same four-state machine as on Polygon (§6.3): Open for Trading, Closed for Trading, Manual Halt, Automatic Halt. `"OpenForTrading"` is the only string rendering confirmed for the POC; treat any other value as not-open.

Inspect the deployed interface, phase, and configuration with the CLI:

```
stellar contract invoke --network testnet \
  --id "$ORDERBOOK" --source-account "$ALIAS" --send=no -- --help

stellar contract invoke --network testnet \
  --id "$ORDERBOOK" --source-account "$ALIAS" --send=no -- get_order_book_phase

stellar contract invoke --network testnet \
  --id "$ORDERBOOK" --source-account "$ALIAS" --send=no -- get_config
```

### 7.6 Order encoding <a href="#id-76-order-encoding" id="id-76-order-encoding"></a>

Although `order_data` is a Soroban `Bytes` value, the 21X orderbook expects **EVM-style 32-byte padded words**. Do **not** encode as compact `u64 || u64` bytes.

Field layout:

| Position | Field                 | Type                     | Description                                      |
| -------- | --------------------- | ------------------------ | ------------------------------------------------ |
| 1        | `quantity`            | `uint64` as 32-byte word | Scaled base quantity.                            |
| 2        | `price`               | `uint64` as 32-byte word | Scaled quote price.                              |
| 3        | `orderType`           | `uint8` as 32-byte word  | `0 = Limit`, `1 = Market`.                       |
| 4        | `executionCondition`  | `uint8` as 32-byte word  | `0 = Standard`, `1 = IOC`, `2 = BOC`, `3 = FOK`. |
| 5        | `validityConstraints` | `uint8` as 32-byte word  | `0 = GFD`, `1 = GTD`.                            |
| 6        | `lifetime`            | `uint8` as 32-byte word  | GTD lifetime in days. Valid range `0-90`.        |

**Common encodings**

```
Minimal standard limit order
  word32(quantity) || word32(price)

Explicit standard limit order
  word32(quantity) || word32(price) || word32(0) || word32(0)

Explicit BOC limit order
  word32(quantity) || word32(price) || word32(0) || word32(2)

Explicit IOC limit order
  word32(quantity) || word32(price) || word32(0) || word32(1)

Explicit FOK limit order
  word32(quantity) || word32(price) || word32(0) || word32(3)

Explicit GTD limit order
  word32(quantity) || word32(price) || word32(0) || word32(executionCondition)
   || word32(1) || word32(lifetime_days)
```

Defaults when fields are omitted: `orderType = 0` (Limit), `executionCondition = 0` (Standard), `validityConstraints = 0` (GFD), `lifetime = 0`.

The contract accepts payloads containing two through six complete 32-byte words; omitted trailing fields take the defaults above. If a sixth `lifetime` word is present, `validityConstraints` must be `1` (GTD). Do not explicitly encode a sixth lifetime word for GFD, even when the value is zero.

**Python helper**

```
from decimal import Decimal

def word32(value: int) -> str:
    return int(value).to_bytes(32, "big").hex()

def scale_decimal(value: str, internal_scale: str) -> int:
    scaled = Decimal(value) * Decimal(internal_scale)
    if scaled != scaled.to_integral_value():
        raise ValueError(f"{value} is not representable at scale {internal_scale}")
    return int(scaled)

def encode_order_data(
    quantity: str,
    price: str,
    base_scale: str,
    quote_scale: str,
    order_type: int = 0,
    execution_condition: int = 0,
    validity_constraints: int = 0,
    lifetime: int = 0,
) -> str:
    if order_type not in (0, 1):
        raise ValueError("order_type must be 0 (Limit) or 1 (Market)")
    if execution_condition not in (0, 1, 2, 3):
        raise ValueError("execution_condition must be 0, 1, 2, or 3")
    if validity_constraints not in (0, 1):
        raise ValueError("validity_constraints must be 0 (GFD) or 1 (GTD)")
    if order_type == 1 and execution_condition not in (1, 3):
        raise ValueError("market orders require IOC (1) or FOK (3)")
    if order_type == 1 and validity_constraints != 0:
        raise ValueError("market orders cannot be GTD")
    if validity_constraints == 0 and lifetime != 0:
        raise ValueError("lifetime is only valid for GTD orders")
    if validity_constraints == 1 and not 0 <= lifetime <= 90:
        raise ValueError("GTD lifetime must be between 0 and 90 days")

    quantity_i = scale_decimal(quantity, base_scale)
    price_i    = scale_decimal(price,    quote_scale)
    if quantity_i <= 0:
        raise ValueError("quantity must be greater than zero")
    if order_type == 0 and price_i <= 0:
        raise ValueError("limit order price must be greater than zero")
    if order_type == 1 and price_i < 0:
        raise ValueError("market order price cannot be negative")
    words = [
        word32(quantity_i),
        word32(price_i),
        word32(order_type),
        word32(execution_condition),
    ]
    if validity_constraints == 1:
        words.extend([
            word32(validity_constraints),
            word32(lifetime),
        ])
    return "".join(words)


# Example: 100 XAMA1 @ 1.05 XUSDT, Standard limit
order_data = encode_order_data(
    quantity="100",
    price="1.05",
    base_scale="10000000",
    quote_scale="10000000",
)
print(order_data)
```

This helper intentionally emits four words for a non-GTD order and six for GTD. The contract also accepts the shorter defaulted forms described above. `scale_decimal` rejects values that do not scale to an exact integer (§5.5).

**Validating `order_data`**

Validate the encoded payload before invoking the orderbook. Valid payloads contain two through six complete 32-byte words: **128, 192, 256, 320, or 384 hex characters**. Manually editing hex strings is a frequent source of malformed payloads - generate the value from decimal inputs instead.

```
ORDER_DATA="<ORDER_DATA_HEX>"

case "${#ORDER_DATA}" in
  128|192|256|320|384) ;;
  *) echo "Invalid order_data hex length: ${#ORDER_DATA}" >&2; exit 1 ;;
esac

case "$ORDER_DATA" in
  (*[!0-9a-fA-F]*) echo "Invalid order_data: expected hex only" >&2; exit 1 ;;
esac
```

A one-character truncation is enough to fail Soroban `Bytes` parsing before simulation. Fail fast on the client.

### 7.7 cross\_identifier and reporting\_data <a href="#id-77-cross_identifier-and-reporting_data" id="id-77-cross_identifier-and-reporting_data"></a>

`cross_identifier` is raw bytes that must decode to a `u32`. It may be empty (interpreted as zero) or exactly **4 bytes** of big-endian hex; any other length fails with `InvalidInputOrderData (#2004)`.

```
<empty>   -> 0
00000000  -> 0
```

**Default scheme.** Use `00000000` when an explicit zero value is preferable. `cross_identifier` is an optional field used in self-trade scenarios; request additional information from 21X when defining a non-zero scheme.

`reporting_data` is a raw bytes field for reporting and attribution metadata. As on Polygon (§6.4), the 21X backend interprets and attempts to match the two lowest 32-bit values within it, while all remaining bits are free for participant-defined use and need not be zero - an optional place to carry your own internal reference (for example a correlation id or GUID). **Default scheme:** use the placeholder value `00` for sandbox integrations; this is accepted by the POC orderbook. The sandbox identity already includes the `00` placeholder, so a working integration can be built before any participant-specific reporting scheme is finalised.

> The same defaulting approach applies on Polygon to `reportingData` and `crossIdentifier`. Use the zero-placeholder shapes shown in §6.4 unless 21X provides a production reporting or correlation scheme.

### 7.8 Submitting orders <a href="#id-78-submitting-orders" id="id-78-submitting-orders"></a>

Always simulate with `--send=no` before submitting with `--send=yes`:

```
stellar contract invoke \
  --network testnet \
  --id "$ORDERBOOK" \
  --source-account "$ALIAS" \
  --send=no \
  -- new_sell_order \
  --user "$USER" \
  --order_data "$ORDER_DATA" \
  --cross_identifier "$CROSS_IDENTIFIER" \
  --reporting_data "$REPORTING_DATA"
```

Sell example - `100 XAMA1 @ 1.20 XUSDT`, Standard limit:

```
ORDERBOOK="CCGMSRH63Z7SAQVRH3O4VHOXMLWJZ2MOYWHWMQF7RKUJCBUYWWBQ35RQ"
USER="<USER_G_ADDRESS>"
ORDER_DATA="000000000000000000000000000000000000000000000000000000003b9aca000000000000000000000000000000000000000000000000000000000000b71b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
CROSS_IDENTIFIER="00000000"
REPORTING_DATA="00"

stellar contract invoke --network testnet --id "$ORDERBOOK" \
  --source-account "$ALIAS" --send=yes \
  -- new_sell_order \
  --user "$USER" \
  --order_data "$ORDER_DATA" \
  --cross_identifier "$CROSS_IDENTIFIER" \
  --reporting_data "$REPORTING_DATA"
```

Buy example - `100 XAMA1 @ 0.80 XUSDT`, Standard limit:

```
ORDER_DATA="000000000000000000000000000000000000000000000000000000003b9aca0000000000000000000000000000000000000000000000000000000000007a120000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
CROSS_IDENTIFIER="00000000"

stellar contract invoke --network testnet --id "$ORDERBOOK" \
  --source-account "$ALIAS" --send=yes \
  -- new_buy_order \
  --user "$USER" \
  --order_data "$ORDER_DATA" \
  --cross_identifier "$CROSS_IDENTIFIER" \
  --reporting_data "$REPORTING_DATA"
```

> **Sequence numbers and retries.** Each Stellar transaction consumes the source account's sequence number, so transactions from one source account are strictly serialised - submit one at a time and wait for the result before the next, or use distinct source accounts (channel accounts) for parallel submission. If the RPC responds with `TRY_AGAIN_LATER` or `tryAgainLater`, the transaction was **not** accepted: rebuild it against the current sequence number and resubmit with backoff. A transaction also carries an expiry (time bounds / max ledger); once that passes without inclusion, it can never be applied, which makes "expired" a safe signal that the order was not placed.

### 7.9 Cancelling orders <a href="#id-79-cancelling-orders" id="id-79-cancelling-orders"></a>

Cancellation is a Soroban call signed by the order owner. Persist `order_id` from the `OrderReceived` event when the order is placed.

```

# Simulate
stellar contract invoke --network testnet --id "$ORDERBOOK" \
  --source-account "$ALIAS" --send=no \
  -- cancel_sell_order --user "$USER" --order_id "$ORDER_ID"


# Submit
stellar contract invoke --network testnet --id "$ORDERBOOK" \
  --source-account "$ALIAS" --send=yes \
  -- cancel_sell_order --user "$USER" --order_id "$ORDER_ID"
```

Use `cancel_buy_order` for buy-side cancellation. Participant cancellation requires the order owner, `can_cancel` permission, and an orderbook phase that is open or halted; it is not available after the market moves to a closed phase. Cancelling a non-existent or already-cancelled order id fails with `NoSuchOrderId (#8)`; keep client-side order state idempotent.

### 7.10 Events and rejections <a href="#id-710-events-and-rejections" id="id-710-events-and-rejections"></a>

Soroban events are emitted as a **topic vector** plus a **data vec**. The Rust struct in the contract source defines the conceptual fields, but the on-chain emission places the most important participant-facing fields in the topic vector for cheap filtering, and the rest in the data body. For the v1.2 interface, treat the topic vector as the canonical field location: the order id, in particular, is a topic, not a data field, and parsers that look for a named `order_id` JSON key in the body will not find it.

**Topic vector layout**

| Event           | topic\[0]                | topic\[1]        | topic\[2]      |
| --------------- | ------------------------ | ---------------- | -------------- |
| `OrderReceived` | `symbol "OrderReceived"` | `address client` | `u64 order_id` |
| `NewBuyOrder`   | `symbol "NewBuyOrder"`   | `address client` | -              |
| `NewSellOrder`  | `symbol "NewSellOrder"`  | `address client` | -              |
| `CancelOrder`   | `symbol "CancelOrder"`   | `address client` | `u64 order_id` |
| `OrderRejected` | `symbol "OrderRejected"` | `address client` | `u64 order_id` |

For `NewBuyOrder` and `NewSellOrder` the `order_id` is the first `u64` in the data body (alongside `quantity`, `price`, and `event_id`). Always read it from there for these two events, and from `topic[2]` for the others.

**Sample payloads**

```
// new_sell_order - resting on the book
topics: [{"symbol":"OrderReceived"}, {"address":"<client>"}, {"u64":"<order_id>"}]
data  : vec[ u64 quantity, u64 price, ..contract-specific.. , u128 event_id ]

topics: [{"symbol":"NewSellOrder"}, {"address":"<client>"}]
data  : vec[ u64 order_id, u64 quantity, u64 price, u128 event_id ]

// cancel_sell_order
topics: [{"symbol":"CancelOrder"}, {"address":"<client>"}, {"u64":"<order_id>"}]
data  : vec[ u64 quantity, u64 price, u32 cancellation_type, address token, address to_address, u128 event_id ]
```

The data-body ordering is contract-specific and may evolve across orderbook versions. Use the topic vector for the order id; use the data body for the trade-level numbers (quantity, price) and only as far as your integration genuinely needs them.

**Reference enums**

```
pub enum OrderKind     { Buy = 1, Sell = 2 }
pub enum OrderType     { Limit = 0, Market = 1 }
pub enum CancellationType { ByParticipant = 0, ByAdmin = 1, ByContract = 2 }

pub enum RejectionReasons {
    None = 0,
    SelfTrade = 1,
    MaxMatches = 2,
    CircuitBreakerPriceOutOfMaximumStaticRange  = 3,
    CircuitBreakerPriceOutOfMinimumStaticRange  = 4,
    CircuitBreakerPriceOutOfMaximumDynamicRange = 5,
    CircuitBreakerPriceOutOfMinimumDynamicRange = 6,
    PartialRejected = 7,
    FullyRejected   = 8,
}
```

**Matching events**

When an incoming order crosses existing liquidity, the orderbook emits a trade event in addition to (or in place of) the resting-order event. An incoming buy that matches a resting sell emits `NewBuyInitiatedTrade`. For a full match, the transaction emits `OrderReceived`, base/quote token transfer events, `NewBuyInitiatedTrade`, and commission transfer events; no `NewBuyOrder` is emitted because no remainder rests on the book. For a partial match where the incoming buy is larger than the available sell liquidity, the transaction emits `NewBuyInitiatedTrade` for the matched quantity and `NewBuyOrder` for the residual buy.

> **Execution price vs limit price.** The same single-price execution model as on Polygon applies (§6.8): the whole match executes at one price - the last execution price clamped into the range allowed by the participating orders' limits - so the fill price is frequently neither side's limit. Reconcile fills against the token transfer events in the same transaction rather than assuming the incoming limit price.

**Monitoring events in production**

Parsing the CLI's printed event output is suitable for sandbox experiments only. A production integration should consume events from the Soroban RPC **`getEvents`** endpoint instead: filter by the orderbook contract id and, because `client` is `topic[1]` on every lifecycle event, by your own address as a topic filter. `getEvents` is paginated and covers a bounded retention window of recent ledgers - poll it on a schedule well inside that window, persist the last processed ledger/cursor, and resume from it. As on Polygon, fills and venue-initiated cancellations of your resting orders arrive in transactions you did not submit, so receipt-watching alone is not sufficient.

**OrderRejected**

The transaction succeeded but matching rules, controls, or execution-condition behaviour rejected the order or its remainder. Read `order_id` from the topic vector and the rejection details (`reason`, `quantity_not_executed`, side, price) from the data body.

## 8. Chain differences <a href="#id-8-chain-differences" id="id-8-chain-differences"></a>

| Topic                | Polygon Amoy                                                                      | Stellar Testnet                                                                                                              |
| -------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Signing identity     | EVM transaction sender is the trading wallet.                                     | The Soroban call carries an explicit `user` address; the transaction is signed by the source account.                        |
| Order entry          | `newBuyOrder(bytes,bytes,bytes)` / `newSellOrder(bytes,bytes,bytes)`.             | `new_buy_order(user, order_data, cross_identifier, reporting_data)` / `new_sell_order(...)`.                                 |
| Order data encoding  | `abi.encode` with two through six 32-byte slots.                                  | Two through six 32-byte big-endian words inside Soroban `Bytes`.                                                             |
| Order options        | Standard, IOC, BOC, FOK, GFD, GTD via the explicit field layout.                  | Standard, IOC, BOC, FOK, GFD, GTD via the explicit field layout.                                                             |
| Token authorization  | Restricted token receivers must be 21X beneficiaries.                             | Trustline + token authorization; participant authorization on the orderbook.                                                 |
| Allowance            | ERC-20 allowance, no expiration.                                                  | Soroban allowance with `expiration_ledger`.                                                                                  |
| Phase return type    | `uint8` (open = `1`).                                                             | String enum (open = `"OpenForTrading"`).                                                                                     |
| Order id surface     | Decode with the canonical EVM v1.2 ABI; do not assume a topic position.           | Topic vector (`topic[2]`) for `OrderReceived`, `CancelOrder`, `OrderRejected`; data body for `NewBuyOrder` / `NewSellOrder`. |
| Transaction ordering | Per-wallet nonces; parallel submission requires explicit nonce management (§6.6). | Per-source-account sequence numbers; parallel submission requires channel accounts (§7.8).                                   |
| Event monitoring     | `eth_getLogs` / WebSocket subscription using the v1.2 ABI and topics (§6.8).      | Soroban RPC `getEvents`, filter by contract id and `client` topic (§7.10).                                                   |
| Native fees          | POL / MATIC.                                                                      | XLM.                                                                                                                         |
| Simulation           | `eth_call` / ethers `staticCall`.                                                 | Stellar CLI / SDK with `--send=no`.                                                                                          |

### 8.1 Pre-funding and allowance behaviour <a href="#id-81-pre-funding-and-allowance-behaviour" id="id-81-pre-funding-and-allowance-behaviour"></a>

Allowance behaviour is **configuration-dependent, not chain-dependent**. Whether the orderbook locks/transfers tokens **when an order is placed** ("pre-funded") or only **when it matches** ("no-prefund") is a property of the specific orderbook deployment. Stellar can behave exactly like Polygon - and vice versa - depending on how the orderbook was compiled and initialised. Always read `getConfig` / `get_config` for the pair you are trading and treat the simulation result as authoritative, rather than assuming a per-chain rule.

**Behaviour by mode:**

* **Pre-funded.** The relevant token is locked or transferred into the orderbook when the order is posted - via `transferFrom` on Polygon, or via the Soroban allowance on Stellar. A sell-side resting order moves the base token; a buy-side resting order moves the quote token (notional plus commission). The allowance is consumed at placement, and cancellation returns the token balance but does **not** restore the consumed allowance (re-approve before placing again - see §6.9).
* **No-prefund.** No token moves when the order rests; settlement transfers occur directly between the trading wallets at matching time. During matching, the orderbook checks each collected non-pre-funded order's wallet for sufficient **balance and allowance** - cumulatively, counting all orders collected from the same wallet in that match. An order that fails the check is cancelled on chain with cancellation type `ByContract` and matching continues with the next eligible order (see §5.6). On Stellar the allowance must remain valid for the order's lifetime - refresh it before its `expiration_ledger`.

Both EVM v1.2 and Stellar v1.2 support configuration-dependent funding behavior. Confirm the active mode through `getConfig` / `get_config` for the discovered orderbook and re-check it after any contract redeployment.

## 9. Troubleshooting <a href="#id-9-troubleshooting" id="id-9-troubleshooting"></a>

### 9.1 Permissions and authorization <a href="#id-91-permissions-and-authorization" id="id-91-permissions-and-authorization"></a>

EVM v1.2 uses ABI custom errors; the selector is the first four bytes of revert data.

<table><thead><tr><th>EVM error</th><th width="145.7879638671875">Selector</th><th>Cause / action</th></tr></thead><tbody><tr><td><code>OrderBook_InvalidClient()</code></td><td><code>0xae3d18fd</code></td><td>Wallet is not a valid registered client. Confirm onboarding and the discovered orderbook address.</td></tr><tr><td><code>OrderBook_NotAllowedToBuy()</code></td><td><code>0x00c9360e</code></td><td>Client lacks buy permission. Ask 21X to update its whitelist record.</td></tr><tr><td><code>OrderBook_NotAllowedToSell()</code></td><td><code>0x25b56fb0</code></td><td>Client lacks sell permission. Ask 21X to update its whitelist record.</td></tr><tr><td><code>OrderBook_NotAllowedToCancel()</code></td><td><code>0x52ad6da4</code></td><td>Client lacks cancel permission. Confirm <code>canCancel</code> before retrying.</td></tr><tr><td><code>OrderBook_ExcludedForAccessManagedRoles()</code></td><td><code>0xb95f30af</code></td><td>The wallet holds an orderbook admin, operator, or controller role and is barred from participant order entry. Use a participant wallet.</td></tr><tr><td><code>AccessManaged_Unauthorized(address)</code></td><td><code>0x55b9b114</code></td><td>Caller lacks the privileged authority required by the method. Participant integrations should not call role-gated administration methods.</td></tr></tbody></table>

Stellar uses numeric orderbook contract codes:

<table><thead><tr><th width="248.38427734375">Stellar error</th><th>Cause / action</th></tr></thead><tbody><tr><td><code>NotAllowedToBuy (#4)</code> / <code>NotAllowedToSell (#5)</code></td><td>Registered participant lacks the requested side permission. Confirm client permissions with 21X.</td></tr><tr><td><code>ClientNotFound (#6)</code></td><td>Account is not registered in the orderbook's client registry. Confirm the <code>user</code> address and orderbook id.</td></tr><tr><td><code>NotAllowedToCancel (#7)</code></td><td>Participant lacks <code>can_cancel</code>. Confirm permissions before retrying.</td></tr><tr><td><code>InvalidClient (#9)</code></td><td>Client data is invalid for the requested operation. Reconfirm onboarding and the <code>user</code> address.</td></tr><tr><td><code>ExcludedForAccesssControlRoles (#1015)</code></td><td>Address holds a privileged orderbook role and cannot submit participant orders. Use a participant account. The triple <code>s</code> in <code>Accesss</code> is the contract's canonical error spelling.</td></tr><tr><td><code>Unauthorized (#4001)</code></td><td>Method requires an elevated role. Use participant-facing methods, events, and authenticated history endpoints.</td></tr></tbody></table>

`Receiver must be a beneficiary` is emitted by a restricted EVM token, not by the orderbook. It means the receiving wallet must be enabled as a beneficiary for that token.

### 9.2 Encoding and input validation <a href="#id-92-encoding-and-input-validation" id="id-92-encoding-and-input-validation"></a>

<table><thead><tr><th width="117.9371337890625">Chain</th><th>Error</th><th>Cause / action</th></tr></thead><tbody><tr><td>EVM</td><td><code>OrderBook_InvalidOrderType(uint8)</code> (<code>0x2c45f09d</code>)</td><td><code>orderType</code> is not Limit (<code>0</code>) or Market (<code>1</code>).</td></tr><tr><td>EVM</td><td><code>OrderBook_InvalidInputOrderData()</code> (<code>0xedd3a621</code>)</td><td>Unsupported ABI length, missing/interleaved fields, invalid value width, or malformed payload. Encode two through six ordered ABI slots (§6.4).</td></tr><tr><td>EVM</td><td><code>OrderBook_InvalidExecutionCondition(uint8)</code> (<code>0xf55b59e0</code>)</td><td>Condition is outside <code>0-3</code> or incompatible with the order type. Market permits only IOC or FOK.</td></tr><tr><td>EVM</td><td><code>OrderBook_InvalidValidityConstraint(uint8)</code> (<code>0xaea3ead0</code>)</td><td>Validity is outside GFD (<code>0</code>) / GTD (<code>1</code>), or a Market order attempts GTD.</td></tr><tr><td>EVM</td><td><code>OrderBook_InvalidOrderLifetime()</code> (<code>0xa9431627</code>)</td><td>Lifetime is above 90 or is supplied for a combination other than Limit + GTD.</td></tr><tr><td>Stellar</td><td><code>InvalidOrderType (#2000)</code></td><td><code>order_type</code> is not <code>0</code> or <code>1</code>.</td></tr><tr><td>Stellar</td><td><code>InvalidOrderExecutionCondition (#2001)</code></td><td>Condition is outside <code>0-3</code> or incompatible with the order type.</td></tr><tr><td>Stellar</td><td><code>InvalidOrderValidityConstraint (#2002)</code></td><td>Validity is outside <code>0-1</code> or incompatible with a Market order.</td></tr><tr><td>Stellar</td><td><code>InvalidOrderLifetime (#2003)</code></td><td>Lifetime or its field combination is invalid.</td></tr><tr><td>Stellar</td><td><code>InvalidInputOrderData (#2004)</code></td><td>Unsupported word count, malformed fields, or <code>cross_identifier</code> is neither empty nor four bytes. Use §7.6-§7.7.</td></tr><tr><td>Stellar</td><td><code>InvalidInputValueToBig (#2005)</code></td><td>A decoded value exceeds the target integer width. Reject it before submission.</td></tr><tr><td>Stellar</td><td><code>CastOverflowTooLargeValueToCastFromU128ToI128 (#1029)</code></td><td>A value exceeds the signed range used by a control calculation. Reject oversized input before submission.</td></tr><tr><td>Stellar CLI</td><td><code>order_data</code> is not parseable as <code>Bytes</code></td><td>Hex is malformed, odd-length, or contains incomplete 32-byte words. Validate 128, 192, 256, 320, or 384 hex characters.</td></tr></tbody></table>

Across both chains, validate before encoding: quantity must be positive; Limit price must be positive; Market price may be zero; Market permits only IOC/FOK and cannot be GTD; a sixth slot/word requires Limit + GTD with lifetime `0-90`. `crossIdentifier` / `cross_identifier` must be empty or exactly four raw bytes.

### 9.3 Balances and allowances <a href="#id-93-balances-and-allowances" id="id-93-balances-and-allowances"></a>

<table><thead><tr><th width="154.939208984375">Chain</th><th>Error / symptom</th><th>Cause / action</th></tr></thead><tbody><tr><td>EVM</td><td><code>OrderBook_NoPrefund_InsufficientAllowance(address,address,uint256)</code> (<code>0x023142cc</code>)</td><td>A no-prefund order reached matching without enough allowance. Restore allowance for the required token and account for all concurrently resting orders.</td></tr><tr><td>EVM token</td><td><code>ERC20InsufficientAllowance</code></td><td>Token approval is missing, too small, or was consumed by earlier pre-funded orders. Re-approve or maintain a suitably bounded standing approval.</td></tr><tr><td>EVM token</td><td><code>ERC20InsufficientBalance</code></td><td>Wallet cannot cover the transfer. Top up the appropriate base or quote token.</td></tr><tr><td>EVM</td><td>Allowance is lower after cancellation</td><td>In pre-funded mode, placement consumed allowance; returning tokens does not restore it. Re-approve before reusing the funds.</td></tr><tr><td>Both</td><td>Buy order requires more quote than notional</td><td>Settlement also charges commission. Size balance and allowance for notional plus the applicable commission (§6.5).</td></tr><tr><td>Stellar</td><td><code>InsufficientAllowanceForNoPrefund (#1)</code></td><td>A no-prefund order lacks sufficient live allowance at matching time. Renew the allowance and its expiration ledger.</td></tr><tr><td>Stellar token</td><td><code>Error(Contract, #10)</code> observed from the token contract</td><td>The resulting balance is outside the token contract's allowed range, commonly because quote balance cannot cover value plus commission. Confirm the failing contract id before diagnosing.</td></tr><tr><td>Stellar token</td><td><code>Error(Contract, #13)</code> observed from the token contract</td><td>Required trustline is absent. Confirm the failing contract id, create the trustline, then retry.</td></tr></tbody></table>

Soroban numeric error namespaces are contract-specific. Always identify which contract emitted `Error(Contract, #N)` before mapping the number; token-contract `#10` is unrelated to orderbook `AlreadyInitialized (#10)`.

### 9.4 Pre-trade controls and matching rejections <a href="#id-94-pre-trade-controls-and-matching-rejections" id="id-94-pre-trade-controls-and-matching-rejections"></a>

| Control failure                      | EVM v1.2 custom error / selector                                                           | Stellar code                                                |
| ------------------------------------ | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------- |
| Market not in an allowed phase       | `OrderBook_ForbiddenDueToMarketStatus(...)` / `0x931b0c21`                                 | `ForbiddenDueToMarketStatus (#1014)`                        |
| Invalid tick-size price              | `OrderBook_TickSize_InvalidPrice(uint256,uint256)` / `0xed7cd145`                          | `TickSizeInvalidPrice (#1016)`                              |
| Pre-trade controls not configured    | `OrderBook_PreTradeControlsNotSet()` / `0xd1c7b9a7`                                        | `PreTradeControlsNotSet (#1017)`                            |
| Price above range                    | `OrderBook_PreTradeControlPriceAboveMaxRange()` / `0x2a246225`                             | `PreTradeControlPriceAboveMaxRange (#1018)`                 |
| Price below range                    | `OrderBook_PreTradeControlPriceBelowMinRange()` / `0x9e88e9b2`                             | `PreTradeControlPriceBelowMinRange (#1019)`                 |
| Order value above range              | `OrderBook_PreTradeControlOrderValueAboveMaxRange()` / `0xa0fd1bca`                        | `PreTradeControlOrderValueAboveMaxRange (#1020)`            |
| Order volume above range             | `OrderBook_PreTradeControlOrderVolumeAboveMaxRange()` / `0x2ad371e4`                       | `PreTradeControlOrderVolumeAboveMaxRange (#1021)`           |
| Order value below range              | `OrderBook_PreTradeControlOrderValueBelowMinRange()` / `0x5ef8d87d`                        | `PreTradeControlOrderValueBelowMinRange (#1022)`            |
| Order volume below range             | `OrderBook_PreTradeControlOrderVolumeBelowMinRange()` / `0xbd643fd0`                       | `PreTradeControlOrderVolumeBelowMinRange (#1023)`           |
| Volatility management not configured | `OrderBook_VolatilityManagementNotSet()` / `0x3da15eed`                                    | `VolatilityManagementNotSet (#1024)`                        |
| Above maximum static range           | Not listed as a separate v1.2 custom revert; inspect `OrderRejected` and the canonical ABI | `VolatilityManagementPriceOutOfMaximumStaticRange (#1025)`  |
| Below minimum static range           | Not listed as a separate v1.2 custom revert; inspect `OrderRejected` and the canonical ABI | `VolatilityManagementPriceOutOfMinimumStaticRange (#1026)`  |
| Above maximum dynamic range          | Not listed as a separate v1.2 custom revert; inspect `OrderRejected` and the canonical ABI | `VolatilityManagementPriceOutOfMaximumDynamicRange (#1027)` |
| Below minimum dynamic range          | Not listed as a separate v1.2 custom revert; inspect `OrderRejected` and the canonical ABI | `VolatilityManagementPriceOutOfMinimumDynamicRange (#1028)` |

Use REST pair data and `get_config` to inspect thresholds, limits, static reference price, liquidity band, and the price collar factor before submitting. An `OrderRejected` event indicates that the transaction itself succeeded but the order was rejected by matching rules, controls, or execution-condition behaviour; check `reason`, `quantity_not_executed`, side, price, and pre-submission book state.

> **Boundary behaviour.** Orders at the exact `minimumOrderValue` may be rejected by pre-trade controls (for example, `PreTradeControlOrderValueBelowMinRange`). Use values comfortably above the minimum unless intentionally testing boundary rejection.

Configuration-not-set errors indicate a venue deployment/configuration problem, not a participant payload problem. Stop submitting and report the discovered pair id and orderbook address to 21X.

### 9.5 Cancellation, lookup, and event decoding <a href="#id-95-cancellation-lookup-and-event-decoding" id="id-95-cancellation-lookup-and-event-decoding"></a>

| Chain   | Error / symptom                                  | Cause / action                                                                                                                                 |
| ------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| EVM     | `OrderBook_NoSuchOrderId(uint64)` (`0xbbe8af6d`) | Order id does not exist on the selected side, or is already terminal. Confirm side, owner, orderbook address, and local state before retrying. |
| Stellar | `OrderNotFound (#2)` / `NoSuchOrderId (#8)`      | Order cannot be found for the requested lookup or cancellation. Treat an already-terminal order idempotently.                                  |
| Both    | Cancellation fails during a closed phase         | Participant cancellation is allowed while open or halted, not closed. Reconcile venue-initiated terminal events rather than blindly retrying.  |
| EVM     | Event does not decode or order id is missing     | ABI does not match EVM v1.2. Load the canonical compiled ABI and verify topic-0 against §6.8. Do not assume a fixed indexed-topic position.    |
| Stellar | Order id parser returns nothing                  | `OrderReceived`, `CancelOrder`, and `OrderRejected` carry it in `topic[2]`; `NewBuyOrder` / `NewSellOrder` carry it in the data body (§7.10).  |

### 9.6 REST endpoint authentication <a href="#id-96-rest-endpoint-authentication" id="id-96-rest-endpoint-authentication"></a>

Authenticated wallet, order, and trade history endpoints require a bearer token. Calls without authentication return HTTP `401`. Use the public market-data endpoints for unauthenticated discovery, or obtain API credentials from 21X for participant-scoped history.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.21x.eu/integration-guide/21x-integration-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
