# Introduction

DeltaDeFi is a decentralized exchange built on Cardano, powered by Hydra L2 — the best place to trade ADA onchain.

We deliver the performance of a centralized exchange with the security of self-custody: tightest spreads, sub-second fills, and your keys always in your hands.

## Why DeltaDeFi

{% hint style="success" %}
**Instant Confirmation** — \~50ms average on Hydra L2
{% endhint %}

{% hint style="success" %}
**10bps Flat Fee** — 0.10% per trade, no gas fees, no hidden costs
{% endhint %}

{% hint style="success" %}
**Binance-Compatible API** — Full REST + WebSocket for bots, strategies, and integrations
{% endhint %}

{% hint style="success" %}
**Self-Custody** — Non-custodial by design, with L1 settlement guarantee
{% endhint %}

## Products

<table><thead><tr><th width="164.49609375">Product</th><th width="136.5234375">Status</th><th>Description</th></tr></thead><tbody><tr><td><strong>Spot Trading</strong></td><td>Live</td><td>Tightest spreads. Sub-second fills. #1 ADA on-chain.</td></tr><tr><td><strong>Vaults</strong></td><td>Coming Soon</td><td>Managed USDC strategies with on-chain NAV.</td></tr><tr><td><strong>XP Program</strong></td><td>Season 1</td><td>Highest rewards for earliest believers. Trade, Deposit, Refer to earn XP.</td></tr></tbody></table>


# Learn

Understand the philosophy of DeltaDeFi's design

Although trading on DeltaDeFi is as easy as it seems, the design of this protocol is a combination of multiple design choices and research items. In this section, we will walk through the magic behind the scenes to bring the seamless trading experience on Cardano.

## What we cover

* [**Architecture**](/about/learn/architecture) — How DeltaDeFi works under the hood: accounts, the App Vault, Hydra integration, intent-based processing, and the order book.
* [**Trade**](/about/learn/trade) — Spot trading mechanics, performance specs, and supported order types.
* [**Whitepaper**](/about/learn/whitepaper) — The full technical whitepaper.

## Products at a glance

**Spot Trading** (Live) — Order-book DEX on Hydra L2 with \~50ms confirmation, 0.10% flat fee, and spreads 5–6x tighter than AMM alternatives.

**Vaults** (Coming Soon) — Managed USDC strategies with on-chain NAV tracking. Zero management fees.

**XP Program** (Season 1) — Earn XP by trading, depositing, and referring. Early participants are rewarded most.


# Architecture

In this session, we will follow the user journey, from account creation to withdrawal, to explain everything behind the scenes. After reading this session, you will have a much clearer perspective on DeltaDeFi's philosophy and understand how efficient trading can be performed in a decentralized manner.


# Account

Every DeltaDeFi account is composed of 2 keys, the master key and the operation key. When you use your Cardano wallet to connect to DeltaDeFi, your wallet is the golden source of truth for your account. Once you have created an account, an operation key will be generated. Here is the difference between the two:

|                                | Master Key                                           | Operation Key                                                                                                                                                         |
| ------------------------------ | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Where it comes from            | Your Cardano wallet                                  | Generated                                                                                                                                                             |
| Actions it can authorize       | All, including rotation of trade key                 | The master key owner can define the access right. In current design, it is by default only in app actions like placing order. Withdrawal is not allowed with this key |
| Information DeltaDeFi controls | The public key hash                                  | The public key hash and the encrypted key by user defined password with AES-GCM algorithm                                                                             |
| Value held by the key          | The key holds all value as it is your Cardano wallet | The key holds exactly empty value except user send funds to it outside of DeltaDeFi                                                                                   |
| Signing transactions           | Like how you perform signing anywhere else           | Use API Key to obtain the encrypted key decrypt it for programmatic signing                                                                                           |

When you first sign in DeltaDeFi and create an account, an operation key is generated on the client side and encrypted with your provided password. The encrypted operation key with public key hash information will be sent to DeltaDeFi's server to complete the account opening process.

After that, all the signatures needed for trading could then be obtained programmatically to enable a seamless user experience.

***

### Related FAQ

