> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sx.bet/llms.txt
> Use this file to discover all available pages before exploring further.

# Filling orders

> Fill an existing order on the SX Bet orderbook as a taker, with built-in betting delay and odds matching.

<Note>**Rate limit:** All `POST /orders/*` endpoints share a combined limit of 5,500 requests/min. See [Rate Limits](/developers/rate-limits).</Note>

This endpoint fills orders on the exchange based on the specified desiredOdds and oddsSlippage. Order matching is done internally after the built-in betting delay, optimizing the taker experience particularly during in-play betting. Furthermore, if any new orders with better odds are added during the betting delay window, those orders will be filled. Lastly, if there isn't sufficient size to support the full stake amount, the response will include a isPartialFill: true flag to indicate that the fill was only partially filled. Takers can then attempt to fill again if they choose to do so.

To fill orders on sx.bet via the API, make sure you first enable betting. The simplest way is to place a test bet through [sx.bet](https://sx.bet) (or [toronto.sx.bet](https://toronto.sx.bet) for testnet) with the account you'll be using. To do it programmatically, use the [POST /orders/approve](/api-reference/post-approve) endpoint.

<Info>Your assets must be on SX Mainnet to place bets.</Info>


## OpenAPI

````yaml POST /orders/fill/v2
openapi: 3.0.1
info:
  title: SX Bet API
  version: 1.0.0
  description: >-
    REST API for the SX Bet decentralized sports betting exchange. Retrieve
    sports data, markets, and orderbook information. Post, cancel, and fill
    orders with signed payloads.


    Base URLs:

    - **Mainnet**: `https://api.sx.bet`

    - **Testnet**: `https://api.toronto.sx.bet`
servers:
  - url: https://api.sx.bet
    description: Mainnet (SX Network, chainId 4162)
  - url: https://api.toronto.sx.bet
    description: Testnet (Toronto, chainId 79479957)
security: []
tags:
  - name: Connection
    description: Server metadata and heartbeat management
  - name: Sports Data
    description: Sports, leagues, teams, fixtures, and live scores
  - name: Markets
    description: Active, specific, and popular betting markets
  - name: Trades
    description: Matched trades and portfolio history
  - name: Orders
    description: Orderbook queries, posting, cancelling, and filling orders
paths:
  /orders/fill/v2:
    post:
      tags:
        - Orders
      summary: Fill an order
      operationId: fillOrder
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - market
                - baseToken
                - isTakerBettingOutcomeOne
                - stakeWei
                - desiredOdds
                - oddsSlippage
                - fillSalt
                - taker
                - takerSig
              properties:
                market:
                  type: string
                  description: The market hash of the market you are filling an order on
                baseToken:
                  type: string
                  description: >-
                    The address of the ERC-20 token representing the currency of
                    the fill. Token addresses vary by network — see the
                    `addresses` field in GET /metadata or the References page
                    for the correct address.
                isTakerBettingOutcomeOne:
                  type: boolean
                  description: >-
                    Whether or not taker is betting outcome 1 (team 1 wins), if
                    false then taker is betting outcome 2 (team 2 wins)
                stakeWei:
                  type: string
                  description: >-
                    The stake amount for this bet in wei units - see Unit
                    Conversion. Minimum 1 USDC.
                desiredOdds:
                  type: string
                  description: >-
                    The worst taker odds acceptable for filling, used as an
                    anchor when applying oddsSlippage - note that any order
                    found with taker odds better than the desiredOdds can still
                    fill if found at the time of order matching
                oddsSlippage:
                  type: integer
                  description: >-
                    An integer between 0-100 representing the percentage of
                    tolerance that is acceptable based on desiredOdds
                fillSalt:
                  type: string
                  description: >-
                    Random 32 byte string to identify this fill. Must match the
                    fillSalt used when computing the signing payload
                taker:
                  type: string
                  description: Address of the taker taking the bet
                takerSig:
                  type: string
                  description: Your wallet signature over the fill payload.
            example:
              market: N/A
              baseToken: '0x6629Ce1Cf35Cc1329ebB4F63202F3f197b3F050B'
              isTakerBettingOutcomeOne: true
              stakeWei: '50000000'
              desiredOdds: '83000000000000000000'
              oddsSlippage: 5
              fillSalt: 0x...
              taker: 0xYourWalletAddress
              takerSig: 0x...
      responses:
        '201':
          description: ''
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    description: '`success` or `failure` if the request succeeded or not'
                  data:
                    type: object
                    properties:
                      fillHash:
                        type: string
                        description: Hash of the submitted fill
                      isPartialFill:
                        type: boolean
                        description: Whether the fill was only partially filled
                      totalFilled:
                        type: string
                        description: Total amount filled in wei units
                      averageOdds:
                        type: string
                        description: >-
                          Average odds of the fill in SX protocol format
                          (implied * 10^20)
              example:
                status: success
                data:
                  fillHash: >-
                    0x840763ae29b7a6adfa0e315afa47be30cdebd5b793d179dc07dc8fc4f0034965
                  isPartialFill: false
                  totalFilled: '50000000'
                  averageOdds: '73000000000000000000'
        '400':
          description: >-
            Error Codes:


            `INSUFFICIENT_KYC` — user has not registered on sx.bet


            `AFTER_ORDER_EXPIRY` — One of the orders have expired


            `BASE_TOKENS_NOT_SAME` — All orders must be for the same `baseToken`


            `MARKETS_NOT_SAME` — All orders must be for the same market


            `DIRECTIONS_NOT_SAME` — All orders must be betting on the same side
            `isMakerBettingOutcomeOne`


            `INVALID_ORDERS` — Order is now inactive


            `INVALID_ODDS` — Invalid desiredOdds, must be less than 10^20


            `INVALID_ODDS_SLIPPAGE` — Invalid oddsSlippage, must be an integer
            between 0-100


            `MATCH_STATE_INVALID` — The fixture for the order is in an invalid
            state and is not bettable anymore


            `TAKER_SIGNATURE_MISMATCH` — The taker signature generated for the
            request is invalid


            `PROXY_ACCOUNT_INVALID` — The proxy account is invalid (only
            applicable if proxyTaker was specified in request)


            `TAKER_AMOUNT_TOO_LOW` — The stakeWei specified is too low for the
            current token


            `META_TX_RATE_LIMIT_REACHED` — Cannot have more than 10 meta
            transactions at once


            `INSUFFICIENT_SPACE` — There is not enough space to fill the matched
            orders due to other pending fills


            `FILL_ALREADY_SUBMITTED` — The fill has already been submitted


            `ODDS_STALE` — No orders could be found for the desiredOdds and
            oddsSlippage, try again with greater oddsSlippage


            `FILL_TIMED_OUT` — The fill request timed out before completing


            `MARKET_DOESNT_EXIST` — The specified market does not exist
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                  errorCode:
                    type: string
      x-codeSamples:
        - lang: javascript
          label: Sign & Fill Order
          source: >-
            import { Wallet, ZeroAddress, ZeroHash, randomBytes, hexlify } from
            "ethers";


            async function fillOrder() {
              // get the following from https://api.sx.bet/metadata
              const EIP712FillHasherAddress = process.env.EIP712_FILL_HASHER_ADDRESS;
              const chainId = Number(process.env.CHAIN_ID); // Mainnet — use 79479957 for testnet
              const domainVersion = process.env.DOMAIN_VERSION;

              const wallet = new Wallet(process.env.SX_PRIVATE_KEY);
              const takerAddress = wallet.address;
              const stakeWei = "50000000"; // 50 USDC
              const marketHash = "0x0246b760b06009ece42d08e706563de1967e7f1b4799d0f559244e3f80bbc496"; // Liverpool vs Arsenal
              const baseToken = "0x6629Ce1Cf35Cc1329ebB4F63202F3f197b3F050B"; // Mainnet — see References for testnet address
              const desiredOdds = "83000000000000000000"; // ~1.20 decimal odds
              const oddsSlippage = 5; // 5% slippage, so worst decimal odds ~1.14
              const isTakerBettingOutcomeOne = true; // taker is betting that team 1 wins
              const fillSalt = BigInt(hexlify(randomBytes(32))).toString();

              const domain = {
                name: "SX Bet",
                version: domainVersion,
                chainId,
                verifyingContract: EIP712FillHasherAddress,
              };

              const types = {
                Details: [
                  { name: "action", type: "string" },
                  { name: "market", type: "string" },
                  { name: "betting", type: "string" },
                  { name: "stake", type: "string" },
                  { name: "worstOdds", type: "string" },
                  { name: "worstReturning", type: "string" },
                  { name: "fills", type: "FillObject" },
                ],
                FillObject: [
                  { name: "stakeWei", type: "string" },
                  { name: "marketHash", type: "string" },
                  { name: "baseToken", type: "string" },
                  { name: "desiredOdds", type: "string" },
                  { name: "oddsSlippage", type: "uint256" },
                  { name: "isTakerBettingOutcomeOne", type: "bool" },
                  { name: "fillSalt", type: "uint256" },
                  { name: "beneficiary", type: "address" },
                  { name: "beneficiaryType", type: "uint8" },
                  { name: "cashOutTarget", type: "bytes32" },
                ],
              };

              const message = {
                action: "N/A",
                betting: "N/A",
                stake: "N/A",
                worstOdds: "N/A",
                worstReturning: "N/A",
                market: marketHash,
                fills: {
                  stakeWei,
                  marketHash,
                  baseToken,
                  desiredOdds,
                  oddsSlippage,
                  isTakerBettingOutcomeOne,
                  fillSalt,
                  beneficiary: ZeroAddress,
                  beneficiaryType: 0,
                  cashOutTarget: ZeroHash,
                },
              };

              const signature = await wallet.signTypedData(domain, types, message);

              const apiPayload = {
                market: marketHash,
                baseToken,
                isTakerBettingOutcomeOne,
                stakeWei,
                desiredOdds,
                oddsSlippage,
                taker: takerAddress,
                takerSig: signature,
                fillSalt,
              };

              const response = await fetch(`https://api.sx.bet/orders/fill/v2`, { // Mainnet — use https://api.toronto.sx.bet for testnet
                method: "POST",
                body: JSON.stringify(apiPayload),
                headers: { "Content-Type": "application/json" },
              });
            }

````