NAV Navbar
  • Overview
  • Troubleshooting
  • Important Information
  • Exchange Information
  • Authentication
  • Tickers
  • Offers
  • Trades
  • Fees
  • Deposits
  • Withdrawals
  • Orders
  • Balances
  • Websocket API
  • Errors
  • Overview

    Introduction

    Welcome to the Switcheo Exchange API documentation.

    This documentation is intended for developers who want to write applications to interact with the Switcheo Exchange programatically.

    Before you proceed with the API documentation, be sure to explore Switcheo Exchange at https://switcheo.exchange.

    If you have technical questions, you can ask them at our slack channel.

    API Requests

    The Switcheo API uses REST architecture. API requests and responses use the JSON format.

    There are three types of API endpoints.

    Base URLs

    Use the following TestNet URLs when developing your application:

    Type Base URL
    UI https://beta.switcheo.exchange/
    API https://test-api.switcheo.network
    WS wss://test-ws.switcheo.io

    Use the MainNet URLs for actual trading and market data:

    Type Base URL
    UI https://switcheo.exchange/
    API https://api.switcheo.network
    WS wss://ws.switcheo.io

    Rate Limits

    All endpoints are rate-limited. We use a dynamic algorithm for determining these limits. The HTTP error code 429 will be returned if this limit is exceeded. You should implement an exponential backoff strategy when encountering this error code.

    Troubleshooting

    The following steps can be used to troubleshoot potential issues:

    1. Check the Important Information section. Possible issues include the address format, amount format, parameter casing, private key format, wrong parameters included to be signed, wrong timestamp.

    2. Trace each step of signing parameters using the example in Signing Request Parameters, this example has the expected inputs and outputs at each step of generating a signature.

    CORS

    When developing on a localhost server, you might encounter a CORS error.

    To avoid this, please run your localhost server on port 8080.

    Important Information

    Subject Things to note
    Addresses Addresses must be in the correct format.
    Amounts Amounts must be converted to the correct format.
    Contract Hash The correct contract hash must be used depending on whether you are using the TestNet or MainNet endpoints.
    Parameter casing Parameters must be snake cased: e.g. contract_hash and not contractHash
    Private keys Private keys must be in the correct format.
    Signature Not all parameters should be included to generate the signature, excluded parameters are specified in their respective endpoint's documentation.
    Timestamp If a timestamp parameter is required, then it should first be fetched from the server. If the timestamp is not within an acceptable range of the exchange's timestamp then an invalid signature error will be returned.

    Addresses

    An address in Switcheo is always represented by a hex string, and is prefixed by a 0x only if it is an Ethereum address. Addresses should always be in a lowercase hex string representation.

    NEO Addresses

    Getting the user's address

    const { wallet } = require('@cityofzion/neon-js')
    wallet.getScriptHashFromPublicKey('031c37f6cce9627dc635d026deddd1200013c1b78dac767cdb507339a831183fd9')
    // Result: 87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f
    
    // you can also retrieve the script hash from a wallet address directly with:
    wallet.getScriptHashFromAddress('AQV8FNNi2o7EtMNn4etWBYx1cqBREAifgE')
    // Result: 87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f
    

    For NEO, an address refers to the RIPEMD160 hash of the the user's ECDSA public key.

    An example implemention to derive an address from a user's public key can be found in the neon-js javascript library.

    Please note the difference in terminology between Switcheo and neon-js. Switcheo's address is equivalent to neon-js's scriptHash.

    Ethereum Addresses

    For Ethereum, an addresses refers to the Keccak hash of the right-most 160-bits of the user's ECDSA public key, as specified in the Ethereum Yellow Paper.

    Ethereum addresses are sometimes displayed with uppercase letters for verification purposes. When submitting addresses through the Switcheo API however, the address should always be fully lowercased.

    Amounts

    When specifying amounts as request parameters, the amounts should first be converted by following these steps:

    1. Multiply the original amount by 10 to the power of the precision allowed by the given token.
    2. Drop any decimals, and convert the resulting integer to a string

    For example, if the token's precision is 8, and the original amount is 9.12345678:

    1. Following the above steps: 9.12345678 * (10 ^ 8) = 912345678.00
    2. Drop any decimals to get: 912345678
    3. Convert the result to a string to get "912345678"

    The list of supported assets and their corresponding precisions can be found in the Tokens section.

    Parameter Casing

    Parameters used to generate a signature or sent in API requests should always be snake cased.

    Parameters are camel cased in the examples because the examples are in JavaScript and it is JavaScript's convention to use camel case.

    The code in the examples make use of helper methods to automatically convert camel cased keys into snake cased keys.

    Private Keys

    Please check the documentation of the respective blockchains for signing with private keys.

    For NEO, there is both a WIF and a private key.

    Example WIF: L479CJz4ZyxHiumy2viAjBFk8nixKeMY45DCQa5p4n4AT6M6WsWq

    Example private key: cd7b887c29a110e0ce53e81d6dd02805fc7b912718ff8b6659d8da42887342bd

    The private key should be used for signing, not the WIF.

    Exchange Information

    This section consists of endpoints that allow retrieval of Switcheo Exchange information.

    Authentication is not required for these endpoints.

    Timestamp

    Retrieve the current epoch timestamp in the exchange.

    HTTP Request

    GET /v2/exchange/timestamp

    Example response

    {
      "timestamp": 1534392760908
    }
    

    Notes

    This value should be fetched and used when a timestamp parameter is required for API requests.

    If the timestamp used for your API request is not within an acceptable range of the exchange's timestamp then an invalid signature error will be returned. The acceptable range might vary, but it should be less than one minute.

    Contracts

    HTTP Request

    GET /v2/exchange/contracts

    Example response

    {
        "NEO": {
            "V1": "<contract hash NEO 1>",
            "V1_5": "<contract hash NEO 1.5>",
            "V2": "<contract hash NEO 2>"
        },
        "ETH": {
            "V1": "<contract address ETH V1>"
        }
    }
    

    Retrieve the currently deployed contract hashes by Switcheo.

    Please note that a different set of contract hashes should be used depending on the Network you intend to work with (TestNet vs the MainNet).

    Network URL
    TestNet Retrieve contract hashes from [TestNet_URL]/v2/exchange/contracts
    MainNet Retrieve contract hashes from [MainNet_URL]/v2/exchange/contracts

    Note also that, ETH contract hashes always include a 0x prefix, while NEO never includes a 0x prefix.

    Tokens

    Retrieve a list of supported tokens on Switcheo.

    HTTP Request

    GET /v2/exchange/tokens

    Example response

    // GET /v2/exchange/tokens?show_listing_details=1&show_inactive=1
    {
      "NEO": {
            "hash": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
            "decimals": 8,
            "precision": 3,
            "trading_active": true
            "active": true,
            "listing_info": {
                "deposits": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "trading": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "cancellations": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "withdrawals": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                }
            }
    
     },
      ...
      "SWC": {
            "hash": "0x00bb907302e508707108cd835621dfd2b44ca7cf",
            "decimals": 18,
            "precision": 1,
            "trading_active": true
            "active": true,
            "listing_info": {
                "deposits": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "trading": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "cancellations": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                },
                "withdrawals": {
                    "start": 1514764800,
                    "end": 7983792000,
                    "paused": false
                }
            }
       }
      ...
    }
    

    Request parameters

    Parameter Type Required Description
    show_listing_details Boolean no Show all details for each token (default is false). If false, only hash & decimals are returned, otherwise all parameters below are returned.
    show_inactive Boolean no Show inactive tokens (default is false)

    Response parameters

    Parameter Description
    hash Contract hash of the token
    decimals Number of decimal places to use when submitting order amounts (e.g. if a token has 8 decimals, then an order for 1.2 tokens should be submitted as 120000000)
    precision The maximum amount precision that can be submitted in orders (e.g. if a token has 8 decimals and 2 precision, 123000000 would be a valid order amount to submit, but not 12340000)
    minimum_quantity The minimum order amount for any orders submitted involving this token. Note that this applies to both the order want_amount and offer_amount (or quantity, if using new format).
    trading_active Whether this token is currently actively trading
    active Whether this token is currently visible on the Switcheo Exchange UI
    listing_info Status of the token for trading activities ["deposits", "trading", "cancellations", "withdrawals"] (only returned if show_listing_details is truthy)
    start Starting time for the activity (in epoch seconds)
    end Ending time for the activity (in epoch seconds)
    paused Whether the trading of the token is temporarily paused

    Pairs

    Retrieve available currency pairs on Switcheo Exchange filtered by the base parameter. Defaults to all pairs.

    The valid base currencies are currently: NEO, GAS, SWTH, USD.

    HTTP Request

    GET /v2/exchange/pairs

    Example response without details

    // GET /v2/exchange/pairs?bases=["NEO"]&show_details=0
    [
      "GAS_NEO",
      "SWTH_NEO",
      ...
    ]
    
    

    Example response with details // GET /v2/exchange/pairs?bases=["NEO"]&show_details=1 js [ { "name": "GAS_NEO", "price_precision": 3 "quantity_precision": 3 }, { "name": "SWTH_NEO", "price_precision": 6, "quantity_precision": 2 }, ... ]

    Request parameters

    Parameter Type Required Description
    bases Array<string> no Provides pairs for these base symbols. Possible values are NEO, GAS, SWTH, USD.
    show_details Boolean no Show further details for token
    show_inactive Boolean no Show inactive tokens (default is to not return inactive tokens)

    Response parameters for show_details=0

    Parameter Description
    Array List of token pairings (ticker) <QUOTE>_<BASE> where <QUOTE> is the trading token symbol (e.g. SWTH), while <BASE> is the base token symbol (e.g. NEO)

    Response parameters for show_details=1

    Parameter Description
    name The ticker name as <QUOTE>_<BASE> where <QUOTE> is the trading token symbol (e.g. SWTH), while <BASE> is the base token symbol (e.g. NEO)
    precision The maximum price precision that can be submitted (e.g. if precision is 2,

    an order on this pair for 1.99 or 1.90000000 price is valid, but 1.999 is not)

    Announcement Message

    Retrieve the currently active Switcheo Exchange Announcement

    HTTP Request

    GET /v2/exchange/announcement_message

    Example response

    {
        "message": "Welcome to Switcheo Exchange!!",
        "message_type": "info"
    }
    

    Response parameters

    Parameter Description
    message HTML formatted message
    message_type Importance of Message - Possible Values: "alert" \

    Authentication

    As a decentralised exchange, Switcheo does not use passwords or API keys. Instead, authentication is done by signing the request payload or blockchain transaction using the blockchain-specific digital signature with the user's private key.

    Currently, all supported blockchains uses the ellipitic curve digital signature algorithim (ECDSA). However, the curves and hashing algorithim used for each blockchain differ slightly per blockchain.

    Blockchain Signature Algo Curve Hash Function
    NEO ECDSA NIST P-256 SHA-256
    ETH ECDSA secp256k1 SHA-3 (Keccak)

    Action Authentication

    Two steps are required to perform an action.

    1. In the first step:
      • Sign the parameters of the request using the user's private key
      • Send both the raw parameters and the result of signing the parameters to the first API endpoint
      • A response with either a message or transaction will be returned
    2. In the second step:
      • Sign the returned message or transaction with the user's private key
      • Send the signed message or transaction to the second API endpoint

    Signing Messages for NEO

    Signing a message for NEO

    const { wallet } = require('@cityofzion/neon-js')
    function signMessage(message, privateKey) {
      return wallet.generateSignature(message, privateKey)
    }
    signMessage('Hello', '<private key>')
    
    

    neon-js can be used to sign messages for NEO.

    View implementation details

    Signing Request Parameters

    Signing parameters for API requests

    // 1. Serialize parameters into a string
    // Note that parameters must be ordered alphanumerically
    const rawParams = { blockchain: 'neo', timestamp: 1529380859, apple: 'Z', }
    const stableStringify = require('json-stable-stringify')
    const parameterString = stableStringify(rawParams)
    // parameterString: '{"apple":"Z","blockchain":"neo","timestamp":1529380859}'
    
    // 2. Serialize the parameter string into a hex string
    const Neon = require('@cityofzion/neon-js')
    const parameterHexString = Neon.u.str2hexstring(parameterString)
    
    // 3. Zero pad (parameterHexString.length / 2) into a two digit hex string
    const lengthHex = (parameterHexString.length / 2).toString(16).padStart(2, '0')
    // lengthHex: 37
    
    // 4. Concat lengthHex and parameterHexString
    const concatenatedString = lengthHex + parameterHexString
    
    // 5. Wrap concatenatedString in an empty neo transaction and serialize it
    const serializedTransaction = '010001f0' + concatenatedString + '0000'
    
    // 6. Sign serializedTransaction with the user's privateKey
    const signature = signMessage(serializedTransaction, '<private key>')
    
    // 7. Combine the raw parameters with the signature
    // to get the final parameters to send
    const parametersToSend = { ...rawParams, signature }
    

    To perform an action, request parameters have to be signed to generate a signature parameter. This signature parameter should then be sent together with the other parameters in the request.

    1. Convert the API parameters into a string, with parameters ordered alphanumerically
    2. Serialize the parameter string into a hex string
    3. Zero pad the length / 2 of the result from (2) into a two digit hex string
    4. Concat the result of (3) and (2)
    5. Wrap the result of (4) in a neo transaction
    6. Sign the result of (5) with the user's private key
    7. Send the result of (6) together with the raw parameters to the API endpoint

    Example

    Using the following parameters as an example:

    { blockchain: 'neo', timestamp: 1529380859, apple: 'Z' }

    1. Convert the parameters into a string with parameters ordered alphanumerically: {"apple":"Z","blockchain":"neo","timestamp":1529380859}
    2. Serialize the parameter into a hex string to get: 7b226170706c65223a225a222c22626c6f636b636861696e223a226e656f222c2274696d657374616d70223a313532393338303835397d
    3. The length of this string is 110, divide this by 2 to get 55
    4. Convert 55 to hexadecimal to get 37
    5. Zero pad 37 into a two digit string if needed. In this case 37 is already two digits so no padding is needed, but if the value was something like 8 then it should be padded to become 08
    6. Form a string by concatenating 37, and the result of (2) to get: 377b226170706c65223a225a222c22626c6f636b636861696e223a226e656f222c2274696d657374616d70223a313532393338303835397d
    7. Prepend 010001f0 and append 0000 to (6) to get: 010001f0377b226170706c65223a225a222c22626c6f636b636861696e223a226e656f222c2274696d657374616d70223a313532393338303835397d0000
    8. Let the user's private key be cd7b887c29a110e0ce53e81d6dd02805fc7b912718ff8b6659d8da42887342bd
    9. Sign the result from (7) with the private key in (8) to get f3831797cbd4244d1ccffafc42739e662e8b06c7a6f98efe5155d0eab1cf5c50fbac6d2a4c4487cbf71498b81e1e9478f06bef02d32da5d8f8bb7fdfc449879a

    View a full example implementation

    Signing Transactions

    Signing a transaction for NEO

    // Send the parameters for the first step of an action
    // and retrieve the response
    const response = ...
    const { transaction } = response
    
    // verify the transaction data to ensure that it matches the user's intention
    ...
    
    const { tx, wallet } = require('@cityofzion/neon-js')
    
    function signTransaction(transaction, privateKey) {
      const serializedTxn = tx.serializeTransaction(transaction, false)
      return wallet.generateSignature(serializedTxn, privateKey)
    }
    
    // send the result to the second API endpoint
    const signatureToSend = signTransaction(transaction, '<private key>')
    

    The second step of an action usually requires the returned transaction to be signed, this is done by:

    1. Checking the returned transaction data to ensure it matches the user's intention
    2. Serializing the transaction, this can be done with neon-js (View implementation details)
    3. Signing the serialized transaction with the user's private key

    Tickers

    This tickers section consists of endpoints that allow retrieval of market data on Switcheo Exchange.

    Authentication is not required for these endpoints.

    Candlesticks

    Returns candlestick chart data filtered by url parameters.

    HTTP Request

    GET /v2/tickers/candlesticks

    Example request

    {
      "pair": "SWTH_NEO",
      "interval": 1,
      "start_time": 1531213200,
      "end_time": 1531220400
    }
    

    Example response

    [
      {
        "time": "1531215240",
        "open": "0.00049408",
        "close": "0.00049238",
        "high": "0.000497",
        "low": "0.00048919",
        "volume": "110169445.0",
        "quote_volume": "222900002152.0"
      },
      {
        "time": "1531219800",
        "open": "0.00050366",
        "close": "0.00049408",
        "high": "0.00050366",
        "low": "0.00049408",
        "volume": "102398958.0",
        "quote_volume": "205800003323.0"
      },
      ...
    ]
    
    

    Request parameters

    Parameter Type Required Description
    pair string yes Only show chart data of this trading pair
    start_time integer yes Start of time range for data in epoch seconds
    end_time integer yes End of time range for data in epoch seconds
    interval integer yes Candlestick period in minutes Possible values are: 1, 5, 30, 60, 360, 1440

    Response parameters

    Parameter Description
    time Epoch time for the beginning of the interval (in seconds).
    open Opening price at the start of the interval.
    close Closing price at the end of the interval.
    high Highest price during the interval.
    low Lowest price during the interval.
    volume Volume in base token traded during the interval.
    quote_volume Volume in quoted token traded during the interval.

    Last 24 hours

    Returns 24-hour data for all pairs and markets.

    HTTP Request

    GET /v2/tickers/last_24_hours

    Example response

    [
      {
        "pair": "SWTH_NEO",
        "open": "0.00047221",
        "close": "0.00049769",
        "high": "1.2",
        "low": "0.0004563",
        "volume": "11897236125.0",
        "quote_volume": "19927606119564.0"
      },
      {
        "pair": "GAS_NEO",
        "open": "0.0",
        "close": "0.0",
        "high": "0.0",
        "low": "0.0",
        "volume": "0.0",
        "quote_volume": "0.0"
      }
    ]
    
    

    Response parameters

    Parameter Description
    time Epoch time for the beginning of the interval (in seconds).
    open Opening price at the start of the interval.
    close Closing price at the end of the interval.
    high Highest price during the interval.
    low Lowest price during the interval.
    volume Volume in base token traded during the interval.
    quote_volume Volume in quoted token traded during the interval.

    Last price

    Returns last price of the requested symbol(s) / base(s). Defaults to all symbols & bases.

    HTTP Request

    GET v2/tickers/last_price

    Example request

    {
      "symbols": ["SWTH","GAS"]
    }
    

    Example response

    {
        "GAS": {
            "NEO": "0.31200000"
        },
        "SWTH": {
            "GAS": "0.00410000",
            "NEO": "0.00106600"
        }
    }
    
    

    Request parameters

    Parameter Type Required Description
    symbols array no Return the price for only these symbols.
    bases array no Return the price for only these bases.

    Response parameters

    Parameter Description
    symbol JSON Object containing a list of base:price tuples
    base Base token symbol
    price Price of symbol in base units with 8 decimal precision

    Offers

    An offer represents an open order on the Switcheo Exchange offer book.

    Funds used to make an offer are locked in the contract until the order is cancelled or filled.

    List Offers

    Example request - ETH Pair

    {
      "pair": "JRC_ETH",
      "contract_hash": "0x607af5164d95bd293dbe2b994c7d8aef6bec03bf"
    }
    

    Example response

     [
        {
            "id": "e4a76e85-53dc-4a25-ab44-4eed504ce0e0",
            "address": "0x0fc8f7bab5feb402ed624b5f5fc88a0648a7f3ae",
            "available_amount": 2.4043723e+24,
            "offer_amount": 1e+25,
            "want_amount": 1500000000000000000,
            "offer_asset": "JRC",
            "want_asset": "ETH"
        },
        ....
    ]
    

    Retrieves the 70 best offers (per side) on the offer book.

    HTTP Request

    GET /v2/offers

    Request Parameters

    Parameter Type Required Description
    pair string yes Only return offers from this pair.
    contract_hash string no Only return offers for this contract hash.

    Response parameters

    Parameter Description
    id Unique identifier for the offer object.
    address Address of the offer maker
    available_amount Remaining amount of the offer_asset that has not been taken by other orders.
    offer_amount Total amount of the offer_asset.
    want_amount Total amount of the want_asset.
    offer_asset Symbol of the token that the offer maker is offering.
    want_asset Symbol of the token that the offer maker wants .

    Example

    Full list offers example

    Offer book

    Example request

    {
      "pair": "SWTH_NEO",
      "contract_hash": "eed0d2e14b0027f5f30ade45f2b23dc57dd54ad2"
    }
    

    Example response

    {
      asks: [
        {
          "price": "0.00046103",
          "quantity": "9378.0"
        },
        {
          "price": "0.00046759",
          "quantity": "1084.30496802"
        }
      ],
      bids: [
        {
        "price": "0.00045645",
        "quantity": "6678.0"
        },
        {
          "price": "0.0004534",
          "quantity": "12279.38328187"
        },
      ]
    }
    

    Retrieves the offer book.

    HTTP Request

    GET /v2/offers/book

    Request Parameters

    Parameter Type Required Description
    pair string yes Only return offers from this pair.
    contract_hash string no Only return offers for this contract hash.

    Response parameters

    Parameter Description
    price Bid or Ask price.
    quantity If bids side, returns amount of tokens being bought. If asks side, returns amount of tokens that is being sold.

    Trades

    A trade represents a fill of an offer.

    This happens when an incoming order matches an offer on the opposite side of the order book in price.

    Trades can be seen on the Trade History column on Switcheo Exchange.

    List Trades

    Example request

    {
      "blockchain": "neo",
      "pair": "SWTH_NEO",
      "limit": 3,
      "contract_hash": "<contract hash>"
    }
    

    Example response

    [
      {
        "id": "712a5019-3a23-463e-b0e1-80e9f0ad4f91",
        "fill_amount": 9122032316,
        "take_amount": 20921746,
        "event_time": "2018-06-08T11:32:03.219Z",
        "is_buy": false
      },
      {
        "id": "5d7e42a2-a8f3-40a9-bce5-7304921ff691",
        "fill_amount": 280477933,
        "take_amount": 4207169,
        "event_time": "2018-06-08T11:31:42.200Z",
        "is_buy": false
      },
      ...
    ]
    

    Retrieves trades that have already occurred on Switcheo Exchange filtered by the request parameters.

    HTTP Request

    GET /v2/trades

    Request Parameters

    Parameter Type Required Description
    contract_hash string yes Only return trades for this contract hash.
    pair string yes Only return trades for this pair.
    from integer no Only return trades after this time in epoch seconds.
    to integer no Only return trades before this time in epoch seconds.
    limit integer no Only return this number of trades (min: 1, max: 10000, default: 5000).

    Response parameters

    Parameter Description
    id Unique identifier for the trade object.
    fill_amount Amount of tokens that is given by the trade to the offer that it is filling.
    take_amount Amount of tokens that the trade takes from the offer's available_amount that it is filling.
    event_time Datetime that the trade occurs in Zulu Time (UDT+0)
    is_buy Whether the side of the trade is a buy.

    Example

    Full list trades example

    Recent Trades

    Example response

    [
      {
      "id": "dc1c8926-dda1-4f39-afae-0872da950340",
      "pair": "SWTH_NEO",
      "side": "sell",
      "price": "0.00046835",
      "quantity": "84.0",
      "total": "0.0393414",
      "timestamp": 1537924944
      },
      ...
    ]
    

    Returns 20 most recent trades on the selected pair sorted by executed time in descending order (most recent first).

    HTTP Request

    GET /v2/trades/recent

    Request Parameters

    Parameter Type Required Description
    pair string yes Only return trades for this pair.

    Response parameters

    Parameter Description
    id Unique identifier for the trade object.
    pair The pair on which the trade occurred.
    side Whether the trade was a buy or sell on this pair. Possible values are: buy, sell. If the pair is SWTH_NEO and the side is buy then the trade bought SWTH using NEO. If the side is sell then the trade sold SWTH for NEO.
    price Buy or sell price to 8 decimal places precision.
    quantity If buy side, returns amount of tokens that the trade takes from the offer's available_amount that it is filling. If sell side, returns amount of tokens that the trade gives the offer that it is filling
    total If buy side, returns amount of tokens that the trade gives the offer that it is filling. If sell side, returns amount of tokens that the trade takes from the offer's available_amount that it is filling
    timestamp Time that trade was broadcasted in epoch seconds

    Fees

    This section consists of endpoints which allow the retrieval of fee data on Switcheo Exchange.

    Authentication is not required for these endpoints.

    Fees

    Example response

    [
    {
        "eth_address": "0x3be1f07cdb14d7a19a150dba525b09a6caefde97",
        "maker": {
            "default": 0
        },
        "taker": {
            "default": 0.0015
        },
        "native_fee_discount": 0.5,
        "native_fee_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
        "enforce_native_fees": [
            "RHT",
            "RHTC"
        ],
        "native_fee_exchange_rates": {
            "NEO": "952.38095238",
            "GAS": "297.14285714",
            ...
            "ETH": "0",
            "JRC": "0",
            "SWC": "0"
        }
    }
    ]
    
    

    Returns fee data for various blockchains and pairs

    HTTP Request

    GET /v2/fees

    Response parameters

    Parameter Description
    maker / default Default rate for maker orders, before discount (in %)
    taker / default Default rate for taker orders, before discount (in %)
    native_fee_discount Discount applied to fee for use of native token (as a multiplier)
    native_fee_asset_id NEO contract hash of the Native Token (i.e. SWTH)
    enforce_native_fee List of asset tickers where fee must be paid in Native Tokens
    native_fee_exchange_rates List of token:value tuples, containing the exchange rate in Native Token

    Deposits

    Description

    Deposits allows movement of funds from your wallet into the Switcheo smart contract. This movement of funds is free of charge. Trading on Switcheo Exchange can only be done using funds that have been successfully deposited into the smart contract.

    Deposits are not instantaneous. Once a deposit has been executed, funds in your wallet balance would be deducted by the amount of tokens you chose to deposit. Funds deducted from your wallet balance will be added to your contract balance but put on hold until Switcheo has determined that it has been successfully broadcasted to the blockchain.

    TestNet Faucet

    For the convenience of testing API endpoints, tokens can be received through our TestNet faucet. To use the faucet:

    1. Go to https://beta.switcheo.exchange/
    2. Click on the TestNet/MainNet selector at the bottom of the page
    3. Select TestNet V2
    4. Click on WALLET LOGIN to login
    5. Click on the FAUCET button to receive tokens for testing

    Create Deposit

    Create a deposit

    function createDeposit ({ blockchain, address, assetID, amount, privateKey }) {
      const signableParams = { blockchain, assetID, amount, timestamp: getTimestamp(),
                               contractHash: CONTRACT_HASH }
      const signature = signParams(signableParams, privateKey)
      const apiParams = { ...signableParams, address, signature }
      return api.post(API_URL + '/deposits', apiParams)
    }
    
    // NOTE: in this example, the parameters can be in camel case because
    // the `signParams` and `api.post` method automatically convert param keys
    // to snake case
    createDeposit({
      blockchain: 'neo',
      address: user.address,
      assetID: 'SWTH',
      amount: toNeoAssetAmount(7),
      privateKey: user.privateKey
    })
    

    Example request

    {
      "blockchain": "neo",
      "asset_id": "SWTH",
      "amount": "100000000",
      "timestamp": 1531543361074,
      "contract_hash": "<contract hash>",
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f",
      "signature": "<signature>"
    }
    

    Example response

    {
      "id": "ad5a6e05-d992-47c0-9f52-79ca173dccd1",
      "transaction": {
        "hash": "a53f26b21f2ede25909e8ac3bf094ac3318e31d5cd654bde4ba734478f1368b2",
        "sha256": "caa6727a795ef2dba75c7ea143b6020ffc0d2d4164d7be9639ebb9a1bbd7a6d1",
        "type": 209,
        "version": 1,
        "attributes": [
          [
            null
          ]
        ],
        "inputs": [
          [
            null
          ]
        ],
        "outputs": [
          [
            null
          ]
        ],
        "scripts": [],
        "script": "0800e1f505000000001432e125258b7db0a0dffde5bd03b2b859253538ab145f8e3fcb095b55f53c44a1cab6e9c1a0da67cf8753c1076465706f73697467d24ad57dc53db2f245de0af3f527004be1d2d0ee",
        "gas": 0
      },
      "script_params": {
        "scriptHash": "eed0d2e14b0027f5f30ade45f2b23dc57dd54ad2",
        "operation": "deposit",
        "args": [
          "5f8e3fcb095b55f53c44a1cab6e9c1a0da67cf87",
          "32e125258b7db0a0dffde5bd03b2b859253538ab",
          100000000
        ]
      }
    }
    

    This endpoint creates a deposit which can be executed through Execute Deposit. To be able to make a deposit, sufficient funds are required in the depositing wallet.

    HTTP Request

    POST /v2/deposits

    Request Parameters

    Parameter Type Required Description
    blockchain string yes Blockchain that the token to deposit is on. Possible values are: neo.
    asset_id string yes The asset symbol or ID to deposit.
    amount amount yes Amount of tokens to deposit.
    contract_hash string yes Switcheo Exchange contract hash to execute the deposit on.
    timestamp timestamp yes The exchange's timestamp to be used as a nonce.
    signature string yes Signature of the request payload. See Authentication for more details.
    address address yes The depositer's address. Do not include this in the parameters to be signed.

    Example

    Full create deposit example

    Execute Deposit

    Execute a deposit

    function executeDeposit ({ deposit, privateKey }) {
      const signature = signTransaction(deposit.transaction, privateKey)
      const url = `${API_URL}/deposits/${deposit.id}/broadcast`
      return api.post(url, { signature })
    }
    

    Example request

    {
      "signature": "<signature>"
    }
    

    This is the second endpoint required to execute a deposit. After using the Create Deposit endpoint, you will receive a response which requires additional signing.

    The signature should then be attached as the signature parameter in the request payload.

    Note that a sha256 parameter is provided for convenience to be used directly as part of the ECDSA signature process. In production mode, this should be recalculated for additional security.

    HTTP Request

    POST /v2/deposits/:id/broadcast

    Request Parameters

    Parameter Type Description
    signature string Signed response from create deposit endpoint. (See how and what to sign for different blockchains above)

    Full execute deposit example

    Withdrawals

    Description

    Withdrawals allow free movement of tokens from the Switcheo smart contract into your wallet. This movement of tokens is free of charge.

    Once a withdrawal has been executed, tokens in your contract balance would be deducted. Tokens that are put on hold by orders cannot be withdrawn.

    Withdrawals are not instantaneous. Tokens deducted from your contract balance will be added to your wallet balance but put on hold until the withdrawal has been fully executed.

    Create Withdrawal

    Create a withdrawal

    function createWithdrawal ({ blockchain, address, assetID, amount, privateKey }) {
      const signableParams = { blockchain, assetID, amount,
                               contractHash: CONTRACT_HASH, timestamp: getTimestamp() }
      const signature = signParams(signableParams, privateKey,)
      const apiParams = { ...signableParams, address, signature }
      return api.post(API_URL + '/withdrawals', apiParams)
    }
    
    // NOTE: in this example, the parameters can be in camel case because
    // the `signParams` and `api.post` method automatically convert param keys
    // to snake case
    createWithdrawal({
      blockchain: 'neo',
      address: user.address,
      assetID: 'SWTH',
      amount: (toNeoAssetAmount(1)),
      privateKey: user.privateKey
    })
    

    Example request

    {
      "blockchain": "neo",
      "asset_id": "SWTH",
      "amount": "100000000",
      "timestamp": 1531544358560,
      "contract_hash": "<contract hash>",
      "signature": "<signature>",
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f"
    }
    

    Example response

    {
      "id": "e0f56e23-2e11-4848-b749-a147c872cbe6"
    }
    

    This endpoint creates a withdrawal which can be executed through Execute Withdrawal. To be able to make a withdrawal, sufficient funds are required in the contract balance.

    A signature of the request payload has to be provided for this API call.

    HTTP Request

    POST /v2/withdrawals

    Request Parameters

    Parameter Type Required Description
    blockchain string yes Blockchain that the token to withdraw is on. Possible values are: neo.
    asset_id string yes The asset symbol or ID to withdraw.
    amount amount yes Amount of tokens to withdraw.
    timestamp timestamp yes The exchange's timestamp to be used as a nonce.
    contract_hash string yes Switcheo Exchange contract hash to execute the withdraw on.
    signature string yes Signature of the request payload. See Authentication for more details.
    address address yes The withdrawer's address. Do not include this in the parameters to be signed.

    Example

    Full create withdrawal example

    Execute Withdrawal

    Executing a withdrawal

    function executeWithdrawal ({ withdrawal, privateKey }) {
        const signableParams = { id: withdrawal.id, timestamp: getTimestamp() }
        const signature = signParams(signableParams, privateKey)
        const url = `${API_URL}/withdrawals/${withdrawal.id}/broadcast`
        return api.post(url, { ...signableParams, signature })
    }
    

    Example request

    {
      "id": "998f1bdc-f26f-44f2-b204-403e24d5777f",
      "timestamp": 1531545149715,
      "signature": "<signature>"
    }
    

    Example response

    {
      "event_type": "withdrawal",
      "amount": -100000000,
      "asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
      "status": "confirming",
      "id": "998f1bdc-f26f-44f2-b204-403e24d5777f",
      "blockchain": "neo",
      "reason_code": 9,
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f",
      "transaction_hash": null,
      "created_at": "2018-07-14T05:12:29.699Z",
      "updated_at": "2018-07-14T05:12:29.765Z",
      "contract_hash": "<contract hash>"
    }
    

    This is the second endpoint required to execute a withdrawal. After using the Create Withdrawal endpoint, you will receive a response which requires additional signing.

    HTTP Request

    POST /v2/withdrawals/:id/broadcast

    Request Parameters

    Parameter Type Required Description
    id string yes id parameter in the response from create withdrawal endpoint.
    timestamp timestamp yes The exchange's timestamp to be used as a nonce.
    signature string yes Signature of the request payload. See Authentication for more details.

    Example

    Full execute withdrawal example

    Orders

    Description

    Orders are instructions to buy or sell assets on Switcheo Exchange.

    At the moment, only Limit orders are available. Market, Fill-Or-Cancel, Make-Or-Cancel, etc. strategies are not available yet.

    As such, orders will contain a combination of zero or one make and/or zero or more fills.

    Once an order is placed, the funds required for the order is removed from the user's balance and placed on hold until the order is filled or the order is cancelled.

    The Order Object

    Example order

    [
      {
        "id": "c415f943-bea8-4dbf-82e3-8460c559d8b7",
        "blockchain": "neo",
        "contract_hash": "c41d8b0c30252ce7e8b6d95e9ce13fdd68d2a5a8",
        "address": "20abeefe84e4059f6681bf96d5dcb5ddeffcc377",
        "side": "buy",
        "offer_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
        "want_asset_id": "602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7",
        "offer_amount": "100000000",
        "want_amount": "20000000",
        "transfer_amount": "0",
        "priority_gas_amount": "0",
        "use_native_token": false,
        "native_fee_transfer_amount": 0,
        "deposit_txn": null,
        "created_at": "2018-05-15T10:54:20.054Z",
        "status": "processed",
        "order_status": "completed",
        "fills": [...],
        "makes": [...]
      }
    ]
    
    Attribute Description
    id Unique identifier for the order object.
    blockchain The blockchain that the order exists on.
    contract_hash Switcheo Exchange contract hash that the order is on.
    address Wallet Address of the order maker.
    side Whether the order maker is buying or selling.
    offer_asset_id Asset ID of the token that the order maker is offering.
    want_asset_id Asset ID of the token that the order maker wants.
    offer_amount Total amount of the token that the order maker is offering.
    want_amount Total amount of the token that the order maker wants.
    transfer_amount Amount (out of the offer_amount) that was deposited into the contract in order to create the order.
    priority_gas_amount Amount of gas paid by the order maker as priority.
    use_native_token Whether SWTH tokens was used by the order maker to pay taker fees.
    native_fee_transfer_amount Amount of SWTH that was deposited into the contract in order to pay the taker fees of the order.
    deposit_txn Transaction that was used for deposits related to the order creation.
    created_at Time when the order was created.
    status Status of the order in the context of the blockchain. Possible values are pending (after creation), processed (after broadcast), expired (created but not broadcasted for a long time)
    order_status Status of the order in the context of the exchange. Possible values are open (on orderbook waiting to be filled),cancelled (cancelled open order), completed (maker order that is entirely filled or broadcasted filler order)
    fills Refer to the fills section for more details.
    makes Refer to the makes section for more details.

    The Fill Object

    Example fill

    {
      "id": "6531a67c-6b2e-49b6-8a33-20dfb32b5d8e",
      "offer_hash": "fcc8ef7fa17cd540b2e0cbbed9e231db9994279b08618208a4dee292370b38b9",
      "offer_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
      "want_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
      "fill_amount": "100000000",
      "want_amount": "1000000",
      "filled_amount": "100000000",
      "fee_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
      "fee_amount": "1500",
      "price": "0.01",
      "txn": [Object],
      "status": "success",
      "created_at": "2018-06-08T07:23:32.299Z",
      "transaction_hash": "c51232abf42935a52d6c27122e5de5f92b33ffc43f9a85c5ee6353009c81f80c"
    }
    

    When an order is created, the order matching engine will match the order against existing offers.

    If any matching offers are found, then fills are created. These fills represent the filling of the order by the matching offers.

    Attribute Description
    id Unique identifier for the fill object.
    offer_hash The hash of the corresponding offer for this fill object.
    offer_asset_id Asset ID of the token that the order maker is offering.
    want_asset_id Asset ID of the token that the order maker wants.
    fill_amount Amount of tokens that the target offer wants.
    want_amount Amount of tokens that is being taken from the target offer.
    filled_amount Amount of tokens that is given to the target offer.
    fee_asset_id Asset id of the token used for fees.
    fee_amount Amount of fees paid for the fill.
    price The buy or sell price of order.
    txn The transaction representing this fill.
    status Status of the fill. Possible values are pending (after order creation), confirming (after order broadcast), success (after broadcast success), expired (after order creation but not broadcasted for a long while)
    created_at Time when the fill was created.
    transaction_hash Transaction hash of the transaction representing this fill.

    The Make Object

    Example make

    {
      "id": "dc8a36dd-c405-4999-875a-ce619aecbb5c",
      "offer_hash": "3423bd82c6e2ec36ccba7a949d5732905e5c6b179517c8aebd9caf72977d817d",
      "available_amount": "1000",
      "offer_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
      "offer_amount": "1234567800",
      "want_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
      "want_amount": "111111102",
      "filled_amount": "1234567800",
      "txn": [Object],
      "cancel_txn": [Object],
      "price": "0.09",
      "status": "success",
      "created_at": "2018-06-08T07:21:19.988Z",
      "transaction_hash": "ff6e73805aed42d445ec0e8d47375e024a7d8c99cd5b8c375d607fec61b80567"
    }
    

    When an order is created, the order matching engine will match the order against existing offers.

    If the order is not fully filled by existing offers, a make is created. This make represents the unfilled amount of the order.

    Attribute Description
    id Unique identifier for the make object.
    offer_hash The hash of the corresponding offer for this make object.
    available_amount Remaining amount of the offered tokens in the make that has not been filled by other offers.
    offer_asset_id Asset ID of the token that the make is offering.
    offer_amount Amount of tokens that the make is offering.
    want_asset_id Asset ID of the token that the make wants.
    want_amount Amount of tokens that the make wants.
    filled_amount Amount of tokens out of the make's offer_amount that has been taken by other orders.
    txn The transaction representing this make.
    cancel_txn If this make was cancelled, this parameter would be the transaction that represents the cancellation.
    price Buy or sell price of order.
    status Status of the make. Possible values are pending (after order creation), confirming (after order broadcast), success (after broadcast success), cancelling (after cancellation broadcasted), cancelled (after cancellation broadcast success), expired (after order creation but not broadcasted for a long while)
    created_at Time when the make was created.
    transaction_hash Transaction hash of the transaction representing this make.

    List Orders

    Example request

    {
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f",
      "contract_hash": "<contract hash>"
    }
    

    Example Response

    [
      {
        "id": "c415f943-bea8-4dbf-82e3-8460c559d8b7",
        "blockchain": "neo",
        "contract_hash": "c41d8b0c30252ce7e8b6d95e9ce13fdd68d2a5a8",
        "address": "20abeefe84e4059f6681bf96d5dcb5ddeffcc377",
        "side": "buy",
        "offer_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
        "want_asset_id": "602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7",
        "offer_amount": "100000000",
        "want_amount": "20000000",
        "transfer_amount": "0",
        "priority_gas_amount": "0",
        "use_native_token": false,
        "native_fee_transfer_amount": 0,
        "deposit_txn": null,
        "created_at": "2018-05-15T10:54:20.054Z",
        "status": "processed",
        "order_status": "processed",
        "fills": [...],
        "makes": [...]
      }
    ]
    

    Retrieves orders from a specific address filtered by the given parameters.

    HTTP Request

    GET /v2/orders

    Request Parameters

    Parameter Type Required Description
    address address yes Only return orders made by this address.
    pair string no Only return orders from this pair.
    contract_hash string yes Only return orders from this contract hash.
    from integer no Only return orders that are last updated at or after this time
    order_status string no Only return orders have this status. Possible values are open, cancelled, completed
    before_id string no Only return orders that are created before the order with this id
    limit integer no Only return up to this number of orders (min: 1, max: 200, default: 50).

    Example

    Full list orders example

    Create Order

    This endpoint creates an order which can be executed through Broadcast Order. Orders can only be created after sufficient funds have been deposited into the user's contract balance. A successful order will have zero or one make and/or zero or more fills.

    HTTP Request

    POST /v2/orders

    Request Parameters

    For the below descriptions, the order maker refers to your API user.

    Create an order

    function createOrder({ pair, blockchain, side, price,
                           wantAmount, useNativeTokens, orderType,
                           privateKey, address }) {
      const signableParams = { pair, blockchain, side, price, wantAmount,
                               useNativeTokens, orderType, timestamp: getTimestamp(),
                               contractHash: CONTRACT_HASH }
    
      const signature = signParams(signableParams, privateKey)
      const apiParams = { ...signableParams, address, signature }
      return api.post(API_URL + '/orders', apiParams)
    }
    
    // NOTE: in this example, the parameters can be in camel case because
    // the `signParams` and `api.post` method automatically convert param keys
    // to snake case
    createOrder({
      pair: 'SWTH_NEO',
      blockchain: 'neo',
      address: user.address,
      side: 'buy',
      price: (0.001).toFixed(8),
      // if the side is 'buy', then this is the amount of SWTH you want
      // if the side is 'sell' then this is the amount of NEO you want
      wantAmount: toAssetAmount(20.5, 'SWTH'),
      useNativeTokens: true,
      orderType: 'limit',
      privateKey: user.privateKey
    })
    

    Example request

    {
      "pair": "SWTH_NEO",
      "blockchain": "neo",
      "side": "buy",
      "price": "0.00100000",
      "want_amount": "2050000000",
      "use_native_tokens": true,
      "order_type": "limit",
      "timestamp": 1531541888559,
      "contract_hash": "<contract hash>",
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f",
      "signature": "<signature>"
    }
    

    Example response

    {
      "id": "cfd3805c-50e1-4786-a81f-a60ffba33434",
      "blockchain": "neo",
      "contract_hash": "eed0d2e14b0027f5f30ade45f2b23dc57dd54ad2",
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f",
      "side": "buy",
      "offer_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
      "want_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
      "offer_amount": "2050000",
      "want_amount": "2050000000",
      "transfer_amount": "0",
      "priority_gas_amount": "0",
      "use_native_token": true,
      "native_fee_transfer_amount": 0,
      "deposit_txn": null,
      "created_at": "2018-07-13T07:58:11.340Z",
      "status": "pending",
      "order_status": "nil",
      "fills": [
        {
          "id": "2eaa3621-0e7e-4b3d-9c8c-454427f20949",
          "offer_hash": "bb70a40e8465596bf63dbddf9862a009246e3ca27a4cf5140d70f01bdd107277",
          "offer_asset_id": "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
          "want_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
          "fill_amount": "1031498",
          "want_amount": "2050000000",
          "filled_amount": "",
          "fee_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
          "fee_amount": "1537500",
          "price": "0.00050317",
          "txn": [Object],
          "status": "pending",
          "created_at": "2018-07-13T07:58:11.353Z",
          "transaction_hash": "97ad8c0af68d22304e7f2d09d04f3beed29a845fe57de53444fff1507b752b99"
        }
      ],
      "makes": []
    }
    
    Parameter Type Required Description
    blockchain string yes Blockchain that the pair is on. Possible values are: neo.
    contract_hash string yes Switcheo Exchange contract hash to execute the order on.
    pair string yes Pair to trade, e.g. SWTH_NEO.
    side string yes Whether to buy or sell on this pair. Possible values are: buy, sell. If the pair is SWTH_NEO and the side is buy then the order is to buy SWTH using NEO. If the side is sell then the order is to sell SWTH for NEO.
    price string yes Buy or sell price to 8 decimal places precision.
    want_amount amount yes If the pair is SWTH_NEO and the side is buy then this is the amount of SWTH you want. If the side is sell then this is the amount of NEO you want.
    use_native_tokens boolean yes Whether to use SWTH as fees or not. Possible values are: true or false.
    order_type string yes Order type, possible values are: limit, otc.
    otc_address address no Address of the counterparty in OTC trades. Must be provided if and only if order_type is otc.
    timestamp timestamp yes The exchange's timestamp to be used as a nonce.
    signature string yes Signature of the request payload. See Authentication for more details.
    address address yes Address of the order maker. Do not include this in the parameters to be signed.

    Example

    Full create order example

    Execute Order

    This is the second endpoint required to execute an order. After using the Create Order endpoint, you will receive a response which needs to be signed.

    Format of signatures parameter

    {
      makes: {
        <make_id>: <signature>
      },
      fills: {
        <fill_id_1>: <signature_1>,
        <fill_id_2>: <signature_2>
      }
    }
    

    Every txn of the fills and makes in the Create Order response should be signed, and structured in the signatures format shown on the right.

    HTTP Request

    POST /v2/orders/:id/broadcast

    Request Parameters

    Broadcast an order

    function signArray(array, privateKey) {
      return array.reduce((map, item) => {
        map[item.id] = signTransaction(item.txn, privateKey)
        return map
      }, {})
    }
    
    function broadcastOrder({ order, privateKey }) {
      const { fills, makes } = order
      const signatures = {
        fills: signArray(order.fills, privateKey),
        makes: signArray(order.makes, privateKey)
      }
      const url = `${API_URL}/orders/${order.id}/broadcast`
      return api.post(url, { signatures })
    }
    

    Example request

    {
      "signatures": {
        "fills": {
          "c821c814-d4a3-475b-b461-e909d8c8a59a": "<signature_1>"
        },
        "makes": {
          "d034djb1-9sd8-5b6k-1f9g-40fd9jntk86k": "<signature_2>",
          "ufdh03kt-23jg-h6k5-45fd-56dfy7ks0g9a": "<signature_3>"
        }
      }
    }
    
    Parameter Type Required Description
    signatures hash yes See the section description and example for the format.

    Example

    Full broadcast order example

    Create Cancellation

    Create a cancellation

    function createCancellation({ order, address, privateKey }) {
      const signableParams = { orderId: order.id, timestamp: getTimestamp() }
      const signature = signParams(signableParams, privateKey)
      const apiParams = { ...signableParams, signature, address }
      return api.post(API_URL + '/cancellations', apiParams)
    }
    

    This is the first API call required to cancel an order. Only orders with makes and with an available_amount of more than 0 can be cancelled.

    HTTP Request

    POST /v2/cancellations

    URL Parameters

    Example request

    {
      "order_id": "69c60da5-5832-4705-8390-de4bb4ed62c5",
      "timestamp": 1531471743957,
      "signature": "<signature>",
      "address": "87cf67daa0c1e9b6caa1443cf5555b09cb3f8e5f"
    }
    

    Example response

    {
      "id": "e4cf0472-59e3-4887-b2d3-720b98da0de6",
      "transaction": {
        "hash": "b4013bdfde6370198f043f2a5fb235242d20280361241d85ee0774c63856f65b",
        "sha256": "f760aaa9efe99059af46a2a9640e91527119e78f18322729ab620e20116b3cf8",
        "type": 209,
        "version": 1,
        "attributes": [
          [
            null
          ]
        ],
        "inputs": [
          [
            null
          ]
        ],
        "outputs": [
          [
            null
          ]
        ],
        "scripts": [],
        "script": "206e62f9555edc1f791d36f6f081d44b249e8696ab73f41cc809db73316eff6e65349b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc532e125258b7db0a0dffde5bd03b2b859253538ab52c10b63616e63656c4f6666657267d24ad57dc53db2f245de0af3f527004be1d2d0ee",
        "gas": 0
      },
      "script_params": {
        "scriptHash": "eed0d2e14b0027f5f30ade45f2b23dc57dd54ad2",
        "operation": "cancelOffer",
        "args": [
          "9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc532e125258b7db0a0dffde5bd03b2b859253538ab",
          "6e62f9555edc1f791d36f6f081d44b249e8696ab73f41cc809db73316eff6e65"
        ]
      }
    }
    
    Parameter Type Required Description
    order_id string yes The ID of the order to cancel.
    timestamp timestamp yes The exchange's timestamp to be used as a nonce.
    signature string yes Signature of the request payload. See Authentication for more details.
    address address yes Address of the order maker. Do not include this in the parameters to be signed.

    Example

    Full create cancellation example

    Execute Cancellation

    Execute a cancellation

    function executeCancellation({ cancellation, privateKey }) {
      const signature = signTransaction(cancellation.transaction, privateKey)
      const url = `${API_URL}/cancellations/${cancellation.id}/broadcast`
      return api.post(url, { signature })
    }
    

    This is the second endpoint that must be called to cancel an order. After calling the Create Cancellation endpoint, you will receive a transaction in the response which must be signed.

    Note that a sha256 parameter is provided for convenience to be used directly as part of the ECDSA signature process.

    In production mode, this should be recalculated for additional security.

    Example request

    {
      "signature": "<signature>"
    }
    

    HTTP Request

    POST /v2/cancellations/:id/broadcast

    URL Parameters

    Parameter Type Required Description
    signature string yes Signature of the transaction. See Authentication for more details.

    Example

    Full execute cancellation example

    Computing the Offer Hash

    Computing the offer_hash

    const invoke = {
        scriptHash: contractHash,
        operation: 'makeOffer',
        args: [
          u.reverseHex(userHash),
          u.reverseHex(offerAssetID), new BigNumber(offerAmount).toNumber(),
          u.reverseHex(wantAssetID), new BigNumber(wantAmount).toNumber(),
          u.str2hexstring(uuid),
        ],
      }
    
    const offerKeyBytes = invoke.args[0] + invoke.args[1] + invoke.args[3] +
      numToHex(invoke.args[2]) + numToHex(invoke.args[4]) + invoke.args[5]
    const offerHash = u.reverseHex(u.hash256(offerKeyBytes))
    
    const numToHex = (num) => {
      if (typeof num !== 'number') throw new Error('numToHex received a non-number')
      if (num < 0) throw Error.new(`numToHex received a negative number (${num})!`)
      if (num <= 16) {
        return u.num2hexstring(num)
      }
      return u.num2hexstring(num, 8, true)
    }
    
    

    In the previous sections, you may have noticed that offer_hashes are generated for fills and makes right after creation.

    To compute the offer_hash yourself, you can take reference from the example code snippet that is shown on the right. You can find the u library from neon-js.

    Balances

    Description

    There are two types of balances.

    Balance Description
    Wallet balance Number of tokens present in your wallet.
    Contract balance Number of tokens present in the Switcheo smart contract.

    Trading on Switcheo Exchange can only be done using your contract balance.

    List balances

    Example request:

    {
      "addresses": [
        "<address 1>"
      ],
      "contract_hashes": [
        "<contract hash 1>",
        "<contract hash 2>"
      ]
    }
    
    // The URL should be:
    // /v2/balances?addresses[]=address_1&contract_hashes[]=contract_hash_1&contract_hashes[]=contract_hash_2
    

    Example response:

    {
      "confirming": {
        "GAS": [
          {
            "event_type": "withdrawal",
            "asset_id": "602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7",
            "amount": -100000000,
            "transaction_hash": null,
            "created_at": "2018-07-12T10:48:48.866Z"
          }
        ]
      },
      "confirmed": {
        "GAS": "47320000000.0",
        "SWTH": "421549852102.0",
        "NEO": "50269113921.0"
      },
      "locked": {
        "GAS": "500000000.0",
        "NEO": "1564605000.0"
      }
    }
    

    List contract balances of the given address and contract.

    The purpose of this endpoint is to allow convenient querying of a user's balance across multiple blockchains, for example, if you want to retrieve a user's NEO and ethereum balances.

    As such, when using this endpoint, balances for the specified addresses and contract hashes will be merged and summed.

    HTTP Request

    /v2/balances

    URL parameters

    Parameter Type Required Description
    addresses array yes Only return balances for these addresses
    contract_hashes array yes Only return balances from these contract hashes.

    Example

    Full list balances example

    Websocket API

    This section documents the Switcheo Exchange websocket interface, which is used for transfer of streaming data to clients. It is recommended to use socket.io for connecting to this interface.

    Authentication is not required for these endpoints.

    Offers

    Example response

    [
      "join",
      {
        contractHash: "91b83e96f2a7c4fdf0c1688441ec61986c7cae26",
        pair: "FTWX_NEO"
       }
    ]
    

    Join Room

    Request parameters

    Parameter Description
    contractHash Address of the exchange contract to subscribe to.
    pair Asset pair to subscribe to.

    Response parameters

    Parameter Type Description

    Coming soon..

    Trades

    Coming soon..

    Orders

    Coming soon..

    Errors

    The Switcheo API uses the following error codes:

    Error Code Meaning
    400 Bad Request -- Your request is badly formed.
    401 Unauthorized -- You did not provide a valid signature.
    404 Not Found -- The specified endpoint or resource could not be found.
    406 Not Acceptable -- You requested a format that isn't json.
    422 Unprocessible Entity -- Your request had validation errors.
    429 Too Many Requests -- Slow down requests using an exponential backoff strategy.
    500 Internal Server Error -- We had a problem with our server. Try again later.
    503 Service Unavailable -- We're temporarily offline for maintenance. Please try again later.