* [How do I get my API keys?](/start-trading/developers/auth)
* [How can I sign a Cardano transaction?](/faq/cardano#how-can-i-sign-a-cardano-transaction)
* [How exactly is my operation key generated?](/faq/product#how-exactly-is-my-operation-key-generated)


# App Vault

All user fund in DeltaDeFi sits on a single validator address - App Vault. When you send funds to the App Vault address, you can create an on-chain proof of asset ownership record.  With that proof, you can redeem the equivalent asset value from the App Vault. In this session, we will dive deeper into what exactly you are trading on DeltaDeFi, given all values are sitting on the same address all the time.

### Depositing

Depositing is an action where there is actual value inflow to the App Vault. At the time of deposit, users can create a distinct proof of asset ownership.

### Trading

Trading is then a notion of users trading against each other's proof of asset ownership, with the underlying asset value itself untouched.

### Withdrawal

Withdrawal is an action where there is actual value outflow from the App Vault. At the time of withdrawal, users can use their proof of asset ownership to redeem assets out of the DeltaDeFi validator system.


# Hydra

The (not a) secret sauce of DeltaDeFi to enable efficient trading is that we build with Hydra, a Cardano state channel L2 technology.

### Compressing App Information with Merkle Tree

Although inside Hydra we can theoretically do anything we want, releasing all the constraints we have on Cardano L1, we still have to consider the hard L1 protocol limitation at the time of committing UTxOs to and decommitting UTxOs from Hydra.

One obvious limitation is the size of app states. Hypothetically DeltaDeFi has 10,000 users, it will then be technically super difficult to carry all app information into and out of Hydra. Therefore, at the time of committing and decommitting UTxOs, we will compress all the information needed in a Merkle tree root to support indefinitely scalable DApp states.

Since inside Hydra we can relax execution units and transaction fee limitations, we can perform huge transactions once after UTxOs are committed to break down into many distinct UTxOs. From there, our exchange behaves like any other L1 order book DEX, except we can have less care on efficiency since every transaction has exactly 0 cost. At the time of decommitting UTxOs, we will perform the mirrored set of huge transactions to compress app states back into the Merkle root hash.

The limitation of this approach is that on L1, when we handle deposits and withdrawals, we have to follow the same rules as all other Cardano L1 transactions, performing transactions one by one to the script UTxO containing the affected Merkle root hash.

### Data Integrity of Merkle Tree Element

Since the Merkle tree root hash itself does not contain the records themselves, and losing the actual records poses a significant threat in terms of permanent lock of user funds, DeltaDeFi will make the entire Merkle tree operation record public to avoid this risk.

***

### Related FAQ

* [I have heard about the Hydra Head protocol being custodial. Is my fund deposited into DeltaDeFi safe?](https://docs.deltadefi.io/about/learn/architecture/pages/YOlyP8nUjCIvAZuB7hb9#i-have-heard-about-the-hydra-head-protocol-being-custodial.-is-my-fund-deposited-into-deltadefi-safe)


# Intent and Process

DeltaDeFi has reproduced the account-based model in UTxOs for abstracting the UTxO model complexity in building the DApp. With that notion, most user actions in DeltaDeFi start with initializing an intent:

* It requires the account's signature (either master key or operation key) to produce the intent
* DeltaDeFi will process the intents in a queue to prevent UTxO contention
* Applicable to L1 deposit and all Hydra actions

### Sacrifying Decentralization?

DeltaDeFi software system is crucial to make the entire product work. However, with such design, one thing that we will never sacrifice is the users' fund safety. To put in simple terms:

* Without users' signature, value can never transfer to other accounts
* Without DeltaDeFi software, the DEX cannot function in an efficient way

### Emergency Actions

That being said, we still want to keep our DEX as decentralized as possible. One line that we hold strongly is that users have a route to withdraw assets out of the system without DeltaDeFi's permission. Any users, in case of any emergency incidents such as an official software disruption, can perform emergency withdrawal by crafting a valid Cardano transaction themselves.&#x20;

However, any emergency actions without coordinating with DeltaDeFi's software might affect other users' experience, such as failing to fill an order supposed to be as instructed by the order book engine. To prevent such an abuse, the emergency actions have been enforced with a time lag, such that in case of misuse, DeltaDeFi can have a sufficient time window to account for the self-initiated emergency actions without affecting other normal users' experience.


# Order Book

Every order instruction will go into the single-threaded order book engine. However, DeltaDeFi's order book is indeed completely detached from the on-chain logic.&#x20;

### Order Book Engine

* Provide instructions on which order is matched or cancelled
* Ensuring the fairness of the DEX
* Purely off-chain

### On-chain Validators

* Safeguard value movement within DeltaDeFi
* Instructions are valid only when approved by the users' private key

We acknowledge that fairness is important to traders, therefore, we will make the market trading records available to the public. Such that any malicious behaviours can be detected by the community, posing a soft restriction on our team to behave honestly.

To learn more about the order book engine, please visit the whitepaper.


# Trade

DeltaDeFi offers spot trading on an order-book model, powered by Hydra L2 for near-instant execution.

## Key specs

| Metric             | Value                                  |
| ------------------ | -------------------------------------- |
| Avg confirmation   | \~50ms on Hydra L2                     |
| Trading fee        | 0.10% flat (10bps)                     |
| Gas fees           | None                                   |
| Spread vs AMM      | \~5–6x tighter                         |
| Cost per $1K trade | \~$1.40 (vs \~$8.50 on AMM)            |
| Custody            | Non-custodial, L1 settlement guarantee |

## How it works

1. **Connect wallet** — Create a DeltaDeFi account linked to your Cardano wallet address.
2. **Deposit** — Transfer ADA or supported tokens into your trading account.
3. **Trade** — Place limit or market orders on the order book. Orders are matched on Hydra L2 with sub-second confirmation.
4. **Withdraw** — Move funds back to Cardano L1 at any time.

All trades happen on Hydra L2, giving you centralized-exchange speed without giving up custody of your assets.

## Order types

See [Order Types](/about/learn/trade/order-types) for details on supported order types including limit orders and market orders.

## API access

DeltaDeFi provides a Binance-compatible REST + WebSocket API for programmatic trading. See [Developers](/start-trading/developers) for full API documentation and SDKs in TypeScript, Python, Rust, and Go.


# Order Types

{% hint style="success" %}
**DeltaDeFi Protocol Supports All Possible Order Types**
{% endhint %}

DeltaDeFi can empower all order types existing in traditional finance. However, at the initial stage, we will only support limit orders and market orders.

### Limit Order

Limit orders will always execute with the limit price specified as the order maker, except in case of price crossing at the moment of order placing, where your order will be filled with a better price as an order taker.

### Market Order

Our implementation of market order is implicitly an "enhanced market order", which you can configure the maximum slippage. If there is insufficient market depth to fill all the instructed quantity within the maximum slippage, the remaining order size will be created as limit order at the market price when the order is submitted.

### Other Order Types

With current architecture, DeltaDeFi can be upgraded to support more order types. Please provide direct feedback to the team if you think any additional order type could benefit you or other potential users!


# Whitepaper

{% file src="/files/tJdqb19app4GHau8EhES" %}


# Getting Started

DeltaDeFi works like any typical centralized exchange, except for its non-custodial nature. Users deposit value into their account and then start trading based on the account balance.

In this session, we will guide you through all the major features at DeltaDeFi, as simple as it is.


# Create Account

Signing in is as simple as just connecting your wallet. Choose your preferred wallet and sign a message to prove your wallet ownership to sign in.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F2MeJiM5mmdgjTi4Y742I%2Fimage.png?alt=media&amp;token=7d2cb687-67b4-4f09-84c6-a538436a3644" alt=""><figcaption></figcaption></figure>

If it is your first-time sign-in, you will be asked to define your trading password. You may also optionally enter a referral code at this step to receive a starting bonus, if you have one.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FXpUF1kLxPJfKwCZeXbdk%2Fimage.png?alt=media&amp;token=ff4b0dbb-042a-4a7f-9250-a3e0eff008e4" alt=""><figcaption></figcaption></figure>

After setting up your trading password, you can make deposit anytime.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FQyFqLyYhjtpGEJN4rQSf%2Fimage.png?alt=media&amp;token=51c9ebe0-437e-43d0-9426-e35d65fc161f" alt=""><figcaption></figcaption></figure>

***

### Related FAQ

* [Why do I have to create an account?](/faq/product#i-have-to-create-account)
* [Why are only limited wallets supported in the web app?](/faq/product#only-limited-wallets-are-supported-in-the-web-app)


# Deposit

### Regular Deposit

You can deposit through the trading interface. Once the transaction is signed and submitted, we will process the deposit, and the balance will be available for trade following the next deposit cycle.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FK150deWLFwAK6UBtAtJn%2FUser%20Guide%20Image-2.png?alt=media&amp;token=40684a68-90bc-4ed9-a1b5-fe1b421ba1a7" alt=""><figcaption></figcaption></figure>

### Fast Deposit

You can deposit through the trading interface. Once the transaction is signed and submitted, we will process the fast deposit, and the balance will be available for trade within 1 - 2 minutes.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FYiZD5YxS15k2tRAq6ULn%2FUser%20Guide%20Image-3.png?alt=media&amp;token=24a6e54f-9381-4ba6-86bc-bee1f0d2bb5b" alt=""><figcaption></figcaption></figure>

### Successful Deposit

After successful deposit, the balance will be reflected on trading page.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FY4DIVCPyZ6NBi53r27K3%2Fsc.jpeg?alt=media&amp;token=d78a1899-2240-49c5-b617-79e9b607398d" alt=""><figcaption></figcaption></figure>

***

### Related FAQ

* [What is the minimum amount of deposit and withdrawal?](/faq/product#the-minimum-deposit-amount)
* [How long does it take to deposit & withdraw?](/faq/product#how-long-does-it-take-to-deposit-and-withdrawal)


# Place Order

You can place orders through the order panel, and there are separate

|                          | Limit Order                   | Market Order                                                                                                                                                                                                                                          |
| ------------------------ | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order side (buy or sell) | :heavy\_check\_mark: Required | :heavy\_check\_mark: Required                                                                                                                                                                                                                         |
| Price                    | :heavy\_check\_mark: Required | :heavy\_multiplication\_x: Not required                                                                                                                                                                                                               |
| Amount (order size)      | :heavy\_check\_mark: Required | :heavy\_check\_mark: Required                                                                                                                                                                                                                         |
| Limit slippage           | :heavy\_minus\_sign: NA       | <p><span data-gb-custom-inline data-tag="emoji" data-code="2795">➕</span> Advanced<br><br>When there is no limit set for slippage, we will try to fill your order size as much as your purchasing power can support through the order book depth.</p> |

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F18rS1rl9RDDhmOOzHDuf%2FUser%20Guide%20Image.png?alt=media&amp;token=4474e7ab-48db-45ac-b1f8-8b764d4f175c" alt=""><figcaption></figcaption></figure>

***

### Related FAQ

* [What is the minimum order size for trade?](/faq/product#what-is-the-minimum-order-size-for-trade)
* [How can I conduct trades using APIs?](/faq/product#how-can-i-conduct-trades-using-apis)
* [Why am I unable to place 2 market buy orders concurrently?](/faq/product#why-am-i-unable-to-place-2-market-buy-orders-concurrently)


# Cancel Order

You can see all the open orders in the "Open Order" table, and you can cancel any open order there.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FaMxoEvQWfFvX8P1q1Pln%2FScreenshot%202026-01-21%20at%2015.09.43.png?alt=media&amp;token=54b4de95-613c-4aca-9d71-9c045091d110" alt=""><figcaption></figcaption></figure>

***

### Related FAQ

* [Can I cancel orders programmatically?](/faq/product#can-i-cancel-orders-programmatically)


# Withdrawal

### Regular Withdrawal

You can withdraw through the trading interface. Once the withdrawal is signed and submitted, we will process the withdrawal, and the withdrawal will be deposited to your wallet following the next deposit cycle.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FxoD7Sn3tciQd3c1AkS1I%2FUser%20Guide%20Image-5.png?alt=media&amp;token=6d88c537-353a-4eb0-addb-78d818033d6f" alt=""><figcaption></figcaption></figure>

### Fast Withdrawal

You can withdraw through the trading interface. Once the withdrawal is signed and submitted, we will process the fast withdrawal, and the withdrawal will be deposited to your wallet within 1 - 2 minutes.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FqhjuTN90tTT77G3rd5hL%2FUser%20Guide%20Image-4.png?alt=media&amp;token=2f7c2a8b-cad5-43d9-8d53-c61f1fa7bc0f" alt=""><figcaption></figcaption></figure>

### Successful Withdrawal&#x20;

After successful Withdrawal, the balance will be reflected on trading page.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FY4DIVCPyZ6NBi53r27K3%2Fsc.jpeg?alt=media&amp;token=d78a1899-2240-49c5-b617-79e9b607398d" alt=""><figcaption></figcaption></figure>

***

### Related FAQ

* [What is the minimum amount of deposit and withdrawal?](/faq/product#the-minimum-deposit-amount)
* [How long does it take to deposit & withdraw?](/faq/product#how-long-does-it-take-to-deposit-and-withdrawal)


# API Key / Dashboard

You can navigate to the app dashboard from the nav bar. Here it shows all the balance information, deposit records, withdrawal records, and API Key,

If you want to trade programmatically, here is also the entrance point to obtain the API key. For details, please refer to the [Developers](/start-trading/developers) session.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fn6JUV1cEYbdZfwax5n5I%2FScreenshot%202026-01-22%20at%2018.30.54.png?alt=media&amp;token=667c4a4b-c850-4277-938f-caf8a53cefa8" alt=""><figcaption></figcaption></figure>


# Fee

### Interacting with DeltaDeFi

The table below summarizes all potential actions interacting with DeltaDeFi.&#x20;

<table><thead><tr><th width="175.52734375">Actions</th><th width="150.09765625">DeltaDeFi Fees</th><th width="150.2421875">Other Fees</th><th>Remarks</th></tr></thead><tbody><tr><td>Fast Deposit</td><td>-</td><td>L1 tx fees</td><td>Min size applies<sup>1</sup></td></tr><tr><td>Regular Deposit</td><td>-</td><td>L1 tx fees</td><td>Min size applies<sup>1</sup></td></tr><tr><td>Place Order</td><td>-</td><td>-</td><td>Min size applies<sup>2</sup></td></tr><tr><td>Cancel Order</td><td>-</td><td>-</td><td>-</td></tr><tr><td>Fill Order</td><td>Trading fee applies</td><td>-</td><td>-</td></tr><tr><td>Fast Withdrawal</td><td>1 ADA</td><td>-</td><td>Min size applies<sup>1</sup></td></tr><tr><td>Regular Withdrawal</td><td>1 ADA</td><td>-</td><td>Min size applies<sup>1</sup></td></tr></tbody></table>

<sup>1</sup> For deposit and withdrawal events, min size of `2 + 0.5 * number of types of token` applies.

<sup>2</sup> For orders placement, minimal 5 USD equiv min order size applies.

### Trading Fee

We apply trading fees to all executed orders.

| Tiers           | Maker | Taker |
| --------------- | ----- | ----- |
| Standard        | 0.1%  | 0.1%  |
| Advance Tiering | TBC   | TBC   |


# Hummingbot


# Overview

This section documents the Delta-DeFi team's fork of \[Hummingbot]\(https\://github.com/hummingbot/hummingbot), which adds a native \*\*Delta-DeFi exchange connector\*\*. You can use it to run any Hummingbot

### What's included

The fork extends upstream Hummingbot with:

* A **Delta-DeFi exchange connector** covering spot trading, order book streaming, user account streams, health monitoring, and risk guards.
* A **custom script loader** that lets you point Hummingbot at any external directory of V2 strategy scripts — useful when strategies are maintained in a separate repository.

### How order submission works

Delta-DeFi settles trades on Cardano, so every order submission is a signed Cardano transaction. The connector delegates signing to [`sidan-gin`](https://github.com/sidan-lab/gin) — an open-source Python library maintained by the Delta-DeFi team for Cardano development.

```mermaid
graph LR
  A[V2 strategy] --> B[Delta-DeFi connector]
  B --> C[Delta-DeFi API]
  B --> D[sidan-gin]
  D -->|signed tx| C
```

`sidan-gin` is a general-purpose Cardano Python library — it's not Hummingbot-specific. It's installed separately via pip. See [Installing sidan-gin](/start-trading/getting-started/hummingbot/installing-sidan-gin) for why this step is required and easy to miss.


# Installation

The fork installs the same way as upstream Hummingbot from source.

### Prerequisites

* Conda (Miniconda or Anaconda)
* Git
* A C compiler toolchain (for Cython compilation)

Refer to the [upstream source-install guide](https://hummingbot.org/installation/hummingbot-client/) for OS-specific toolchain notes.

### Clone and install

```bash
git clone https://github.com/deltadefi-protocol/hummingbot.git
cd hummingbot

# Run Setup & Deploy
make setup
make deploy

# Attach to the running instance
docker attach hummingbot
```

The conda environment is named `hummingbot`. Keep this exact name — the `sidan-gin` install step on the next page depends on activating it.

### Verify

```bash
bin/hummingbot_quickstart.py
```

The Hummingbot CLI should launch. Exit with `exit`.

{% hint style="warning" %}
Do **not** try to trade on Delta-DeFi yet. You must install `sidan-gin` first, otherwise orders will fail to sign.

Continue to Installing sidan-gin.
{% endhint %}


# Installing sidan-gin

sidan-gin is an open-source Python library maintained by the Sidan-Lab team for building on Cardano.

It provides general Cardano primitives — wallets, signing, and cipher decryption — and is published independently so any Python project targeting Cardano can reuse it.

Because Hummingbot is Python-based, this fork uses `sidan-gin` to sign the Cardano transactions that submit orders to Delta-DeFi.

* **Repository:** <https://github.com/sidan-lab/gin>
* **Distribution:** pip (PyPI)
* **Scope:** not Hummingbot-specific — reusable by any Cardano Python project

### What the connector uses it for

1. Decrypting the **operation key** returned by the Delta-DeFi API
2. Initializing a Cardano signing wallet from the decrypted key
3. Signing every order transaction before submission to Delta-DeFi

Without `sidan-gin`, the connector authenticates and streams market data — but **every order silently fails** because no transaction can be signed.

### Signing flow

```mermaid
sequenceDiagram
  participant U as User
  participant HB as Hummingbot
  participant API as Delta-DeFi API
  participant SG as sidan-gin

  U->>HB: connect delta-defi + password
  HB->>API: auth + fetch operation key
  API-->>HB: encrypted_operation_key
  HB->>SG: decrypt_with_cipher(key, password)
  SG-->>HB: signing wallet ready

  Note over HB: strategy places order
  HB->>SG: sign(order_tx)
  SG-->>HB: signed tx
  HB->>API: submit signed tx
```

For the API-side contract of the encrypted key, see [Operation Key](https://docs.deltadefi.io/start-trading/developers/api-documentation/account/operation-key).

### Install

`sidan-gin` must be installed **inside the activated `hummingbot` conda environment**:

```bash
conda activate hummingbot
pip install sidan-gin
```

{% hint style="danger" %}
If you run `pip install sidan-gin` **without** activating the `hummingbot` conda env first, pip installs it into your base Python. Hummingbot still won't find it — even though `pip install` reports success.

Check with `which python` — the path should be inside the `hummingbot` env, for example:

```
/opt/miniconda3/envs/hummingbot/bin/python
```

{% endhint %}

### Verify

```bash
conda activate hummingbot
python -c "from sidan_gin import Wallet, decrypt_with_cipher; print('sidan-gin OK')"
```

Expected output:

```
sidan-gin OK
```

A `ModuleNotFoundError` means the package is not in the active environment — re-check the step above.

### What you'll see if it's missing

On startup, the connector logs:

```
sidan-gin package not available. Transaction signing will not be available.
Install with: pip install sidan-gin
```

`status` will still show the connector as green — but every `buy`, `sell`, or strategy-placed order will be rejected at the signing step.


# Connecting to Delta-DeFi on hummingbot

With the fork installed and `sidan-gin` available in the `hummingbot` conda env, connect from the Hummingbot CLI:

```
>>> connect delta-defi
Enter your Delta-DeFi API key >>> <your_api_key>
Enter your Delta-DeFi trading password >>> <your_trading_password>
```

Verify:

```
>>> status
>>> balance
```

Delta-DeFi should appear with a green status indicator.

### Getting your API key

See [API Key / Dashboard](https://docs.deltadefi.io/start-trading/getting-started/api-key-dashboard) for how to generate an API key and set your trading password on the Delta-DeFi platform.

### Trading password

Enter the **same trading password** you used when generating the API key. This password is used to:

1. Authenticate with the Delta-DeFi platform
2. Decrypt the encrypted operation key returned by the API — the decrypted key is then handed to `sidan-gin` to initialize your signing wallet

### What happens behind the scenes

```mermaid
sequenceDiagram
  participant U as User
  participant HB as Hummingbot
  participant API as Delta-DeFi API
  participant SG as sidan-gin

  U->>HB: connect delta-defi<br/>api_key + trading_password
  HB->>API: auth (api_key)
  API-->>HB: session
  HB->>API: GET /account/operation-key
  API-->>HB: encrypted_operation_key
  HB->>SG: decrypt + init wallet
  SG-->>HB: signing wallet ready
  Note over HB: status = READY
```

Related API references:

* [Auth](https://docs.deltadefi.io/start-trading/developers/auth)
* [Operation Key](https://docs.deltadefi.io/start-trading/developers/api-documentation/account/operation-key)


# External Scripts Path (optional)

This fork adds the ability to load V2 strategy scripts from **any directory on disk**, not just the built-in `hummingbot/scripts/` folder. This is useful when strategies are maintained in a separate repository.

### Default behavior

If you do nothing, Hummingbot loads scripts from `hummingbot/scripts/` — exactly like upstream. The `external_scripts_path` feature is fully opt-in.

### Enabling an external directory

From the Hummingbot CLI:

```
>>> config external_scripts_path /absolute/path/to/your/scripts
```

From this point on, Hummingbot loads scripts **only** from that path.

### Lookup behavior

```mermaid
graph TD
  A[create / start command] --> B{external_scripts_path<br/>set?}
  B -- Yes --> C[Load from external path ONLY]
  B -- No --> D[Load from built-in<br/>hummingbot/scripts/ ONLY]
```

{% hint style="warning" %}
The switch is **exclusive**. When `external_scripts_path` is set, the built-in `scripts/` folder becomes inaccessible. You cannot use both simultaneously.

To revert to the built-in folder, unset the path:

```
>>> config external_scripts_path
```

(Leave the value blank.)
{% endhint %}

### When to use this

* Strategy scripts are maintained in a separate git repo and you don't want to copy them into the fork.
* You want `git status` inside the hummingbot fork to stay clean while iterating on strategies.


# Running the Bot

Nothing at the V2 strategy layer is Delta-DeFi-specific beyond selecting `delta-defi` as the connector. Follow the official [Hummingbot V2 Strategies guide](https://hummingbot.org/strategies/scripts/#script-examples) for the full flow.

### Short version

```
>>> create --v2-config [SCRIPT_NAME]
# Select a script from the list
# Follow prompts to set trading pair, order amounts, spreads, etc.
# Save the config

>>>start --v2 [SCRIPT_CONFIG_FILE]
```

### Selecting Delta-DeFi as the connector

In your script config, use the connector ID `delta-defi`:

```yaml
exchange: delta-defi
trading_pair: ADA-USDM
# remaining strategy params
```

### Stopping the bot

```
>>> stop
```

Open orders are cancelled as part of shutdown, subject to the usual Hummingbot cancel-all flow.


# Troubleshooting

| Symptom                                                                                 | Likely cause                                                      | Fix                                                                                                                                                                                         |
| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Log: `sidan-gin package not available. Transaction signing will not be available.`      | `sidan-gin` not installed in the `hummingbot` conda env           | `conda activate hummingbot && pip install sidan-gin` — then restart Hummingbot                                                                                                              |
| `connect delta-defi` succeeds, `status` is green, but orders never land on the exchange | Same as above — connector authed but can't sign                   | Same fix                                                                                                                                                                                    |
| `ModuleNotFoundError: No module named 'sidan_gin'` at startup                           | pip installed `sidan-gin` to the wrong Python                     | `conda activate hummingbot` first, then `pip install sidan-gin`. Verify with `which python` — it should point inside the env                                                                |
| Strategy scripts missing from the `create` dropdown                                     | `external_scripts_path` is set but the directory is wrong / empty | Check with `config external_scripts_path`. Unset the value to fall back to built-in scripts.                                                                                                |
| `connect delta-defi` returns 401 / auth error                                           | Wrong API key or trading password                                 | Re-run `connect delta-defi` with the credentials you set when generating the API key. See [API Key / Dashboard](https://docs.deltadefi.io/start-trading/getting-started/api-key-dashboard). |
| Unexpected API status codes in logs                                                     | —                                                                 | See [Delta-DeFi status codes](https://docs.deltadefi.io/start-trading/developers/status-code)                                                                                               |

### Getting further help

* Hummingbot-general issues: [Hummingbot Discord](https://discord.gg/hummingbot)
* Delta-DeFi platform issues: see the [FAQ](https://docs.deltadefi.io/faq/general) sections on the main docs site


# Developers

Developers are DeltaDeFi's first-class citizens. Everything you can do from the web app, you can also do with your API key.

Thus, DeltaDeFi empowers users to monitor account status in real time and place order instructions instantly.&#x20;


# Base Url

The DeltaDefi API operates securely over HTTPS. All URLs provided in the documentation have the following base url.

#### API  Endpoint

| Environment |                           URL Endpoint                           |
| :---------: | :--------------------------------------------------------------: |
|   Pre-Prod  | [https://api-staging.deltadefi.io](https://api-dev.deltadefi.io) |
|   Mainnet   |     [https://api.deltadefi.io](https://api-dev.deltadefi.io)     |

#### Websocket Endpoint

| Environment |                    Websocket Endpoint                    |
| :---------: | :------------------------------------------------------: |
|   Pre-Prod  | [wss://stream-staging.deltadefi.io](#websocket-endpoint) |
|   Mainnet   |     [wss://stream.deltadefi.io](#websocket-endpoint)     |


# Auth

Access to all our APIs requires an API key obtained from the dashboard.&#x20;

Simply connect your wallet and navigate to the Dashboard page.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FRRQDYp3qINTwC2JbmwV8%2FScreenshot%202026-01-22%20at%2018.49.37.png?alt=media&amp;token=d8fd4e13-c44e-4e82-a0bd-3eef7fc532f4" alt=""><figcaption></figcaption></figure>

This key must be included in the headers as "X-API-KEY" for authentication.

```sh
// Example snippet

curl --location 'https://api-staging.deltadefi.io' \
--header 'X-API-KEY: 4125f1d710037fd548a36123cf6dc63d'
```


# Trading Pairs / Symbols

* ADAUSDM
* NIGHTUSDM


# Assets

Currently these are the supported assets

<table><thead><tr><th align="center">Assets</th><th align="center">Unit</th></tr></thead><tbody><tr><td align="center">ADA</td><td align="center"><code>lovelace</code></td></tr><tr><td align="center">USDM (Preprod)</td><td align="center"><pre><code>c69b981db7a65e339a6d783755f85a2e03afa1cece9714c55fe4c9135553444d
</code></pre></td></tr><tr><td align="center">USDM (Mainnet)</td><td align="center"><pre><code>c48cbb3d5e57ed56e276bc45f99ab39abe94e6cd7ac39fb402da47ad0014df105553444d
</code></pre></td></tr><tr><td align="center">USDC¹ (Preprod)</td><td align="center"><pre><code>0483b457673b527c1b6e8ca680a5f3a5676f27cdfea0c9bf285d09385553444358
</code></pre></td></tr><tr><td align="center">USDC¹ (Mainnet)</td><td align="center"><pre><code>1f3aec8bfe7ea4fe14c5f121e2a92e301afe414147860d557cac7e345553444378
</code></pre></td></tr><tr><td align="center">NIGHT (Preprod)</td><td align="center"><pre><code>3363b99384d6ee4c4b009068af396c8fdf92dafd111e58a857af04294e49474854
</code></pre></td></tr><tr><td align="center">NIGHT (Mainnet)</td><td align="center"><pre><code>0691b2fecca1ac4f53cb6dfb00b7013e561d1f34403b957cbb5af1fa4e49474854
</code></pre></td></tr></tbody></table>

> ¹ The USDC used on DeltaDeFi is USDCx — the officially bridged version of USDC on Cardano. Given its official status, for simplicity the platform denotes it simply as USDC.


# Status code

## 🚨 API Error Codes

### Response Format

All API errors return a consistent JSON structure with both human-readable messages and machine-readable codes for programmatic handling.

{% tabs %}
{% tab title="Response Structure" %}

```json
  {
    "error": "Invalid request data",
    "code": 4000
  }
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
  interface ErrorResponse {
    error: string;
    code: number;
  }
```

{% endtab %}

{% tab title="Go" %}

```go
  type ErrorResponse struct {
      Error string `json:"error"`
      Code  int16  `json:"code"`
  }
```

{% endtab %}
{% endtabs %}

***

📊 Error Code Reference

| Error code |                        Message                       |
| :--------: | :--------------------------------------------------: |
|    4000    |                 Invalid request data                 |
|    4010    |                  Unauthorized access                 |
|    4050    |          Insufficient balance to place order         |
|    4100    |           Order size must be at least 5 ADA          |
|    4101    |          Order price must be greater then 0          |
|    4102    |       Price must have at most 4 decimal places       |
|    4103    |      Quantity must have at most 4 decimal places     |
|    4104    |   Post-only order would match with existing orders   |
|    4105    |   Post-only flag can only be used with limit orders  |
|    4106    |              Invalid trading pair symbol             |
|    4107    |         Order Quantity must be greater then 0        |
|    4108    | Max Slippage basis point must be between 0 and 10000 |
|    4109    |    Insufficient liquidity to execute market order    |
|    4110    |        Maximum number of open orders exceeded        |
|    4111    |  Price exceeds maximum allowed limit for this market |
|    4112    |   Price below minimum allowed limit for this market  |
|    4200    |                    Order not found                   |
|    4201    |                   Order is not open                  |
|    4202    |                Order State in invalid                |
|    4290    |      Rate limit exceeded, please try again later     |
|    4300    |        Transaction expired, please build again       |
|    4301    |              UTxO has already been spent             |
|    4302    |        Transaction has already been submitted        |
|    4400    |                    User not found                    |
|    4402    |                 Transaction not found                |
|    4404    |                Invalid status paramter               |
|    4405    |               Invalid interval paramter              |
|    4406    |       Account is missing required operation key      |
|    4407    |              Failed to sign transaction              |
|    5000    |                 Internal Server Error                |
|    5001    |        System resources temporaily unavailable       |
|    5002    |  Trading is currently locked, please try again later |


# Getting started

1. Connect Wallet and retrieve your api key [Auth](/start-trading/developers/auth)
2. Test API connection

{% tabs %}
{% tab title="curl" %}

```powershell
curl --location 'https://api.deltadefi.io/accounts/balance' \
--header 'X-API-KEY: <your_api_key>'
```

A successful response should return an empty array with a status code <kbd><mark style="color:green;">200<mark style="color:green;"></kbd>

```
[]
```

{% endtab %}
{% endtabs %}


# Deposit funds

{% hint style="info" %}
:sparkles:Pre-requisite:  You must create an account and obtain an API key via the user interface

[Create account here](/start-trading/getting-started/create-account)
{% endhint %}

{% stepper %}
{% step %}

### &#x20;Build a deposit transaction

You must first build a transaction using your current UTxO state before processing.&#x20;

[Cardano](/faq/cardano#how-can-i-get-utxos-from-my-wallet-address)

* For in-depth API details[Build deposit transaction](/start-trading/developers/api-documentation/account/build-deposit-transaction).&#x20;
* For a list of supported assets, view [Assets](/start-trading/developers/assets)

In the following example, we're depositing 10 Ada, equivalent to `10_000_000` lovelace

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/accounts/deposit/build' \
--header 'x-api-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "deposit_amount": [
        {
            "unit": "lovelace",
            "quantity": "10000000"
        }
    ], 
    "input_utxos": [
        {
            "input": {
                "tx_hash": "6a33db7b4da84707b088d29fd6ec3072f03599427a4854c7ebe88c3052524385",
                "output_index": 4
            },
            "output": {
                "address": "addr_test1qr77kjlsarq8wy22g4flrcznjh5lkug5mvth7qhhkewgmezwvc8hnnjzy82j5twzf8dfy5gjk04yd09t488ys9605dvq4ymc4x",
                "amount": [
                    {
                        "unit": "lovelace",
                        "quantity": "77261137"
                    }
                ],
                "data_hash": null,
                "plutus_data": null,
                "script_ref": null,
                "script_hash": null
            }
        }
    ]
}
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "deposit_amount": [
    {
      "unit": "lovelace",
      "quantity": "10000000"
    }
  ],
  "input_utxos": [
    {
      "input": {
        "tx_hash": "6a33db7b4da84707b088d29fd6ec3072f03599427a4854c7ebe88c3052524385",
        "output_index": 4
      },
      "output": {
        "address": "addr_test1qr77kjlsarq8wy22g4flrcznjh5lkug5mvth7qhhkewgmezwvc8hnnjzy82j5twzf8dfy5gjk04yd09t488ys9605dvq4ymc4x",
        "amount": [
          {
            "unit": "lovelace",
            "quantity": "77261137"
          }
        ],
        "data_hash": null,
        "plutus_data": null,
        "script_ref": null,
        "script_hash": null
      }
    }
  ]
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/accounts/deposit/build',
  headers: { 
    'X-API-KEY': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Submit a deposit transaction

With the returned <mark style="color:orange;">`tx_hex`</mark> from step 1, you will need to sign it before submitting it.

[Cardano](/faq/cardano#how-can-i-sign-a-cardano-transaction)

For in-depth API details [Submit deposit transaction](/start-trading/developers/api-documentation/account/submit-deposit-transaction)

{% tabs %}
{% tab title="curl" %}

```sh

curl --location 'https://api.deltadefi.io/accounts/deposit/submit' \
--header 'X-API-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "signed_tx": "<your_signed_tx>"
}

```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "signed_tx": "<your_signed_tx>"
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/accounts/deposit/submit',
  headers: { 
    'X-API-key': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/accounts/deposit/submit"
  method := "POST"

  payload := strings.NewReader(`{
    "signed_tx": "<your_signed_tx>"
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-key", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

***

### :white\_check\_mark: Verifying deposit

After you have made a successful deposit request, you can check your latest account balance via the [Account Balances](/start-trading/developers/api-documentation/account/balances) API.

{% tabs %}
{% tab title="curl" %}

```sh
curl --location 'https://api.deltadefi.io/accounts/balance' \
--header 'X-API-KEY: <your_api_key>'
```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/accounts/balance',
  headers: { 
    'X-API-KEY': '<your_api_key>'
  }
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/accounts/balance"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

Your Response should look something like below:

```json
[
    {
        "asset": "ada",
        "asset_unit": "",
        "free": 0,
        "locked": 100
    }
]
```

***

### Related FAQ

* [How do I get my API keys?](/start-trading/developers/auth)
* [What is the minimum amount of deposit and withdrawal?](/faq/product#the-minimum-deposit-amount)
* [How long does it take to deposit & withdraw?](/faq/product#how-long-does-it-take-to-deposit-and-withdrawal)
* [What are locked and free balances?](/faq/product#what-are-locked-and-free-balance)
* [How can I get UTxOs from my wallet address?](/faq/cardano#how-can-i-get-utxos-from-my-wallet-address)
* [How can I sign a Cardano transaction?](/faq/cardano#how-can-i-sign-a-cardano-transaction)


# Verifying account balance

{% hint style="info" %}
:sparkles:Pre-requisite:  You must create an account and obtain an API key via the user interface

[Create account here](/start-trading/getting-started/create-account)
{% endhint %}

### :white\_check\_mark: Verifying account balance

After you have made a successful deposit through our frontend UI, you can check your latest account balance via the [Account Balances](/start-trading/developers/api-documentation/account/balances) API.

{% tabs %}
{% tab title="curl" %}

```sh
curl --location 'https://api.deltadefi.io/accounts/balance' \
--header 'X-API-KEY: <your_api_key>'
```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/accounts/balance',
  headers: { 
    'X-API-KEY': '<your_api_key>'
  }
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/accounts/balance"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

Your Response should look something like below:

```json
[
    {
        "asset": "ada",
        "asset_unit": "",
        "free": 0,
        "locked": 100
    }
]
```

### Related FAQ

* [How do I get my API keys?](/start-trading/developers/auth)
* [How long does it take to deposit & withdraw?](/faq/product#how-long-does-it-take-to-deposit-and-withdrawal)
* [What are locked and free balances?](/faq/product#what-are-locked-and-free-balance)


# Place a new order

{% hint style="info" %}
:sparkles:Pre-requisite:  You account must have free balances in order to place a new order.   &#x20;

[What are locked and free balances?](/faq/product#what-are-locked-and-free-balances)
{% endhint %}

{% stepper %}
{% step %}

### Build a limit order transaction

In the following example, we will be creating a limit order.

To place a new order, you must provide the following:

* price&#x20;
* quantity
* side
* symbol
* type

For an in-depth API reference [Build order transaction](/start-trading/developers/api-documentation/order/build-order-transaction)

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/order/build' \
--header 'x-api-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
	"symbol": "ADAUSDX",
    "side": "buy",
    "type": "limit",
    "quantity": 100,
    "price": 0.93    
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "symbol": "ADAUSDX",
  "side": "buy",
  "type": "limit",
  "quantity": 100,
  "price": 0.93
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/order/build',
  headers: { 
    'x-api-key': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}
{% endtabs %}

{% endstep %}

{% step %}

### Submit a limit order transaction

After the order transaction is built, you will then need to [sign it](/faq/cardano#how-can-i-sign-a-cardano-transaction) before submitting it.

To submit:

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/order/submit' \
--header 'X-API-KEY: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "order_id": "<order_id>",
    "signed_tx":"<signed_tx>"
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "order_id": "<order_id>",
  "signed_tx": "<signed_tx>"
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api-staging.deltadefi.io/order/submit',
  headers: { 

    'X-API-KEY': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api-staging.deltadefi.io/order/submit"
  method := "POST"

  payload := strings.NewReader(`{
    "order_id": "<order_id>",
    "signed_tx":"<signed_tx>"
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDI1Mzk5NDAsInN1YiI6ImFkZHJfdGVzdDFxcXpnZzVwY2FleWVhNjl1cHRsOWRhNWc3ZmFqbTRtMHl2eG5keDlmNGx4cGtlaHFnZXp5MHMwNHJ0ZHdsYzB0bHZ4YWZwZHJmeG5zZzd3dzY4Z2UzajdsMGxuc3pzdzJ3dCJ9.OAchsj0tv06NxD9Br0aj0Zw5XzpG8kUFKBuVPtz5AKA")
  req.Header.Add("X-API-KEY", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% endstep %}

{% step %}

### Build a market order transaction

In this example we will be creating a market order.

For an in-depth API reference [Build order transaction](/start-trading/developers/api-documentation/order/build-order-transaction)

To place a market order, provide the following:

* price&#x20;
* quantity
* side
* symbol
* type
* limit\_slippage / max\_slippage\_basis\_point (either one)

***limit\_slippage (bool)***: If set to false, the market order will allow unlimited slippage until the entire order quantity is filled, where the account's purchasing power allows

***max\_slippage\_basis\_points (int)***: Maximum Slippage is the maximum acceptable deviation between the expected price (market price) and the actual executed price in a market order transaction

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api-staging.deltadefi.io/order/build' \
--header 'x-api-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "symbol": "ADAUSDX",
    "side": "buy",
    "type": "market",
    "quantity": 100,
    "limit_slippage": true
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "symbol": "ADAUSDX",
  "side": "buy",
  "type": "market",
  "quantity": 100,
  "limit_slippage": false
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api-staging.deltadefi.io/order/build',
  headers: { 
    'x-api-key': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api-staging.deltadefi.io/order/build"
  method := "POST"

  payload := strings.NewReader(`{
    "symbol": "ADAUSDX",
    "side": "buy",
    "type": "market",
    "quantity": 100,
    "limit_slippage":false
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("x-api-key", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

After the transaction is built, follow step 2 above to submit the transaction.

***

{% endstep %}
{% endstepper %}

### :book: Get Order Records

After an order is created, you can find your order records with the [Order record](/start-trading/developers/api-documentation/account/order-records) API

For open orders:

* Pass the query param <mark style="color:green;">**`openOrder`**</mark>

For orderHistory:

* pass the query param <mark style="color:orange;">**`orderHistory`**</mark>&#x20;

For tradingHistory

* pass the query param <mark style="color:yellow;">**`tradingHistory`**</mark>&#x20;

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/accounts/order-records?status=open' \
--header 'x-api-key: <your_api_key>'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/accounts/order-records?status=open',
  headers: { 
    'x-api-key': '<your_api_key>'
  }
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/accounts/order-records?status=open"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("x-api-key", "<your_api_key>")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

***

### Related FAQ

* [What order types are available? ](/about/learn/trade/order-types)
* [Placing orders through website](/start-trading/getting-started/place-order)
* [How can I sign a Cardano transaction?](/faq/cardano#how-can-i-sign-a-cardano-transaction)[ ](/start-trading/getting-started/place-order)


# Cancel an order

{% stepper %}
{% step %}

### Build a cancel order transaction

To build a cancel order transaction, simply include its order's ID in the path param payload.

For in-depth API details [Cancel Order](/start-trading/developers/api-documentation/order/build-cancel-order-transaction)

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location --request DELETE 'https://api.deltadefi.io/order/fdcd1b64-504f-4504-8000-61b3306f345b/build' \
--header 'x-api-key: <your_api_key>' \
--data ''
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = '';

let config = {
  method: 'delete',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/order/fdcd1b64-504f-4504-8000-61b3306f345b/build',
  headers: { 
    'x-api-key': '<your_api_key>'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/order/fdcd1b64-504f-4504-8000-61b3306f345b/build"
  method := "DELETE"

  payload := strings.NewReader(``)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("x-api-key", "<your_api_key>")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% endstep %}

{% step %}

### Submit a cancel order transaction

With the returned tx\_hex from step 1, you will need to [sign it](/faq/cardano#how-can-i-sign-a-cardano-transaction) before submitting it.

For in-depth API details [Broken mention](broken://pages/X0YE15uuYU3i5me7UgFx)

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location --request DELETE 'https://api.deltadefi.io/order/submit' \
--header 'x-api-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "signed_tx": "<your_api_key>"
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "signed_tx": "<your_api_key>"
});

let config = {
  method: 'delete',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/order/submit',
  headers: { 
    'x-api-key': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api.deltadefi.io/order/submit"
  method := "DELETE"

  payload := strings.NewReader(`{
    "signed_tx": "<your_api_key>"
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("x-api-key", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

***

### Related FAQ

* [How can I sign a Cardano transaction?](/faq/cardano#how-can-i-sign-a-cardano-transaction)


# Withdraw funds

{% stepper %}
{% step %}

### Build withdrawal transaction&#x20;

Please note only free balances are able to withdraw from the current hydra cycle. [Deposit funds](/start-trading/developers/getting-started/deposit-funds#free-and-locked-balances)

For in-depth API details [Build withdrawal transaction](/start-trading/developers/api-documentation/account/build-withdrawal-transaction)

In the following example we're withdrawing 10 Ada, equivalent  to 10\_000\_000 lovelace.

{% tabs %}
{% tab title="curl" %}

```sh
curl --location 'https://api-staging.deltadefi.io/accounts/withdrawal/build' \
--header 'x-api-key: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
	"withdrawal_amount": [
		{
			"unit": "lovelace",
			"quantity": "1000000"
		},
	]
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "withdrawal_amount": [
    {
      "unit": "lovelace",
      "quantity": "1000000"
    },
  ]
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api-staging.deltadefi.io/accounts/withdrawal/build',
  headers: { 
    'x-api-key': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api-staging.deltadefi.io/accounts/withdrawal/build"
  method := "POST"

  payload := strings.NewReader(`{
	"withdrawal_amount": [
		{
			"unit": "lovelace",
			"quantity": "10000000"
		},
	]
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("x-api-key", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% endstep %}

{% step %}

### Submit withdrawal transaction

With the returned <mark style="color:orange;">`tx_hex`</mark> from step 1, you will need to [sign it](/faq/cardano#how-can-i-sign-a-cardano-transaction) before submitting it.

For in-depth API details [Submit withdrawal transaction](/start-trading/developers/api-documentation/account/submit-withdrawal-transaction)

{% tabs %}
{% tab title="curl" %}

```sh
curl --location 'https://api-staging.deltadefi.io/accounts/withdrawal/submit' \
--header 'X-API-KEY: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "signed_tx": ""
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "signed_tx": ""
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api-staging.deltadefi.io/accounts/withdrawal/submit',
  headers: { 
    'X-API-KEY': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "https://api-staging.deltadefi.io/accounts/withdrawal/submit"
  method := "POST"

  payload := strings.NewReader(`{
    "signed_tx": ""
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

***

### :white\_check\_mark: Verifying withdrawal

After you have made a successful withdrawal request, you can check your latest account balance via the [Account Balances](/start-trading/developers/api-documentation/account/balances) API.

{% tabs %}
{% tab title="curl" %}

```sh
curl --location 'https://api-staging.deltadefi.io/accounts/balance' \
--header 'X-API-KEY: <your_api_key>'
```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://api-staging.deltadefi.io/accounts/balance',
  headers: { 
    'X-API-KEY': '<your_api_key>'
  }
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "net/http"
  "io"
)

func main() {

  url := "https://api-staging.deltadefi.io/accounts/balance"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Your requested withdrawal amount will be converted from <mark style="color:green;">`Free`</mark> will to <mark style="color:orange;">`Locked`</mark> , and will be distributed during the next hydra closed. &#x20;
{% endhint %}

Your Response should look something like below:

```json
[
    {
        "asset": "ada",
        "asset_unit": "",
        "free": 0,
        "locked": 100
    }
]
```

{% endstep %}
{% endstepper %}

***

### Related FAQ

* [What is the minimum amount of deposit and withdrawal?](/faq/product#the-minimum-deposit-amount)
* [How long does it take to deposit & withdraw?](/faq/product#how-long-does-it-take-to-deposit-and-withdrawal)
* [What are locked and free balances?](/faq/product#what-are-locked-and-free-balances)
* [How can I sign a Cardano transaction?](/faq/cardano#how-can-i-sign-a-cardano-transaction)


# API Documentation


# Account


# Create new api key

Create a new API key for programmatic access to the DeltaDeFi trading API. API keys provide a more permanent authentication method compared to JWT tokens.

***

## Create new API key

> Create new API key

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/new-api-key":{"get":{"description":"Create new API key","tags":["accounts"],"summary":"Create new API key","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.CreateNewAPIKeyResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.CreateNewAPIKeyResponse":{"type":"object","properties":{"api_key":{"type":"string"},"created_at":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```

## Important Notes

{% hint style="warning" %}
**Security Warning:**

* Creating a new API key will invalidate your previous API key.
* Never share your API key or commit it to version control.
  {% endhint %}

{% hint style="info" %}
**Authentication:** You can authenticate this request using:

* Your current API key in the `X-API-KEY` header
  {% endhint %}


# Get spot account

Manage your DeltaDeFi spot trading account. A spot account is required for trading and holds your encrypted operation key.

***

## Get spot account

> Get spot account details for a user

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/spot-account":{"get":{"description":"Get spot account details for a user","tags":["accounts"],"summary":"Get spot account","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetSpotAccountResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.GetSpotAccountResponse":{"type":"object","properties":{"account_id":{"type":"string"},"account_type":{"type":"string"},"created_at":{"type":"string"},"encrypted_operation_key":{"type":"string"},"operation_key_hash":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```

## Understanding Operation Keys

The operation key is a crucial security component:

* **Generated client-side**: Never sent to the server in plain text
* **Encrypted with your password**: Uses AES-GCM encryption
* **Used for signing trades**: Authorizes trading operations without your master wallet

{% hint style="warning" %}
The encrypted operation key is stored on DeltaDeFi's servers, but only you can decrypt it with your password. Never share your password or unencrypted operation key.
{% endhint %}


# Build deposit transaction

## Build deposit transaction

> Build deposit transaction

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/deposit/build":{"post":{"description":"Build deposit transaction","tags":["accounts"],"summary":"Build deposit transaction","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.BuildDepositTransactionResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_requests.BuildDepositTransactionRequest"}}},"description":"Build deposit transaction request","required":true}}}},"components":{"schemas":{"espresso_internal_api_response.BuildDepositTransactionResponse":{"type":"object","properties":{"tx_hex":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}},"espresso_internal_api_requests.BuildDepositTransactionRequest":{"type":"object","required":["deposit_amount","input_utxos"],"properties":{"deposit_amount":{"type":"array","items":{"$ref":"#/components/schemas/rum.Asset"}},"input_utxos":{"type":"array","items":{"$ref":"#/components/schemas/rum.UTxO"}}}},"rum.Asset":{"type":"object","required":["quantity","unit"],"properties":{"quantity":{"type":"string"},"unit":{"type":"string"}}},"rum.UTxO":{"type":"object","required":["input","output"],"properties":{"input":{"$ref":"#/components/schemas/rum.Input"},"output":{"$ref":"#/components/schemas/rum.Output"}}},"rum.Input":{"type":"object","required":["output_index","tx_hash"],"properties":{"output_index":{"type":"integer"},"tx_hash":{"type":"string"}}},"rum.Output":{"type":"object","required":["address","amount"],"properties":{"address":{"type":"string"},"amount":{"type":"array","items":{"$ref":"#/components/schemas/rum.Asset"}},"data_hash":{"type":"string"},"plutus_data":{"type":"string"},"script_hash":{"type":"string"},"script_ref":{"type":"string"}}}}}}
```


# Submit deposit transaction

## Submit deposit transaction

> Submit deposit transaction

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/deposit/submit":{"post":{"description":"Submit deposit transaction","tags":["accounts"],"summary":"Submit deposit transaction","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.SubmitDepositTransactionResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_requests.SubmitDepositTransactionRequest"}}},"description":"Submit deposit transaction request","required":true}}}},"components":{"schemas":{"espresso_internal_api_response.SubmitDepositTransactionResponse":{"type":"object","properties":{"tx_hash":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}},"espresso_internal_api_requests.SubmitDepositTransactionRequest":{"type":"object","required":["signed_tx"],"properties":{"signed_tx":{"type":"string"}}}}}}
```


# Deposit records

## Get deposit records

> Get deposit records for the authenticated user with pagination

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/deposit-records":{"get":{"description":"Get deposit records for the authenticated user with pagination","tags":["accounts"],"summary":"Get deposit records","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","name":"page","in":"query"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","name":"limit","in":"query"}],"responses":{"200":{"description":"Paginated deposit records","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_DepositRecord"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_DepositRecord":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_entities.DepositRecord"}},"total_count":{"type":"integer"},"total_page":{"type":"integer"}}},"espresso_internal_api_entities.DepositRecord":{"type":"object","properties":{"assets":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_entities.AssetRecord"}},"created_at":{"type":"string"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.TransactionStatus"}]},"tx_hash":{"type":"string"}}},"espresso_internal_api_entities.AssetRecord":{"type":"object","properties":{"asset":{"type":"string"},"asset_unit":{"type":"string"},"qty":{"type":"string"}}},"schema.TransactionStatus":{"type":"string","enum":["building","submitted","submission_failed","confirmed"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Withdrawal records

## Get withdrawal records

> Get withdrawal records for the authenticated user with pagination

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/withdrawal-records":{"get":{"description":"Get withdrawal records for the authenticated user with pagination","tags":["accounts"],"summary":"Get withdrawal records","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","name":"page","in":"query"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","name":"limit","in":"query"}],"responses":{"200":{"description":"Paginated withdrawal records","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_WithdrawalRecord"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_WithdrawalRecord":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_entities.WithdrawalRecord"}},"total_count":{"type":"integer"},"total_page":{"type":"integer"}}},"espresso_internal_api_entities.WithdrawalRecord":{"type":"object","properties":{"assets":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_entities.AssetRecord"}},"created_at":{"type":"string"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.TransactionStatus"}]}}},"espresso_internal_api_entities.AssetRecord":{"type":"object","properties":{"asset":{"type":"string"},"asset_unit":{"type":"string"},"qty":{"type":"string"}}},"schema.TransactionStatus":{"type":"string","enum":["building","submitted","submission_failed","confirmed"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Order record

## Get a single order record

> Get a single order record by order ID

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/account/order":{"get":{"description":"Get a single order record by order ID","tags":["accounts"],"summary":"Get a single order record","parameters":[{"schema":{"type":"string"},"description":"Order ID","name":"id","in":"query","required":true}],"responses":{"200":{"description":"Order details","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.OrderResponse":{"type":"object","properties":{"account_id":{"type":"string"},"active_order_utxo_id":{"type":"string"},"base_qty":{"type":"string"},"commission":{"type":"string"},"commission_rate_bp":{"type":"integer"},"commission_unit":{"type":"string"},"created_at":{"type":"string"},"executed_base_qty":{"type":"string"},"executed_price":{"type":"string"},"executed_quote_qty":{"type":"string"},"id":{"type":"string"},"locked_base_qty":{"type":"string"},"locked_quote_qty":{"type":"string"},"market_order_limit_price":{"type":"string"},"ob_open_order_base_qty":{"type":"string"},"order_execution_records":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderExecutionRecordResponse"}},"price":{"type":"string"},"quote_qty":{"type":"string"},"side":{"allOf":[{"$ref":"#/components/schemas/schema.OrderSide"}]},"slippage_bp":{"type":"integer"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.OrderStatus"}]},"symbol":{"type":"string"},"type":{"allOf":[{"$ref":"#/components/schemas/schema.OrderType"}]},"updated_at":{"type":"string"}}},"espresso_internal_api_response.OrderExecutionRecordResponse":{"type":"object","properties":{"account_id":{"type":"string"},"commission":{"type":"string"},"commission_unit":{"type":"string"},"counter_party_order_id":{"type":"string"},"created_at":{"type":"string"},"execution_price":{"type":"string"},"filled_base_qty":{"type":"string"},"filled_quote_qty":{"type":"string"},"id":{"type":"string"},"order_id":{"type":"string"},"role":{"allOf":[{"$ref":"#/components/schemas/schema.OrderExecutionRole"}]}}},"schema.OrderExecutionRole":{"type":"string","enum":["maker","taker"]},"schema.OrderSide":{"type":"string","enum":["buy","sell"]},"schema.OrderStatus":{"type":"string","enum":["building","processing","open","closed","failed","cancelled"]},"schema.OrderType":{"type":"string","enum":["market","limit"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Open orders

## Get open orders

> Get open orders for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/open-orders":{"get":{"description":"Get open orders for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.","tags":["accounts"],"summary":"Get open orders","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"string"},"description":"Trading pair symbol","name":"symbol","in":"query","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","name":"page","in":"query"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","name":"limit","in":"query"}],"responses":{"200":{"description":"Paginated open orders with decimal-adjusted quantities","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderResponse"}},"total_count":{"type":"integer"},"total_page":{"type":"integer"}}},"espresso_internal_api_response.OrderResponse":{"type":"object","properties":{"account_id":{"type":"string"},"active_order_utxo_id":{"type":"string"},"base_qty":{"type":"string"},"commission":{"type":"string"},"commission_rate_bp":{"type":"integer"},"commission_unit":{"type":"string"},"created_at":{"type":"string"},"executed_base_qty":{"type":"string"},"executed_price":{"type":"string"},"executed_quote_qty":{"type":"string"},"id":{"type":"string"},"locked_base_qty":{"type":"string"},"locked_quote_qty":{"type":"string"},"market_order_limit_price":{"type":"string"},"ob_open_order_base_qty":{"type":"string"},"order_execution_records":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderExecutionRecordResponse"}},"price":{"type":"string"},"quote_qty":{"type":"string"},"side":{"allOf":[{"$ref":"#/components/schemas/schema.OrderSide"}]},"slippage_bp":{"type":"integer"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.OrderStatus"}]},"symbol":{"type":"string"},"type":{"allOf":[{"$ref":"#/components/schemas/schema.OrderType"}]},"updated_at":{"type":"string"}}},"espresso_internal_api_response.OrderExecutionRecordResponse":{"type":"object","properties":{"account_id":{"type":"string"},"commission":{"type":"string"},"commission_unit":{"type":"string"},"counter_party_order_id":{"type":"string"},"created_at":{"type":"string"},"execution_price":{"type":"string"},"filled_base_qty":{"type":"string"},"filled_quote_qty":{"type":"string"},"id":{"type":"string"},"order_id":{"type":"string"},"role":{"allOf":[{"$ref":"#/components/schemas/schema.OrderExecutionRole"}]}}},"schema.OrderExecutionRole":{"type":"string","enum":["maker","taker"]},"schema.OrderSide":{"type":"string","enum":["buy","sell"]},"schema.OrderStatus":{"type":"string","enum":["building","processing","open","closed","failed","cancelled"]},"schema.OrderType":{"type":"string","enum":["market","limit"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Trade orders

## Get trade orders

> Get trade orders (orders with executions) for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/trade-orders":{"get":{"description":"Get trade orders (orders with executions) for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.","tags":["accounts"],"summary":"Get trade orders","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"string"},"description":"Trading pair symbol","name":"symbol","in":"query","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","name":"page","in":"query"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","name":"limit","in":"query"}],"responses":{"200":{"description":"Paginated trade orders with decimal-adjusted quantities","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderResponse"}},"total_count":{"type":"integer"},"total_page":{"type":"integer"}}},"espresso_internal_api_response.OrderResponse":{"type":"object","properties":{"account_id":{"type":"string"},"active_order_utxo_id":{"type":"string"},"base_qty":{"type":"string"},"commission":{"type":"string"},"commission_rate_bp":{"type":"integer"},"commission_unit":{"type":"string"},"created_at":{"type":"string"},"executed_base_qty":{"type":"string"},"executed_price":{"type":"string"},"executed_quote_qty":{"type":"string"},"id":{"type":"string"},"locked_base_qty":{"type":"string"},"locked_quote_qty":{"type":"string"},"market_order_limit_price":{"type":"string"},"ob_open_order_base_qty":{"type":"string"},"order_execution_records":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderExecutionRecordResponse"}},"price":{"type":"string"},"quote_qty":{"type":"string"},"side":{"allOf":[{"$ref":"#/components/schemas/schema.OrderSide"}]},"slippage_bp":{"type":"integer"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.OrderStatus"}]},"symbol":{"type":"string"},"type":{"allOf":[{"$ref":"#/components/schemas/schema.OrderType"}]},"updated_at":{"type":"string"}}},"espresso_internal_api_response.OrderExecutionRecordResponse":{"type":"object","properties":{"account_id":{"type":"string"},"commission":{"type":"string"},"commission_unit":{"type":"string"},"counter_party_order_id":{"type":"string"},"created_at":{"type":"string"},"execution_price":{"type":"string"},"filled_base_qty":{"type":"string"},"filled_quote_qty":{"type":"string"},"id":{"type":"string"},"order_id":{"type":"string"},"role":{"allOf":[{"$ref":"#/components/schemas/schema.OrderExecutionRole"}]}}},"schema.OrderExecutionRole":{"type":"string","enum":["maker","taker"]},"schema.OrderSide":{"type":"string","enum":["buy","sell"]},"schema.OrderStatus":{"type":"string","enum":["building","processing","open","closed","failed","cancelled"]},"schema.OrderType":{"type":"string","enum":["market","limit"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Trades

## Get account trades

> Get execution records (trades) for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/trades":{"get":{"description":"Get execution records (trades) for the authenticated user with pagination. Quantities are returned in human-readable format adjusted for token decimals.","tags":["accounts"],"summary":"Get account trades","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"string"},"description":"Trading pair symbol","name":"symbol","in":"query","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","name":"page","in":"query"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","name":"limit","in":"query"}],"responses":{"200":{"description":"Paginated account trades with decimal-adjusted quantities","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderExecutionRecordResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_response_OrderExecutionRecordResponse":{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderExecutionRecordResponse"}},"total_count":{"type":"integer"},"total_page":{"type":"integer"}}},"espresso_internal_api_response.OrderExecutionRecordResponse":{"type":"object","properties":{"account_id":{"type":"string"},"commission":{"type":"string"},"commission_unit":{"type":"string"},"counter_party_order_id":{"type":"string"},"created_at":{"type":"string"},"execution_price":{"type":"string"},"filled_base_qty":{"type":"string"},"filled_quote_qty":{"type":"string"},"id":{"type":"string"},"order_id":{"type":"string"},"role":{"allOf":[{"$ref":"#/components/schemas/schema.OrderExecutionRole"}]}}},"schema.OrderExecutionRole":{"type":"string","enum":["maker","taker"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Build withdrawal transaction

{% openapi src="/files/OBUoSkAj2jNQTKXIyjqv" path="/accounts/withdrawal/build" method="post" %}
[swagger.json](https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FsdIBJKR1DMlG9SEXQglg%2Fswagger.json?alt=media\&token=4dd3ae5d-c407-4a6c-a867-62de5adc1817)
{% endopenapi %}


# Submit withdrawal transaction

{% openapi src="/files/OBUoSkAj2jNQTKXIyjqv" path="/accounts/withdrawal/submit" method="post" %}
[swagger.json](https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FsdIBJKR1DMlG9SEXQglg%2Fswagger.json?alt=media\&token=4dd3ae5d-c407-4a6c-a867-62de5adc1817)
{% endopenapi %}


# Account Balances

## Get account balance

> Get account balance

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/balance":{"get":{"description":"Get account balance","tags":["accounts"],"summary":"Get account balance","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true},{"schema":{"type":"string"},"description":"Filter by asset unit (e.g. lovelace)","name":"asset_unit","in":"query"}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_entities.AssetBalance"}}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_entities.AssetBalance":{"type":"object","properties":{"asset":{"type":"string"},"asset_unit":{"type":"string"},"free":{"type":"string"},"locked":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Max deposit amount

## Get maximum deposit amount

> Get the maximum amount of lovelace that can be deposited

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/max-deposit":{"get":{"description":"Get the maximum amount of lovelace that can be deposited","tags":["accounts"],"summary":"Get maximum deposit amount","parameters":[{"schema":{"type":"string"},"description":"API Key","name":"X-API-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetMaxDepositResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.GetMaxDepositResponse":{"type":"object","properties":{"max_deposit":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Transferal records

## Get transferal records

> Get transferal records for the authenticated user, including both incoming and outgoing transfers with pagination. Each record has a 'direction' field indicating "incoming" or "outgoing", and a 'status' field indicating "pending" or "confirmed".

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/transferal-records":{"get":{"description":"Get transferal records for the authenticated user, including both incoming and outgoing transfers with pagination. Each record has a 'direction' field indicating \"incoming\" or \"outgoing\", and a 'status' field indicating \"pending\" or \"confirmed\".","parameters":[{"schema":{"type":"string"},"description":"API Key","in":"header","name":"X-API-KEY","required":true},{"schema":{"type":"integer"},"description":"Page number for pagination, default is 1","in":"query","name":"page"},{"schema":{"type":"integer"},"description":"Limit number of records per page, default is 10","in":"query","name":"limit"},{"schema":{"type":"string"},"description":"Filter by transfer status: 'pending' (not yet spent) or 'confirmed' (already spent). If omitted, returns all records.","in":"query","name":"status"}],"responses":{"200":{"description":"Paginated transferal records","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_TransferalRecord"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"summary":"Get transferal records","tags":["accounts"]}}},"components":{"schemas":{"espresso_internal_api_response.PaginatedResponse-espresso_internal_api_entities_TransferalRecord":{"properties":{"data":{"items":{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferalRecord"},"type":"array"},"total_count":{"type":"integer"},"total_page":{"type":"integer"}},"type":"object"},"espresso_internal_api_entities.TransferalRecord":{"properties":{"assets":{"items":{"$ref":"#/components/schemas/espresso_internal_api_entities.AssetRecord"},"type":"array"},"created_at":{"type":"string"},"direction":{"allOf":[{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferDirection"}],"description":"\"incoming\" or \"outgoing\""},"status":{"allOf":[{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferStatus"}],"description":"\"pending\" or \"confirmed\""},"transferal_type":{"$ref":"#/components/schemas/schema.TransferalType"},"tx_hash":{"type":"string"}},"type":"object"},"espresso_internal_api_entities.AssetRecord":{"properties":{"asset":{"type":"string"},"asset_unit":{"type":"string"},"qty":{"type":"number"}},"type":"object"},"espresso_internal_api_entities.TransferDirection":{"enum":["incoming","outgoing"],"type":"string"},"espresso_internal_api_entities.TransferStatus":{"enum":["pending","confirmed"],"type":"string"},"schema.TransferalType":{"enum":["normal","deposit","withdrawal"],"type":"string"},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"properties":{"code":{"type":"integer"},"error":{"type":"string"}},"type":"object"}}}}
```

## Get transferal record by transaction hash

> Get a single transferal record by its transaction hash. Returns the record with direction (incoming/outgoing) and status (pending/confirmed).

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"ApiKeyAuth":[]}],"paths":{"/accounts/transferal-records/{tx_hash}":{"get":{"description":"Get a single transferal record by its transaction hash. Returns the record with direction (incoming/outgoing) and status (pending/confirmed).","parameters":[{"schema":{"type":"string"},"description":"API Key","in":"header","name":"X-API-KEY","required":true},{"schema":{"type":"string"},"description":"Transaction hash","in":"path","name":"tx_hash","required":true}],"responses":{"200":{"description":"Transferal record details","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferalRecord"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"404":{"description":"Intent not found or intent expired","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"summary":"Get transferal record by transaction hash","tags":["accounts"]}}},"components":{"schemas":{"espresso_internal_api_entities.TransferalRecord":{"properties":{"assets":{"items":{"$ref":"#/components/schemas/espresso_internal_api_entities.AssetRecord"},"type":"array"},"created_at":{"type":"string"},"direction":{"allOf":[{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferDirection"}],"description":"\"incoming\" or \"outgoing\""},"status":{"allOf":[{"$ref":"#/components/schemas/espresso_internal_api_entities.TransferStatus"}],"description":"\"pending\" or \"confirmed\""},"transferal_type":{"$ref":"#/components/schemas/schema.TransferalType"},"tx_hash":{"type":"string"}},"type":"object"},"espresso_internal_api_entities.AssetRecord":{"properties":{"asset":{"type":"string"},"asset_unit":{"type":"string"},"qty":{"type":"number"}},"type":"object"},"espresso_internal_api_entities.TransferDirection":{"enum":["incoming","outgoing"],"type":"string"},"espresso_internal_api_entities.TransferStatus":{"enum":["pending","confirmed"],"type":"string"},"schema.TransferalType":{"enum":["normal","deposit","withdrawal"],"type":"string"},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"properties":{"code":{"type":"integer"},"error":{"type":"string"}},"type":"object"}}}}
```


# Operation key

## Get operation key

> Get operation key

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"security":[{"operationKeyAuth":[]}],"paths":{"/accounts/operation-key":{"get":{"description":"Get operation key","tags":["accounts"],"summary":"Get operation key","parameters":[{"schema":{"type":"string"},"description":"operation Key","name":"X-operation-KEY","in":"header","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetOperationKeyResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.GetOperationKeyResponse":{"type":"object","properties":{"encrypted_operation_key":{"type":"string"},"operation_key_hash":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# App


# Market config

Get all supported trading pairs and assets with their metadata. This endpoint provides essential information for trading including token decimals, symbols, and trading pair configurations.

## Get market configuration

> Get all supported trading pairs and assets with their metadata

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/app/market-config":{"get":{"description":"Get all supported trading pairs and assets with their metadata","tags":["app"],"summary":"Get market configuration","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetMarketConfigResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.GetMarketConfigResponse":{"type":"object","properties":{"assets":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.MarketConfigAsset"}},"trading_pairs":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.MarketConfigTradingPair"}}}},"espresso_internal_api_response.MarketConfigAsset":{"type":"object","properties":{"decimals":{"type":"integer"},"max_qty_dp":{"type":"integer"},"symbol":{"type":"string"},"trading_pairs":{"type":"array","items":{"type":"string"}},"unit":{"type":"string"}}},"espresso_internal_api_response.MarketConfigTradingPair":{"type":"object","properties":{"base_token":{"$ref":"#/components/schemas/espresso_internal_api_response.MarketConfigToken"},"price_max_dp":{"type":"integer"},"quote_token":{"$ref":"#/components/schemas/espresso_internal_api_response.MarketConfigToken"},"symbol":{"type":"string"}}},"espresso_internal_api_response.MarketConfigToken":{"type":"object","properties":{"decimals":{"type":"integer"},"max_qty_dp":{"type":"integer"},"symbol":{"type":"string"},"unit":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/app/market-config'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/app/market-config'
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "net/http"
  "io"
)

func main() {
  url := "https://api.deltadefi.io/app/market-config"
  method := "GET"

  client := &http.Client{}
  req, err := http.NewRequest(method, url, nil)
  if err != nil {
    fmt.Println(err)
    return
  }

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

**Response:**

```json
{
  "assets": [
    {
      "symbol": "ADA",
      "unit": "lovelace",
      "decimals": 6,
      "max_qty_dp": 2,
      "trading_pairs": ["ADAUSDM"]
    },
    {
      "symbol": "USDM",
      "unit": "c48cbb3d5e57ed56e276bc45f99ab39abe94e6cd7ac39fb402da47ad.0014df105553444d",
      "decimals": 6,
      "max_qty_dp": 2,
      "trading_pairs": ["ADAUSDM"]
    }
  ],
  "trading_pairs": [
    {
      "symbol": "ADAUSDM",
      "base_token": {
        "symbol": "ADA",
        "unit": "lovelace",
        "decimals": 6,
        "max_qty_dp": 2
      },
      "quote_token": {
        "symbol": "USDM",
        "unit": "c48cbb3d5e57ed56e276bc45f99ab39abe94e6cd7ac39fb402da47ad.0014df105553444d",
        "decimals": 6,
        "max_qty_dp": 2
      },
      "price_max_dp": 4
    }
  ]
}
```

***

## Understanding the Response

### Assets

Each asset includes:

| Field          | Type    | Description                                                               |
| -------------- | ------- | ------------------------------------------------------------------------- |
| symbol         | string  | Human-readable asset name (e.g., ADA, USDM)                               |
| unit           | string  | On-chain asset identifier (policy ID + asset name, or "lovelace" for ADA) |
| decimals       | integer | Number of decimal places for the token on-chain                           |
| max\_qty\_dp   | integer | Maximum decimal places allowed for quantity inputs                        |
| trading\_pairs | array   | List of trading pairs this asset is involved in                           |

### Trading Pairs

Each trading pair includes:

| Field          | Type    | Description                                 |
| -------------- | ------- | ------------------------------------------- |
| symbol         | string  | Trading pair identifier (e.g., "ADAUSDM")   |
| base\_token    | object  | The base asset (what you're buying/selling) |
| quote\_token   | object  | The quote asset (what you're pricing in)    |
| price\_max\_dp | integer | Maximum decimal places for price inputs     |

{% hint style="info" %}
Use this endpoint to dynamically discover available trading pairs and properly format quantities and prices in your trading application.
{% endhint %}


# Get mock USDM (testnet only)

{% openapi src="/files/OBUoSkAj2jNQTKXIyjqv" path="/app/mock-usdx" method="post" %}
[swagger.json](https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FsdIBJKR1DMlG9SEXQglg%2Fswagger.json?alt=media\&token=4dd3ae5d-c407-4a6c-a867-62de5adc1817)
{% endopenapi %}


# Submit USDM transaction (testnet only)

{% openapi src="/files/OBUoSkAj2jNQTKXIyjqv" path="/app/submit-tx" method="post" %}
[swagger.json](https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FsdIBJKR1DMlG9SEXQglg%2Fswagger.json?alt=media\&token=4dd3ae5d-c407-4a6c-a867-62de5adc1817)
{% endopenapi %}


# Trading liveness

## Get trading lock status

> Get the current trading lock status.

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/health/trading-lock-status":{"get":{"description":"Get the current trading lock status.","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetTradingLockStatusResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"summary":"Get trading lock status","tags":["Health"]}}},"components":{"schemas":{"espresso_internal_api_response.GetTradingLockStatusResponse":{"properties":{"is_locked":{"type":"boolean"}},"type":"object"},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"properties":{"code":{"type":"integer"},"error":{"type":"string"}},"type":"object"}}}}
```


# Market


# Market Price

returns the last traded price

## Get market price

> Get market price

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/market/market-price":{"get":{"description":"Get market price","tags":["market"],"summary":"Get market price","parameters":[{"schema":{"type":"string"},"name":"symbol","in":"query","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.GetMarketPriceResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.GetMarketPriceResponse":{"type":"object","properties":{"price":{"type":"number"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Order


# Build order transaction

Build a new order transaction. This endpoint creates an unsigned transaction that must be signed and submitted via the [Submit Order Transaction](/start-trading/developers/api-documentation/order/submit-order-transaction) endpoint.

***

## Build place order transaction

> Build place order transaction

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/orders/build":{"post":{"description":"Build place order transaction","tags":["order"],"summary":"Build place order transaction","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.BuildPlaceOrderTransactionResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"406":{"description":"Not Acceptable","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_requests.BuildPlaceOrderTransactionRequest"}}},"description":"Build place order transaction request","required":true}}}},"components":{"schemas":{"espresso_internal_api_response.BuildPlaceOrderTransactionResponse":{"type":"object","properties":{"order_id":{"type":"string"},"tx_hex":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}},"espresso_internal_api_requests.BuildPlaceOrderTransactionRequest":{"type":"object","required":["side","symbol","type"],"properties":{"base_quantity":{"type":"string"},"max_slippage_basis_point":{"type":"string"},"post_only":{"description":"LimitSlippage         bool   `json:\"limit_slippage\"`","type":"boolean"},"price":{"type":"string"},"quote_quantity":{"description":"Quantity float64          `json:\"quantity\" binding:\"required\"`","type":"string"},"side":{"$ref":"#/components/schemas/schema.OrderSide"},"symbol":{"type":"string"},"type":{"$ref":"#/components/schemas/schema.OrderType"}}},"schema.OrderSide":{"type":"string","enum":["buy","sell"]},"schema.OrderType":{"type":"string","enum":["market","limit"]}}}}
```

## Request Parameters

| Parameter                   | Type    | Required    | Description                                                                                         |
| --------------------------- | ------- | ----------- | --------------------------------------------------------------------------------------------------- |
| symbol                      | string  | Yes         | Trading pair symbol (e.g., `ADAUSDM`)                                                               |
| side                        | string  | Yes         | Order side: `buy` or `sell`                                                                         |
| type                        | string  | Yes         | Order type: `limit` or `market`                                                                     |
| base\_quantity              | string  | Conditional | Quantity in base asset (e.g., ADA). **Use either `base_quantity` OR `quote_quantity`, not both.**   |
| quote\_quantity             | string  | Conditional | Quantity in quote asset (e.g., USDM). **Use either `base_quantity` OR `quote_quantity`, not both.** |
| price                       | string  | Conditional | Order price. **Required for limit orders, ignored for market orders.**                              |
| max\_slippage\_basis\_point | string  | No          | Maximum slippage in basis points. **Only applicable for market orders.**                            |
| post\_only                  | boolean | No          | If `true`, order only posts if it doesn't match immediately. **Only applicable for limit orders.**  |

***

## Order Types

### Limit Order

A limit order is placed at a specific price. It will only execute at that price or better.

**Required parameters:**

* `symbol`, `side`, `type` (set to `limit`)
* `price` - The limit price
* Either `base_quantity` or `quote_quantity`

**Optional parameters:**

* `post_only` - Set to `true` to ensure the order only acts as a maker (adds liquidity). If it would match immediately, the order is rejected.

### Market Order

A market order executes immediately at the best available price. No price is specified.

**Required parameters:**

* `symbol`, `side`, `type` (set to `market`)
* Either `base_quantity` or `quote_quantity`

**Optional parameters:**

* `max_slippage_basis_point` - Maximum acceptable slippage (1 basis point = 0.01%). If not set, unlimited slippage is allowed.

{% hint style="warning" %}
**Market Order Slippage:** If `max_slippage_basis_point` is not set, the market order will fill at any price until the order is complete or your balance is exhausted. Set a slippage limit to protect against unfavorable fills.
{% endhint %}

***

## Quantity Specification

You must specify **either** `base_quantity` **or** `quote_quantity`, but **not both**.

| Field           | Description                        | Example           |
| --------------- | ---------------------------------- | ----------------- |
| base\_quantity  | Amount of base asset (e.g., ADA)   | `"100"` = 100 ADA |
| quote\_quantity | Amount of quote asset (e.g., USDM) | `"93"` = 93 USDM  |

**Example for ADAUSDM pair:**

* Buy 100 ADA: `{"base_quantity": "100", "side": "buy", ...}`
* Buy $93 worth of ADA: `{"quote_quantity": "93", "side": "buy", ...}`

***

## Code Examples

### Limit Order Example

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/order/build' \
--header 'X-API-KEY: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "symbol": "ADAUSDM",
    "side": "buy",
    "type": "limit",
    "base_quantity": "100",
    "price": "0.93"
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "symbol": "ADAUSDM",
  "side": "buy",
  "type": "limit",
  "base_quantity": "100",
  "price": "0.93"
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/order/build',
  headers: { 
    'X-API-KEY': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data: data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {
  url := "https://api.deltadefi.io/order/build"
  method := "POST"

  payload := strings.NewReader(`{
    "symbol": "ADAUSDM",
    "side": "buy",
    "type": "limit",
    "base_quantity": "100",
    "price": "0.93"
}`)

  client := &http.Client{}
  req, err := http.NewRequest(method, url, payload)
  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

### Market Order Example

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/order/build' \
--header 'X-API-KEY: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "symbol": "ADAUSDM",
    "side": "buy",
    "type": "market",
    "base_quantity": "100",
    "max_slippage_basis_point": "100"
}'
```

{% endtab %}

{% tab title="NodeJs (axios)" %}

```javascript
const axios = require('axios');
let data = JSON.stringify({
  "symbol": "ADAUSDM",
  "side": "buy",
  "type": "market",
  "base_quantity": "100",
  "max_slippage_basis_point": "100"  // 1% max slippage
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.deltadefi.io/order/build',
  headers: { 
    'X-API-KEY': '<your_api_key>', 
    'Content-Type': 'application/json'
  },
  data: data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {
  url := "https://api.deltadefi.io/order/build"
  method := "POST"

  payload := strings.NewReader(`{
    "symbol": "ADAUSDM",
    "side": "buy",
    "type": "market",
    "base_quantity": "100",
    "max_slippage_basis_point": "100"
}`)

  client := &http.Client{}
  req, err := http.NewRequest(method, url, payload)
  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("X-API-KEY", "<your_api_key>")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

### Post-Only Limit Order Example

{% tabs %}
{% tab title="Curl" %}

```sh
curl --location 'https://api.deltadefi.io/order/build' \
--header 'X-API-KEY: <your_api_key>' \
--header 'Content-Type: application/json' \
--data '{
    "symbol": "ADAUSDM",
    "side": "buy",
    "type": "limit",
    "base_quantity": "100",
    "price": "0.90",
    "post_only": true
}'
```

{% endtab %}
{% endtabs %}

***

## Response

```json
{
  "order_id": "550e8400-e29b-41d4-a716-446655440000",
  "tx_hex": "84a400818258203b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b700018182583900..."
}
```

| Field     | Type   | Description                                                                                                                                                |
| --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| order\_id | string | Unique order identifier. Use this when submitting the signed transaction.                                                                                  |
| tx\_hex   | string | Unsigned transaction hex. Sign this and submit via [Submit Order Transaction](/start-trading/developers/api-documentation/order/submit-order-transaction). |

***

## Next Steps

After building the order:

1. **Sign the transaction** using your wallet - see [How to sign a Cardano transaction](/faq/cardano#how-can-i-sign-a-cardano-transaction)
2. **Submit the signed transaction** via [Submit Order Transaction](/start-trading/developers/api-documentation/order/submit-order-transaction)

***

## Error Codes

| Code | Error                           | Description                                        |
| ---- | ------------------------------- | -------------------------------------------------- |
| 4050 | Insufficient balance            | Not enough free balance to place the order         |
| 4100 | Order size too small            | Order must be at least 5 ADA equivalent            |
| 4101 | Invalid order price             | Price must be greater than 0                       |
| 4102 | Invalid price decimal places    | Price has too many decimal places                  |
| 4103 | Invalid quantity decimal places | Quantity has too many decimal places               |
| 4104 | Post-only would match           | Post-only order would match immediately (rejected) |
| 4106 | Invalid symbol                  | Trading pair not found                             |
| 4109 | Insufficient liquidity          | Not enough liquidity for market order              |
| 4110 | Max open orders exceeded        | Too many open orders                               |

***

## Related

* [Submit Order Transaction](/start-trading/developers/api-documentation/order/submit-order-transaction)
* [Cancel Order](/start-trading/developers/api-documentation/order/build-cancel-order-transaction)
* [Order Records](/start-trading/developers/api-documentation/account/order-records)
* [Order Types](/about/learn/trade/order-types)


# Submit order Transaction

## Submit place order transaction

> Submit place order transaction

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/orders/submit":{"post":{"description":"Submit place order transaction","tags":["order"],"summary":"Submit place order transaction","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_requests.SubmitPlaceOrderTransactionRequest"}}},"description":"Submit place order transaction request","required":true}}}},"components":{"schemas":{"espresso_internal_api_response.OrderResponse":{"type":"object","properties":{"account_id":{"type":"string"},"active_order_utxo_id":{"type":"string"},"base_qty":{"type":"string"},"commission":{"type":"string"},"commission_rate_bp":{"type":"integer"},"commission_unit":{"type":"string"},"created_at":{"type":"string"},"executed_base_qty":{"type":"string"},"executed_price":{"type":"string"},"executed_quote_qty":{"type":"string"},"id":{"type":"string"},"locked_base_qty":{"type":"string"},"locked_quote_qty":{"type":"string"},"market_order_limit_price":{"type":"string"},"ob_open_order_base_qty":{"type":"string"},"order_execution_records":{"type":"array","items":{"$ref":"#/components/schemas/espresso_internal_api_response.OrderExecutionRecordResponse"}},"price":{"type":"string"},"quote_qty":{"type":"string"},"side":{"allOf":[{"$ref":"#/components/schemas/schema.OrderSide"}]},"slippage_bp":{"type":"integer"},"status":{"allOf":[{"$ref":"#/components/schemas/schema.OrderStatus"}]},"symbol":{"type":"string"},"type":{"allOf":[{"$ref":"#/components/schemas/schema.OrderType"}]},"updated_at":{"type":"string"}}},"espresso_internal_api_response.OrderExecutionRecordResponse":{"type":"object","properties":{"account_id":{"type":"string"},"commission":{"type":"string"},"commission_unit":{"type":"string"},"counter_party_order_id":{"type":"string"},"created_at":{"type":"string"},"execution_price":{"type":"string"},"filled_base_qty":{"type":"string"},"filled_quote_qty":{"type":"string"},"id":{"type":"string"},"order_id":{"type":"string"},"role":{"allOf":[{"$ref":"#/components/schemas/schema.OrderExecutionRole"}]}}},"schema.OrderExecutionRole":{"type":"string","enum":["maker","taker"]},"schema.OrderSide":{"type":"string","enum":["buy","sell"]},"schema.OrderStatus":{"type":"string","enum":["building","processing","open","closed","failed","cancelled"]},"schema.OrderType":{"type":"string","enum":["market","limit"]},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}},"espresso_internal_api_requests.SubmitPlaceOrderTransactionRequest":{"type":"object","required":["order_id","signed_tx"],"properties":{"order_id":{"type":"string"},"signed_tx":{"type":"string"}}}}}}
```


# Cancel Order

Cancel a single order by order ID. This endpoint directly cancels the order without requiring a separate build/submit step.

## Cancel an order

> Cancel a single order by order ID

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/order/{orderId}/cancel":{"post":{"description":"Cancel a single order by order ID","tags":["order"],"summary":"Cancel an order","parameters":[{"schema":{"type":"string"},"description":"Order ID","name":"orderId","in":"path","required":true}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.CancelOrderResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"404":{"description":"Order Not Found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}}}}},"components":{"schemas":{"espresso_internal_api_response.CancelOrderResponse":{"type":"object","properties":{"order_id":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}}}}}
```


# Cancel all Order

Cancel all open orders for a given symbol. This endpoint directly cancels all orders without requiring a separate build/submit step.

## Cancel all orders

> Cancel all open orders for a given symbol

```json
{"openapi":"3.1.1","info":{"title":"Espresso API Server","version":"1.0"},"paths":{"/order/cancel-all":{"post":{"description":"Cancel all open orders for a given symbol","tags":["order"],"summary":"Cancel all orders","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.CancelAllOrdersResponse"}}}},"400":{"description":"Bad Request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"404":{"description":"Order Not Found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"422":{"description":"Unprocessable Entity","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}},"500":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_response.ErrorJSONWithCodeResponse"}}}}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/espresso_internal_api_requests.CancelAllOrdersRequest"}}},"description":"Cancel all orders request","required":true}}}},"components":{"schemas":{"espresso_internal_api_response.CancelAllOrdersResponse":{"type":"object","properties":{"order_ids":{"type":"array","items":{"type":"string"}},"symbol":{"type":"string"}}},"espresso_internal_api_response.ErrorJSONWithCodeResponse":{"type":"object","properties":{"code":{"type":"integer"},"error":{"type":"string"}}},"espresso_internal_api_requests.CancelAllOrdersRequest":{"type":"object","required":["symbol"],"properties":{"symbol":{"type":"string"}}}}}}
```


# Websocket Endpoints


# Recent trades

`/market/recent-trade/:symbol?api_key=<your_api_key>`&#x20;

## This websocket will feed notifications for

* new trades for a specific trading pair

**Query params**

| Name     | Value             |
| -------- | ----------------- |
| api\_key | \<your\_api\_key> |

**Stream Response**

{% tabs %}
{% tab title="recent trades" %}

```json
[
  {
    "timestamp": "2025-08-21T03:43:00.204624Z",
    "symbol": "ADAUSDM",
    "side": "sell",
    "price": 0.7803,
    "amount": 4.6
  },
  {
    "timestamp": "2025-08-21T03:43:00.20169Z",
    "symbol": "ADAUSDM",
    "side": "buy",
    "price": 0.78,
    "amount": 5.4
  },
  {
    "timestamp": "2025-08-21T03:42:41.033791Z",
    "symbol": "ADAUSDM",
    "side": "buy",
    "price": 0.78,
    "amount": 10
  },
  {
    "timestamp": "2025-08-20T22:53:00.007111Z",
    "symbol": "ADAUSDM",
    "side": "sell",
    "price": 0.78,
    "amount": 4.6
  },
  {
    "timestamp": "2025-08-20T22:53:00.004846Z",
    "symbol": "ADAUSDM",
    "side": "buy",
    "price": 0.75,
    "amount": 5.4
  },
]
```

{% endtab %}
{% endtabs %}


# Account streams

Real-time WebSocket stream for account-related updates including balances, orders, and points.

## Connection

```
wss://api.deltadefi.io/accounts/stream?api_key=<your_api_key>
```

**Query Parameters**

| Name     | Type   | Required | Description  |
| -------- | ------ | -------- | ------------ |
| api\_key | string | Yes      | Your API key |

***

## Event Types

This WebSocket stream provides the following event types:

| Event Type | Sub Type      | Description                                                         |
| ---------- | ------------- | ------------------------------------------------------------------- |
| Account    | `balance`     | Account balance updates when deposits, withdrawals, or trades occur |
| Account    | `order_info`  | Real-time order status updates (new orders, fills, cancellations)   |
| Account    | `dlta_points` | Points/rewards updates when you earn DLTA points                    |

***

## Event Formats

{% tabs %}
{% tab title="order\_info" %}
Real-time order updates. Sent whenever an order status changes (created, partially filled, fully filled, cancelled).

```json
{
  "type": "Account",
  "sub_type": "order_info",
  "order": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "account_id": "550e8400-e29b-41d4-a716-446655440001",
    "status": "open",
    "symbol": "ADAUSDM",
    "base_qty": "100.00",
    "quote_qty": "93.00",
    "side": "buy",
    "price": "0.93",
    "type": "limit",
    "locked_base_qty": "100.00",
    "locked_quote_qty": "93.00",
    "executed_base_qty": "0",
    "executed_quote_qty": "0",
    "ob_open_order_base_qty": "100.00",
    "commission_unit": "lovelace",
    "commission": "0",
    "commission_rate_bp": 10,
    "executed_price": "0",
    "created_at": "2024-01-01T00:00:00Z",
    "updated_at": "2024-01-01T00:00:00Z",
    "order_execution_records": []
  }
}
```

**Order Status Values:**

* `building` - Order is being built
* `processing` - Order is being processed
* `open` - Order is active on the order book
* `closed` - Order is fully filled
* `failed` - Order failed
* `cancelled` - Order was cancelled
  {% endtab %}

{% tab title="dlta\_points" %}
Points updates when you earn DLTA rewards from trading activity.

```json
{
  "type": "Account",
  "sub_type": "dlta_points",
  "dlta_points": {
    "delta": "150",
    "new_total": "15150",
    "season_points": "5150",
    "source_type": "trade",
    "source_ref": "550e8400-e29b-41d4-a716-446655440000",
    "league": "gold"
  }
}
```

**Fields:**

| Field          | Type   | Description                                                            |
| -------------- | ------ | ---------------------------------------------------------------------- |
| delta          | string | Points earned in this update                                           |
| new\_total     | string | New total points balance                                               |
| season\_points | string | Points earned this season                                              |
| source\_type   | string | Source of points: `trade`, `referral`, `bonus`                         |
| source\_ref    | string | Reference ID (e.g., order ID for trades)                               |
| league         | string | Current league tier: `bronze`, `silver`, `gold`, `platinum`, `diamond` |
| {% endtab %}   |        |                                                                        |

{% tab title="balance" %}
Account balance updates when deposits, withdrawals, or trades occur.

```json
{
  "type": "Account",
  "sub_type": "balance",
  "balance": [
    {
      "asset": "usdm",
      "asset_unit": "5066154a102ee037390c5236f78db23239b49c5748d3d349f3ccf04b55534458",
      "free": 1153.006812,
      "locked": 0
    },
    {
      "asset": "ada",
      "asset_unit": "",
      "free": 1383.52097,
      "locked": 0
    }
  ]
}
```

**Fields:**

| Field         | Type   | Description                         |
| ------------- | ------ | ----------------------------------- |
| asset         | string | Asset symbol (e.g., `ada`, `usdm`)  |
| asset\_unit   | string | On-chain asset unit (empty for ADA) |
| free          | number | Available balance for trading       |
| locked        | number | Balance locked in open orders       |
| {% endtab %}  |        |                                     |
| {% endtabs %} |        |                                     |

***

## Connection Example

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const WebSocket = require('ws');

const ws = new WebSocket('wss://api.deltadefi.io/accounts/stream?api_key=<your_api_key>');

ws.on('open', function open() {
  console.log('Connected to account stream');
});

ws.on('message', function message(data) {
  const event = JSON.parse(data);
  
  switch (event.sub_type) {
    case 'order_info':
      console.log('Order update:', event.order);
      break;
    case 'dlta_points':
      console.log('Points earned:', event.dlta_points.delta);
      break;
    case 'balance':
      console.log('Balance update:', event.balance);
      break;
    default:
      console.log('Event:', event);
  }
});

ws.on('close', function close() {
  console.log('Disconnected from account stream');
});

ws.on('error', function error(err) {
  console.error('WebSocket error:', err);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import websocket
import json

def on_message(ws, message):
    event = json.loads(message)
    
    if event.get('sub_type') == 'order_info':
        print(f"Order update: {event['order']}")
    elif event.get('sub_type') == 'dlta_points':
        print(f"Points earned: {event['dlta_points']['delta']}")
    elif event.get('sub_type') == 'balance':
        print(f"Balance update: {event['balance']}")
    else:
        print(f"Event: {event}")

def on_error(ws, error):
    print(f"Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print("Connection closed")

def on_open(ws):
    print("Connected to account stream")

ws = websocket.WebSocketApp(
    "wss://api.deltadefi.io/accounts/stream?api_key=<your_api_key>",
    on_open=on_open,
    on_message=on_message,
    on_error=on_error,
    on_close=on_close
)

ws.run_forever()
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/gorilla/websocket"
)

type Event struct {
    Type      string          `json:"type"`
    SubType   string          `json:"sub_type"`
    Order     json.RawMessage `json:"order,omitempty"`
    DltaPoints json.RawMessage `json:"dlta_points,omitempty"`
    Balance   json.RawMessage `json:"balance,omitempty"`
}

func main() {
    url := "wss://api.deltadefi.io/accounts/stream?api_key=<your_api_key>"
    
    c, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    defer c.Close()

    fmt.Println("Connected to account stream")

    for {
        _, message, err := c.ReadMessage()
        if err != nil {
            log.Println("read:", err)
            return
        }

        var event Event
        json.Unmarshal(message, &event)

        switch event.SubType {
        case "order_info":
            fmt.Printf("Order update: %s\n", event.Order)
        case "dlta_points":
            fmt.Printf("Points update: %s\n", event.DltaPoints)
        case "balance":
            fmt.Printf("Balance update: %s\n", event.Balance)
        default:
            fmt.Printf("Event: %s\n", message)
        }
    }
}
```

{% endtab %}
{% endtabs %}

***

## Related

* [Market Price Streams](/start-trading/developers/websocket-endpoints/market-price-streams)
* [Market Depth Streams](/start-trading/developers/websocket-endpoints/market-depth-streams)
* [Recent Trades](/start-trading/developers/websocket-endpoints/recent-trades)


# Market price streams

`/market/market-price/:symbol?api_key=<your_api_key>`&#x20;

## This websocket will feed notifications for

* Latest market-price (Last trade price)

**Query params**

| Name     | Value             |
| -------- | ----------------- |
| api\_key | \<your\_api\_key> |

**Stream Response**

{% tabs %}
{% tab title="market price" %}

```json
// exmaple response for market price
{
  type: "Market",
  sub_type: "market_price",
  price: 0.75
}


```

{% endtab %}
{% endtabs %}


# Market depth streams

`/market/depth/:symbol?api_key=<your_api_key>`&#x20;

## This websocket will feed notifications for

* newly created orders that exists on the order book

**Query params**

| Name     | Value             |
| -------- | ----------------- |
| api\_key | \<your\_api\_key> |

**Stream Response**

{% tabs %}
{% tab title="market price" %}

```json
{
  "timestamp": 1755747950587,
  "bids": [
    {
      "price": 0.195,
      "quantity": 30
    }
  ],
  "asks": [
    {
      "price": 0.3495,
      "quantity": 50.65
    }
  ]
}


```

{% endtab %}
{% endtabs %}


# SDKs


# Typescript

### About

DeltaDeFi's Typescript SDK provides utility functions to interact with the API service and sign transactions with provided keys.

### Installation

The SDK is hosted on npmjs.com, so you can directly import it using your favorite package manager.

```
npm i @deltadefi-protocol/sdk
```

```
yarn add @deltadefi-protocol/sdk
```

### Getting Started

Placing and canceling orders are as simple as below.

```typescript
import { ApiClient } from "@deltadefi-protocol/sdk";

export const getApiClient = async (): Promise<ApiClient> => {
  const network = process.env.NETWORK;
  const apiKey = process.env.API_KEY;
  const operationKeyEncryptionPassword =
    process.env.OPERATION_KEY_ENCRYPTION_PASSWORD!;

  const apiClient = new ApiClient({
    network: network as "preprod" | "mainnet",
    apiKey: apiKey,
  });

  await apiClient.loadOperationKey(operationKeyEncryptionPassword);
  return apiClient;
};
```

### Posting Order

```typescript
// Posting order instantly without fee
export const orders = async () => {
  const apiClient = await getApiClient();

  const orderRequest: PostOrderRequest = {
    symbol: "ADAUSDM",
    side: "sell",
    type: "limit",
    quantity: 100,
    price: 16,
  };

  const res = await apiClient.postOrder(orderRequest);
  console.log("Post Order Response:", res);
};

```

### Cancel Order

```typescript
// Canceling order instantly without fee
const cancelRes = await apiClient.cancelOrder(res.order.order_id);
console.log("Cancel Order Response:", cancelRes);
```

### Detailed SDK demo

<https://github.com/deltadefi-protocol/sdks-demo/tree/main/typescript>


# Python

### About

DeltaDeFi's Python SDK provides utility functions to interact with the API service and sign transactions with provided keys.

### Installation

The SDK is hosted on npmjs.com, so you can directly import it using your favorite package manager.

```python
pip3 install deltadefi
```

### Getting Started

Placing and canceling orders are as simple as below.

```python
import os

from deltadefi import ApiClient
from dotenv import load_dotenv

load_dotenv(".env", override=True)
api_key = os.environ.get("DELTADEFI_API_KEY")
password = os.environ.get("TRADING_PASSWORD")

api = ApiClient(api_key=api_key)
api.load_operation_key(password)
```

### Posting Order

```python
res = api.post_order(
    symbol="ADAUSDM",
    side="sell",
    type="limit",
    quantity=51,
    price=15,
)

print("Order submitted successfully.", res)
```

### Detailed SDK demo

<https://github.com/deltadefi-protocol/sdks-demo/tree/main/python>


# DLTA Points (XP)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F3PNwCkXC3biJgLXD6y87%2Fimage.png?alt=media&amp;token=e0162f67-1454-4c6f-820d-5e30b7e803f3" alt=""><figcaption></figcaption></figure>

**Highest rewards for earliest believers.** Every action on DeltaDeFi earns XP, and early participants are rewarded most.

## How to earn XP

There are three ways to earn XP:

### Trade

Every dollar traded on DeltaDeFi earns XP. Makers earn extra XP compared to takers — providing liquidity on the order book is rewarded more.

### Deposit

Depositing funds into your DeltaDeFi trading account earns XP.

### Refer

Referrers earn **5%** of their referees' points earned from trading. Share your referral link and earn as your friends trade.

## Multipliers

The current season features a **3x active multiplier** — XP earnings are boosted for active participants.

## Why earn XP?

* XP will be a core indicator for the upcoming **token airdrop** — the largest share will go to early participants.
* On hitting certain status / tier, there will be exclusive perks.
* Quests for earning bonus XP will be available.
* We are committed to making our early adopters feel at home on DeltaDeFi.


# L1 Swap Integration

DeltaDeFi is a L2 protocol that operates in Hydra head. Therefore, a typical user cannot access to DeltaDeFi's liquidity with their L1 wallet. In order to improve accessibility of DeltaDeFi's liquidity, we have implemented a liquidity bridge pattern to allow placing a direct swap in Cardano L1.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FrMRvWcR2lrfyQg73GLcL%2Fimage.png?alt=media&amp;token=a7d33ae7-6170-4dd4-b2fa-36903ee4a70b" alt=""><figcaption></figcaption></figure>

### Who should use this?

* DEX aggregator - this pattern primarily serves DEX aggregator. With the L1 swap infrastructure, it makes integration seamless. DeltaDeFi can be seen as a typical L1 exchange in the integration work.
* Cardano programmatic trader / arbitrageur - the swap allows direct L1 programmatic access to DeltaDeFi's liquidity pool trading strategies to include DeltaDeFi's order book at ease

{% hint style="info" %}
Test Tokens: Request test USDCx and NIGHT tokens for preprod at <https://alpha-app.deltadefi.io/testing-usd-request>
{% endhint %}

***


# Getting Started

### Configuration

```
npm install @deltadefi-protocol/khor@1.1.1
```

Obtain constants for creating transactions

```typescript
import { BlockfrostProvider, MeshWallet } from "@meshsdk/core";
import { KhorConstants, SwapIntentTx } from "@deltadefi-protocol/khor";

// Setup
const blockfrost = new BlockfrostProvider("YOUR_BLOCKFROST_API_KEY");
const wallet = new MeshWallet({
  networkId: 1,
  fetcher: blockfrost,
  submitter: blockfrost,
  key: { type: "mnemonic", words: "your 24 words here".split(" ") },
});

// Get all required variables
const userAddress = await wallet.getChangeAddress();
const utxos = await wallet.getUtxos();
const collateral = (await wallet.getCollateral())[0];

// Create swap intent
const config = new KhorConstants("mainnet");
const swapIntentTx = new SwapIntentTx(config);
```

### Create Swap Intent

Create a new swap intent to place a limit order on L1.

{% hint style="warning" %}
Minimum Order Value: Order value must be at least 10 USDCx equivalent.
{% endhint %}

```typescript
const result = await swapIntentTx.createSwapIntent(
  {
    utxos,
    collateral,
    changeAddress: userAddress,
    accountAddress: userAddress,
    fromAmount: [{ unit: config.tokens.night, quantity: "100000000" }], // 100 NIGHT
    toAmount: [{ unit: config.tokens.usdcx, quantity: "5000000" }], // 5 USDCx
    // Optional parameters:
    // deposit: 2_000_000,        // default: 2 ADA
    // expiry: 10 * 60 * 1000,    // default: 10 mins (in milliseconds)
  },
  blockfrost
);

// Sign and submit
const signedTx = await wallet.signTx(result.txHex);
const txHash = await wallet.submitTx(signedTx);
```

### Cancel Swap Intent

Cancel an existing swap intent and reclaim locked assets.

{% hint style="warning" %}
Cancellation Timing: Users can only cancel their swap intent 10+ minutes after creation.
{% endhint %}

```typescript
// Get user's swap intents
const myIntents = await swapIntentTx.fetchSwapIntentUtxosByAddress(blockfrost, userAddress);
const intentToCancel = myIntents[0];

// Check if cancellable
if (!swapIntentTx.isCancellable(intentToCancel)) {
  const cancellableAt = swapIntentTx.getCancellableAt(intentToCancel);
  throw new Error(`Intent not cancellable yet. Try again at ${new Date(cancellableAt!)}`);
}

// Cancel swap intent
const result = await swapIntentTx.cancelSwapIntent(
  {
    utxos,
    collateral,
    changeAddress: userAddress,
    oracleUtxo: config.oracleUtxo,
    swapIntentUtxo: intentToCancel,
  },
  blockfrost
);

// Sign and submit
const signedTx = await wallet.signTx(result.txHex);
const txHash = await wallet.submitTx(signedTx);
```

### Open Source

The full Aiken contract that processed the swap and its off-chain SDK can be accessed at <https://github.com/deltadefi-protocol/khor>.

Network parameters and constants can also be found in the SDK.

### Supported Pairs

* `ADAUSDCx`
* `ADAUSDM`
* `NIGHTUSDM`
* `ADANIGHT`


# Craft Transaction without SDK

### Create Swap Intent

Building a swap intent is straightforward - you just need to create a transaction output at the swap intent script address, locking `fromAmount + deposit` with a valid `SwapIntentDatum`.

<table><thead><tr><th width="161.8687744140625">Network</th><th>Address (to deposit and place swap intent)</th></tr></thead><tbody><tr><td>Mainnet</td><td><code>addr1zyjg3n7aut48cgfy8s974uc79sfm985jvlend7nng9cq5ekll0mlqdcg2cee0s4ea9vaa9u79xmftptm8akvk55yslks48uca3</code></td></tr><tr><td>Preprod</td><td><code>addr_test1zrulf7dqhh92neevg7rlx64029fqy3yk750pwwqrc9hvdwkll0mlqdcg2cee0s4ea9vaa9u79xmftptm8akvk55yslksh40p2w</code></td></tr></tbody></table>

{% hint style="warning" %}
Minimum Order Value: Order value must be at least 10 USDM / USDCx equivalent.
{% endhint %}

#### SwapIntentDatum Structure

```rust
// Aiken
pub type SwapIntentDatum {
  account_address: Address, // User's address to receive output tokens
  from_amount: MValue, // Assets user is selling
  to_amount: MValue, // Minimum assets user expects to receive
  created_at: Int, // Slot number (used for cancellation timing)
  deposit: Lovelace, // Min UTxO deposit in lovelace (typically 2000000)
}

pub type MValue = Pairs<PolicyId, Pairs<AssetName, Int>>
```

```typescript
// Type definition (imported from @meshsdk/core)
type SwapIntentDatum = ConStr0<
  [
    PubKeyAddress | ScriptAddress, // account_address
    Pairs<PolicyId, Pairs<AssetName, Integer>>, // from_amount (MValue)
    Pairs<PolicyId, Pairs<AssetName, Integer>>, // to_amount (MValue)
    Integer, // created_at (slot)
    Lovelace, // deposit
  ]
>;

// Constructor function that builds a SwapIntentDatum for on-chain storage
const datum = swapIntentDatum({
  accountAddress: "addr_test1...",
  fromAmount: [{ unit: config.tokens.night, quantity: "100000000" }],
  toAmount: [{ unit: config.tokens.usdm, quantity: "5000000" }],
  createdAt: 12345678,
  deposit: 2000000, // optional, default 2 ADA
});
```

#### The transaction must

1. Create output at swap intent script address with:
   * Value: `fromAmount + deposit`
   * Inline datum: `SwapIntentDatum`

#### Example Datum

* SELL 50 ADA for 12.5 USDCx

```json
{
  "accountAddress": "addr_test1...",
  "fromAmount": [{ "unit": "lovelace", "quantity": "50000000" }],
  "toAmount": [{ "unit": "c69b981db7a65e339a6d783755f85a2e03afa1cece9714c55fe4c9135553444d", "quantity": "12500000" }],
  "createdAt": 12345678,
  "deposit": 2000000
}
```

* BUY 60 ADA with 15 USDCx

```json
{
  "accountAddress": "addr_test1...",
  "fromAmount": [{ "unit": "c69b981db7a65e339a6d783755f85a2e03afa1cece9714c55fe4c9135553444d", "quantity": "15000000" }],
  "toAmount": [{ "unit": "lovelace", "quantity": "60000000" }],
  "createdAt": 12345678,
  "deposit": 2000000
}
```

***

### Cancel Swap Intent

Cancellation is only allowed after the intent expires (\~10 minutes from `createdAt`).

{% hint style="warning" %}
Cancellation Timing: Users can only cancel their swap intent 10+ minutes after creation.
{% endhint %}

#### CancelIntent Redeemer

```rust
// Aiken
pub type SpendRedeemer {
  ProcessSwap
  CancelIntent
  SpamPrevention
}
```

```typescript
// Type definition (imported from @meshsdk/core)
export type CancelIntent = ConStr1<[]>;

// Constructor function that builds a CancelIntent
const redeemer = cancelIntent();
```

#### The transaction must

1. Reference the oracle UTxO (read-only)
2. Spend the swap intent UTxO with redeemer `CancelIntent`
3. Set `invalidBefore` to `createdAt + 600` slot (\~10 minutes)
4. Either
   * Must set `extra_signatories` with `accountAddress`'s payment key hash, OR
   * Input value sent back to `accountAddress`


# Integration APIs

DeltaDeFi hosts official APIs to improve accessibility of the L1 swap contracts. The entire swap is still mostly handled through Aiken smart contract, the API provides additional information to facilitate informed trading decisions. These endpoints are designed for aggregators integrating with DeltaDeFi's L1 swap infrastructure. All endpoints listed below are public and do not require API key authentication.

### URL

| Environment | URL Endpoint                            |
| ----------- | --------------------------------------- |
| Pre-Prod    | `https://operator-staging.deltadefi.io` |
| Mainnet     | `https://operator.deltadefi.io`         |

***

### GET - Market Depth

Get the current market depth for a trading pair post fee. The `price` shown in depth response has already factored in fees — it is exactly what you could expect to trade at.

#### Example Request

```
GET /swapIntent/depth/NIGHTUSDM
```

#### Example Response

```json
{
  "timestamp": 1773113131587,
  "bids": [
    { "price": "0.05090", "quantity": "31395" }
  ],
  "asks": [
    { "price": "0.05311", "quantity": "3977.5" },
    { "price": "0.05210", "quantity": "6220" }
  ]
}
```

#### Response Fields

| Field     | Type   | Description                                                    |
| --------- | ------ | -------------------------------------------------------------- |
| timestamp | number | Unix timestamp in milliseconds                                 |
| bids      | array  | Buy orders — price/quantity objects sorted by descending price |
| asks      | array  | Sell orders — price/quantity objects sorted by ascending price |

#### Supported Symbols

| Symbol      | Type       | Description                                                                           |
| ----------- | ---------- | ------------------------------------------------------------------------------------- |
| `ADAUSDCx`  | Direct     | ADA/USDC pair — 0.2% spread (0.1% trading + 0.1% operator)                            |
| `NIGHTUSDM` | Direct     | NIGHT/USDC pair — 0.2% spread                                                         |
| `ADANIGHT`  | Cross-pair | Synthetic depth from NIGHTUSDC + ADAUSDC — 0.4% spread (0.2% trading + 0.2% operator) |

***

### GET - Supported Pairs

Get the list of supported trading pairs. Use this to understand which pairs are available for integration.

#### Example Request

```
GET /pairs
```

#### Example Response

```json
[6:44 PM]{
    "pairs": [
        {
            "symbol": "ADAUSDM",
            "baseToken": "ADA",
            "baseTokenUnit": "lovelace",
            "quoteToken": "USDM",
            "quoteTokenUnit": "c48cbb3d5e57ed56e276bc45f99ab39abe94e6cd7ac39fb402da47ad0014df105553444d",
            "priceDp": 4,
            "quantityDp": 1
        },
        {
            "symbol": "NIGHTUSDM",
            "baseToken": "NIGHT",
            "baseTokenUnit": "0691b2fecca1ac4f53cb6dfb00b7013e561d1f34403b957cbb5af1fa4e49474854",
            "quoteToken": "USDM",
            "quoteTokenUnit": "c48cbb3d5e57ed56e276bc45f99ab39abe94e6cd7ac39fb402da47ad0014df105553444d",
            "priceDp": 5,
            "quantityDp": 1
        },
        {
            "symbol": "ADAUSDCx",
            "baseToken": "ADA",
            "baseTokenUnit": "lovelace",
            "quoteToken": "USDCx",
            "quoteTokenUnit": "1f3aec8bfe7ea4fe14c5f121e2a92e301afe414147860d557cac7e345553444378",
            "priceDp": 4,
            "quantityDp": 1
        },
        {
            "symbol": "ADANIGHT",
            "baseToken": "ADA",
            "baseTokenUnit": "lovelace",
            "quoteToken": "NIGHT",
            "quoteTokenUnit": "0691b2fecca1ac4f53cb6dfb00b7013e561d1f34403b957cbb5af1fa4e49474854",
            "priceDp": 3,
            "quantityDp": 1
        }
    ]
}
```

#### Response Fields

| Field                   | Type   | Description                                                          |
| ----------------------- | ------ | -------------------------------------------------------------------- |
| pairs                   | array  | List of supported trading pairs                                      |
| pairs\[].symbol         | string | Trading pair symbol used across APIs                                 |
| pairs\[].baseToken      | string | Human-readable base token name                                       |
| pairs\[].baseTokenUnit  | string | On-chain unit identifier (policyId + asset name) for the base token  |
| pairs\[].quoteToken     | string | Human-readable quote token name                                      |
| pairs\[].quoteTokenUnit | string | On-chain unit identifier (policyId + asset name) for the quote token |
| pairs\[].priceDp        | number | Decimal places for price display                                     |
| pairs\[].quantityDp     | number | Decimal places for quantity display                                  |

***

### GET - Swap Intent UTxOs

Get all UTxOs at the swap intent script address with parsed datum information. Responses are cached for 60 seconds to reduce on-chain queries.

#### Example Request

```
GET /swapIntent/utxos
```

#### Example Response

```json
[
  {
    "tx_hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
    "output_index": 0,
    "address": "addr_test1wz...",
    "amount": [
      { "unit": "lovelace", "quantity": "5000000" },
      { "unit": "c48f0767b...", "quantity": "10000000" }
    ],
    "swap_intent": {
      "accountAddress": "addr_test1qz...",
      "fromAmount": [{ "unit": "c48f0767b...", "quantity": "10000000" }],
      "toAmount": [{ "unit": "lovelace", "quantity": "30000000" }],
      "createdAt": 1773113131,
      "deposit": 2000000
    },
    "is_valid": true
  },
  {
    "tx_hash": "b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3",
    "output_index": 1,
    "address": "addr_test1wz...",
    "amount": [
      { "unit": "lovelace", "quantity": "3000000" }
    ],
    "swap_intent": null,
    "is_valid": false
  }
]
```

#### Response Fields

The response is an array of UTxO objects:

| Field                       | Type        | Description                                                             |
| --------------------------- | ----------- | ----------------------------------------------------------------------- |
| tx\_hash                    | string      | Transaction hash of the UTxO                                            |
| output\_index               | number      | Output index of the UTxO                                                |
| address                     | string      | Script address holding the UTxO                                         |
| amount                      | array       | Assets held in the UTxO (unit + quantity)                               |
| is\_valid                   | boolean     | Whether the UTxO holds sufficient value to cover `fromAmount` + deposit |
| swap\_intent                | object/null | Parsed swap intent datum, or `null` if the datum is not parseable       |
| swap\_intent.accountAddress | string      | Address of the account that created the swap intent                     |
| swap\_intent.fromAmount     | array       | Assets being swapped from (on-chain format: unit + quantity)            |
| swap\_intent.toAmount       | array       | Minimum assets expected to receive (on-chain format: unit + quantity)   |
| swap\_intent.createdAt      | number      | Slot number when the swap intent was created                            |
| swap\_intent.deposit        | number      | Deposit amount in lovelace (optional, defaults to protocol default)     |

{% hint style="info" %}
UTxOs where `swap_intent` is `null` are present at the script address but do not contain a valid swap intent datum. These can be safely ignored by integrators.
{% endhint %}

***

### GET - Order Status

Get the status of a swap intent order by its UTxO reference. The UTxO reference is split into path segments (instead of `txHash#outputIndex`) to avoid URL encoding issues.

#### Example Request

```
GET /orders/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2/0
```

#### Example Response — On Book

An order that is on-chain at the swap intent script address, waiting to be processed.

```json
{
  "txHash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "outputIndex": 0,
  "status": "on_book",
  "order": {
    "side": "buy",
    "symbol": "ADAUSDCx",
    "fromAmount": [{ "unit": "c48f0767b...", "quantity": "5000000" }],
    "toAmount": [{ "unit": "lovelace", "quantity": "15000000" }],
    "price": "0.3520"
  },
  "expiryTime": 1773113731587
}
```

#### Example Response — Processing

The operator is actively settling this order.

```json
{
  "txHash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "outputIndex": 0,
  "status": "processing"
}
```

#### Example Response — Expired

The order is still on-chain but has passed the 600-slot (\~10 minute) expiry window and is eligible for cancellation.

```json
{
  "txHash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "outputIndex": 0,
  "status": "expired",
  "order": {
    "side": "sell",
    "symbol": "NIGHTUSDM",
    "fromAmount": [{ "unit": "ab4a4f55...", "quantity": "50000000" }],
    "toAmount": [{ "unit": "c48f0767b...", "quantity": "2500000" }],
    "price": "0.05100"
  },
  "expiryTime": 1773113731587
}
```

#### Example Response — Completed

The order was successfully processed. This status is available for up to 1 hour after settlement.

```json
{
  "txHash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "outputIndex": 0,
  "status": "completed",
  "settlementTxHash": "f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8"
}
```

#### Example Response — Not Found

The order does not exist, was already spent, or completed more than 1 hour ago.

```
HTTP 404
```

```json
{
  "error": "ORDER_NOT_FOUND"
}
```

#### Response Fields

| Field            | Type   | Description                                                                                             |
| ---------------- | ------ | ------------------------------------------------------------------------------------------------------- |
| txHash           | string | Transaction hash of the swap intent UTxO                                                                |
| outputIndex      | number | Output index of the swap intent UTxO                                                                    |
| status           | string | Order status: `on_book`, `processing`, `expired`, or `completed`                                        |
| order            | object | Order details (present for `on_book` and `expired` statuses)                                            |
| order.side       | string | `buy` or `sell`                                                                                         |
| order.symbol     | string | Trading pair symbol (e.g. `ADAUSDCx`)                                                                   |
| order.fromAmount | array  | Assets being swapped from (on-chain format: unit + quantity)                                            |
| order.toAmount   | array  | Minimum assets expected to receive (on-chain format: unit + quantity)                                   |
| order.price      | string | Effective price (quote per base)                                                                        |
| expiryTime       | number | Unix timestamp in milliseconds when the order becomes cancellable (present for `on_book` and `expired`) |
| settlementTxHash | string | Transaction hash of the settlement (present for `completed` status only)                                |

#### Order Status Lifecycle

| Status       | Description                                                                         |
| ------------ | ----------------------------------------------------------------------------------- |
| `on_book`    | Order is on-chain at the script address, within the 10-minute validity window       |
| `processing` | Operator has claimed the order and is actively settling it on L2                    |
| `expired`    | Order is on-chain but past the 10-minute validity window; eligible for cancellation |
| `completed`  | Order was successfully settled (visible for up to 1 hour after settlement)          |

***

### POST - Build Cancel Order

Build a cancel transaction for a swap intent order. This immediately reserves the order so the swap processor will not attempt to fill it, preventing contention.

The cancel transaction can be built at any time, but the on-chain submission will only succeed after the order's 10-minute expiry window has passed (enforced by the Plutus smart contract).

#### Example Request

```
POST /cancel/build
Content-Type: application/json
```

```json
{
  "txHash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "outputIndex": 0
}
```

#### Example Response

```json
{
  "txHex": "84a400818258..."
}
```

#### Request Fields

| Field       | Type   | Description                                                 |
| ----------- | ------ | ----------------------------------------------------------- |
| txHash      | string | Transaction hash of the swap intent UTxO (64-character hex) |
| outputIndex | number | Output index of the swap intent UTxO (non-negative integer) |

#### Response Fields

| Field | Type   | Description                                                                        |
| ----- | ------ | ---------------------------------------------------------------------------------- |
| txHex | string | Unsigned transaction CBOR hex. Sign this with the user's wallet before submitting. |

#### Error Responses

| Status | Error                                  | Description                                                    |
| ------ | -------------------------------------- | -------------------------------------------------------------- |
| 400    | Swap intent UTxO not found on-chain    | The UTxO does not exist at the script address                  |
| 400    | Invalid swap intent datum              | The UTxO does not contain a valid swap intent                  |
| 400    | Swap intent is already being processed | Another process (swap or cancel) has already claimed this UTxO |
| 422    | Validation error                       | Invalid txHash or outputIndex format                           |

***

### POST - Submit Cancel Order

Submit a signed cancel transaction. The operator co-signs the transaction and submits it to the Cardano network. The transaction will be rejected on-chain if the 10-minute expiry window has not yet passed.

#### Example Request

```
POST /cancel/submit
Content-Type: application/json
```

```json
{
  "signedTx": "84a400818258..."
}
```

#### Example Response

```json
{
  "txHash": "f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8d9c0b1a2f7e8"
}
```

#### Request Fields

| Field    | Type   | Description                                          |
| -------- | ------ | ---------------------------------------------------- |
| signedTx | string | User-signed transaction CBOR hex from the build step |

#### Response Fields

| Field  | Type   | Description                                          |
| ------ | ------ | ---------------------------------------------------- |
| txHash | string | Confirmed transaction hash of the cancel transaction |

#### Error Responses

| Status | Error                            | Description                                              |
| ------ | -------------------------------- | -------------------------------------------------------- |
| 400    | No cancel build found            | Must call `/cancel/build` first to build the transaction |
| 400    | Cancel transaction not confirmed | Transaction was submitted but not confirmed on-chain     |
| 422    | Validation error                 | Invalid signedTx format                                  |

***

### Cancel Flow

1. **Build** — Call `POST /cancel/build` with the UTxO reference. This reserves the order so it will not be processed by the swap operator.
2. **Sign** — Sign the returned `txHex` with the user's wallet (the wallet that created the swap intent).
3. **Submit** — Call `POST /cancel/submit` with the signed transaction. The operator co-signs and submits to the network.
4. **Confirmation** — The operator waits for on-chain confirmation and returns the confirmed transaction hash.

{% hint style="info" %}
You can build the cancel transaction before the expiry window passes, but the submit step will only succeed on-chain after \~10 minutes from order creation. This allows you to prepare the cancellation in advance.
{% endhint %}


# Services and Charges

### Operator Services

The L1 swap integration is processed by an operator which will take execution risk on DeltaDeFi's order book. That being said

The order will be processed if

1. The current order book depth can absorb the swap (use [Integration APIs](/start-trading/l1-swap-integration/apis#get-market-depth) to check whether the book depth would fill the order)
2. The expiry time in datum has not passed

Therefore, to facilitate smooth order matching, we suggest adding an adequate buffer (max slippage tolerance) at building the swap intent datum. If the order instruction cannot be fulfilled by the time of arriving Cardano L1, we would skip processing in our core workflow. There are occassion we will trigger episodic order filling after core processing time initially and before expiry, however, we do not guarantee such case. Any expired orders can be cancelled in a fully non-custodial manner.

### Charges

The operator charges an additional 0.1% per swap processed. Therefore:

* For `ADAUSDCx` / `ADAUSDM` /  `NIGHTUSDM`, in total 0.2% will be charged (0.1% for DeltaDeFi trading fee)
* For `ADANIGHT`, in total 0.4% will be charged (0.2% for DeltaDeFi trading fee)

> A minimum fee applies to cover the L1 transaction cost, split across all orders in the batch. For small orders, this minimum may exceed the percentage above. The effective fee is always the greater of the two. Users always receive at least the amount specified in toAmount. If the market fill is better than expected, the surplus (minus the fee) is passed back to the user as price improvement.

The charges are reflected in [Integration APIs](/start-trading/l1-swap-integration/apis#get-market-depth), so when you see the market depth from the API the fee is already taken into account.

We by default suggest a higher buffer / slippage tolerance (e.g. 3-5%) at order placement. If there is significant buffer at order instruction, we will always capped the fee stated above (0.1% per swap processed) and the users will receive additional tokens than the amount specified at `toAmount`.


# General

## Roadmap

<details>

<summary>What is the current status of DeltaDeFi?</summary>

DeltaDeFi Spot Trading is **live on Cardano mainnet**. We launched beta mainnet in November 2025 and the full release with multi-pair support, deposits, and withdrawals is now live.

Our current focus is on Hydra reliability and scalability — achieving zero corrupted states with 100+ TPS in complex UTxO sets.

</details>

<details>

<summary>What is the decentralization roadmap?</summary>

We are taking a step-by-step approach to full decentralization:

1. ~~Open source & verifiable~~ ✅
2. ~~Live on Mainnet~~ ✅
3. **Hydra — Reliability & Scalability** ← current
4. Community node operators
5. Smart contract auditing (internal review, community bug bounty, independent 3rd-party verification)
6. Token Launch + Open Governance

</details>

<details>

<summary>Any token for DeltaDeFi?</summary>

Yes, we have concrete token plans built around three core principles:

* **>50% Community Owned** — The majority of token supply will be allocated to users of the protocol.
* **Massive Airdrop** — The largest share will be distributed to early participants.
* **100% Revenue Distributed** — All protocol fees will flow back to token holders.

Our [XP Program](/start-trading/dlta-points-xp) (Season 1) is the core mechanism to identify and reward early supporters. Every trade, deposit, and referral earns XP that will count toward the airdrop.

</details>

<details>

<summary>Any plans to go multi-chain?</summary>

No. While we thought of the multi-chain strategy in the early days, now we are more in a stage of focusing on the technology itself and bringing as much sought-after trading experience to the Cardano community natively, before considering diluting our focus.

</details>

## Design

<details>

<summary>Why Cardano?</summary>

Our team is deeply rooted in the Cardano ecosystem. We build on Cardano of course, since we love Cardano. But more importantly, our understanding of Cardano enables us to build products that fill gaps in DeFi, which is a unique opportunity that exists in the Cardano ecosystem.

</details>

<details>

<summary>Why order book?</summary>

In the realm of trading, we believe the order book model is the true model that serves the actual demand of trading and stands the test of time. As a project aims to bridge the gap between centralized trading experience with the DeFi world, we have then chosen order book model to build the decentralized exchange.

</details>

<details>

<summary>Why Hydra?</summary>

In order to trade with speed and bring as close user experience to centralized services as possible, we have to build on top of any available scaling technology. So far, Hydra is the only scaling technology that works on Cardano. After assessing factors like potential features, support, and limitations, we decided that Hydra is a technology that meets the bar of DeltaDeFi's need, and then started investing in this technology.

</details>

## Hydra

<details>

<summary>What is the relationship between DeltaDeFi and Hydra team?</summary>

There is no relationship. Apart from the fact that DeltaDeFi is one of a few teams that is actively building on top of Hydra and providing actual user feedback to the Hydra team. DeltaDeFi is like a community member in the Hydra family.

</details>

<details>

<summary>I have heard about the Hydra Head protocol being custodial. Is my fund deposited into DeltaDeFi safe?</summary>

Hydra's fund safety comes from "at least one honest participant". Achieving sufficient decentralization in Hydra comes with some decisions on who could host the DeltaDeFi Hydra node and open-sourcing the infrastructure.

Given that the decentralization of how we use Hydra can be improved over time, and also with limited funding, our team decides to focus every resource possible on bringing the right product to Cardano at first.

We will start testing by hosting all nodes and then invite trusted community parties to host part of the Hydra nodes. DeltaDeFi will become more and more decentralized as time goes by, and eventually a fully decentralized DApp for the community.

</details>

<details>

<summary>Who is hosting the Hydra node right now?</summary>

Currently we host the Hydra nodes ourselves, as we are working closely with the Hydra team on [several issues](https://github.com/deltadefi-protocol/hydra-issues). Once Hydra software stabilizes, we will begin inviting community node operators to co-host — see the decentralization roadmap above.

</details>


# Product

## Onboarding

<details>

<summary>Why do I have to create an account?</summary>

In DeltaDeFi, users conduct their trading on their trading accounts, which are derived from the users' wallet addresses. Therefore, the first step interacting with DeltaDeFi is indeed creating an account.

This step is indeed identical to how you interact with other Cardano DApps, where you try to connect your wallet.

</details>

<details>

<summary>Why are only limited wallets supported in the web app?</summary>

To protect users from signing malicious transactions, fellow Cardano wallets would try resolving inputs from the Cardano blockchain to display the entire transaction information to users at the time of signing. However, since DeltaDeFi conducts trades in Hydra, an L2 network, most wallets fail to resolve inputs from L1 and decide to block the transactions from being signed by users.

Therefore, when placing trade through the web app, we can only support wallets that do not enforce the full resolution of inputs or have dedicated support for the Hydra network. Since Hydra is a relatively new technology, relatively few wallets do have the support in place and causing limited wallet support.

</details>

<details>

<summary>How exactly is my operation key generated?</summary>

All the users' operation key is generated using [Mesh SDK](https://meshjs.dev/apis/wallets/meshwallet#generateWallet), and then encrypted by the AES-GCM algorithm with an initialization vector size of 12 ([implementation](https://github.com/MeshJS/web3-sdk/blob/main/src/functions/crypto/encryption.ts#L4)). Then, in several programming languages, we have the equivalent decryption logic in:

* Typescript - [Mesh web3-sdk](https://github.com/MeshJS/web3-sdk/blob/main/src/functions/crypto/encryption.ts#L53)
* Rust - [whisky](https://github.com/sidan-lab/whisky/blob/master/packages/whisky-wallet/src/encryption/cipher.rs#L53)
* Golang - [rum](https://github.com/sidan-lab/rum/blob/main/cipher.go#L67)
* Python - [gin](https://github.com/sidan-lab/gin/blob/main/src/sidan_gin/encryption/cipher.py#L71)

Everything's open source and verifiable.

</details>

## Deposit & Withdrawal

<details>

<summary>What is the minimum amount of deposit and withdrawal?</summary>

Adhering to the Cardano blockchain protocol parameter, we enforced a minimum deposit and withdrawal of 2 ADA per transaction to ensure the minUTxO requirement is fulfilled.

</details>

<details>

<summary>How long does it take to deposit &#x26; withdraw?</summary>

Since all trading activities happen in Hydra, all deposit proceed has to be committed into Hydra before trading. Likewise, all the tradable value withdrawal has to be decommitted from Hydra back to Cardano L1.

Therefore, after you have placed the instruction to perform a deposit or withdrawal, the instructions are only fully performed when we close and re-open the active Hydra Head, which we call a "Hydra cycle". In future, when incremental commit and decommit mature, we can add deposit and withdrawal intervals between each Hydra cycle.

We are constantly assessing the optimal cycle length, which is currently a wide range like 30 minutes to 12 hours. Please refer to the application for the latest workflow.

</details>

## Trade

<details>

<summary>What is the minimum order size for trade?</summary>

DeltaDeFi technically supports all sizes of trading, as little as 0.1 ADA. However, we have imposed a minimum size of **5 ADA equivalent** as the minimum order size (unless particularly specified) to prevent spamming.

</details>

## Products

<details>

<summary>What are Vaults?</summary>

Vaults are managed USDC strategies with on-chain NAV (Net Asset Value) tracking. They allow users to deposit funds into professionally managed trading strategies without needing to actively trade themselves. Vaults are currently **Coming Soon** — stay tuned for launch details.

</details>

<details>

<summary>What is the XP Program?</summary>

The XP Program (currently in Season 1) rewards early DeltaDeFi users. There are three ways to earn XP:

* **Trade** — Every trade on DeltaDeFi earns XP. Makers earn extra XP compared to takers.
* **Deposit** — Depositing funds into your trading account earns XP.
* **Refer** — Referrers earn 5% of their referees' trading XP.

XP will be a core indicator for the upcoming token airdrop — the earliest and most active participants receive the highest rewards.

For more details, see [DLTA Points (XP)](/start-trading/dlta-points-xp).

</details>

## Developer

<details>

<summary>How can I conduct trades using APIs?</summary>

Conducting trades with APIs is identical to placing orders on the website. For supported programming languages, you can directly use our official SDKs. For other languages, we also have open API specifications.

The only differences between using the web app and APIs to place orders are:

1. You have to load your wallet in the code base to conduct transaction signing.
2. It is possible to submit an order request through APIs with an incorrect payload, and the server will return errors accordingly (like missing price for limit order).

For details, please check out our developer documentation.

</details>

<details>

<summary>Why am I unable to place 2 market buy orders concurrently?</summary>

When conducting a market order, some value has to be locked up to prevent overspending the account balance. While we get a precise number of value to lock up for sell orders, which equals the order size, the value for buy market orders cannot be pre-determined since it is only finalized at the time of filling.

Therefore, particularly for market buy orders without maximum slippage configuration, within the moment after orders are placed and before matching, we will hold up entire balance for the selling token, which lead to concurrent buy market orders without maximum slippage failing. In that case, only the first order can be processed successfully and the rest would receive an error of insufficient balance.

If you need to optimize concurrent orders for your trading strategy, we recommend to simply use limit order or configure maximum slippage for your market order to have a more fine-grained control on your assets' availability.

</details>

<details>

<summary>Can I cancel orders programmatically?</summary>

Yes, it is the same as placing trades.

</details>

<details>

<summary>What are locked and free balances?</summary>

***Free***

This is the balance available to trade or to withdraw.

***Locked***

This is the balance that is in transition states, which are not available for trade or withdrawal. It represents all the statuses below:

1. Deposit in progress
2. Withdrawal in progress
3. Balance held up by active orders (e.g. limit orders on book)

</details>


# Cardano

## How can I get UTxOs from my wallet address?

If you want to get UTxO information for testing out APIs, you can find the UTxO information from various wallet interfaces:

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FYZoRzrCbCFLPM2DJzCv8%2Fimage.png?alt=media&amp;token=ffd17e3b-4434-4c56-9c62-9cb4ab63edd5" alt=""><figcaption><p>Example: Getting UTxO information from Eternl wallet</p></figcaption></figure>

If you want wallet UTxO information programmatically, the UTxO type accepted by our APIs is identical to the [Mesh](https://meshjs.dev/) type (Typescript SDK) and other SIDAN Lab tool chains:

* Rust - [whisky](https://github.com/sidan-lab/whisky)
* Golang - [rum](https://github.com/sidan-lab/rum)
* Python - [gin](https://github.com/sidan-lab/gin)

If you use an SDK like Mesh, there are [utility functions](https://meshjs.dev/providers/blockfrost#fetchAddressUtxos) to get address information directly to the type. Alternatively, you can directly use several Cardano service providers like Blockfrost or Maestro and parse the return type to the one compatible to our API request schema.

***

## How can I sign a Cardano transaction?

For interacting with DeltaDeFi APIs, we suggest signing the Cardano transactions through our DeltaDeFi SDKs, which are built on top of the Mesh and SIDAN Lab open source tool chain.

* [Typescript SDK](https://github.com/deltadefi-protocol/typescript-sdk) - [Mesh](https://meshjs.dev/)
* [Rust SDK](https://github.com/deltadefi-protocol/rust-sdk) - [whisky](https://github.com/sidan-lab/whisky)
* [Golang SDK](https://github.com/deltadefi-protocol/go-sdk) - [rum](https://github.com/sidan-lab/rum)
* [Python SDK](https://github.com/deltadefi-protocol/python-sdk) - [gin](https://github.com/sidan-lab/gin)

For signing the transaction with your [operation key](/about/learn/architecture/account), you first obtain the encrypted key with your API Key then decrypt it to the private key so that you can use the same tool chain above to perform transaction signing. There are also [end-to-end examples](https://github.com/deltadefi-protocol/sdks-demo) of integrating these SDKs to perform trades, which can help you speed up enjoying trading on DeltaDeFi.

***

## Can DeltaDeFi support hardware wallet?

Yes we can definitely support hardware wallet. Since each hardware wallet provider has different nuances to integrate, if your hardware wallet is not included in the list, please create a ticket and our team will follow up adding the integration.

Supported hardware wallet:

* Ledger


# Disclaimer

To be compliant with the local regulations, the DeltaDeFi protocol can’t be accessed by citizens and residents of the USA, Japan and some other jurisdictions. Although it is impossible to prevent users from the above-mentioned territories from accessing blockchain and development modules, the website and other parts of the Delta DeFi ecosystem are blocked for certain geographies. Please note that by trying to access Delta DeFi via VPN or lying about your citizenship you are breaking the law.


# Project Catalyst F11 Comprehensive Report

Detailed comprehensive report can be found below:

<https://docs.google.com/document/d/1CF_yfq3_qPx4aGnx0bSWsoztUSRsFobiiSCRYmi41PM/edit?usp=sharing>


# Project Catalyst F12 Milestone Reporting


# Smart Contract Design Document

Below session illustrates the detailed logic, structure, pseudocode, and flow diagram of the DeltaDeFi smart contract

## Detailed Logic, Structure & Pseudocode of the Smart Contract

Below 2 validators illustrate the detailed logic, structures and pseudocode code of the smart contract of DeltaDeFi

### Take Orders Validator

#### Parameters:

* `oracle_nft`: The policy id of `OracleNFT`
* `param_long_token`: The long side of token in trading pairs
* `param_short_token`: The short side of token in trading pairs

#### Datum:

* `account_address`: The address of the account number of the owner
* `is_long`: If the current order is for buying long token (`buy_token`)
* `list_price_times_10k`: Order exchange in a rate of `list_price` \* `lot_size` = quantity of `param_short_token`
* `lot_size` : Quantity of `sell token` in this order
* `owner:` The pub key hash of owner of the order

#### User Action:

1. Core logic of taking orders - Redeemer `TakeOrders`
   1. Withdrawal script of `take_orders` validating
2. Cancelling order which is mistakenly listed onchain - Redeemer `CancelOrder`
   1. Whole value spent to `Account` with correct owner in datum
   2. signed by both `operating_key` and owner

#### Pseudocode:

<pre><code>validator virtual_dex_take_orders(oracle_nft, param_long_token, param_short_token)

Purpose of the validator:
- To validate whether the wallet can Withdraw stake rewards; AND
- To validate whether the wallet can publish delegation certificate

// Validation logic:
Accumulate proceeds supposed send to order creators, check output value to them:
1. Look through all inputs -> if from same address -> get (account_address, change_account_address, receive_value)
2. Merge all results above with same account_address
3. Check each unique account_address, if outputs to trade_account + change_account >= to_receive
<strong>
</strong><strong>return true if the above validations are passed. Otherwise, return false.
</strong></code></pre>

### Virtual DEX Validator

#### Parameters:

* `oracle_nft`: The policy id of `OracleNFT`
* `take_orders`: The script hash of `take_orders` withdrawal script

#### User Action:

1. `Normal operation`:
   1. Reference to oracle utxo
   2. Accumulate proceeds supposed send to order creators, check output value to them
   3. Signed by operation key

#### Pseudocode:

<pre><code>validator virtual_dex(oracle_nft, take_orders)

<strong>// Purpose of the validator:
</strong>- To validate whether the wallet can spend of transaction output 

// Validation logic:
- Perform the validation based on the specified TakeOrders or CancelOrder redeemer
- For TakeOrder: validate transaction has sufficient signatures
- For CancelOrder: validate if the order value is returned and operation key is signed

return true if either above validation is passed. Otherwise, return false.
</code></pre>

## Flow Diagram

The flow diagram shows the flows for different scenarios. The first scenario illustrates an ADA seller creates an order and the order matches another subsequent order requesting to sell USD stablecoin. After the validation of the smart contract, the smart contract will unlock the funds and execute the transactions shown per user wallet. The expected output to each user wallet ("account'") is shown in the diagram for the first scenario. The second scenario is basically the reverse situation compared to first scenario.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FWJgTiVkC2VDuK9JST0ZP%2FDeltaDeFi%20Smart%20Contract%20Pseudocode%20and%20Flow%20Diagram.png?alt=media&amp;token=52176917-a28e-4ae2-8ed6-3f221f79b7c0" alt=""><figcaption></figcaption></figure>


# Technical Architecture

Below technical architecture illustrates the system architecture, including both off-chain and on-chain components of DeltaDeFi.

## System architecture, including both off-chain and on-chain components

Below system architecture illustrates both off-chain and on-chain components of DeltaDeFi. As shown in the architecture, only the matched orders will be submitted to blockchain, causing transaction fee. Otherwise, there will be no transaction fee caused for any order creation, modification, and cancellation. Immediate order response will be provided to user as well. The whole offchain part is below hosted in AWS cloud as shown in the diagram below while the interaction with the public blockchain is via cardano node API services.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FXOaTAwOWaBlPbYPlobP5%2Fimage.png?alt=media&amp;token=a998b621-ca2c-4d7c-b603-2841ee3124e5" alt=""><figcaption></figcaption></figure>

## Comprehensive Diagram illustrating the architecture, data flow, and component interactions

The off-chain components as shown below include the DeltaDeFi SDK, frontend application and backend application. The DeltaDeFi SDK are something we build to allow programmatic users to submit trading transactions without the need to understand all details about cardano transaction building, submission, etc. The frontend application and backend application are being hosted in AWS cloud. The redis database is being used to cache transactions. The AWS RDS database will store information including activities logs, order  information, users information. The breakdown of the elastic container services show how we group the backend services into different microservices including API server, order management system and order server. Once any order is being matched with another order, API server will submit the offchain order onchain using some Cardano node API services. The Cardano node API services are being used as the middleware to allow the offchain components to interact with the onchain components e.g. smart contract and cardano node.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F1R34V0Ljmdh3e9qyY9FQ%2FDeltaDeFi%20Technical%20Architecture.png?alt=media&amp;token=fd6dc973-66ed-4989-8bb8-5fd6c6c87231" alt=""><figcaption></figcaption></figure>


# User Flow Diagram & Wireframes

The pictures shown below are the user flow digram and wireframes for account opening, deposit, and order processing.

The Account Opening Wireframes & Flow Diagram illustrates the user interfaces and flow that the user will experience when they set up an account in DeltaDeFi protocol. The flow mainly requires users to connect with DeltaDeFi with a compatible cardano wallet and make initial deposit to complete the whole account opening process. After completing all the required actions, user will be able to trade using the established trading account.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FlCKo0qKkSAOewJuieNBi%2FAccount%20Opening%20Wireframes%20%26%20Flow.png?alt=media&amp;token=ac7d9789-3ac7-4baa-b501-04764e8c542b" alt=""><figcaption><p>Account Opening Wireframes &#x26; Flow Diagram</p></figcaption></figure>

The Deposit Wireframes & Flow Diagram illustrates the user interfaces and flow that the user will experience when they deposit more virtual assets into DeltaDeFi account. The flow mainly consists of selecting the virtual asset(s) and amount to be deposited and signing blockchain transaction to confirm the deposit. After completing all the required actions, user will be able to trade more assets using the established trading account.

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FjdedQeBBGTdLOun0EHCy%2FDeposit%20Wireframes%20%26%20Flow.png?alt=media&amp;token=f9570ba0-864b-4aad-961f-25fa69bacc92" alt=""><figcaption><p>Deposit Wireframes &#x26; Flow Diagram</p></figcaption></figure>

The Order Processing Wireframs & Flow Diagram illustrates the user interfaces and flow that the user will experience when they place trading orders in DeltaDeFi. For order placement, the flow mainly consists of selecting buy or sell ADA position, defining the price (in USD stablecoin) for the limit order, selecting the number of lot, signing blockchain transaction to confirm the transaction. After completing all the required actions, user will be able to submit a valid limit order, pending to be matched by market order.&#x20;

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FhR3vQY0sbv9CULr0pSP8%2FOrder%20Processing%20Wireframes%20%26%20Flow.png?alt=media&amp;token=75a1e74f-17e8-48b2-8e46-86d364d9502d" alt=""><figcaption></figcaption></figure>


# Backend and Frontend Integration Description

## API Client Architecture

A generic, type-safe HTTP client for REST API calls:

### Features:

* TypeScript generic support for type-safe responses
* JWT authentication via headers
* JSON/text response handling
* Optional request/response logging
* Relay mode for external APIs
* No-cache policy for fresh data

### Parameters:

* endpoint - API endpoint path
* method - HTTP method (GET, POST, PUT, DELETE)
* headers - Custom headers (e.g., Authorization)
* body - Request payload (auto-serialized)
* isJson - Response type toggle (default: true)
* log - Debug logging toggle
* relay - External API mode (bypasses base URL)

## Data Fetching Patterns

### Technology Stack:

* React Query - Data fetching and caching
* Zustand - Client-side state management
* Custom WebSocket Hook - Real-time data streaming

#### API Client and Data Fetching Testing

We tested all backend integrated APIs using the fetch/XHR tab under the network tab of `Developer Tools`  tab in google chrome

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FL8yTdbjROZwmmyUT05PC%2Fimage.png?alt=media&amp;token=60a52415-6955-4272-b749-3b0658c7b12c" alt=""><figcaption></figcaption></figure>

## WebSocket Integration

### Features:

* Automatic reconnection with exponential backoff
* Ping/pong heartbeat mechanism
* JWT authentication support
* Multi-message handling
* Clean connection lifecycle management

#### Websocket Testing

We tested all backend integrated websocket using the socket tab under the network tab of `Developer Tools`  tab in google chrome

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F6k6IVetIPqhBk4XVAkwM%2Fimage.png?alt=media&amp;token=a2d0e06f-4752-42f8-ab49-56827416725e" alt=""><figcaption></figcaption></figure>

## Testing Coverage

### Test Scenarios:

* GET/POST/PUT requests with bodies
* Custom header merging (Authorization)
* JSON/text response handling
* Error handling (404, 500, network errors)
* Relay mode (external APIs)
* Request/response logging
* Null/undefined body handling
* Environment variable handling


# Frontend & Backend & Smart Contract Integration Process and Functionalities Testing

Below documentation illustrate the key testing process of frontend & backend integration

## Frontend & Backend Integration Verification

<details>

<summary><strong>Sign in to Account</strong></summary>

After the user has pressed the connect wallet button and signed the wallet ownership verification message, frontend will send a signin request to backend using the `SignIn` API

### POST - SignIn (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FFzXeD3Ijqropuxip8lvK%2Fimage.png?alt=media&amp;token=f01ca2cd-5bed-4c1e-9872-ca9b4d5b6984" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - SignIn (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FJ2Z5hWEbBgwGHv3DltnG%2Fimage.png?alt=media&amp;token=2f098c20-12ac-4866-80cc-e84d51636947" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FQ8Jj2vYGEaiAi4zTz3zd%2Fimage.png?alt=media&amp;token=f16fff5e-d0ae-490d-96e5-0f9f288b7dbe" alt=""><figcaption></figcaption></figure>

### POST - SignIn (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FI0s9DQIQS8SkUVzWFZaw%2Fimage.png?alt=media&amp;token=b1c6d580-abce-4804-a8f6-7dfb1c23c7f1" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FKVxO3RYRlLOTcKwLw3f9%2Fimage.png?alt=media&amp;token=6e4f2829-4915-4ebd-a8ac-a8338d569e98" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Spot Account Information</summary>

After the user has performed a successful sign-in, frontend will call the GET spot-account API to retrieve necessary account information related to the user account

### GET - Spot-account (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FjJ2fFlCfe5bBMB6c1TzD%2Fimage.png?alt=media&amp;token=ea0e5aab-463b-44d3-9ee4-d7f85cdc6189" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - Spot-account (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F0lHluqHcG6rxb4x71FkA%2Fimage.png?alt=media&amp;token=8eef9bbf-a04e-4b53-b9e7-98a8c3c0cb1e" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F5O5PaFyL2Wt5pEZAcUZY%2Fimage.png?alt=media&amp;token=beb977c2-019f-4beb-81a1-e3b65921c0e6" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Build Deposit Transaction (Regular Deposit)</summary>

After successful signin, user can press the deposit button and select the "Regular deposit" to deposit funds when next hydra open event occurs. After inputting the deposit amount per asset, the user can press confirm to build the deposit transaction. User's wallet signature is required to authorized the deposit transaction. Smart contract is being integrated in this action as well (Please see the smart contract integration part below for more information).

### POST - /accounts/deposit/build (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F76rWhg9cbyWHqjWB9gpd%2Fimage.png?alt=media&amp;token=8d1a2faf-afae-443e-8088-c37979b70f50" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - /accounts/deposit/build (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FkFdkr9iBOQfkv5m8x6ww%2Fimage.png?alt=media&amp;token=b002913e-c894-4a4d-8574-bab94cb04a10" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FL6gcvizvt5EJNb1mbLwN%2Fimage.png?alt=media&amp;token=f16f86f2-5450-45be-8bd2-507a2921895a" alt=""><figcaption></figcaption></figure>

### POST - /accounts/deposit/build (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FppVA8J9ToHz1Z7HyWLGn%2Fimage.png?alt=media&amp;token=464064dc-890f-434f-b779-4491f5617070" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FHIG20AEOLYogsOZNfyv0%2Fimage.png?alt=media&amp;token=6142d237-1c02-41b7-ac82-5a2d432f3f7b" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Submit Deposit Transaction (Regular Deposit)</summary>

Continuing from the Build Deposit Transaction, frontend will submit the user-signed deposit transaction to the Cardano blockchain. The transaction must have been previously built using the /accounts/deposit/build endpoint and signed with the user's wallet

### POST - /accounts/deposit/submit (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F6pz7lhnyf61iUKnVE2PE%2Fimage.png?alt=media&amp;token=72681f11-9dfd-4c7a-9456-34232e4fee22" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - /accounts/deposit/submit (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FZaOaA4nsFYuTrODqJvpw%2Fimage.png?alt=media&amp;token=6511f333-5b69-4e68-84af-9a3dbb19065d" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FguCEPTFajt6jTUwuTHOQ%2Fimage.png?alt=media&amp;token=f4ec2d83-1f81-4a81-ba18-6ef6e57474f6" alt=""><figcaption></figcaption></figure>

### POST - /accounts/deposit/submit (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FE16L9FKt65doNfBucUOB%2Fimage.png?alt=media&amp;token=1bebd392-88a2-4183-b6eb-09c5cb7d0339" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FuaFsMUkgjiqGaRFOvNEX%2Fimage.png?alt=media&amp;token=5666cee2-dc91-4555-aca2-a0f1ac1a7abb" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Build Transferral Transaction (Fast Deposit)</summary>

After successful signin, user can press the deposit button and select the "Fast Deposit" to deposit funds shortly with aid of an operator. After inputting the deposit amount per asset, the user can press confirm to build the deposit transaction.

### POST - /accounts/transferal/build (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FzQp9nRhiZgfY4XWupE7C%2Fimage.png?alt=media&amp;token=80467c28-a0a2-4fa8-a391-71d68207411c" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - /accounts/transferal/build (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FVNB162iU6YHwHQzjtgfU%2Fimage.png?alt=media&amp;token=fa5ad929-c8f8-45e7-af73-09a033ba6fe3" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F0JdBrmDlajhUqUtTDDjf%2Fimage.png?alt=media&amp;token=12836b25-1d73-43ae-ad4e-cbf983402d09" alt=""><figcaption></figcaption></figure>

### POST - /accounts/transferal/build (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F0ZAU2cuGRVF0RjVbBOse%2Fimage.png?alt=media&amp;token=edb336f6-ba4a-4304-b32a-0b71b1b4f341" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FHwNcrAe7zVa8JZPHCKvL%2Fimage.png?alt=media&amp;token=c1f42bc7-e973-44d3-9b43-c6802149047b" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Build Request Transferral Transaction (Fast Withdrawal)</summary>

After successful signin, user can press the deposit button and select the "Fast Withdrawal" to withdrawfunds shortly with aid of an operator. After inputting the withdraw amount per asset, the user can press confirm to build the deposit transaction.

### POST - /accounts/request-transferal/build (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F2iYc3TW1lu8JYmiZQfpl%2Fimage.png?alt=media&amp;token=cf63ef4d-9a98-4002-84b5-6c66669411a5" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - /accounts/transferal/build (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F3JEv1YQlwzgIIDPQFE3A%2Fimage.png?alt=media&amp;token=6ad80530-b644-4db6-a1a6-f68400c1174b" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FBTGprShFy8IQ4evK8kN2%2Fimage.png?alt=media&amp;token=ab4b15e4-d3b7-4319-9358-757c2bbb72b2" alt=""><figcaption></figcaption></figure>

### POST - /accounts/transferal/build (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FjHrvn0kps07U3Jc2eNbj%2Fimage.png?alt=media&amp;token=c7db6261-9ca1-4d7f-a75e-eac34bc0a1d3" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F0mMkVk6Utac3jYKoCKey%2Fimage.png?alt=media&amp;token=ec2776ad-b660-4261-9cf5-0e541224ccc1" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Submit Request Transferral Transaction (Fast Withdrawal)</summary>

Continuing from the Build Request Transferral Transaction, the frontend submits a user-signed request transferal transaction to the Cardano blockchain.&#x20;

### POST - /accounts/request-transferal/submit (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FC0ce1L9L5joKBCK2rRwF%2Fimage.png?alt=media&amp;token=270f5751-e2cf-4d9e-909e-f851ad9f6a2e" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - /accounts/transferal/submit (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FHrPuc7hKJdOLGdBjcM5Y%2Fimage.png?alt=media&amp;token=b62f8d3d-364f-4872-85be-53b09ff5bc21" alt=""><figcaption></figcaption></figure>

The request param is aligned with the required request param from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fjocnp76kDy2SSmLUTXDl%2Fimage.png?alt=media&amp;token=ca47be92-1380-450d-b0c0-fe9c5098dd79" alt=""><figcaption></figcaption></figure>

### POST - /accounts/transferal/submit (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FkJwXIPoRjVvYLaxgrDvu%2Fimage.png?alt=media&amp;token=a962b592-9121-48da-bca9-b022a3e67f89" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FE368zIyPV7tpn9IQ6Is5%2Fimage.png?alt=media&amp;token=6544770e-639f-4fe8-985e-637e17fbd3b2" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Deposit Records</summary>

After successful signin, user can visit the dashboard page to view the regular deposit records. Frontend will call the GET deposit-records API to retrieve the regular deposit records by the user.

### GET - Deposit-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FRSmKtC9qo6EHVSxKUZRH%2Fimage.png?alt=media&amp;token=72849b9f-54c0-4a05-b9b5-6a119ac44f66" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - Deposit-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FY8Rl9g6agYtxnE2wIJvJ%2Fimage.png?alt=media&amp;token=8c9bb7d9-aa80-4f70-a17a-75154ed300c1" alt=""><figcaption></figcaption></figure>

The deposit records shown in dashboard page are aligned with the data returned by the backend API. The backend API response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F1jEbOn5WWx4CYKGRzSWJ%2Fimage.png?alt=media&amp;token=096a1115-c15f-4cf6-93cb-e74c7e847d30" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Transferral Records (To Get Fast Deposit and Withdrawal records)</summary>

After successful signin, user can visit the dashboard page to view the fast deposit records. Frontend will call the GET transferl-records API to retrieve the fast deposit records by the user.

### GET - transferal-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FlmL0tk9iWb19puamUhnx%2Fimage.png?alt=media&amp;token=5f355d14-b92d-40ee-9b0b-fac0627ac4c0" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - transferal-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FnGYwSri0HXUWTMJ9BaNk%2Fimage.png?alt=media&amp;token=f4b424f8-5970-448c-b25c-94d5cb98562c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FcZpWtX6bBVTjRmPeIJJb%2Fimage.png?alt=media&amp;token=eb9576aa-5a46-41d8-810f-e5b95d4f351b" alt=""><figcaption></figcaption></figure>

The transferal records shown in dashboard page are aligned with the data returned by the backend API. The backend API response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FWEgScOkOHNNtQtSXvqO3%2Fimage.png?alt=media&amp;token=b3132cae-9a63-46eb-922c-da7fad34dcc6" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Account Balance</summary>

After successful signin, user can visit the trading page to view the account's available balance. Frontend will call the GET account-balance API to retrieve the account balance by the user.

### GET - account-balance (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FLIlepv54QakEiPeq0K1v%2Fimage.png?alt=media&amp;token=d19bd352-cc85-4bc0-9699-360a07426aa4" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - account-balance (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FnNfiAT58XEK3nD6tGCu6%2Fimage.png?alt=media&amp;token=e3f83def-33ea-4537-9d30-0100572656c0" alt=""><figcaption></figcaption></figure>

The available balance shown in trading page are aligned with the api response from backend. The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F11QoYq7LYidT3bjL1dvb%2Fimage.png?alt=media&amp;token=5db35700-cffb-410c-bf3e-224ab79421c9" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Order Records (by Open Order)</summary>

After successful signin, user can visit the trading page to view the open order records. Frontend will call the GET order-records API filtered by status (openOrder) to retrieve the open order records by the user.

### GET - order-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F1xK9Fa2zBxPkOXWuwgbf%2Fimage.png?alt=media&amp;token=5e95c447-df90-4ae7-90ad-f30ce1f2acbd" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - order-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F3ViUNIM7lBGcZlNCSoWO%2Fimage.png?alt=media&amp;token=e0807210-7e81-421b-8f45-76ed79e65610" alt=""><figcaption></figcaption></figure>

The open order records shown in trading page are aligned with the api response from backend. The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FzJ1EAfen2wZowz32qtr3%2Fimage.png?alt=media&amp;token=83477ad7-e392-407e-967e-c9ce1d0f1fa4" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Order Records (by Order History)</summary>

After successful signin, user can visit the trading page to view the order history records. Frontend will call the GET order-records API filtered by status (orderHistory) to retrieve the order history records by the user.

### GET - order-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FP4TQZ2Imu4IGJvBuJCAK%2Fimage.png?alt=media&amp;token=f65eddba-9c11-4bee-aa44-c888f87aaea3" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - order-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FmC2nPhE0pa3u2vNVqx7I%2Fimage.png?alt=media&amp;token=2b18b4a3-64dd-4b28-912d-92fbbf55d9ca" alt=""><figcaption></figcaption></figure>

The order history records shown in trading page are aligned with the api response from backend. The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FIHwbaAby2ukGEMnmnylA%2Fimage.png?alt=media&amp;token=2769f428-9f3a-4492-8495-f77552962ed9" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Order Records (by Trade History)</summary>

After successful signin, user can visit the trading page to view the trade history records. Frontend will call the GET order-records API filtered by status (tradeHistory) to retrieve the trade history records by the user.

### GET - order-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FrIfgDuIj0z8i350TA7dt%2Fimage.png?alt=media&amp;token=6291fa92-c0d7-42cf-a989-40877cab66dc" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - order-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FMN038XCJRB7dvYUhDKtm%2Fimage.png?alt=media&amp;token=4a9538b2-772c-4630-ac95-9f3849c5f663" alt=""><figcaption></figcaption></figure>

The trade history records shown in trading page are aligned with the api response from backend. The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F6xz58czvcfBTLxa0uBoC%2Fimage.png?alt=media&amp;token=459369cc-f064-4c30-b9b5-067e628edf48" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get API Key</summary>

After successful signin, user can visit the dashboard page to view the api-key. Frontend will call the GET api-key API to retrieve the api key by the user.

### GET - api-key (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FGwSUN9FjWt7AKykySZ02%2Fimage.png?alt=media&amp;token=4e761571-d24c-4268-a6ca-f14b37d57c18" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - api-key (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fvr8U8k1f1AvRFoy86r9y%2Fimage.png?alt=media&amp;token=38c18f51-9303-41c5-82c1-1a015e7bdf6a" alt=""><figcaption></figcaption></figure>

The api key shown in dashboard page is aligned with the api response from backend. The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FQhbjgl7T6OFfsxQwLCYy%2Fimage.png?alt=media&amp;token=c7e24d00-9caf-4a22-bc40-a8f97512c497" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Build Place Order Transaction</summary>

After successful signin, user can visit the trading page to place order. Frontend will call the POST order/build API to construct an unsigned Cardano transaction for placing a limit or market order. The transaction must be signed by the user's operation key and then submitted using the /order/submit endpoint.

### POST - order/build (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FCytsygXvENSqyw8WqwBc%2Fimage.png?alt=media&amp;token=920ad9e0-0402-4f7b-8f91-105437b34306" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - order/build (Request Parameters)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FqlaXV3NsBMinQgCGz7Oz%2Fimage.png?alt=media&amp;token=b2715606-4717-45f8-a61f-1030da241f23" alt=""><figcaption></figcaption></figure>

The request param's fields are aligned with the required request params from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FmrdW0S9HsWG2NoddzGQa%2Fimage.png?alt=media&amp;token=95721bd7-98d4-4286-b85d-cf211eda898c" alt=""><figcaption></figcaption></figure>

### POST - order/build (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FOALI0PIE52DrZWRCkxau%2Fimage.png?alt=media&amp;token=79f51a18-a4b8-4125-ba33-6b62ad6fe8bd" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fmut8jpSWubWseyyJrJhn%2Fimage.png?alt=media&amp;token=c81ebe1a-fd02-4eed-b3e5-b46b0dd2f14f" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Submit Place Order Transaction</summary>

Continue from the Build Place Order Transaction section, frontend submits a signed order transaction to hydra. Use this endpoint after signing the transaction hex returned from /order/build

### POST - order/submit (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FCYfomudVoXDZT4XR6mns%2Fimage.png?alt=media&amp;token=c5bfd552-5cc8-4ace-8db2-519338bb5e13" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### POST - order/submit (Request Parameters)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fh0WqLrpvjlWbHtgl9z0D%2Fimage.png?alt=media&amp;token=f5ffc041-053a-459f-a034-4c35c3fcb9f1" alt=""><figcaption></figcaption></figure>

The request param's fields are aligned with the required request params from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FUmZqxSmpYxrOb8nWN4CO%2Fimage.png?alt=media&amp;token=e858b494-fd84-4882-8212-4d97eb3bb1f4" alt=""><figcaption></figcaption></figure>

### POST - order/submit (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FE5CYUYDSX29DhlCUsJ1L%2Fimage.png?alt=media&amp;token=d2777206-89bb-4872-83d7-1c1782762449" alt=""><figcaption></figcaption></figure>

The response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FznZmUbEVnmGzBmdLf4ht%2Fimage.png?alt=media&amp;token=07bd80b1-3a65-45f0-9537-801ee435581e" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Build Cancel Order Transaction</summary>

After successful signin, user can visit the trading page to cancel order. Frontend will call the DELETE order/{id}/build API to construct an unsigned Cardano transaction for cancelling a specific order by its ID. The transaction must be signed by the user's operation key and then submitted using the /order/submit endpoint.

### DELETE - order/{id}/build (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FKCmJtfJdiojs58T0hIRS%2Fimage.png?alt=media&amp;token=d8adb959-3ab6-455d-9250-131595dcf54a" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### DELETE - order/{id}/build (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FIIhDGO0yrAeXuG0gboPu%2Fimage.png?alt=media&amp;token=ecc06831-24a2-4f89-a273-32c460deb0d8" alt=""><figcaption></figcaption></figure>

The response field is aligned with the required response's field from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fe4cewLp9HAH8cg0QhRkO%2Fimage.png?alt=media&amp;token=c0ffb926-4831-4b19-9a76-37a75678024a" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Submit Cancel Order Transaction</summary>

Continue from the Build Cancel Order Transaction section, frontend submits a signed order transaction to hydra. Use this endpoint after signing the transaction hex returned from /order/{id}/build

### DELETE - order/submit (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FjxElNR89rwEUAMA7IhvU%2Fimage.png?alt=media&amp;token=5c4b14c6-bca3-4440-8ad3-ad3cc578094e" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### DELETE - order/submit (Request params)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FXbDHcJE3WpyLbmX0nHEV%2Fimage.png?alt=media&amp;token=4d316b26-427f-4ca5-934f-af7c65f21fa7" alt=""><figcaption></figcaption></figure>

The request param's fields are aligned with the required request params from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FJ5DYMrB0pypCwQlfWP5W%2Fimage.png?alt=media&amp;token=059d4605-8fb9-4567-b727-0ce842e5017f" alt=""><figcaption></figcaption></figure>

### DELETE - order/submit (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FKQX0vwvrzgkcYIuTzl60%2Fimage.png?alt=media&amp;token=63687f7b-6517-4af8-b4c9-412dd7da3d9d" alt=""><figcaption></figcaption></figure>

The response field is aligned with the required response's field from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Ff2tPyYXaiP2LVvPgMZSh%2Fimage.png?alt=media&amp;token=eef76657-7075-4b18-9280-c4a971286d9f" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Get Withdrawal Records</summary>

After successful signin, user can visit the dashboard page to view the regular withdrawal records. Frontend will call the GET withdrawal-records API to retrieve the regular withdrawal records by the user.

### GET - Withdrawal-records (Status Code)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FMWhVsM6OlWMknvOmL3JO%2Fimage.png?alt=media&amp;token=54973700-8e1f-4dc3-af93-cc6cc9094432" alt=""><figcaption></figcaption></figure>

The `200 status code` shows the api is being called and responded successfully

### GET - Withdrawal-records (Response)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F9QaMRsCDXo2x5YFJIVna%2Fimage.png?alt=media&amp;token=3a7578ed-0573-409b-90d9-9b65737130a4" alt=""><figcaption></figcaption></figure>

The withdrawal records shown in dashboard page are aligned with the data returned by the backend API. The backend API response fields are aligned with the required response fields from the backend API

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FWdw9gvDR83IUSvZzeOLW%2Fimage.png?alt=media&amp;token=50365b47-7144-447f-938e-ff922c3934f2" alt=""><figcaption></figcaption></figure>

</details>

## Smart Contract Integration Verification

To validate our scripts, user would need to make a regular deposit and assess the deposit transaction according to below steps:

<details>

<summary>Step 1: Assess the datum in User's deposit transaction to start looking into the details of the relevant smart contracts</summary>

After signing and submitting the deposit transaction, user will be able to find the deposit transaction in browser wallet (e.g. eternl, vespr, etc.). User view the deposit transaction in Cardano Explorer and browse the "Reference Input" section. Click to expand the datum information for further verification in <https://cardananium.github.io/cquisitor/> (A tool supporting decode by CSL to verify all involved script information)

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FN2bzpYisSbeDCENtotnH%2Fimage.png?alt=media&amp;token=bc9326ec-b8c1-4417-832f-12c35429e608" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 2: Get the detailed script information in Cquisitor using the identified datum</summary>

Copy the full datum found in step 1 to <https://cardananium.github.io/cquisitor/>. Select `Decode by CSL` as the tool, `PlutusData` as the CSL type, `preprod` as network type, `BasicConversions` as Schema

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FoATvis8X6slg9Ak9JiSp%2Fimage.png?alt=media&amp;token=b8fc2688-321a-43fb-876c-ff5becc10f74" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3: Cross check the script hashes shown in Cquisitor, Cardano Explorer, team's disclosed script transaction id and team's open-sourced smart contract</summary>

AppOracle will always be taken as the reference input in all L1 transactions to pass the validation of each script. It acts as a bridge to connect every scripts all together and shares the policyId and script address info among them. The output's field sequence shown in the JSON in cquisitor is according to team's open-source smart contract's pub type AppOracleDatum:

Visit <https://github.com/deltadefi-protocol/aiken-virtual-dex/blob/staging/lib/hydra_dex/types.ak> and locate the `pub type AppOracleDatum`:

```
pub type WithdrawalScriptHashes {
  app_deposit: ScriptHash,
  app_withdrawal: ScriptHash,
  emergency_cancel_order: ScriptHash,
}

pub type AppOracleDatum {
  operation_key: VerificationKeyHash,
  stop_key: VerificationKeyHash,
  oracle_nft: PolicyId,
  oracle_address: Address,
  app_vault_address: Address,
  app_deposit_request_token: PolicyId,
  app_deposit_request_address: Address,
  dex_account_balance_token: PolicyId,
  dex_account_balance_address: Address,
  dex_order_book_token: PolicyId,
  dex_order_book_address: Address,
  emergency_cancel_order_request_token: PolicyId, // Not used in MVP
  emergency_cancel_order_request_address: Address, // Not used in MVP
  emergency_withdrawal_request_token: PolicyId, // Not used in MVP
  emergency_withdrawal_request_address: Address, // Not used in MVP
  all_withdrawal_script_hashes: WithdrawalScriptHashes,
  hydra_info: HydraInfo,
}
```

For example, since `app_vault_address` is located as the 5th field of AppOracleDatum, it will be shown as the `4th field` in the JSON outputted by cquisitor.

For the MVP, the team has only deployed below scripts with the corresponding `transaction hashes` :

1. APPVAULT\_SPEND:   `03fadf38750b7c90902286e083924b8837c86ee96e54d82dc101a15701f5ebc1`
2. APPDEPOSITREQUEST\_MINT: `d4dc6ca99616a73edafa77602f33670a58f4fe61b76a043307efad9dba90dc5c`
3. APPDEPOSITREQUEST\_SPEND:  `f952a21d49443c13a63ea5ecf9f22fa8d16337c468fbf58e31f6f73fa2dfec9b`
4. DEXACCOUNTBALANCE\_SPEND:  `5fde15ee7dbee50dbdea46fcff34700810cee3260eb1c78a6375ae804b4c8bd4`
5. DEXORDERBOOK\_SPEND:  `3798b056eecd06f7ce900b8d332f4b236a112176aefb053d6aebc30775decb11`
6. ACCOUNTOPERATION\_APPDEPOSIT:  `f2279a6f91f2341f88e512ca56d190badfeac7e7a52812855464f03ed8662114`
7. ACCOUNTOPERATION\_APPWITHDRAWAL: `de545edb93fc67d47a7b7b5c734dcd23a46fc205b6350930ddd9e578d21f49b2`

</details>

<details>

<summary>Step 3.1: Verify the APPVAULT_SPEND script</summary>

tx id: `03fadf38750b7c90902286e083924b8837c86ee96e54d82dc101a15701f5ebc1`&#x20;

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FN9ePy1pw6ihKG4Q5s2rp%2Fimage.png?alt=media&amp;token=d4438e85-2af4-43f7-b7c4-b8853cfb83dd" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fv7ij85RAqpCvCXdU8dey%2Fimage.png?alt=media&amp;token=f1c67439-ce24-4dcf-893a-4d613bea442a" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.2: Verify the APPDEPOSITREQUEST_MINT script</summary>

tx id:  `d4dc6ca99616a73edafa77602f33670a58f4fe61b76a043307efad9dba90dc5c`&#x20;

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FoCuvR7vAfXPDcIqvkgqA%2Fimage.png?alt=media&amp;token=3bcc33d7-e778-4406-a508-70fc6545b5a9" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FfrjNp1AnhwZnzR8uPb6Z%2Fimage.png?alt=media&amp;token=ceb94b5d-573b-4732-9f1f-aa5810840eb8" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.3: Verify the APPDEPOSITREQUEST_SPEND script</summary>

Txid: `f952a21d49443c13a63ea5ecf9f22fa8d16337c468fbf58e31f6f73fa2dfec9b`&#x20;

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2F4grICLjI9jY4Gm1SVBy5%2Fimage.png?alt=media&amp;token=2718a013-26b8-4a03-8f27-18335c98951b" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FejtpTICRLhshQMBwMlTD%2Fimage.png?alt=media&amp;token=65ce904a-c39c-451f-829e-772a67dac2b0" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.4: Verify the DEXACCOUNTBALANCE_SPEND script </summary>

Txid: `5fde15ee7dbee50dbdea46fcff34700810cee3260eb1c78a6375ae804b4c8bd4`

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FSrWYgPm5cDovCjIGXuBH%2Fimage.png?alt=media&amp;token=5471d585-91e7-4e5d-ab92-cb1d3b9b9d75" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FDxEHzRHEZIQQ3MZxKUgc%2Fimage.png?alt=media&amp;token=a6d11e7f-6cec-42d5-a759-bb05c4ed2d3b" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.5: Verify the DEXORDERBOOK_SPEND script </summary>

Txid: `3798b056eecd06f7ce900b8d332f4b236a112176aefb053d6aebc30775decb11`

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FaZCaWIEwKknOTZhRBQ3S%2Fimage.png?alt=media&amp;token=3f7f824c-0ecf-49dc-bf55-669d6167c648" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2Fg2vYwN9pIlpWIFr4P2b8%2Fimage.png?alt=media&amp;token=8b1e3ce0-6ac3-4bad-b318-da191c1700ab" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.6: Verify the ACCOUNTOPERATION_APPDEPOSIT script</summary>

Txid: `f2279a6f91f2341f88e512ca56d190badfeac7e7a52812855464f03ed8662114`

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FFsrXbxD1Uxe2BfME7ssU%2Fimage.png?alt=media&amp;token=c218a698-0a2b-4133-bd4a-eae7f84b5927" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FMhecDsDSXZJRIuegDb3I%2Fimage.png?alt=media&amp;token=5554e5b0-817a-4848-9f8c-7416d0bcdae1" alt=""><figcaption></figcaption></figure>

</details>

<details>

<summary>Step 3.7: Verify the ACCOUNTOPERATION_APPWITHDRAWAL script</summary>

Txid: `de545edb93fc67d47a7b7b5c734dcd23a46fc205b6350930ddd9e578d21f49b2`

Search the trasnaction by tx id in Cardano explorer and locate the `script hash` in Outputs

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FetBjxmWHsnJo6SkHDrQo%2Fimage.png?alt=media&amp;token=7277303d-178d-4c0c-b659-005f92f37660" alt=""><figcaption></figcaption></figure>

Validated the identified script hash with the output shown in cquisitor

<figure><img src="https://1470549554-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fnb9FXL5o0rWQgsqKVTBO%2Fuploads%2FW6SzlrowuHe1Ra06fQYL%2Fimage.png?alt=media&amp;token=8f78cf46-cbe3-41ec-bb71-21774b1fe79b" alt=""><figcaption></figcaption></figure>

</details>


