# Introduction to Nexus

Sovereign Yield on Bitcoin.

> 🚀 Trade and Earn (On Nexus)
>
> Trust Yourself. Stay on Bitcoin.

Our Mission: Activate Bitcoin’s dormant trillions.

Nexus is a Bitcoin-native execution fabric. It enables seamless trading and yield generation natively on Bitcoin Layer 1 with zero bridges, wrapped assets, validators, or custodians. Your capital remains exactly where it belongs: in your own sovereign control. Yield is generated exclusively via real arbitrage fees, not inflationary token emissions .

{% hint style="info" %}
🧲 Now onboarding TVL: Seeking self-custodial LPs, professional market makers, and arbitragers to bootstrap Bitcoin-native liquidity. Ready to deploy? Jump straight to the [Node Deployment Guide](/deployment-and-integration/node-setup).
{% endhint %}

#### The Fatal Binary

Historically, institutions and treasury managers faced a brutal choice: Hoard Bitcoin safely (but suffer inflation decay), or seek yield (and surrender 100% of your principal to a custodian).

Over the last cycle, centralized bankruptcies and cross-chain bridge hacks evaporated billions. The industry accepted this catastrophic friction because of a single, flawed illusion: The assumption that financial execution requires custody.

Developers blindly copy-pasted Ethereum's Turing-complete "Pooled State" model onto Bitcoin, falsely believing that to compute a trade or calculate slippage, a central contract *must first hold your money*.

#### The Nexus Axiom: Decoupling Coordination from Execution

Nexus Protocol exists to shatter this illusion by proving a foundational cryptographic truth: Sovereign capital never needs to move to be calculated.

Nexus completely decouples the *intent to trade* from the *physical settlement of capital*:

1. Off-Chain Coordination: All heavy computational logic—order matching, routing, and slippage calculations—is extracted into an off-chain Coordination Network.
2. On-Chain Settlement: Using native primitives like [Partially Signed Bitcoin Transactions (PSBTs)](/protocol-architecture/psbt-engine) and [Hash Time Locked Contracts (HTLCs)](/yield-economics-and-amm-design/fast-execution-accounts), capital only moves at the exact microsecond a strictly profitable trade is cryptographically assembled.

Execution without Custody. Sovereign Yield on Bitcoin.

#### Platform Capabilities

Nexus serves as the execution and liquidity backbone of Bitcoin, offering institutional-grade infrastructure for generating sustainable, mathematically proven yield natively on BTC:

* Institutional Capital Efficiency: Proprietary AMM models, including [Constant Product (CPMM)](/yield-economics-and-amm-design/amm-models) , [Concentrated Liquidity (CLMM)](/yield-economics-and-amm-design/amm-models) and [Single-Sided Liquidity (FPSSL)](/yield-economics-and-amm-design/fpssl), generate non-dilutable transaction fee yields derived from market volatility.
* Dual-Mode Execution: Operate purely passive yield strategies (Maker) or execute aggressive algorithmic arbitrage scripts (Taker) securely from the same self-custodial wallet infrastructure.
* MEV Resistance & Privacy: Trading intents and proprietary strategies remain strictly private off-chain until final execution, closing zero-day attack vectors for mempool front-running.
* Enterprise Customization: Structurally integrates with [institutional MPC policy engines](/deployment-and-integration/institutional-mpc) (e.g., Fireblocks, Safeheron). Asset managers deploy automated strategies while internal auditors securely authorize individual transactions against strict compliance rules.

***

#### 📚 Concept Guide

<details>

<summary><strong>Nexus Protocol / Coordination Network</strong></summary>

The overarching decentralized financial layer. It does not exist as a single smart contract or centralized server, but rather as an interconnected mesh of self-hosted nodes calculating and routing liquidity cryptographically.

</details>

<details>

<summary><strong>Nexus Composer</strong></summary>

The central parsing and routing entity. It receives market intents from Takers, matches them against the optimal liquidity curves generated by Maker nodes, and constructs the mathematical foundation of the draft PSBT. The Composer never holds funds.

</details>

<details>

<summary><strong>Nexus Node</strong></summary>

The core software binary hosted by participating institutions. It supports two concurrent operational models: Maker Nexus (passive yield/AMM) and Taker Nexus (high-frequency arbitrage/intents).

</details>


# System Overview

Structuring the definitive Sovereign Execution Backend for native Bitcoin yield.

#### Defining "Sovereign Yield"

Nexus Protocol is strictly engineered around a singular philosophical and technical axiom: Sovereign Yield on Bitcoin.

In the context of the Nexus architecture, *Sovereign Yield* is defined by the mathematical and cryptographic separation of asset custody from trade execution. It means generating continuous market-making revenue (arbitrage spreads and protocol fees) where the execution keys are *solely* generated, held, and signed by the sovereign entity's local hardware.

Unlike custodial yield (where keys are surrendered to centralized institutions) or synthetic yield (where assets are bridged/wrapped into different blockchain execution environments), Sovereign Yield derives value purely from native Bitcoin L1 UTXO state transitions via PSBTs.

***

#### Architectural Layout

The OnNexus architecture implements a modular, interoperable framework where three specialized components handle distinct aspects of the trading and liquidity provision workflow. This separation of concerns enables independent scaling, optimization, and upgrade paths while maintaining system-wide consistency and reliability.

#### System Overview

The protocol's architecture reflects the core design principle of separating coordination from execution, enabling sophisticated optimization while preserving Bitcoin's trustless properties through three primary technical components.

Core Technical Components

| Component            | Operator             | Primary Function                                                                   |
| -------------------- | -------------------- | ---------------------------------------------------------------------------------- |
| Nexus Composer       | OnNexus              | Intent routing engine calculating optimal execution paths and assembling PSBTs     |
| Independent Node     | Institutional Makers | Self-hosted, sovereign liquidity provision and autonomous trading capabilities     |
| OnNexus Managed Node | OnNexus              | Managed liquidity platform providing streamlined institutional execution workflows |

High-Level System Diagram

![Architecture](https://986940119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGntGw2VOMdtoGmIpVd6a%2Fuploads%2Fgit-blob-8470a8fc6059f5e62fb363e8cf0214ac6048deca%2Fimage-3.png?alt=media)


# Universal PSBT Engine

The cryptographic foundation for atomic execution and sovereign yield settlement.

Atomic Execution Architecture

Partially Signed Bitcoin Transactions (PSBTs) provide the cryptographic foundation for atomic execution within the Nexus Protocol. Whether clearing trades on the L1 Settlement layer or updating balances via State Channel Rollups, PSBTs ensure that a transaction either executes entirely or fails completely.

This mechanism eliminates counterparty risk by leveraging Bitcoin's native consensus, enabling complex multi-party coordination without exposing asset private keys.

> ‼️ Nexus does not store user funds or private keys. All activity is coordinated cryptographically.

#### The Coordinated Signing Flow

The PSBT orchestration follows a strict, multi-party verification process. No party can execute an incomplete transaction, nor can any party alter the transaction post-signature.

{% stepper %}
{% step %}
Step 1: Draft Construction & Intent Matching

The Nexus Composer receives an [off-chain trading intent](/trading-and-routing-strategies/intent-execution). It queries available liquidity, computes the mathematics (AMM slippage, routing paths), and drafts a raw, unsigned PSBT containing the necessary inputs and output states.
{% endstep %}

{% step %}
Step 2: Taker Signature (Commitment)

The Taker reviews the drafted PSBT, confirming the final output amounts and fee allocations. To commit to the execution, the Taker applies their cryptographic signature to their specific inputs first.
{% endstep %}

{% step %}
Step 3: Maker Verification (Last Look)

The participating Maker (or [Institutional MPC Node](/deployment-and-integration/institutional-mpc)) receives the Taker-signed PSBT. The Maker evaluates the order against real-time oracle pricing and internal risk models to ensure it is not toxic flow (e.g., latency arbitrage). This "Last Look" privilege is essential to shelter Makers from impermanent loss.
{% endstep %}

{% step %}
Step 4: Final Maker Signature

Upon passing validation, the Maker applies the final cryptographic signatures required to unlock their liquidity. The PSBT is now fully formed and valid under Bitcoin consensus rules.
{% endstep %}

{% step %}
Step 5: Network Broadcast / Rollup Settlement

Depending on the routing strategy, the resulting transaction is either propagated to the Bitcoin L1 mempool for direct settlement, or ingested into the [HTLC State Channel](/yield-economics-and-amm-design/fast-execution-accounts) for dynamic, multi-trade deferred settlement.
{% endstep %}
{% endstepper %}

#### Cryptographic Protections

The Universal PSBT Engine enforces zero-trust security using natively supported Bitcoin script mechanisms rather than smart contracts:

* Slippage Guard Outputs: Using strict UTXO mappings, the PSBT intrinsically fails if the output to the Taker falls below their defined tolerance.
* Replace-By-Fee (RBF): Full compatibility allows latency-sensitive trades to aggressively compete for blockspace without reinventing priority logic.
* Time-Lock Mechanisms: Output branches utilize `nLockTime` to auto-cancel stale PSBT drafts, preventing indefinite capital lockups.

***

#### 📚 Concept Guide

<details>

<summary><strong>PSBT (Partially Signed Bitcoin Transactions)</strong></summary>

A native Bitcoin standard (BIP 174) allowing multiple, entirely mutually distrusting parties to contribute inputs and outputs into a single transaction without exposing their private keys. Nexus utilizes this to ensure atomic swaps—the trade either executes perfectly as agreed, or mathematically fails to exist.

</details>

<details>

<summary><strong>Intent-Based Execution</strong></summary>

A structural pivot away from contract-driven DeFi. Rather than broadcasting specific execution commands (e.g., "Use Route A to swap X"), Takers only cryptographically sign their *desired outcome* (e.g., "I will output X only if I receive Y"). This closes the vulnerability to front-running and MEV since the strategy is never exposed.

</details>


# L1 Settlement

Executing trades and finalizing market-making yield directly on Bitcoin L1 without custodial risk.

Bitcoin Layer 1 settlement provides the cryptographic and consensus foundation for all Nexus operations. The protocol leverages Bitcoin primitives to achieve trustless multi-party coordination without introducing bridging or wrapped-asset security assumptions.

#### Core Primitives

Nexus builds upon Bitcoin's fundamental cryptographic mechanisms:

* UTXO Model: Every transaction output represents verifiable ownership through cryptographic signatures, enabling precise tracking of asset states and ownership transfers.
* Multi-Signature Scripts: Native Bitcoin functionality requiring multiple parties for spending authorization, eliminating single points of control.
* PSBT Standard: As detailed in the [PSBT Engine](/protocol-architecture/psbt-engine), this format secures coordination across multiple parties before any transaction is broadcast.

#### The Settlement Concept

DotSwap Nexus achieves cryptographic trustlessness through the systematic elimination of trusted third parties in the settlement layer.

| Component             | Trust Elimination Method                                       | Verification Approach                              |
| --------------------- | -------------------------------------------------------------- | -------------------------------------------------- |
| Asset Custody         | Funds remain in user-controlled UTXOs until atomic execution   | Users verify ownership through private key control |
| Transaction Execution | All operations are embedded in verifiable Bitcoin transactions | Complete blockchain transparency and auditability  |
| Settlement Finality   | Bitcoin consensus provides irreversible confirmation           | Standard block explorer verification               |

#### Absolute Security Guarantees

Because L1 Settlement uses pure Bitcoin:

* No Smart Contract Risk: Execution relies on core Bitcoin script execution, avoiding Turing-complete vulnerabilities.
* No Bridge Risk: Direct Bitcoin Layer 1 settlement entirely eliminates cross-chain dependencies.
* No Upgrade Risk: Protocol changes require explicit user adoption of new UTXO formats rather than forced administrative updates.


# Privacy & MEV Resistance

Decoupling execution intent from settlement to eradicate MEV and protect institutional capital.

In traditional account-based DeFi (e.g., Ethereum Automated Market Makers), every transaction—including trading intents, slippage tolerances, and routing paths—is broadcast to a public mempool prior to execution. This structural transparency creates severe vulnerabilities for Maximal Extractable Value (MEV) attacks, most notably front-running and sandwich attacks, which drain alpha from institutional quantitative strategies.

Nexus fundamentally eliminates these attack vectors through its strict protocol architecture.

#### Local Execution & Maker Privacy

A cardinal rule of the Nexus architecture is the absolute protection of institutional capital. In traditional smart-contract AMMs, a Market Maker’s pricing algorithms, dynamic parameters, and total liquidity depth are fully transparent on-chain, allowing predators to reverse-engineer and exploit quantitative strategies.

Nexus safeguards Market Makers through Local Validation and Execution:

* Proprietary Strategies: Makers calculate yielding curves, update risk parameters, and verify trades entirely within their own local nodes or [Institutional MPC](/deployment-and-integration/institutional-mpc) environments. These strategies are never deployed to a global, transparent state machine.
* Hidden Liquidity: Total available inventory and UTXO depths remain confidential. The public cannot arbitrarily scan a Maker's balance to assess their exact trading capacity.
* The Composer Boundary: This potent privacy layer is predicated on the strict neutrality of the Nexus Composer. The Composer operates solely as a neutral routing and drafting engine. It aggregates trading intents and constructs the draft PSBT, but the Maker's core decision-making logic and private keys remain physically isolated behind their own firewall.

#### Zero-Exposure Intent Lifecycle

The off-chain protocol ensures end-to-end privacy prior to settlement:

1. Private Quoting: The neutral Nexus Composer queries Makers for quotes based on the Taker's intent. The public mempool is blind to this process.
2. Taker Commitment: The Composer crafts the PSBT, and the Taker signs first, mathematically committing to the requested execution.
3. Local "Last Look": The Maker receives the Taker-signed PSBT and evaluates it locally. If the trade aligns with the Maker's private pricing strategy and avoids toxic flow, the Maker signs it.
4. Sealed Settlement (Signing IS Executing): In traditional account-based blockchains, a broadcasted transaction is merely an execution request, leaving it vulnerable in the mempool. In Nexus, a fully signed PSBT is a mathematically finalized, deterministic state transition. The exact inputs and outputs are locked the millisecond the Maker applies the final signature. Broadcasting to the L1 mempool is solely for historical state settlement; miners can only accept or reject the entire sealed package, but they absolutely cannot alter the price, routing, or outcome.

#### Attack Vector Neutralization

Because the L1 network only observes a completed, fully signed multi-party transaction, third-party network validators and mempool snipers cannot intercept it to optimize their own execution.

| Attack Vector     | Vulnerability in Standard AMMs                                   | Nexus Mitigation Mechanism                                                                                                                       |
| ----------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Front-Running     | Snipers see a large pending buy, buy before it, and sell higher. | The intent is matched and prices are locked in the PSBT off-chain. By the time it is broadcast, the price is finalized.                          |
| Sandwich Attacks  | Attackers manipulate the pool price around a victim's trade.     | Execution happens off-chain upon signature. Since the UTXO mapping is deterministic, no intermediary trades can slide between the signed inputs. |
| Strategy Bleeding | Quants broadcast their logical triggers to the blockchain.       | Strategy logic remains in the client's proprietary Node or MPC policy engine. Only the settlement outcome is public.                             |

By relying on State Channels and off-chain PSBT crafting, institutional traders keep their edges sharp. Their liquidity depths, dynamic rebalancing triggers, and proprietary intent-matching formulas remain entirely obfuscated from market competitors until final clearance.


# Node Deployment Guide

Deploy the Dual-Mode Nexus Node to establish your sovereign execution presence.

Independent Nexus Node operation enables quantitative funds, latency-sensitive traders, and institutions to deploy self-hosted liquidity infrastructure with complete asset custody and highly customizable algorithmic trading strategies.

The Nexus Node distribution is a Dual-Mode Toolkit, operating as either a Maker Nexus (for liquidity provision and yield generation) or a Taker Nexus (for high-frequency arbitrage and strict fund protection).

> 📌 Nexus is self-custodial, meaning the asset owner retains control of their Bitcoin through their own infrastructure.

### Terminal Deployment

**Security Confirmation:** By proceeding, you confirm that you fully understand and assume total responsibility for the security of your private keys and funds.Please configure the following information to launch. *(Note: The details below serve as the unique authorization credentials for your node, authorizing Bitcoin network transaction broadcasts and ensuring the continuous operation of the node.)***Deployment Network（mainnet/testnet4）:**

* **Authorization Wallet Mnemonic:** Enter words separated by commas.&#x20;
* **Authorization Address:**
* **Authorization Private Key (64-char hex):**

**Critical Architectural Requirement:** The Taker Nexus and Maker Nexus **must strictly share the same private key**. Furthermore, all Maker market-making addresses across different trading pairs, as well as the Taker trading address, **must be** generated from this specific shared private key.

**Launch Nexus.**&#x4F;nce the terminal deployment is complete, open the Nexus client to finalize your setup.Sign a message using the **Authorization Address** you configured during the terminal deployment to securely access the configuration dashboard.

* Step 1: Configure Basic Nexus Information
* Step 2: Configure Taker and Maker Nexus (On-Demand)

#### Advanced Configurations

If your institutional security policies prohibit arbitrary script execution (`curl | bash`), or if you require explicit mapping of Docker environment variables (`APP_ENV`, custom `ZMQ_HOST` endpoints) into existing CI/CD pipelines, you can utilize our Advanced Quick Deployment or Manual Source Deployment methods.

Please request the comprehensive Enterprise Configuration Manifest during your partner onboarding process via <hello@on.nexus>.

***

#### 📚 Concept Guide

<details>

<summary><strong>Trading Wallet</strong></summary>

The specialized hot/warm wallet environment operated internally by the Self-Hosted Nexus Node. Unlike traditional custodial wallets, it serves purely as an execution vault, holding the private keys necessary exclusively for the cryptographic signing of off-chain intents at millisecond latencies.

</details>

<details>

<summary><strong>Nexus Node</strong></summary>

The core software binary hosted by participating institutions. It supports two concurrent operational models: Maker Nexus (configured specifically to run automated market-making algorithms to generate yield) and Taker Nexus (configured for high-frequency algorithmic traders and arbitrageurs to securely generate/sign optimal execution intents off-chain).

</details>


# Institutional MPC Integration

Integrating cold-storage constraints into high-frequency sovereign yield strategies.

For enterprise asset managers, treasuries, and major quant funds, maintaining self-custody cannot rely on simple hot wallets or single-signature keys. These entities require rigorous internal compliance, multi-party computation (MPC) infrastructure, and segregated authorization workflows.

Nexus Protocol is structurally designed to integrate seamlessly with standard Institutional MPC Infrastructure (supporting frameworks like Fireblocks, Safeheron, and similar institutional providers).

This integration allows asset management institutions to run high-frequency market-making operations on Bitcoin while strictly enforcing their internal compliance and policy engines.

#### The Operational Workflow

The enterprise integration separates the operational capability (quoting and responding to market demand) from the cryptographic authorization (signing the transactions).

{% stepper %}
{% step %}

1. Market Response (Asset Manager Node)

The Asset Management firm operates a Nexus Node configured with their proprietary quoting logic and quantitative models. This node connects to the Nexus Composer, calculates real-time liquidity curves, and responds to trading intents from the market.
{% endstep %}

{% step %}
2\. Transaction Submission

When a market-making match occurs, the Asset Manager's Nexus Node constructs the precise transaction (using PSBT) required to clear the trade. Instead of signing it directly, the node submits this unsigned transaction request directly into the institution's MPC Policy Engine.
{% endstep %}

{% step %}
3\. Policy Verification

The institutional MPC infrastructure evaluates the transaction request against pre-defined rulesets (e.g., maximum trade limits, whitelisted addresses, velocity controls).
{% endstep %}

{% step %}
4\. Auditor Node Approval

To ensure the transaction strictly satisfies the market-making criteria (e.g., confirming the slippage matches the expected yield mathematically), the client's internal auditors or risk-control teams run a separate Auditor Nexus Node. This Auditor Node independently verifies the mathematical integrity of the trade. If it passes, the auditor authorizes the signature via the MPC pipeline.
{% endstep %}

{% step %}
5\. L1 Output Execution

Once the MPC quorum is reached according to the enterprise policy, the PSBT is cryptographically signed and routed back into the Nexus Network for final L1 settlement or State Channel roll-up.
{% endstep %}
{% endstepper %}

#### Strategic Benefits

* No Compromise on Security: Market-making logic can be aggressively optimized by traders without exposing the private keys to hot execution environments.
* Separation of Concerns: Quants handle the pricing models (Asset Manager Node), while Risk/Auditing handles the verification (Auditor Node + Policy Engine).
* Deep Institutional Liquidity: By bridging the gap between high-frequency AMM software and institutional cold-storage/MPC constraints, Nexus unlocks unprecedented capital depth for the Bitcoin ecosystem.

***

#### Become an Institutional Partner

We actively welcome quantitative trading teams, asset managers, and institutional custody providers to establish strategic partnerships with OnNexus.

If you are interested in integrating with the Nexus network, deploying bespoke market-making nodes, or optimizing your enterprise custody infrastructure for High-Frequency Bitcoin Trading, please reach out to our team:

📧 Contact Us: <hello@on.nexus>


# Scale-Invariant Yield Mechanics

The mechanics behind scale-invariant, sovereign yield generation.

> ‼️ Nexus is materially different from custodial yield products, bridges, wrapped-Bitcoin structures, and validator-trust models because BTC remains under owner-controlled custody while the application coordinates DeFi activity around it.

A prevalent misconception in traditional decentralized finance is that as Total Value Locked (TVL) scales, the yield per dollar invested inherently compresses. While true for traditional order books and directional market-making, this axiom does not apply to the [Constant Product Market Maker (CPMM)](/yield-economics-and-amm-design/amm-models) architecture utilized by the Nexus Protocol.

Within Nexus, arbitrage yields are non-dilutable.

#### The Scale-Invariance Theorem

The foundation of CPMM is the invariant curve: $$x \times y = k$$

Because this curve is homogeneous of degree 2, scaling liquidity $$L \equiv \sqrt{k}$$ strictly causes both capital allocation and arbitrage flows to stretch proportionally.

Mechanism Explained

When the external market price shifts from $$P\_{0}$$ to $$P\_{1}$$, an arbitrageur executes a trade against the Nexus pool to capture the spread. To move the AMM price to match the external CEX price, they must push a specific volume $$V\_{\text{in}}$$ against the curve.

Because of the geometric properties of $$x \times y = k$$, if the pool doubles in size ($$TVL\times 2$$), the volume required to move the price from $$P\_{0}$$ to $$P\_{1}$$ also exactly doubles ($$V\_{\text{in}}\times 2$$).

Since liquidity providers collect a fixed fee percentage ($$\gamma$$) on incoming volume, their absolute fee revenue doubles alongside the TVL. Therefore, the relative yield (Fees / TVL) cancels out the size parameter completely:

$$\text{Yield} = \frac{\gamma|\Delta \sqrt{P}|}{(1-\gamma) 2 \sqrt{P\_{0}}}$$

The yield depends entirely on external price volatility ($$|\Delta \sqrt{P}|$$) and the fee rate ($$\gamma$$), completely independent of how large the liquidity pool grows.

#### The Position Profile

Institutions providing liquidity to Nexus must understand their exposure mathematically: Liquidity Providers are long volatility, short drift.

Instead of being diluted by competitors depositing into the same pool, Nexus LPs benefit immensely from deep aggregate liquidity. Massive pools suffer lower slippage on routine trades, attracting larger tier-1 market arbitrage flows, which generate reliable, steady fee accretion during sideways, volatile market action.


# AMM Models (CPMM & CLMM)

Mathematical curves enabling nodes to generate sovereign yield passively without giving up private keys.

The Nexus Protocol supports multiple Automated Market Maker (AMM) mathematical curves to cater to different institutional risk profiles and market environments. Unlike smart-contract based AMMs, these curves are computed off-chain via the Nexus Composer and independently verified by Maker and Taker nodes prior to [PSBT signature execution](/protocol-architecture/psbt-engine).

{% tabs %}
{% tab title="Constant Product (CPMM)" %}
**Constant Product AMM (CPMM)**

Mathematical Foundation

CPMM implements the fundamental invariant: $$x × y = k$$, where x and y represent reserve balances of two assets, and k remains constant across all trading operations (excluding fee accrual).

This model provides continuous liquidity across all price levels spanning from zero to infinity. As derived in the [Non-Dilutable Yield Theorem](/yield-economics-and-amm-design/non-dilutable-yield), the CPMM curve is homogeneous of degree 2, meaning that arbitrage flows scale perfectly linearly with TVL, ensuring reliable yields resistant to liquidity dilution.

Institutional Execution Analysis

* Algorithmic Simplicity: Straightforward implementation for quantitative models tracking Mean-Reversion strategies.
* Continuous Availability: Guaranteed market-making at all theoretical price bands.
* Trade-off: Lower capital efficiency. Uniform distribution across an infinite price range results in suboptimal capital utilization, leading to higher slippage on larger trades relative to pool size.
  {% endtab %}

{% tab title="Concentrated (CLMM)" %}
**Concentrated Liquidity AMM (CLMM)**

Advanced Capital Efficiency Framework

CLMM enables quantitative managers to concentrate their capital bounds within specific, high-velocity price ranges through virtual reserve equations: $$(x + virtual\_x) × (y + virtual\_y) = k$$

By mathematically shifting the price intercepts, CLMM radically improves capital efficiency by focusing liquidity exactly where current trading activity exists.

Institutional Execution Analysis

* Range Specification: LPs define precise upper and lower price boundaries for execution.
* Virtual Amplification: Reduces slippage by orders of magnitude compared to an equivalent CPMM pool size. (e.g. Concentrating liquidity between bounded limits can amplify depth 10x+ over CPMM).
* Trade-off: Requires active, algorithmic range management to prevent capital from sitting idle when the market price breaches the specified bounds.
  {% endtab %}
  {% endtabs %}

#### Fee Economics & Autonomous Distribution

Beyond mathematical capital efficiency, Nexus introduces fundamental operational autonomy for market makers through its fee architecture. In traditional DeFi pools, the protocol mandates a fixed fee (e.g., 0.3%) and a fixed revenue split (e.g., 80% to LPs, 20% to the protocol).

Nexus [Independent Nodes](/deployment-and-integration/node-setup) operate as sovereign yield mechanisms.

Autonomous Pricing

Node operators algorithmically set their own Liquidity Provider (LP) Fee within their node configuration based entirely on their exact quantitative strategy and current market volatility. If an operator provides superior execution or deeper specialized liquidity, they can command a premium fee rate (e.g., 1.5% or 2%).

Settlement & Protocol Infrastructure Fee

The Nexus network only assesses a flat, base infrastructure usage fee (fixed at 0.1%). During the atomic PSBT settlement, fees are distributed cleanly:

* The LP Fee settles directly into the operator-controlled UTXOs.
* The 0.1% Protocol Fee is routed to fund Nexus infrastructure.

This pure free-market approach allows self-custodial entities to compete aggressively on execution quality and price discovery without being constrained by legacy pool models.


# High-Frequency Trading Accounts

Deep liquidity state channels enabling high-frequency, non-custodial swaps and continuous sovereign yield.

While [L1 Settlement](/protocol-architecture/l1-settlement) provides absolute finality, high-frequency quant trading and institutional market-making require execution speeds that transcend the 10-minute Bitcoin block time.

Nexus resolves the inherent scalability constraint of the Bitcoin network through Fast Execution Accounts (State Channels), an L2 Execution Layer that inherits all L1 security guarantees while enabling millisecond latency.

Settlement Layer (L1) vs Execution Layer (L2)

The architecture is explicitly separated:

* Layer 1 (L1) The Settlement Layer: Acts as the final custodian. L1 is strictly used for Funding (opening channels/injecting liquidity) and Settlement (closing channels/withdrawing funds).
* Layer 2 (L2) The Execution Layer: Functions as the high-velocity transaction highway. Trading, order matching, and FPSSL rebalancing occur off-chain via Commitment Transactions.

These deferred state updates are cryptographically signed via [PSBTs](/protocol-architecture/psbt-engine) by channel participants, but they are not broadcast to the Bitcoin mainnet until necessary. This aggregate state rolling enables near-zero gas fees per trade.

The 3/3 Channel Architecture

To abstract complex channel management away from the Taker, Nexus implements a "Joint Market Making" model backing the liquidity pools.

The "Counterparty" providing liquidity to a swapper is a 3-of-3 Multi-Sig Channel composed of:

1. Single-Sided LP A: Provides the Base Asset (e.g., BTC).
2. Single-Sided LP B: Provides the Quote Asset (e.g., USDC).
3. The Protocol Node: Acts as the network coordinator, routing requests and injecting dual-sided matching to facilitate channel settlement.

#### HTLC Safeguards & Rollup Dynamics

For dynamic clearance during high-oscillation periods, High-Frequency Trading Accounts combine with Hash Time Locked Contracts (HTLCs).

Because Make/Take trades adjust the ratio of assets in the channel and accumulate trading fees, the protocol mathematically computes required "Rebalancing Amounts" in real-time (following the [FPSSL formulas](/yield-economics-and-amm-design/fpssl)). A new Commitment Transaction is signed within the channel, logically redistributing UTXO ownership between the internal LPs without requiring an immediate on-chain settlement.

Once LPs exit, the final netted state rolls up to L1.

***

#### 📚 Concept Guide

<details>

<summary><strong>Fast Execution Account</strong></summary>

A Layer-2 state channel implementation built on Hash Time Locked Contracts (HTLCs). It acts as the backbone for high-frequency market-making, allowing participants to consolidate hundreds of separate trades and fee payments off-chain, deferring the expensive L1 network settlement to a single aggregated closure.

</details>

<details>

<summary><strong>HTLC (Hash Time Locked Contract)</strong></summary>

A foundational Bitcoin script condition used extensively inside Fast Execution Accounts. It creates cryptographically secure escrows that mathematically guarantee funds will either be settled upon the revelation of a secret hash, or safely refunded after a predefined block height.

</details>


# FPSSL (Single-Sided Liquidity)

Fairly Paired Single-Sided Liquidity architecture immunizing Bitcoin treasuries against impermanent loss.

#### The Unit of Account Illusion

Historically, Automated Market Makers (AMMs) forced divergent market participants into an unnatural compromise. A Bitcoin treasury measures its success strictly by accumulating more BTC. A stablecoin yield fund measures success strictly in USD. Their risk preferences, positioning, and definitions of "profit" are fundamentally asymmetric.

Yet, legacy DeFi models force both participants into a unified liquidity calculation that dictates a single "Unit of Account" (almost always USD) to measure Impermanent Loss and Yield Distribution.

This creates a fatal contradiction. If a pool's performance is measured in USD, the BTC purist is told they are "losing money" whenever fiat exchange rates fluctuate, entirely defeating their fundamental strategy of stacking native Bitcoin. The industry falsely assumed that a unified liquidity pool must enforce a unified risk metric.

#### The FPSSL Axiom: Asymmetric Risk Sovereignty

Fairly Paired Single-Sided Liquidity (FPSSL) is an exclusive mathematical framework developed by OnNexus to shatter this contradiction. It proves a foundational economic truth: Liquidity pairing does not require a shared unit of measurement.

FPSSL allows institutions to deposit strictly one asset (e.g., pure BTC or pure USD) and mathematically decouples their risk exposure. The routing engine pairs their liquidity to execute trades, but the protocol evaluates Impermanent Loss and Fee Yields strictly in the native currency of the depositor.

If the pool generates fee yield, the BTC depositor logs a pristine gain in BTC, and the USD depositor logs an identical percentage gain in USD. FPSSL respects the absolute sovereignty of your chosen risk profile.

#### Mathematical Fairness Theorem

The foundation of FPSSL rests on a strict uniqueness theorem ensuring Equal Native-Percentage Performance.

When a BTC-only institution deposits BTC, and a USD-only institution deposits USD, the protocol logically pairs them at entry price $$P\_{0}$$. At the time of withdrawal ($$P\_{1}$$), the protocol asserts two axioms:

1. Conservation: The sum of both allocations must equal the total mathematical pool value.
2. Symmetry: Each holder must experience the exact same percentage return measured in their native unit of account.

**Symmetric Impermanent Loss**

Under the FPSSL dynamic allocation weights, if the price of BTC drops, creating an Impermanent Loss scenario of $$-1.0%$$, the mathematical proof guarantees that the BTC depositor loses exactly $$-1.0%$$ of their BTC, and the USD depositor loses exactly $$-1.0%$$ of their USD.

Unlike naive 50/50 splits where directional price swings create massive windfalls for one party while destroying the other, FPSSL forces shared exposure exclusively driven by AMM curve mechanics.

**Provably Fair Fee Yields**

The symmetry applies equally to transaction fees. If the pool accrues $$+5.0%$$ in fee yield via arbitrage flow, both the BTC-holder and USD-holder will register a pristine $$+5.0%$$ gain in their respective settlement assets.

It achieves this by weighting the value allocation at the time of withdrawal based on dynamic ratio distributions:

$$\alpha\_{BTC} = \frac{P\_{1}}{P\_{0} + P\_{1}}$$ $$\alpha\_{USD} = \frac{P\_{0}}{P\_{0} + P\_{1}}$$

#### Protocol Implementation

At the protocol layer, this allows institutions to plug strictly native BTC into the 3/3 Nexus State Channels. The Protocol Node dynamically rebalances the internal Commitment Transactions to ensure that the asset values strictly adhere to the $$\alpha$$ weights.

By abstracting away the secondary asset, Nexus ensures asset managers can deploy pure-BTC yields against market-neutral strategies without bridging into synthetic stables.


# RGB Asset Market Making

#### **Understanding the RGB Protocol**

RGB is a scalable smart contract and asset issuance protocol built on top of the Bitcoin network. By leveraging cutting-edge cryptographic techniques such as "Client-Side Validation" and "Single-Use Seals," RGB enables the secure transfer of complex assets (e.g., stablecoins like USDT) without consuming precious Bitcoin mainnet block space. In short, RGB inherits the robust security of the Bitcoin mainnet while empowering it with highly private and scalable digital asset management capabilities.

#### **Unlocking RGB Market Making & Yield Capture**

As the native Bitcoin ecosystem expands rapidly, Maker Nexus now fully supports automated market making for RGB assets. Our objective is to provide Liquidity Providers with an institutional-grade suite of market-making tools. You can now directly provide liquidity for RGB assets (such as USDT issued via the RGB protocol) on the Nexus platform, precisely capturing market trading opportunities and continuously earning real transaction fee yields.

#### **I. Market Making Capabilities & Protocol Scope**

* **Version Compatibility:** To ensure that market-making capital operates within the most secure and deterministic environment, the Nexus engine currently exclusively supports market making for RGB v0.11 standard assets.
* **High-Frequency Trading Pairs (RGB-BTC):** Current liquidity provisioning is strictly focused on high-frequency RGB-BTC trading pairs. This allows you to build a value bridge between Bitcoin and native RGB assets, capturing market-making dividends from exchange rate volatility.
* **Channel-Free Capital Deployment:** Breaking free from the lock-up constraints of traditional DEXs, market-making capital requires no complex state-channel staking. You can directly use your personal wallet funds to inject or withdraw liquidity at any time, maintaining 100% absolute sovereignty over your market-making principal.

#### **II. Asset Routing & Secure Execution**

* **Invoice-Based Capital Routing:** Similar to utilizing advanced payment networks, importing and exporting RGB assets relies on a precise invoice mechanism. The system automatically generates the corresponding receiving invoices based on your market-making strategy, seamlessly guiding your capital into the designated market-making ranges.
* **Atomic Settlement:** When your maker orders match with market taker demands, the Nexus engine automatically generates a Partially Signed Bitcoin Transaction. This settlement process is strictly "atomic", asset delivery only takes effect when the transaction is fully confirmed on the Bitcoin mainnet. This underlying architecture completely eliminates the possibility of counterparty default, absolutely guaranteeing the security of your market-making funds.
* **Automated UTXO Management:** To ensure maximum capital utilization and continuous order-matching capabilities during sustained market-making operations, the system intelligently handles underlying UTXO states in the background. This allows you to focus entirely on your yield-generating strategies without worrying about operational friction.


# Ecosystem Rewards

The Proof-of-Contribution network equity model.

Instead of the traditional centralized "extraction model," OnNexus operates on a strict Proof-of-Contribution philosophy. Every trade, liquidity deposit, and ecosystem expansion effort is recognized and quantified. To achieve this, OnNexus operates a structured incentive framework designed to reward long-term engagement through our native reward asset: DD Token.

***

#### Objectives

The OnNexus Rewards Program is designed to:

* Deterministic Incentives: Strictly rewarding verified Runes-BTC trading volume and active market-making.
* Sovereign Settlement: Zero-trust, direct distribution to non-custodial V1 wallets, ensuring absolute Sovereign Premium.
* Structural Liquidity: Deepening capital density through a direct economic loop between LPs and Traders, eliminating inflationary marketing mechanics.

***

#### Reward System Overview

The core of the program is the DD Token distribution system. Users earn DD Tokens by completing specific tasks across two modules:

Trade-to-Earn

Traders are systematically rewarded in $DD tokens based on the transaction fees incurred during their trading activities.

Calculation Formula:

The exact amount of $DD tokens distributed to a trader is calculated by taking 20% of the Total Fee, multiplying that figure by 12.5%, and finally dividing that resulting value by the real-time $DD Market Price.

Variable Definitions:

* Total Fee: The aggregate transaction fee paid by the trader, strictly denominated in BTC. If fees are paid in a non-BTC asset, the system dynamically converts this to a BTC value using the asset's average price at the time of the transaction.
* Platform Fee Ratio: The proportion of the actual fee captured by the platform relative to the Total Fee.
* DD Market Price: Denominated in BTC, determined by the real-time asset price on DotSwap On Nexus at the exact moment of transaction confirmation.

### LP Rewards

Liquidity Providers receive $DD token allocations proportional to their specific contribution to a transaction's market-making fees.

Calculation Logic:

The $DD token allocation for an individual LP is determined by taking the base transaction reward (calculated identically to the trader reward: 20% of the Total Fee multiplied by 12.5%, divided by the $DD Market Price) and multiplying it by the individual LP's proportional share of the trade. This share is defined as the specific fee earned by that individual LP divided by the Total LP Fee generated from that transaction.

Variable Definitions:

* Total LP Fee: The aggregate sum of fees earned by all participating LPs for a specific transaction.
* Individual LP Fee: The specific fee amount captured by a single Liquidity Provider for their share of that transaction.
* *Note: Total Fee, Platform Fee Ratio, and DD Market Price follow the exact same definitions as outlined in Module 1.*

#### System Constraints & Operational Rules

* Supported Trading Pairs: The reward protocol is strictly limited to Runes-BTC trading pairs. Transactions involving any other pairs will not generate $DD rewards.
* Distribution & Settlement: Reward allocations are strictly processed and distributed to the user's V1 Wallet only after the transaction is fully confirmed on-chain. Accrued rewards are permanent and do not carry an expiration date.
* Minimum Threshold: All calculated reward values are rounded down. If the calculated allocation is strictly less than 0.0001 $DD, the reward is nullified and will not be distributed.
* Architecture Limitations: Single-sided liquidity pools are temporarily excluded from LP rewards. Support for this architecture will be implemented in subsequent protocol upgrades.

Specific redemption options will be announced by the On Nexus team.


# Intent-Based Execution

Off-chain cryptographic intents protecting capital and ensuring zero gas waste on failed trades.

> ‼️ Nexus is materially different from conventional Bitcoin yield offerings, including centralized yield desks, custodial trading venues, and wrapped-Bitcoin DeFi structures.

In standard DeFi protocols, traders must submit explicit on-chain instructions (e.g., "Swap 1 BTC for EXACTLY X RUNES, executing Route A -> Route B"). This leaks strategy to the mempool and severely limits execution optimization.

Nexus Protocol employs an Intent-Based Execution model. Takers (Trading Firms, Retail Swappers) only dictate their *desired outcome*, allowing the Nexus Composer to independently decipher the optimal execution path across all available Maker nodes.

#### Execution Architecture

The Intent-Based workflow separates the *discovery* of liquidity from the *settlement* of liquidity.

{% stepper %}
{% step %}

1. Intent Submission (Off-Chain)

The Taker submits an encrypted JSON intent to the Nexus network. The intent specifies the input asset, desired output asset, sizing, and explicit slippage/fee constraints.
{% endstep %}

{% step %}
2\. Quotation Engine

The Nexus Composer broadcasts this intent securely to the network of Institutional Makers and standalone Nexus Nodes. Each Maker's quantitative engine evaluates the request and responds with a guaranteed execution quote.
{% endstep %}

{% step %}
3\. PSBT Assembly

Once the Composer identifies the optimal path (often breaking the order into discrete tranches across multiple Makers via [Multi-Maker Routing](/trading-and-routing-strategies/routing)), it constructs the raw Partally Signed Bitcoin Transaction (PSBT).
{% endstep %}

{% step %}
4\. Client Verification & Signature

The compiled PSBT is routed back to the Taker. Because it strictly adheres to the PSBT layout, the Taker can cryptographically verify that the outputs meet the strict parameters of their original intent. If constraints are met, the Taker signs the final input payload.
{% endstep %}

{% step %}
5\. Finality

The fully formed transaction is either settled instantly to an [HTLC State Channel](/yield-economics-and-amm-design/fast-execution-accounts) or broadcast directly into the L1 mempool for absolute finality.
{% endstep %}
{% endstepper %}

#### Programmable Risk Management

Because Intents dictate the exact mathematical boundaries of a trade before any on-chain action occurs, Takers can cryptographically encode strict risk-protection parameters directly into their request. The PSBT will mathematically fail to assemble if these parameters are violated by the market makers:

* Slippage Tolerance (1% - 50%): Enforces a rigid floor on the output amount. If volatility slippage or routing slippage causes the final output to fall below this parameter, the Taker's signature is never applied.
* Execution Deadlines: Using Bitcoin's native `nLockTime` or block-height constraints, intents can be programmed to automatically expire (e.g., after 6 blocks) to prevent stale liquidity from locking up operational capital.
* Fee Ceilings: Takers define an absolute maximum for L1 mining fees and routing network fees. If the network becomes congested and the fee exceeds this cap, the intent is safely discarded without costing the Taker any gas.

#### Unified Liquidity: Bridging AMM & CLOB

Because users only sign off-chain "Intents" (I want X for Y) rather than interacting with a discrete on-chain smart contract, the coordinating engine is completely agnostic to where the counter-liquidity originates.

This architecture fundamentally resolves the classic DeFi division between Automated Market Makers (AMM) and the Central Limit Order Book (CLOB):

* A Maker can deploy a quantitative `x*y=k` price curve (AMM).
* A Maker can deploy a static, single-price Limit Order (CLOB).

From the perspective of the Nexus Composer and the resulting PSBT, *they are mathematically identical*. Both are simply inputs and outputs waiting to be matched. A trader's intent can be seamlessly filled by routing $1M through a blend of CPMM curves and three overlapping Limit Orders simultaneously, settling them together into a single, unified execution path.

#### Institutional Execution Benefits

* No Execution Reverts: L1 transaction fees are ONLY paid when a fully valid, fully matched, cryptographically sound swap occurs. Failed intents do not cost gas.
* Complex Transaction Abstraction: Traders benefit from fragmented multi-maker liquidity depths without needing to comprehend the underlying UTXO graph merging.
* MEV Safety: Since intents are resolved purely off-chain, front-running bots cannot weaponize public mempool data.

***

#### 📚 Concept Guide

<details>

<summary><strong>Intent-Based Execution</strong></summary>

A structural pivot away from contract-driven DeFi. Rather than broadcasting specific execution commands (e.g., "Use Route A to swap X"), Takers only cryptographically sign their *desired outcome* (e.g., "I will output X only if I receive Y"). This closes the vulnerability to front-running and MEV since the strategy is never exposed.

</details>

<details>

<summary><strong>Nexus Composer</strong></summary>

The central parsing and routing entity. It receives market intents from Takers, matches them against the optimal liquidity curves generated by Maker nodes, and constructs the mathematical foundation of the draft PSBT. The Composer never holds funds.

</details>


# Multi-Maker Routing

Sourcing optimal execution paths across a globally fragmented sovereign liquidity network.

Institutional trades often exceed the optimal liquidity depth of a single market maker. To prevent compounding slippage, the Nexus Composer utilizes Multi-Maker Routing, transforming single, monolithic swaps into highly optimized, distributed execution paths.

#### Optimal Liquidity Aggregation

Multi-maker routing is treating liquidity as a distributed optimization problem. The Nexus Composer aggregates the yielding curves from all active CPMM, CLMM, and FPSSL Nodes into a unified order book.

Multi-Objective Optimization Matrix:

1. Order Book Aggregation: Merge independent Maker liquidity curves into a unified depth-by-price mapping.
2. Greedy Price Optimization: Intelligently slice the total order size, distributing tranches to the most cost-effective liquidity sources until the order is filled or the slippage constraint is breached.
3. PSBT Partitioning: Allocate distinct UTXO input/output sets to correspond to each selected maker within a single, atomic PSBT.
4. Synchronous Signatures: Collect off-chain signatures simultaneously from the distributed makers.

#### Execution Quality

By splitting a 10 BTC order into five distinct 2 BTC tranches across completely independent Institutional Maker Nodes, the trader bypasses the steep curve penalty associated with executing a 10 BTC trade against a single CPMM pool.

| Trade Scenario | Direct Single Execution  | Multi-Maker Routing Execution |
| -------------- | ------------------------ | ----------------------------- |
| Liquidity Used | One Maker (Deepest Pool) | 3 Independent Makers          |
| Slippage Curve | Steep exponentially      | Shallow step-wise             |
| Price Impact   | High                     | Minimized                     |

#### Algorithmic Safeguards

When aggregating multi-party quotes within a single PSBT, operational reliability becomes the primary failure vector.

* Latency Optimization: The routing engine actively tracks the ping/response metrics of Maker nodes, systematically routing around non-responsive hardware.
* Atomic Settlement Assurance: The PSBT requires ALL selected Makers to sign. If one Maker drops offline mid-execution, the entire PSBT draft is invalidated, ensuring the Taker never enters a state of partial, unintended fulfillment.


# Slippage & Protocol Fees

Deterministic pricing and absolute front-running protection ensuring execution certainty.

Whenever institutions trade on legacy decentralized exchanges, they bleed capital. This bleeding is categorized as MEV (Maximum Extractable Value), front-running, or "hidden slippage." It is the most persistent, predatory pain point in crypto trading.

Why has the industry accepted this adversarial "dark forest" as a permanent cost of doing business?

Because the ecosystem is trapped in a fatal architectural design: The Mempool Lottery Illusion.

Legacy smart contracts (e.g., EVM models) separate a trader's *Intent* from the *Final Execution Price*. They force traders to broadcast their vulnerable intentions into a public mempool, relying entirely on miners or sequencers to execute the trade fairly. The industry falsely accepted the illusion that price discovery requires exposing your trading intent to public manipulation prior to settlement.

#### The Deterministic Axiom: Cryptographically Bound Execution

Nexus Protocol completely eliminates MEV at the structural layer. It proves a foundational execution truth: The execution parameters must be cryptographically finalized BEFORE hitting the network.

Nexus does not rely on off-chain "grace" to honor quoted prices; it relies on cold Bitcoin cryptography.

Through the use of [Partially Signed Bitcoin Transactions (PSBTs)](/protocol-architecture/psbt-engine), the protocol embeds the trader's exact absolute slippage tolerance directly into the UTXO constraints.

If the executed state of the AMM breaches the defined slippage limit by a single Satoshi, the PSBT intrinsically and mathematically fails. The output branch cannot be unlocked, rendering the entire multi-party transaction invalid. No miner, no sequencer, and no arbitrage bot can alter the execution rate, because the underlying asset is cryptographically forbidden from moving.

This guarantees that an institution will NEVER experience execution at an un-approved limit price. Zero MEV by structural design, not by good faith.

Component Analysis

For algorithmic trading analysis, slippage in Nexus consists of:

1. Impact Slippage: The deterministic price movement natively caused by passing the trade volume across the CPMM/CLMM curve.
2. Routing Slippage: The compounded impact resulting from bridging across distinct fragmented liquidity sources via Multi-Maker Routing.
3. *Note: Volatility Slippage (market moving between Request and Execution) is entirely mitigated by the aforementioned PSBT Slippage Guard.*

#### Transparent Fee Architecture

Nexus employs a competitive, transparent fee model separating purely independent Node Operators from general Protocol Treasuries. This creates natural market-driven yield optimization for liquidity providers.

Institutional Nexus Nodes (Self-Custodial LP)

Entities running bespoke Node and Institutional MPC strategies retain absolute control over their yield metrics.

* Variable LP Fee: Independently defined by the Node operator based on their proprietary market-making algorithmic risk models. (e.g. Setting a high spread on low-liquidity long-tail assets).
* Fixed Protocol Infrastructure Fee: A flat `0.1%` collected automatically via the transaction outputs to fund ongoing Nexus infrastructure and developmental maintenance.
* Settlement: The LP Fees are settled *instantly* and *directly* back to the operator's private, self-custodied wallet on every atomic trade.

Sourced Liquidity Pools (Custodial LP)

For baseline liquidity aggregated globally under the managed Nexus Pool (previously DotSwap):

* Dynamic Fee Share: A strict 4:1 ratio. `80%` of the total transaction fee distributes proportionally among the Liquidity Providers, while `20%` flows to the Protocol Infrastructure.
* Competition: Because independent Institutional Nodes command their own fee markets, algorithmic Taker routines automatically route volume to the most capital-efficient nodes, driving a constant, natural compression on execution costs ecosystem-wide.


# 1. Basics & Guide

**Q: Are my funds safe on Nexus? Can the platform misappropriate my assets?**

**A:** Absolutely safe. DotSwap Nexus is built on a strictly **non-custodial** architecture. Your assets always remain in your own Web3 wallet. The platform never touches, holds, or has the ability to misappropriate your funds. We utilize native Bitcoin technology (such as PSBT) for matching and settlement, eliminating the counterparty risks of centralized exchanges (CEXs) and the smart contract vulnerability risks found on other blockchains.

\
**Q: What is the difference between Nexus and a centralized exchange ?**

**A:** The biggest difference is **control**. On centralized exchanges, you must deposit your crypto into their accounts. On Nexus, no deposits are required. You simply connect your own Bitcoin wallet and trade directly. You are the sole owner of your assets. Additionally, Nexus focuses specifically on the Bitcoin native ecosystem (such as Runes and Ordinals), providing a direct Layer 1 on-chain settlement experience.

\
**Q: What is the "Fast Execution Account" (FEA) I keep seeing? Do I need to understand it as a beginner?**

**A:** The "Fast Execution Account" (FEA) is an advanced feature designed primarily for professional market makers and arbitrageurs to provide faster and more cost-effective off-chain matching. As a beginner retail user, you can simply connect your wallet and trade directly on-chain. **You do not need to understand or use FEA immediately.** You can explore it later when your trading strategies require faster execution speeds and fee optimizations.


# 2. Node Deployment & Configuration

**Q: When configuring Maker liquidity pools (e.g., `POOLS_BTC_*`), why does the node panic on startup with the error `address not match with mnemonic`?**

**A:** This usually occurs because the derivation path index of the mnemonic exceeds the node's scanning range. Currently, the Nexus engine is hardcoded to scan up to index `20` (i.e., scanning from `m/86'/0'/0'/0/0` to `m/86'/0'/0'/0/20`). Please ensure your address is generated within this **0-20**index limit.

\
**Q: Can I set a private key directly for Maker pools via environment variables (like `PRIVATE_KEY_HEX`), similar to the Taker configuration?**

**A:** No, you cannot. There is no equivalent private key variable for Maker pools. To maintain standard deterministic key management for liquidity pools, the system relies strictly on the mnemonic derivation provided in the `.env` file.

\
**Q: Will the system automatically start market-making once the local node is spun up with the configured pool addresses?**

**A:** No. After your Nexus service is successfully running, an upstream enrollment step is required. You must manually register and initialize the pool configuration on the Web Dashboard / Composer before the system actively accepts the pool.


# 3. Settlement & Channel Management

**Q: Will the system alert me if my trading account runs out of funds? I'm worried my trades will fail if I forget to top up.**

**A:** You don't need to worry about forgetting to top up at all. Our system features a handy "auto-deduction" function. Whenever your trading account needs to cover fees, the system will automatically deduct the required amount from your connected main wallet. Simply put: **As long as your main wallet has sufficient funds, your trades and services will never be interrupted.** You do not need to constantly check your balance or manually add funds.

\
**Q: Do the market-making fees earned go to the L1 (on-chain) wallet or the FEA?**

**A:** The settlement route for earned fees depends entirely on how the trade is executed:

1. **Trades routed via FEA:** If the trade is executed through the FEA (Fast Execution Account), the fees go directly into your FEA. This process is fully off-chain, ensuring maximum capital efficiency.
2. **Trades routed via L1 (On-chain):** Your earnings will first be deposited into the platform fee settlement account and then transferred to your on-chain wallet after final settlement. *(Note: We now exclusively use the FEA infrastructure to manage and collect all system service fees.)*


# 4. API Integration & Developer Resources

**Q: How can I get API access to the full liquidity pools (e.g., the DOG/BTC pool) for arbitrage or building trading tools? The documentation I found seems to be strictly for the Nexus node.**

**A:** Our developer documentation is categorized by specific use cases. The Nexus Node APIs you reviewed are exclusively designed for local node deployment and market-making configuration. If you need to fetch full pool data, execute V3 Runes trades, or build arbitrage engines, please refer to our **L1 Swap & Liquidity APIs (V3 Runes Trading)**&#x64;ocumentation.

* For V3 Rune trading APIs, please visit: <https://docs.on.nexus/dotswap/developers/l1-swap-and-liquidity-apis/swap-v3/runes>
* For the general developer portal, please visit: <https://docs.on.nexus/dotswap/developers>


# Ecosystem Resources

Essential ecosystem resources for the sovereign capital network.

#### Official Links

* Interactive App: [https://dotswap.app](https://dotswap.app/)
* X (Twitter): [https://x.com/dot\_swap](https://twitter.com/dot_swap)
* Telegram: <https://t.me/NexusGroup>
* Discord: <https://discord.gg/HR8hksbcQs>
* Medium (Research & Announcements): [https://dotswap.medium.com](https://dotswap.medium.com/)
* Media Kit: [Download Here](https://drive.google.com/drive/folders/1_XxAqMj6EV-yqZIEx7FiUD_apmB7HBzW)

***

#### Technical & Strategic Roadmap (2026 Focus)

Nexus Protocol follows a systematic development approach that balances foundational UTXO innovation with high-frequency capital efficiency.

Institutional Custody Integration (Fireblocks)

Partnering with Fireblocks to bring enterprise-grade custody and transfer networks to our PSBT workflows. This enhances capital efficiency and internal policy compliance, bridging the gap between rigorous self-custody rules and high-frequency intent matching.

Enhanced Private Key Management

Upgrading the core Nexus node cryptographic architecture to completely eliminate single points of failure, granting institutional makers flexible, distributed key management options (MPC) while operating the node.

Splicing: Dynamic Channel Capacity

Leveraging Lightning-adjacent Splicing technology, Nexus State Channels will dynamically adjust capacity in real-time "invisibly" based on settlement volume needs. This maximizes capital efficiency without requiring channel closure and service interruption.

Options Trading & Automated Hedging

Moving beyond spot AMM execution, the Nexus engine is actively integrating options primitives. By connecting automated hedging scripts directly into the Nexus Composer, liquidity providers can dynamically delta-hedge their FPSSL positions natively on Bitcoin.

Vaults: Leverage & Lending

Unlocking capital velocity by working with ecosystem collateralization protocols. Asset managers will be able to borrow against their productive Nexus LP positions or utilize dynamic leverage to amplify returns while enforcing strict programmatic liquidation boundaries within State Channels.


# Partnerships

Deploy physical infrastructure to plug institutional capital into the Nexus Sovereign Execution Backend.

Most "partnerships" in the Web3 space are little more than co-marketing announcements. For institutions, integrating with a decentralized exchange usually means taking on immense counterparty risk—wrapping assets, bridging funds, or surrendering capital to an audited (but exploitable) central smart contract.

The industry operates under the Liquidity Silo Illusion: the belief that to participate in a liquidity network, you must physically move your money into it.

OnNexus flips this model. We are not building a walled garden; we are building a Sovereign Execution Backend. A partnership with OnNexus does not mean you send us capital. It means you deploy a Nexus Node behind your own firewall, plugging your existing capital into a global coordination layer while retaining absolute cryptographic custody.

We are actively seeking integration with four specific profiles of institutional partners:

#### Proprietary Trading Teams (Quants) & Liquidity Providers

For latency-sensitive traders and quantitative funds, OnNexus offers a direct programmatic pipeline to retail and institutional order flow.

* The Proposal: Deploy a Maker Node. Connect your proprietary algorithmic pricing models (CPMM, CLMM, Limit Orders) directly to the Nexus Composer.
* The Value: Execute high-frequency market-making strategies directly from your own self-custodial wallets. Zero smart contract risk. Zero cost for un-filled orders. Pure, non-dilutable fee generation.

#### Asset Management Firms & Treasuries

For Bitcoin miners, family offices, and enterprise treasuries holding massive, idle BTC reserves.

* The Proposal: Deploy a passive Maker Node using our [Fair Proportion Single-Sided Liquidity (FPSSL)](/yield-economics-and-amm-design/fpssl) architecture.
* The Value: Generate continuous, mathematically predictable yield on your native Bitcoin without ever exposing your principal to impermanent loss against volatile quote assets. Your Treasury remains secure in your [MPC policy engine](/deployment-and-integration/institutional-mpc).

#### Centralized Exchanges (CEX)

CEXs historically struggle to offer their users deep, native DeFi access without incurring massive bridge-building overhead or forcing users onto fragmented L2s.

* The Proposal: Integrate the Nexus Composer API directly into your exchange's backend or Web3 wallet offering. Additionally, deploy your idle exchange treasury into a Maker Node.
* The Value:
  * For your users: They gain immediate, seamless access to native Bitcoin liquidity and trading pairs, routed effortlessly through your frontend.
  * For your exchange: You monetize your idle cold-storage treasury by acting as a Liquidity Provider for the network, earning OnNexus yield without moving funds out of institutional custody.

#### Bitcoin Asset Bridges

For bridging protocols attempting to unify liquidity across disparate Bitcoin Layer 2s and sidechains.

* The Proposal: Utilize OnNexus as your underlying cryptographic settlement engine.
* The Value: Route cross-chain intents through the Nexus coordination layer to ensure your users receive the best possible execution price natively on L1 before the asset is bridged, ensuring zero slippage and MEV protection during the transition.

***

#### Technical Integration & Contact

Integration with OnNexus is a technical deployment, not a marketing exercise. We provide the binaries, the API documentation, and direct engineering support to ensure your Nexus Node is tightly coupled with your internal risk-engines.

If your institution fits the profiles above and is ready to deploy sovereign capital, initiate the technical onboarding process:

📧 Contact the Infrastructure Team: <hello@on.nexus>


# Appendix: Glossary

Comprehensive directory of technical terminology, proprietary concepts, and execution primitives utilized across the Nexus Protocol.

To assist new institutional participants, developers, and asset managers, this appendix defines the core architecture concepts, specialized endpoints, and Bitcoin primitives engineered into the Nexus ecosystem.

#### Network & Architecture Framework

* Nexus Coordination Network The overarching decentralized financial layer. It does not exist as a single smart contract or centralized server, but rather as an interconnected mesh of self-hosted nodes calculating and routing liquidity cryptographically.
* Nexus Composer The central parsing and routing entity. It receives market intents from Takers, matches them against the optimal liquidity curves generated by Maker nodes, and constructs the mathematical foundation of the draft PSBT. The Composer never holds funds.
* Nexus Node (Dual-Mode) The core software binary hosted by participating institutions. It supports two concurrent operational models:
  * Maker Nexus: Configured specifically to run automated market-making algorithms (CPMM/CLMM/FPSSL) to strictly generate yield on idle assets.
  * Taker Nexus: Configured for high-frequency algorithmic traders and arbitrageurs to instantly pull market states and securely generate/sign optimal execution intents off-chain.

#### Wallet & Settlement Structures

* Trading Wallet The specialized hot/warm wallet environment operated internally by the Self-Hosted Nexus Node. Unlike traditional custodial wallets, it serves purely as an execution vault, holding the private keys necessary exclusively for the cryptographic signing of off-chain intents at millisecond latencies.
* Fast Execution Account A Layer-2 state channel implementation built on Hash Time Locked Contracts (HTLCs). It acts as the backbone for high-frequency market-making, allowing participants to consolidate hundreds of separate trades and fee payments off-chain, deferring the expensive L1 network settlement to a single aggregated closure.

#### Cryptographic Execution Primitives

* Intent-Based Execution A structural pivot away from contract-driven DeFi. Rather than broadcasting specific execution commands (e.g., "Use Route A to swap X"), Takers only cryptographically sign their *desired outcome* (e.g., "I will output X only if I receive Y"). This closes the vulnerability to front-running and MEV since the strategy is never exposed.
* PSBT (Partially Signed Bitcoin Transactions) A native Bitcoin standard (BIP 174) allowing multiple, entirely mutually distrusting parties to contribute inputs and outputs into a single transaction without exposing their private keys. Nexus utilizes this to ensure atomic swaps—the trade either executes perfectly as agreed, or mathematically fails to exist.
* HTLC (Hash Time Locked Contract) A foundational Bitcoin script condition used extensively inside Fast Execution Accounts. It creates cryptographically secure escrows that mathematically guarantee funds will either be settled upon the revelation of a secret hash, or safely refunded after a predefined block height.

#### Quantitative Liquidity Models

Automated Market Maker (AMM) formulas utilized by the Nexus Maker nodes:

* CPMM (Constant Product Market Maker) The foundational $x \times y = k$ invariant curve. It guarantees continuous liquidity from zero to infinity. In Nexus, arbitrage yield derived from this curve scales linearly with TVL, making the yield inherently non-dilutable.
* CLMM (Concentrated Liquidity Market Maker) A highly capital-efficient evolution utilizing virtual reserves. Through the calculation $(x + \text{virtual}\_x) \times (y + \text{virtual}\_y) = k$, Maker Nodes constrain their liquidity deployment to a hyper-specific price band, dramatically compressing slippage at the cost of requiring active range management.
* FPSSL (Fairly Paired Single-Sided Liquidity) A specialized mathematical curve engineered for liquidity providers wishing to expose only a single asset to the market, avoiding the complex dual-asset exposure traditionally required in CPMM pools.


# Terms of Service

These Terms of Service (the "Agreement") explain the terms and conditions by which you may access and use the Products provided by Nexus (referred to herein as "OnNexus", "we", "our", or "us"). The Products shall include, but shall not necessarily be limited to, <https://swap.dotwallet.com/>, a website-hosted user interface (the "Interface" or "App") and other Products. You must read this Agreement carefully as it governs your use of the Products. By accessing or using any of the Products, you signify that you have read, understand, and agree to be bound by this Agreement in its entirety. If you do not agree, you are not authorized to access or use any of our Products and should not use our Products.

To access or use any of our Products, you must be able to form a legally binding contract with us. Accordingly, you represent that you are at least the age of majority in your jurisdiction (e.g., 18 years old in the United States) and have the full right, power, and authority to enter into and comply with the terms and conditions of this Agreement on behalf of yourself and any company or legal entity for which you may access or use the Interface. If you are entering into this Agreement on behalf of an entity, you represent to us that you have the legal authority to bind such entity.

You further represent that you are not (a) the subject of economic or trade sanctions administered or enforced by any governmental authority or otherwise designated on any list of prohibited or restricted parties (including but not limited to the list maintained by the Office of Foreign Assets Control of the U.S. Department of the Treasury) or (b) a citizen, resident, or organized in a jurisdiction or territory that is the subject of comprehensive country-wide, territory-wide, or regional economic sanctions by the United States. Finally, you represent that your access and use of any of our Products will fully comply with all applicable laws and regulations, and that you will not access or use any of our Products to conduct, promote, or otherwise facilitate any illegal activity.

NOTICE: This Agreement contains important information, including a binding arbitration provision and a class action waiver, both of which impact your rights as to how disputes are resolved. Our Products are only available to you — and you should only access any of our Products — if you agree completely with these terms.

1. Our Products

1.1 The Interface

The Interface provides a web or mobile-based means of access to a decentralized protocol on various public blockchains, including but not limited to Bitcoin, that allows users to trade certain compatible digital assets (the "Nexus protocol" or the "Protocol").

The Interface is distinct from the Protocol and is one, but not the exclusive, means of accessing the Protocol. By using the Interface, you understand that you are not buying or selling digital assets from us and that we do not operate any liquidity pools on the Protocol or control trade execution on the Protocol. When traders pay fees for trades, those fees accrue to liquidity providers for the Protocol. As a general matter, Nexus is not a liquidity provider into Protocol liquidity pools and liquidity providers are independent third parties. The Protocol was initially deployed on the Bitcoin blockchain, and has since been deployed on several other blockchain networks including by parties other than Nexus. Deployments on other networks typically make use of cross-chain bridges, which allow assets native to one blockchain to be transferred to another blockchain. Please note that digital assets that have been "bridged" or "wrapped" to operate on other blockchain networks (including to blockchains compatible with the Bitcoin Virtual Machine that are designed to ensure the Bitcoin blockchain can effectively process more transactions or other blockchains that are frequently referred to as "Layer 2" solutions) are distinct from the original Bitcoin mainnet asset.

To access the Interface, you must use a non-custodial wallet software, which allows you to interact with public blockchains. Your relationship with that non-custodial wallet provider is governed by the applicable terms of service (with respect to this Agreement, and with respect to a third party wallet, the applicable terms of service of such third party). We do not have custody or control over the contents of your wallet and have no ability to retrieve or transfer its contents. By connecting your wallet to our Interface, you agree to be bound by this Agreement and all of the terms incorporated herein by reference.

1.2 Other Products

We may from time to time in the future offer additional products, and such additional products shall be considered a Product as used herein, regardless of whether such product is specifically defined in this Agreement.

1.3 Third Party Services and Content

When you use any of our Products, you may also be using the products, services or content of one or more third parties. Your use of such third party products, services or content may be subject to separate policies, terms of use and fees of these third parties, and you agree to abide by and be responsible for such policies, terms of use and fees, as applicable.

2. Modifications of this Agreement or our Products

2.1 Modifications of this Agreement

We reserve the right, in our sole discretion, to modify this Agreement from time to time. If we make any material modifications, we will notify you by updating the date at the top of the Agreement and by maintaining a current version of the Agreement at <https://swap.dotwallet.com/terms-of-service>. All modifications will be effective when they are posted, and your continued accessing or use of any of the Products will serve as confirmation of your acceptance of those modifications. If you do not agree with any modifications to this Agreement, you must immediately stop accessing and using all of our Products.

2.2 Modifications of our Products

We reserve the following rights, which do not constitute obligations of ours: (a) with or without notice to you, to modify, substitute, eliminate or add to any of the Products; (b) to review, modify, filter, disable, delete and remove any and all content and information from any of the Products.

3. Intellectual Property Rights

3.1 IP Rights Generally

We own all intellectual property and other rights in each of our Products and its respective contents, including, but not limited to, software, text, images, trademarks, service marks, copyrights, patents, designs, and its "look and feel." This intellectual property is available under the terms of our copyright licenses and our Trademark Guidelines. Subject to the terms of this Agreement, we grant you a limited, revocable, non-exclusive, non-sublicensable, non-transferable license to access and use our Products solely in accordance with this Agreement. You agree that you will not use, modify, distribute, tamper with, reverse engineer, disassemble or decompile any of our Products for any purpose other than as expressly permitted pursuant to this Agreement. Except as set forth in this Agreement, we grant you no rights to any of our Products, including any intellectual property rights.

You understand and acknowledge that the Protocol is not a Product and we do not control the Protocol.

You represent and warrant that you have, or have obtained, all rights, licenses, consents, permissions, power and/or authority necessary to grant the rights granted herein for any material that you list, post, promote, or display on or through any of our Products. You represent and warrant that such content does not contain material subject to copyright, trademark, publicity rights, or other intellectual property rights, unless you have necessary permission or are otherwise legally entitled to post the material and to grant us the license described above, and that the content does not violate any laws.

3.2 Third-Party Resources and Promotions

Our Products may contain references or links to third-party resources, including, but not limited to, information, materials, products, or services, that we do not own or control. In addition, third parties may offer promotions related to your access and use of our Products. We do not approve, monitor, endorse, warrant or assume any responsibility for any such resources or promotions. If you access any such resources or participate in any such promotions, you do so at your own risk, and you understand that this Agreement does not apply to your dealings or relationships with any third parties. You expressly relieve us of any and all liability arising from your use of any such resources or participation in any such promotions.

3.3 Additional Rights

We reserve the right to cooperate with any law enforcement, court or government investigation or order or third party requesting or directing that we disclose information or content or information that you provide.

4. Your Responsibilities

4.1 Prohibited Activity

You agree not to engage in, or attempt to engage in, any of the following categories of prohibited activity in relation to your access and use of the Interface:

Intellectual Property Infringement. Activity that infringes on or violates any copyright, trademark, service mark, patent, right of publicity, right of privacy, or other proprietary or intellectual property rights under the law.

Cyberattack. Activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including, but not limited to, the deployment of viruses and denial of service attacks.

Fraud and Misrepresentation. Activity that seeks to defraud us or any other person or entity, including, but not limited to, providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of another.

Market Manipulation. Activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including, but not limited to, the manipulative tactics commonly known as "rug pulls", pumping and dumping, and wash trading.

Securities and Derivatives Violations. Activity that violates any applicable law, rule, or regulation concerning the trading of securities or derivatives, including, but not limited to, the unregistered offering of securities and the offering of leveraged and margined commodity products to retail customers in the United States.

Sale of Stolen Property. Buying, selling, or transferring of stolen items, fraudulently obtained items, items taken without authorization, and/or any other illegally obtained items.

Data Mining or Scraping. Activity that involves data mining, robots, scraping, or similar data gathering or extraction methods of content or information from any of our Products.

Objectionable Content. Activity that involves soliciting information from anyone under the age of 18 or that is otherwise harmful, threatening, abusive, harassing, tortious, excessively violent, defamatory, vulgar, obscene, pornographic, libelous, invasive of another's privacy, hateful, discriminatory, or otherwise objectionable.

Any Other Unlawful Conduct. Activity that violates any applicable law, rule, or regulation of China, the United States or another relevant jurisdiction, including, but not limited to, the restrictions and regulatory requirements imposed by Chinese, and U.S. law.

4.2 Trading

You agree and understand that: (a) all trades you submit through any of our Products are considered unsolicited, which means that they are solely initiated by you; (b) you have not received any investment advice from us in connection with any trades, including those you place via our Auto Routing API; and (c) we do not conduct a suitability review of any trades you submit.

4.3 Non-Custodial and No Fiduciary Duties

Each of the Products is a purely non-custodial application, meaning we do not ever have custody, possession, or control of your digital assets at any time. It further means you are solely responsible for the custody of the cryptographic private keys to the digital asset wallets you hold and you should never share your wallet credentials or seed phrase with anyone. We accept no responsibility for, or liability to you, in connection with your use of a wallet and make no representations or warranties regarding how any of our Products will operate with any specific wallet. Likewise, you are solely responsible for any associated wallet and we are not liable for any acts or omissions by you in connection with or as a result of your wallet being compromised. For the avoidance of doubt, any references herein to a "wallet" shall include the Nexus Wallet.

This Agreement is not intended to, and does not, create or impose any fiduciary duties on us. To the fullest extent permitted by law, you acknowledge and agree that we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, those duties and liabilities are hereby irrevocably disclaimed, waived, and eliminated. You further agree that the only duties and obligations that we owe you are those set out expressly in this Agreement.

4.4 Compliance and Tax Obligations

One or more of our Products may not be available or appropriate for use in your jurisdiction. By accessing or using any of our Products, you agree that you are solely and entirely responsible for compliance with all laws and regulations that may apply to you.

Specifically, your use of our Products or the Protocol may result in various tax consequences, such as income or capital gains tax, value-added tax, goods and services tax, or sales tax in certain jurisdictions.

It is your responsibility to determine whether taxes apply to any transactions you initiate or receive and, if so, to report and/or remit the correct tax to the appropriate tax authority.

4.5 Gas Fees

Blockchain transactions require the payment of transaction fees to the appropriate network ("Gas Fees"). Except as otherwise expressly set forth in the terms of another offer by Nexus, you will be solely responsible to pay the Gas Fees for any transaction that you initiate via any of our Products.

4.6 Release of Claims

You expressly agree that you assume all risks in connection with your access and use of any of our Products. You further expressly waive and release us from any and all liability, claims, causes of action, or damages arising from or in any way relating to your use of any of our Products. If you are a California resident, you waive the benefits and protections of California Civil Code § 1542, which provides: "\[a] general release does not extend to claims that the creditor or releasing party does not know or suspect to exist in his or her favor at the time of executing the release and that, if known by him or her, would have materially affected his or her settlement with the debtor or released party."

4.6 Deposit Errors and Asset Recovery

If you deposit digital assets to an incorrect address or attempt to deposit unsupported tokens, Nexus typically does not provide asset recovery services. These include, but are not limited to:

* Sending tokens to an incorrect or incompatible blockchain address;
* Depositing unsupported tokens or assets;
* Failing to use the Nexus account deposit process and instead transferring directly to a wallet address.

However, if a significant financial loss has occurred due to such an error, Nexus may, at its sole discretion, offer assistance in recovering the misplaced assets. In such cases, Nexus has established a comprehensive recovery procedure designed to help users retrieve their funds.

Please note the following:

* Asset recovery is not guaranteed. While we will make commercially reasonable efforts, we do not commit to successful retrieval.
* Recovery efforts consume substantial resources and may only be offered in select cases deemed eligible by Nexus.
* If we agree to assist in recovering the assets, a service fee ranging from 0.002 BTC to 0.005 BTC will apply, depending on the complexity of the recovery.

By using our Products, you acknowledge and agree that Nexus is not responsible for user errors involving wallet addresses or unsupported tokens, and that any recovery assistance provided is a voluntary service, not an obligation.

5. DISCLAIMERS

5.1 ASSUMPTION OF RISK -- GENERALLY

BY ACCESSING AND USING ANY OF OUR PRODUCTS, YOU REPRESENT THAT YOU ARE FINANCIALLY AND TECHNICALLY SOPHISTICATED ENOUGH TO UNDERSTAND THE INHERENT RISKS ASSOCIATED WITH USING CRYPTOGRAPHIC AND BLOCKCHAIN-BASED SYSTEMS, AND THAT YOU HAVE A WORKING KNOWLEDGE OF THE USAGE AND INTRICACIES OF DIGITAL ASSETS SUCH AS BITCOIN (BTC), SO-CALLED STABLECOINS, AND OTHER DIGITAL TOKENS SUCH AS THOSE FOLLOWING THE BITCOIN TOKEN STANDARD (BRC-20).

IN PARTICULAR, YOU UNDERSTAND THAT THE MARKETS FOR THESE DIGITAL ASSETS ARE NASCENT AND HIGHLY VOLATILE DUE TO RISK FACTORS INCLUDING, BUT NOT LIMITED TO, ADOPTION, SPECULATION, TECHNOLOGY, SECURITY, AND REGULATION. YOU UNDERSTAND THAT ANYONE CAN CREATE A TOKEN, INCLUDING FAKE VERSIONS OF EXISTING TOKENS AND TOKENS THAT FALSELY CLAIM TO REPRESENT PROJECTS, AND ACKNOWLEDGE AND ACCEPT THE RISK THAT YOU MAY MISTAKENLY TRADE THOSE OR OTHER TOKENS. SO-CALLED STABLECOINS MAY NOT BE AS STABLE AS THEY PURPORT TO BE, MAY NOT BE FULLY OR ADEQUATELY COLLATERALIZED, AND MAY BE SUBJECT TO PANICS AND RUNS.

FURTHER, YOU UNDERSTAND THAT SMART CONTRACT TRANSACTIONS AUTOMATICALLY EXECUTE AND SETTLE, AND THAT BLOCKCHAIN-BASED TRANSACTIONS ARE IRREVERSIBLE WHEN CONFIRMED. YOU ACKNOWLEDGE AND ACCEPT THAT THE COST AND SPEED OF TRANSACTING WITH CRYPTOGRAPHIC AND BLOCKCHAIN-BASED SYSTEMS SUCH AS Bitcoin ARE VARIABLE AND MAY INCREASE DRAMATICALLY AT ANY TIME. YOU FURTHER ACKNOWLEDGE AND ACCEPT THE RISK OF SELECTING TO TRADE IN EXPERT MODES, WHICH CAN EXPOSE YOU TO POTENTIALLY SIGNIFICANT PRICE SLIPPAGE AND HIGHER COSTS.

IF YOU ACT AS A LIQUIDITY PROVIDER TO THE PROTOCOL THROUGH THE INTERFACE, YOU UNDERSTAND THAT YOUR DIGITAL ASSETS MAY LOSE SOME OR ALL OF THEIR VALUE WHILE THEY ARE SUPPLIED TO THE PROTOCOL THROUGH THE INTERFACE DUE TO THE FLUCTUATION OF PRICES OF TOKENS IN A TRADING PAIR OR LIQUIDITY POOL.

FINALLY, YOU UNDERSTAND THAT WE DO NOT CREATE, OWN, OR OPERATE CROSS-CHAIN BRIDGES AND WE DO NOT MAKE ANY REPRESENTATION OR WARRANTY ABOUT THE SAFETY OR SOUNDNESS OF ANY CROSS-CHAIN BRIDGE, INCLUDING ITS USE FOR DOTSWAP GOVERNANCE.

IN SUMMARY, YOU ACKNOWLEDGE THAT WE ARE NOT RESPONSIBLE FOR ANY OF THESE VARIABLES OR RISKS, DO NOT OWN OR CONTROL THE PROTOCOL, AND CANNOT BE HELD LIABLE FOR ANY RESULTING LOSSES THAT YOU EXPERIENCE WHILE ACCESSING OR USING ANY OF OUR PRODUCTS. ACCORDINGLY, YOU UNDERSTAND AND AGREE TO ASSUME FULL RESPONSIBILITY FOR ALL OF THE RISKS OF ACCESSING AND USING THE INTERFACE TO INTERACT WITH THE PROTOCOL.

5.2 NO WARRANTIES

EACH OF OUR PRODUCTS ARE PROVIDED ON AN "AS IS" AND "AS AVAILABLE" BASIS. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ANY REPRESENTATIONS AND WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. YOU ACKNOWLEDGE AND AGREE THAT YOUR USE OF EACH OF OUR PRODUCTS IS AT YOUR OWN RISK. WE DO NOT REPRESENT OR WARRANT THAT ACCESS TO ANY OF OUR PRODUCTS WILL BE CONTINUOUS, UNINTERRUPTED, TIMELY, OR SECURE; THAT THE INFORMATION CONTAINED IN ANY OF OUR PRODUCTS WILL BE ACCURATE, RELIABLE, COMPLETE, OR CURRENT; OR THAT ANY OF OUR PRODUCTS WILL BE FREE FROM ERRORS, DEFECTS, VIRUSES, OR OTHER HARMFUL ELEMENTS. NO ADVICE, INFORMATION, OR STATEMENT THAT WE MAKE SHOULD BE TREATED AS CREATING ANY WARRANTY CONCERNING ANY OF OUR PRODUCTS. WE DO NOT ENDORSE, GUARANTEE, OR ASSUME RESPONSIBILITY FOR ANY ADVERTISEMENTS, OFFERS, OR STATEMENTS MADE BY THIRD PARTIES CONCERNING ANY OF OUR PRODUCTS.

SIMILARLY, THE PROTOCOL IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND. ALTHOUGH WE CONTRIBUTED TO THE INITIAL CODE FOR THE PROTOCOL, WE DO NOT PROVIDE, OWN, OR CONTROL THE PROTOCOL, WHICH IS RUN AUTONOMOUSLY WITHOUT ANY HEADCOUNT BY SMART CONTRACTS DEPLOYED ON VARIOUS BLOCKCHAINS. UPGRADES AND MODIFICATIONS TO THE PROTOCOL ARE GENERALLY MANAGED IN A COMMUNITY-DRIVEN WAY BY HOLDERS OF THE UNI GOVERNANCE TOKEN. NO DEVELOPER OR ENTITY INVOLVED IN CREATING THE PROTOCOL WILL BE LIABLE FOR ANY CLAIMS OR DAMAGES WHATSOEVER ASSOCIATED WITH YOUR USE, INABILITY TO USE, OR YOUR INTERACTION WITH OTHER USERS OF, THE PROTOCOL, INCLUDING ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR LOSS OF PROFITS, CRYPTOCURRENCIES, TOKENS, OR ANYTHING ELSE OF VALUE. WE DO NOT ENDORSE, GUARANTEE, OR ASSUME RESPONSIBILITY FOR ANY ADVERTISEMENTS, OFFERS, OR STATEMENTS MADE BY THIRD PARTIES CONCERNING ANY OF OUR PRODUCTS.

ANY PAYMENTS OR FINANCIAL TRANSACTIONS THAT YOU ENGAGE IN WILL BE PROCESSED VIA AUTOMATED SMART CONTRACTS. ONCE EXECUTED, WE HAVE NO CONTROL OVER THESE PAYMENTS OR TRANSACTIONS, NOR DO WE HAVE THE ABILITY TO REVERSE ANY PAYMENTS OR TRANSACTIONS.

5.3 NO INVESTMENT ADVICE

WE MAY PROVIDE INFORMATION ABOUT TOKENS IN OUR PRODUCTS SOURCED FROM THIRD-PARTY DATA PARTNERS THROUGH FEATURES SUCH AS RARITY SCORES, TOKEN EXPLORER OR TOKEN LISTS. WE MAY ALSO PROVIDE WARNING LABELS FOR CERTAIN TOKENS. THE PROVISION OF INFORMATIONAL MATERIALS DOES NOT MAKE TRADES IN THOSE TOKENS SOLICITED; WE ARE NOT ATTEMPTING TO INDUCE YOU TO MAKE ANY PURCHASE AS A RESULT OF INFORMATION PROVIDED. ALL SUCH INFORMATION PROVIDED BY ANY OF OUR PRODUCTS IS FOR INFORMATIONAL PURPOSES ONLY AND SHOULD NOT BE CONSTRUED AS INVESTMENT ADVICE OR A RECOMMENDATION THAT A PARTICULAR TOKEN IS A SAFE OR SOUND INVESTMENT. YOU SHOULD NOT TAKE, OR REFRAIN FROM TAKING, ANY ACTION BASED ON ANY INFORMATION CONTAINED IN ANY OF OUR PRODUCTS. BY PROVIDING TOKEN INFORMATION FOR YOUR CONVENIENCE, WE DO NOT MAKE ANY INVESTMENT RECOMMENDATIONS TO YOU OR OPINE ON THE MERITS OF ANY TRANSACTION OR OPPORTUNITY. YOU ALONE ARE RESPONSIBLE FOR DETERMINING WHETHER ANY INVESTMENT, INVESTMENT STRATEGY OR RELATED TRANSACTION IS APPROPRIATE FOR YOU BASED ON YOUR PERSONAL INVESTMENT OBJECTIVES, FINANCIAL CIRCUMSTANCES, AND RISK TOLERANCE.

6. Indemnification

You agree to hold harmless, release, defend, and indemnify us and our officers, directors, employees, contractors, agents, affiliates, and subsidiaries from and against all claims, damages, obligations, losses, liabilities, costs, and expenses arising from: (a) your access and use of any of our Products; (b) your violation of any term or condition of this Agreement, the right of any third party, or any other applicable law, rule, or regulation; (c) any other party's access and use of any of our Products with your assistance or using any device or account that you own or control; and (d) any dispute between you and (i) any other user of any of the Products or (ii) any of your own customers or users.

7. Limitation of Liability

UNDER NO CIRCUMSTANCES SHALL WE OR ANY OF OUR OFFICERS, DIRECTORS, EMPLOYEES, CONTRACTORS, AGENTS, AFFILIATES, OR SUBSIDIARIES BE LIABLE TO YOU FOR ANY INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA, OR OTHER INTANGIBLE PROPERTY, ARISING OUT OF OR RELATING TO ANY ACCESS OR USE OF OR INABILITY TO ACCESS OR USE ANY OF THE PRODUCTS, NOR WILL WE BE RESPONSIBLE FOR ANY DAMAGE, LOSS, OR INJURY RESULTING FROM HACKING, TAMPERING, OR OTHER UNAUTHORIZED ACCESS OR USE OF ANY OF THE PRODUCTS OR THE INFORMATION CONTAINED WITHIN IT, WHETHER SUCH DAMAGES ARE BASED IN CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, OR OTHERWISE, ARISING OUT OF OR IN CONNECTION WITH AUTHORIZED OR UNAUTHORIZED USE OF ANY OF THE PRODUCTS, EVEN IF AN AUTHORIZED REPRESENTATIVE OF Nexus HAS BEEN ADVISED OF OR KNEW OR SHOULD HAVE KNOWN OF THE POSSIBILITY OF SUCH DAMAGES. WE ASSUME NO LIABILITY OR RESPONSIBILITY FOR ANY: (A) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT; (B) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM ANY ACCESS OR USE OF THE INTERFACE; (C) UNAUTHORIZED ACCESS OR USE OF ANY SECURE SERVER OR DATABASE IN OUR CONTROL, OR THE USE OF ANY INFORMATION OR DATA STORED THEREIN; (D) INTERRUPTION OR CESSATION OF FUNCTION RELATED TO ANY OF THE PRODUCTS; (E) BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE THAT MAY BE TRANSMITTED TO OR THROUGH THE INTERFACE; (F) ERRORS OR OMISSIONS IN, OR LOSS OR DAMAGE INCURRED AS A RESULT OF THE USE OF, ANY CONTENT MADE AVAILABLE THROUGH ANY OF THE PRODUCTS; AND (G) THE DEFAMATORY, OFFENSIVE, OR ILLEGAL CONDUCT OF ANY THIRD PARTY.

WE HAVE NO LIABILITY TO YOU OR TO ANY THIRD PARTY FOR ANY CLAIMS OR DAMAGES THAT MAY ARISE AS A RESULT OF ANY PAYMENTS OR TRANSACTIONS THAT YOU ENGAGE IN VIA ANY OF OUR PRODUCTS, OR ANY OTHER PAYMENT OR TRANSACTIONS THAT YOU CONDUCT VIA ANY OF OUR PRODUCTS. EXCEPT AS EXPRESSLY PROVIDED FOR HEREIN, WE DO NOT PROVIDE REFUNDS FOR ANY PURCHASES THAT YOU MIGHT MAKE ON OR THROUGH ANY OF OUR PRODUCTS.

WE MAKE NO WARRANTIES OR REPRESENTATIONS, EXPRESS OR IMPLIED, ABOUT LINKED THIRD PARTY SERVICES, THE THIRD PARTIES THEY ARE OWNED AND OPERATED BY, THE INFORMATION CONTAINED ON THEM, ASSETS AVAILABLE THROUGH THEM, OR THE SUITABILITY, PRIVACY, OR SECURITY OF THEIR PRODUCTS OR SERVICES. YOU ACKNOWLEDGE SOLE RESPONSIBILITY FOR AND ASSUME ALL RISK ARISING FROM YOUR USE OF THIRD-PARTY SERVICES, THIRD-PARTY WEBSITES, APPLICATIONS, OR RESOURCES. WE SHALL NOT BE LIABLE UNDER ANY CIRCUMSTANCES FOR DAMAGES ARISING OUT OF OR IN ANY WAY RELATED TO SOFTWARE, PRODUCTS, SERVICES, AND/OR INFORMATION OFFERED OR PROVIDED BY THIRD-PARTIES AND ACCESSED THROUGH ANY OF OUR PRODUCTS.

SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY FOR PERSONAL INJURY, OR OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU. IN NO EVENT SHALL OUR TOTAL LIABILITY TO YOU FOR ALL DAMAGES (OTHER THAN AS MAY BE REQUIRED BY APPLICABLE LAW IN CASES INVOLVING PERSONAL INJURY) EXCEED THE AMOUNT OF ONE HUNDRED U.S. DOLLARS ($100.00 USD) OR ITS EQUIVALENT IN THE LOCAL CURRENCY OF THE APPLICABLE JURISDICTION.

THE FOREGOING DISCLAIMER WILL NOT APPLY TO THE EXTENT PROHIBITED BY LAW.

8. Governing Law, Dispute Resolution and Class Action Waivers

8.1 Governing Law

You agree that the laws of Hong Kong, China, without regard to principles of conflict of laws, govern this Agreement and any Dispute between you and us. You further agree that each of our Products shall be deemed to be based solely in Hong Kong, and that although a Product may be available in other jurisdictions, its availability does not give rise to general or specific personal jurisdiction in any forum outside Hong Kong. The parties acknowledge that this Agreement evidences interstate commerce. Any arbitration conducted pursuant to this Agreement shall be governed by the HKIAC Rules. You agree that the courts of Hong Kong, China are the proper forum for any appeals of an arbitration award or for court proceedings in the event that this Agreement's binding arbitration clause is found to be unenforceable.

8.2 Dispute Resolution

We will use our best efforts to resolve any potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us at <https://twitter.com/dotswap\\_brc20> so that we can attempt to resolve it without resorting to formal dispute resolution. If we aren't able to reach an informal resolution within sixty days of your message, then you and we both agree to resolve the potential dispute according to the process set forth below.

Any claim or controversy arising out of or relating to any of our Products, this Agreement, or any other acts or omissions for which you may contend that we are liable, including, but not limited to, any claim or controversy as to arbitrability ("Dispute"), shall be finally and exclusively settled by arbitration under the HKIAC Expedited Procedure. You understand that you are required to resolve all Disputes by binding arbitration. The arbitration shall be held on a confidential basis before a single arbitrator, who shall be selected pursuant to HKIAC rules. The arbitration will be held in Hong Kong, China, unless you and we both agree to hold it elsewhere. Unless we agree otherwise, the arbitrator may not consolidate your claims with those of any other party. Any judgment on the award rendered by the arbitrator may be entered in any court of competent jurisdiction. If for any reason a claim by law or equity must proceed in court rather than in arbitration you agree to waive any right to a jury trial and any claim may be brought only in the courts of Hong Kong, China.

8.3 Class Action and Jury Trial Waiver

You must bring any and all Disputes against us in your individual capacity and not as a plaintiff in or member of any purported class action, collective action, private attorney general action, or other representative proceeding. This provision applies to class arbitration. You and we both agree to waive the right to demand a trial by jury.

9. Miscellaneous

9.1 Entire Agreement

These terms constitute the entire agreement between you and us with respect to the subject matter hereof. This Agreement supersedes any and all prior or contemporaneous written and oral agreements, communications and other understandings (if any) relating to the subject matter of the terms.

9.2 Assignment

You may not assign or transfer this Agreement, by operation of law or otherwise, without our prior written consent. Any attempt by you to assign or transfer this Agreement without our prior written consent shall be null and void. We may freely assign or transfer this Agreement. Subject to the foregoing, this Agreement will bind and inure to the benefit of the parties, their successors and permitted assigns.

9.3 Rewards

In connection with your historic or current use of one or more of our Products, we may provide you certain incentives, prizes or rewards for completing certain activities, such as completing a certain number of transactions ("User Rewards"). Details regarding the criteria for earning a reward will be described within the applicable Product or official Nexus documentation. Upon satisfaction of the criteria for obtaining a reward and subject to your compliance with the associated rewards terms, this Agreement, and applicable law — to be determined exclusively by Nexus — we will use commercially reasonable efforts to promptly transfer the earned reward to the digital wallet that you designate or have connected to the applicable Product. We reserve the right to change, modify, discontinue or cancel any rewards programs (including the frequency and criteria for earning such User Rewards), at any time and without notice to you.

9.4 Not Registered with the SEC or Any Other Agency

We are not registered with the U.S. Securities and Exchange Commission as a national securities exchange or in any other capacity. You understand and acknowledge that we do not broker trading orders on your behalf. We also do not facilitate the execution or settlement of your trades, which occur entirely on public distributed blockchains like Bitcoin. As a result, we do not (and cannot) guarantee market best pricing or best execution through our Products or when using our Auto Routing feature, which routes trades across liquidity pools on the Protocol only. Any references in a Product to "best price" does not constitute a representation or warranty about pricing available through such Product, on the Protocol, or elsewhere.

9.5. Notice

We may provide any notice to you under this Agreement using commercially reasonable means, including using public communication channels. Notices we provide by using public communication channels will be effective upon posting.

9.6 Severability

If any provision of this Agreement shall be determined to be invalid or unenforceable under any rule, law, or regulation of any local, state, or federal government agency, such provision will be changed and interpreted to accomplish the objectives of the provision to the greatest extent possible under any applicable law and the validity or enforceability of any other provision of this Agreement shall not be affected.


# Risk Disclaimer

Dear Nexus users,

We would like to express our gratitude for your unwavering support and positive feedback since the launch of Nexus. Your participation has been instrumental in our success, and we are committed to continuously improving our services to meet your needs.

As an independently operated project, Nexus has dedicated significant resources to its initial development and technical advancements for the benefit of the Nexus users. In order to ensure the long-term sustainability and operational efficiency of our development team, we have implemented a strategy to allocate a portion of our income for the team's ongoing activities. This allocation, representing a percentage of our total equity (0.958%), will be utilized exclusively for the betterment of Nexus and its ecosystem.

As of the most recent update (Jan 15, 2024), Nexus has garnered a significant user base, with active accounts surpassing 2,000 and a considerable trading volume exceeding 340 BTC. We want to assure you that we take this responsibility seriously and will exercise strict control over the use of these funds. Our primary focus is on further enhancing the platform's technology, expanding our services, and providing a seamless trading experience for all users. By investing in our team and resources, we aim to deliver innovative features, improve security measures, and foster a vibrant community on Nexus.

Transparency and fairness are core values we uphold. In the event of similar circumstances in the future, we will continue to adhere to the principles of openness and integrity by making public announcements regarding the allocation and utilization of our income.

Once again, we extend our heartfelt appreciation for your support and trust in Nexus. Together, we will shape the future of decentralized trading.


# Privacy Policy

This Privacy Policy (the “Policy”) explains how SimplePower. Ltd. (“Nexus”, the “Company”, “we”, “us” or “our”) collects, uses, and shares data in connection with the Nexus web app, website <https://swap.dotwallet.com/>, and all of our other properties, products, and services (the “Services”). Your use of the Services is subject to this Policy as well as our Terms of Service.

High Level Summary

1\. Nexus is an incorporated company based in Hong Kong that operates <https://swap.dotwallet.com/> among other products and services. Nexus complies with Chinese laws and regulations.

2\. Nexus does not collect and store personal data, such as first name, last name, street address, date of birth, email address, or IP address, in connection with your use of the Services.

3\. Nexus collects non-identifiable data, such as public on-chain data, and limited off-chain data like device type, browser version, etc. This is to help drive production vision, not track users.

4\. If you specifically sign up to receive emails from us, we will store your email address to allow us to send you those emails. You can unsubscribe at any time. We will not attempt to link your email address to your wallet address, IP address, or other personal data.

5\. Nexus continues to explore methods to further protect consumers' privacy, such as opt-out prompts, migrating to privacy-centric tooling and deploying proxies to anonymize network traffic.

6\. Users are empowered to explore client-side privacy techniques and tools.

7\. Any material changes to privacy will be reflected in an updated privacy policy.

Data We Collect

Privacy is central to everything we do at the Company. And we've enshrined transparency as one of our Company values. Accordingly, we aspire to be transparent about what little data we do collect. We do not maintain user accounts and do not collect and store personal data, such as your name or internet protocol (“IP”) address. When you interact with the Services, we collect only:

1\. Publicly-available blockchain data. When you connect your non-custodial blockchain wallet to the Services, we collect and log your publicly-available blockchain address to learn more about your use of the Services and to screen your wallet for any prior illicit activity. We screen your wallet using intelligence provided by leading blockchain analytics providers. Note that blockchain addresses are publicly-available data that are not created or assigned by us or any central party, and by themselves are not personally identifying.

2\. Information from localStorage and other tracking technologies. We and our third-party services providers may access and collect information from localStorage, mobile deviceID, cookies, web beacons, and other similar technologies to provide and personalize the Services and features of the Services for you across sessions. For example, we may use this information to remember tokens you import, star, or add to your shopping bag. We may also use this information to learn about your preferences, your use of the Services, and our interactions with you. Information we collect from these technologies may include things such as browser type, referring/exit pages, operating system, device or browser language, and other device information. We group and analyze these user journeys collectively, in the aggregate, to improve our product user experience.

3\. Information from other sources. We may receive information about your wallet address or transactions made through the Services from our service providers in order to comply with our legal obligations and prevent the use of our Services in connection with fraudulent or other illicit activities.

4\. Survey or usability information. If you participate in a survey or usability study with us, we will record any biographical information you directly provide to us (for example, your name, email, and job title), the responses you provide to us, and your interactions with the Services.

5\. Correspondence. We will receive any communications and information you provide directly to us via email, customer support, social media, or another support channel (such as Twitter or Discord), or when you participate in any surveys or questionnaires.

6\. Biographical information. If you apply for a job with us, we collect all information provided through our Jobs form, including name, email phone, work and immigration status, and any other resume, cover letter, or free form text you include.

7\. Information you specifically provide us. If you specifically provide us with information (such as your email address), we may use that information for the purposes described when you provide it to us. We will not attempt to link any information you provide to your wallet address, IP address, or other personal data. You do not need to provide us with any personal data to use the Services.

## How We Use Data

We use the data we collect in accordance with your instructions, including any applicable terms in our Terms of Service, and as required by law. We may also use data for the following purposes:

1\. Providing the Services. We use the data we collect to provide, maintain, customize and improve our Services and features of our Services.

2\. Customer support. We may use information to provide customer support for and answer inquiries about the Services.

3\. Safety and security. We may use data to protect against, investigate, and stop fraudulent, unauthorized, or illegal activity. We may also use it to address security risks, solve potential security issues such as bugs, enforce our agreements, and protect our users and Company.

4\. Legal compliance. We may use the information we collect as needed or requested by regulators, government entities, and law enforcement to comply with applicable laws and regulations.

5\. Aggregated data. We may use some of the information we collect or access to compile aggregated data that helps us learn more about how users use the Services and where we can improve your experience.

How We Share Data

We may share or disclose the data we collect:

1\. With service providers. We may share your information with our service providers and vendors to assist us in providing, delivering, and improving the Services.

2\. To comply with our legal obligations. We may share your data in the course of litigation, regulatory proceedings, compliance measures, and when compelled by subpoena, court order, or other legal procedure. We may also share data when we believe it is necessary to prevent harm to our users, our Company, or others, and to enforce our agreements and policies, including our Terms of Service.

3\. Safety and Security. We may share data to protect against, investigate, and stop fraudulent, unauthorized, or illegal activity. We may also use it to address security risks, solve potential security issues such as bugs, enforce our agreements, and protect our users, Company, and ecosystem.

4\. Business changes. We may transfer or share data to another entity in the event of a merger, acquisition, bankruptcy, dissolution, reorganization, asset or stock sale, or other business transaction.

5\. With your consent. We may share your information any other time you provide us with your consent to do so.

We do not share your information with any third parties for any marketing purposes whatsoever.

Third Party Cookies

We use services provided by Google and other third parties that use tracking technology such as cookies, deviceID, and localStorage, to collect information about your use of the Services and our interactions with you. You can opt out of having your online activity and device data collected through these third-party services, including by:

1\. Blocking cookies in your browser by following the instructions in your browser settings. For more information about cookies, including how to see the cookies on your device, manage them, and delete them, visit [www.allaboutcookies.org](http://www.allaboutcookies.org).

2\. Blocking or limiting the use of your advertising ID on your mobile device through the device settings.

3\. Using privacy plug-ins or browsers. Certain browsers and browser extensions can be configured to block third-party cookies and trackers.

4\. Using the platform opt-out provided by Google at <https://adssettings.google.com>. You can learn more about how Google uses your information by reviewing Google’s privacy policy at <https://policies.google.com/privacy>.

5\. Using advertising industry opt-out tools on each device or browser where you use the Services, available at <http://optout.aboutads.info> and [http://optout.networkadvertising.org.](http://optout.networkadvertising.org)

We may integrate technologies operated or controlled by other parties into parts of the Services. For example, the Services may include links that hyperlink to websites, platforms, and other services not operated or controlled by us. Please note that when you interact with these other parties, including when you leave the Site, those parties may independently collect information about you and solicit information from you. You can learn more about how those parties collect and use your data by consulting their privacy policies and other terms.

Security

We implement and maintain reasonable administrative, physical, and technical security safeguards to help protect data from loss, theft, misuse, unauthorized access, disclosure, alteration, and destruction. Nevertheless, transmission via the internet is not completely secure and we cannot guarantee the security of information about you. You are responsible for all of your activity on the Services, including the security of your blockchain network addresses, cryptocurrency wallets, and their cryptographic keys.

Age Requirements

The Services are intended for a general audience and are not directed at children. We do not knowingly receive personal information (as defined by the Provisions on Online Protection of Children’s Personal Information, the U.S. Children’s Privacy Protection Act, or “COPPA”) from children. If you believe we have received personal information about a child under the age of 18, please contact us at <https://twitter.com/dotswap\\_brc20>.

Additional Notice to California Residents (“CCPA Notice”)

The California Consumer Privacy Act of 2018 (“CCPA”) requires certain businesses to provide a CCPA Notice to California residents to explain how we collect, use, and share their personal information, and the rights and choices we offer California residents regarding our handling of their information.

1\. Privacy Practices. We do not “sell” personal information as defined under the CCPA. Please review the “Sharing and Disclosure of Information” section above for further details about the categories of parties with whom we share information.

2\. Privacy Rights. The CCPA gives individuals the right to request information about how we have collected, used, and shared your personal information. It also gives you the right to request a copy of any information we may maintain about you. You may also ask us to delete any personal information that we may have received about you. Please note that the CCPA limits these rights, for example, by prohibiting us from providing certain sensitive information in response to access requests and limiting the circumstances under which we must comply with a deletion request. We will respond to requests for information, access, and deletion only to the extent we are able to associate, with a reasonable effort, the information we maintain with the identifying details you provide in your request. If we deny the request, we will communicate the decision to you. You are entitled to exercise the rights described above free from discrimination.

3\. Submitting a Request. You can submit a request for information, access, or deletion to <https://twitter.com/dotswap\\_brc20>.

4\. Identity Verification. The CCPA requires us to collect and verify the identity of any individual submitting a request to access or delete personal information before providing a substantive response.

5\. Authorized Agents. California residents can designate an “authorized agent” to submit requests on their behalf. We will require the authorized agent to have a written authorization confirming their authority.

Disclosures for European Union Data Subjects

We process personal data for the purposes described in the section titled “How We Use Data” above. Our bases for processing your data include: (i) you have given consent to the process to us or our service provides for one or more specific purposes; (ii) processing is necessary for the performance of a contract with you; (iii) processing is necessary for compliance with a legal obligation; and/or (iv) processing is necessary for the purposes of the legitimate interested pursued by us or a third party, and your interests and fundamental rights and freedoms do not override those interests.

Your rights under the General Data Protection Regulations (“GDPR”) include the right to (i) request access and obtain a copy of your personal data, (ii) request rectification or erasure of your personal data, (iii) object to or restrict the processing of your personal data; and (iv) request portability of your personal data. Additionally, you may withdraw your consent to our collection at any time. Nevertheless, we cannot edit or delete information that is stored on a particular blockchain. Information such as your transaction data, blockchain wallet address, and assets held by your address that may be related to the data we collect is beyond our control.

To exercise any of your rights under the GDPR, please contact us at <https://twitter.com/dotswap\\_brc20>. We may require additional information from you to process your request. Please note that we may retain information as necessary to fulfill the purpose for which it was collected and may continue to do so even after a data subject request in accordance with our legitimate interests, including to comply with our legal obligations, resolves disputes, prevent fraud, and enforce our agreements.

Changes to this Policy

If we make material changes to this Policy, we will notify you via the Services. Nevertheless, your continued use of the Services reflects your periodic review of this Policy and other Company terms, and indicates your consent to them.

Contact Us

If you have any questions about this Policy or how we collect, use, or share your information, please contact us at <https://twitter.com/dots\\_wap>.


# Introduction

Welcome to the **Nexus Developer Documentation** — your gateway to building on the leading decentralized exchange infrastructure for **Bitcoin-native assets**.

***

## What is Nexus?

Nexus is a trustless, non-custodial trading protocol built specifically for the Bitcoin ecosystem. By leveraging **Partially Signed Bitcoin Transactions (PSBTs)**, **multi-signature wallets**, and **UTXO-based liquidity models**, Nexus empowers users to swap Bitcoin-native assets directly — without wrapped tokens, centralized custodians, or smart contracts.

At its core is **Nexus**, a coordination layer and liquidity aggregator that enables self-hosted market makers to contribute to a unified order flow while retaining full control of their funds.

***

## What Can Developers Do?

Nexus offers a robust, modular developer stack for integrating, building, and contributing to Bitcoin-native DeFi:

| Use Case                       | Description                                                                 |
| ------------------------------ | --------------------------------------------------------------------------- |
| **Run a Nexus Node**           | Set up your own node to act as a liquidity provider or custom market maker. |
| **Market Making API**          | Programmatically manage your liquidity intentions and trading strategies.   |
| **Swap Integration**           | Integrate swap capabilities into your dApp, wallet, or frontend.            |
| **Custom Protocol Extensions** | Build on top of Nexus primitives (e.g. LP pools, channels, limit orders).   |
| **Query APIs**                 | Access pool data, trading history, and swap quotes via open endpoints.      |

***

## Tools & Resources

* **Open-source SDKs** for JavaScript and TypeScript
* **RESTful APIs** for pool data, quotes, and swap generation
* **Dockerized node templates** for rapid Nexus deployment
* **Signature templates** for handling PSBT signing flows
* **GitBook Docs** for architecture, flows, and examples

***

## System Requirements

Running a Nexus node requires:

* A public IP address or domain
* A server or VPS with Docker installed
* Bitcoin Core node (recommended in pruned mode)
* Basic familiarity with JSON and HTTP APIs

***

## Join the Ecosystem

Whether you’re building a wallet, launching a token, or operating a market-making bot, Nexus provides the tools and primitives to innovate securely on Bitcoin. With a growing ecosystem and developer-first focus, we invite you to:

* Fork our open-source templates
* Launch your liquidity strategy
* Extend Nexus with your own logic
* Contribute to protocol improvement proposals

Telegram: <https://t.me/NexusGroup>

Discord: <https://discord.gg/HR8hksbcQs>


# Quickstart Guide

## Welcome

Welcome to the Nexus API documents, where you can find all the documentation you need. If the link you currently have does not work, you can always go to <https://www.dotswap.app/> to get the latest documentation address.

## Examples

Every module of this documentation will provide viable examples for Nexus's current process flow. Example execution methods include:

* **curl**, which you can copy to any place that can execute curl to see the results, like the terminal in Mac.
* **Test parameters**, which you can directly copy into the provided apifox documentation for online debugging. (Clicking on any document's interface will take you to the current interface's apifox documentation.)

## Global

* Test environment API prefix: <https://api-testnet4.dotswap.app>
* Production environment API prefix: <https://api.dotswap.app>

## Notes

1. The documentation will provide **TypeScript interfaces**. If there is a discrepancy with the Apifox parameters, the TypeScript parameters in this document will prevail.
2. The notes in each document should cover most of the problems you might encounter, please do not ignore them.
3. On Nexus, all interface BTC communication units are in **satoshis** (0.00000001 BTC). That is, **the backend returns satoshis and also receives in satoshis**.
4. The value of `fee_rate` must be greater than or equal to the priority level in the BTC [Mempool](https://mempool.space/). Access Mempool's fee rate interface 👉 [here](https://mempool.space/api/v1/fees/recommended)

*All examples provided in this document are for the test environment.*


# Version history

<kbd>**☀︎ Nexus V3.1.6 Update Summary**</kbd>

Release Date: January 7, 2026

1\. Maker/Taker Fast Trading Account

Supports Runes-to-Runes trading pairs.

2.Taker High-Frequency Trading (HFT) Account

Supports matching liquidity directly from funds held in the wallet (non-channel based).

<kbd>**☀︎ Nexus V3.0.10 Update Summary**</kbd>

Release Date: November 10, 2025

1\. Transaction Accounting Optimization

Refined the bookkeeping logic for transaction records, enabling more intuitive and accurate data reconciliation.

2.Historical Data Export Enhancements

Improved historical record downloads with finer precision and more detailed numerical retention in exported tables.

<kbd>**☀︎ Nexus V3.0.9 Update Summary**</kbd>

Release Date: November 4, 2025

1\. Pool Data Optimization

Added TVL market share, APR time-period filters, detailed earnings reports, and total dual-sided fee ratio for enhanced transparency and analysis.

2\. Market-Making Range Enhancements

Introduced range-level TVL, APR, and earnings details.

Historical range data will now remain visible even after 100% liquidity removal.

3\. Trading Record Improvements

Added transaction source, average order price, BTC market price tracking, and pool status before and after each swap.

4\. Liquidity Management Record Upgrades

Added detailed tracking for pool changes before and after actions, associated price ranges, and BTC market price records during operations.

5\. Data Export & Margin Display

Enabled filter-by-period exports for earnings, trading, and liquidity data.

Added a real-time margin balance display in the navigation bar for configured addresses.


# Introduction

**Nexus** is the **decentralized coordination engine** that powers **non-custodial, peer-to-peer swaps** on the Bitcoin network. Built with **Bitcoin-native primitives** like **PSBTs** and **multi-signature wallets**, Nexus enables **secure liquidity aggregation** and **automated trade execution** without relying on smart contracts.

**Nexus** acts as a **self-hosted gateway** for **liquidity providers**, **market makers**, and **integrators** to participate in the Nexus protocol in a **trustless** manner.

***

## **Key Features**

* **Bitcoin-Native Design**: Fully aligned with Bitcoin’s UTXO model and built on PSBT and native multisig standards.
* **Self-Hosted Node**: Developers run their own Nexus node to participate in liquidity provision, trade coordination, and signing.
* **Liquidity Curve API**: Market makers expose their bid/ask curves to the network via HTTP endpoints.
* **PSBT Signing Workflow**: Nexus supports automated threshold signing and validation of PSBTs for secure on-chain settlement.
* **Stateless Coordination**: Nexus does not store user funds or private keys. All activity is coordinated cryptographically.

***

## **System Architecture**

* **API Server**: Listens for incoming trade intents and curve queries.
* **Execution Engine**: Matches swap requests to available liquidity across multiple nodes.
* **Threshold Signing Service**: Coordinates multisig or MPC-based co-signing of PSBTs.
* **Bridge Layer**: Facilitates secure communication between the frontend interface and back-end liquidity providers.

***

## **Use Cases**

* **Run a Nexus Node**: Participate as a liquidity provider in the Nexus network.
* **Integrate Liquidity Intent Curves**: Connect your own pricing algorithms or market-making logic.
* **Develop Custom Frontends**: Leverage Nexus as a backend to power your own wallet, aggregator, or trading interface.

***

## **Getting Started**

* Visit the official GitHub repository for source code, configuration templates, and deployment scripts.
* Explore example integrations in our SDK library.
* Join the Nexus developer community on Discord for technical support.

***

**By running or integrating with Nexus, you help strengthen the decentralized liquidity fabric of Bitcoin. Let's build the future of Bitcoin-native finance together.**


# Important Notes

{% hint style="warning" %}
**Note:** This section is currently under development and may be incomplete.
{% endhint %}

1. All backend endpoints return and receive BTC amounts in **Satoshi** units. The frontend displays BTC amounts in **BTC** units.


# Deployment Guide

* [Preparation](/dotswap/developers/nexus-protocol/deployment-guide/preparation)
* [Server Firewall](/dotswap/developers/nexus-protocol/deployment-guide/server-firewall)
* [Node Deployment](/dotswap/developers/nexus-protocol/deployment-guide/node-deployment)
* [Safeheron Configuration](/dotswap/developers/nexus-protocol/deployment-guide/safeheron-configuration)
* [Start providing liquidity (CLMM)](https://github.com/DotSwap-Dev/dotswap-doc/blob/doc-en/en/nexus-dex/deployment-guide/start-providing-liquidity.md)


# Preparation

### 🔔 Two Wallets Required

You must prepare **TWO WALLETS** before deployment:

1. **Margin Wallet** - For margin operations and collateral management
2. **Trading Wallet** - For executing trades and market making operations

#### **Match Infomation for Each Wallet:**

**For Margin Wallet:**

* Wallet Address, to `DOTSWAP_ACCOUNT_ADDRESS`
* Private Key (Hex Format), to `DOTSWAP_ACCOUNT_PRIVATE_KEY`

**For Trading Wallet:**

* Mnemonic/Seed Phrase, to `MNEMONIC`

### Wallet Security Preparation

Security is paramount. You need **TWO** Bitcoin wallets that are fully under your control and supported by the Nexus protocol.

#### **Recommended Wallets:**

* UniSat Wallet
* Xverse Wallet

#### **Critical Information Backup:**

* **Mnemonic/Seed Phrase:** This is the only way to recover your entire wallet. Be sure to write it down by hand on a physical medium and store it in at least two absolutely secure, offline locations. **Never save or transmit your seed phrase in any digital format (screenshots, text files) on a networked device.**
* **Market Making Account Address:** You will need to designate one or more addresses for market making.
* **Hex Private Key for the Address:** The Nexus software requires this private key to sign transactions. Please export it strictly according to your wallet's tutorial and keep it as secure as your seed phrase.

### Server Infrastructure

Your Nexus node requires a stable server environment to run.

#### **Server Providers:**

It is recommended to use Amazon Web Services (AWS), Linode, or other reputable cloud service providers.

#### **Recommended Configuration:**

* **CPU:** 2 Cores
* **Memory (RAM):** 4 GB
* **Storage:** 40 GB
* **Operating System:** Ubuntu 20 (or newer) / CentOS 8 (or newer)
* **Network:** A stable public IPv4 connection.


# Server Firewall

### **Stage 1: Temporary Access for Initial Deployment**

#### **Purpose:**

To log in to the server and execute initial installation commands.

#### **Action:**

* In your cloud provider's firewall settings (e.g., AWS Security Group), add an inbound rule to allow SSH (TCP port 22) traffic from **your current public IP address**.
* **Security Tip:** This rule is temporary. Do not open the SSH port to all IPs (`0.0.0.0/0`), as this poses a significant security risk.

### **Stage 2: Configure Core Node Communication Port (17610)**

#### **Purpose:**

To allow your node to interact with the Nexus network and to allow you to access the management dashboard.

#### **Action:**

You need to add an inbound rule to allow TCP traffic to port `17610` from the following sources:

* **Source 1 (Protocol Communication):** `101.47.30.209/32` and `101.47.27.75/32`. These are the addresses for Nexus's core relay network. Your node must be able to receive instructions from these addresses to function correctly.
* **Source 2 (Personal Management):**`Your current public IP address`.This IP will be allowed to access port 17610 on your server`http://<Your-Server-IP>:17610`from your personal network.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(6).png" alt=""><figcaption></figcaption></figure>

### **Stage 3: Security Hardening (After Successful Deployment)**

#### **Purpose:**

To remove unnecessary public entry points and significantly enhance server security.

#### **Action:**

After you have confirmed that your node is deployed and running stably, you **must perform the following critical step**:

* **Remove SSH Access Rule:** Return to your firewall settings and **delete or disable** the rule allowing SSH (port 22) access that you created in Stage 1.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(2-1).png" alt=""><figcaption></figcaption></figure>

* **How to manage the server after closing SSH?** You will no longer connect via public SSH. Instead, you should **rely exclusively on the secure, in-browser management tools provided by your cloud provider** (e.g., AWS Session Manager, Linode Lish Console), which is the industry-recommended best practice.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(7).png" alt=""><figcaption></figcaption></figure>


# Node Deployment

### Deployment Methods Overview

This guide provides three deployment methods. If you are not sure which one to pick, start with **Method 1: One-Command Deployment**.

| Method                                                     | Best for                                                    | Trade-off                                                 |
| ---------------------------------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------- |
| **Method 1: One-Command Deployment (Recommended)**         | First-time deployment and fastest bootstrap                 | Less manual control                                       |
| **Method 2: Advanced Quick Deployment (Manual Variables)** | Fast deployment with explicit environment variable control  | Sensitive variables are handled directly in shell session |
| **Method 3: Manual Deployment**                            | Teams that need full control and manual review of each step | More setup time and manual work                           |

Before running any method, review [Preparation - Server Infrastructure](/dotswap/developers/nexus-protocol/deployment-guide/preparation#server-infrastructure).

### Method 1: One-Command Deployment (Recommended)

For a fast bootstrap, run:

```shell
curl -fsSL https://on.nexus/install.sh | bash
```

For a fast upgrade, run:

```shellscript
curl -fsSL https://on.nexus/install.sh | bash -s upgrade
```

{% hint style="info" %}
Run this command on your target server. For production environments, review the script before execution.
{% endhint %}

### Method 2: Advanced Quick Deployment (Manual Variables)

```shell
# Log in to the remote server
ssh root@xxx.xxx.xxx.xx
```

```shell
# See below for environment variable configuration requirements
export APP_ENV=test
# Network endpoint variables (configure according to APP_ENV):
# DOTSWAP_HOST, ORD_URL, NODES_BTC_NODE_CONFIG_HOST, NODES_BTC_NODE_CONFIG_USER, NODES_BTC_NODE_CONFIG_PASS, NODES_BTC_NODE_ZMQ_HOST
export DOTSWAP_ACCOUNT_ADDRESS=tb1qmlp2ghv2xfv6h2ypmg9gt58uhmegse6c3tyhzq
export DOTSWAP_ACCOUNT_PRIVATE_KEY_HEX=853ac0c5ba7f629c20a8df8a86ae98e18a47c1262502e8a6ad0d074f3c2cf1af
export MNEMONIC='trumpet ten limb stay exact seven digital verify chronic solve face syrup'
export POOLS_BTC_DOGGOTOTHEMOON=tb1qmlp2ghv2xfv6h2ypmg9gt58uhmegse6c3tyhzq
export POOLS_BTC_BILLIONDOLLARCAT=tb1q7qfcw03psf3tla59ahdazu2huh7vru27k24qnl,tb1pau57plr6p56984zq9xlku5ferak2jjux5ljzajlr4t6ks6lm989s6ph428
export SINGLE_LIQUIDITY_POOLS_BTC_USDCSTARKNETTEST=tb1qzn8v9g34zyqsuy2rqnk0nddyffcdgxznr6jqzu,tb1qf00w6ryyfcemvsejne2rhgdcnjl343yp6h4aux

# Taker config
export TAKER_MNEMONIC='trumpet ten limb stay exact seven digital verify chronic solve face syrup'
export TAKERS_BTC_DOGGOTOTHEMOON=tb1qf00w6ryyfcemvsejne2rhgdcnjl343yp6h4aux

# Optional: enable Safeheron MPC signer
export MPC_SIGNER=safeheron
# Safeheron detailed variables (SAFEHERON_*) are documented in:
# en/nexus-dex/deployment-guide/safeheron-configuration.md

curl -fsSL https://get.docker.com | bash -s docker
env | grep -E '^(POOLS_|TAKERS_|SINGLE_LIQUIDITY_POOLS_)' > .env
curl -fsSL https://on.nexus/docker-compose-v3.yml | docker compose -p dotswap-dex -f - up --wait --force-recreate --pull always
```

Use `sudo` only if your current user cannot run Docker commands directly.

{% hint style="info" %}
Remember to use your own address/private key/mnemonics
{% endhint %}

### Method 3: Manual Deployment

#### Docker Installation

The recommended way to deploy DOTSWAP DEX is using Docker. To install Docker, please refer to Docker's [Installation Guide](https://docs.docker.com/get-started/get-docker/). For questions regarding Docker installation, please refer to [Docker's Troubleshooting Guide](https://docs.docker.com/desktop/troubleshoot-and-support/troubleshoot/).

```shell
# Install Docker
curl -fsSL https://get.docker.com | bash -s docker
```

#### Get Deployment Script

Download the latest configuration file `docker-compose.yml` from [DOTSWAP](https://on.nexus/docker-compose-v3.yml).

#### Environment Variable Configuration

Before running DEX, you need to modify the following environment variables in `docker-compose.yml`:

* `APP_ENV`: Runtime environment. `test` maps to testnet4, `prod` maps to mainnet.
* `DOTSWAP_HOST`: Nexus API endpoint. Configure for both testnet4 and mainnet according to `APP_ENV`.
* `ORD_URL`: Ord service endpoint. Configure for both testnet4 and mainnet according to `APP_ENV`.
* `NODES_BTC_NODE_CONFIG_HOST`: Bitcoin node RPC endpoint (`host:port`). Configure for both testnet4 and mainnet according to `APP_ENV`.
* `NODES_BTC_NODE_CONFIG_USER`: Bitcoin node RPC username. Configure for both testnet4 and mainnet according to `APP_ENV`.
* `NODES_BTC_NODE_CONFIG_PASS`: Bitcoin node RPC password. Configure for both testnet4 and mainnet according to `APP_ENV`.
* `NODES_BTC_NODE_ZMQ_HOST`: Bitcoin node ZMQ endpoint (`tcp://host:port`). Configure for both testnet4 and mainnet according to `APP_ENV`.
* `MPC_SIGNER`: Signing backend. Use `local` (default, local private key), `fireblocks`, or `safeheron`.
* `DOTSWAP_ACCOUNT_ADDRESS`: The wallet address to register with Nexus as the Market Making Account.
* `DOTSWAP_ACCOUNT_PRIVATE_KEY_HEX`: The private key (hex) of the wallet address to register with Nexus, used to prove ownership of this address.
* `MNEMONIC`: The wallet mnemonic phrase for allowing the independent Nexus instance to sign transaction and provide liquidity.
* `POOLS_BTC_TOKEN`: The key is the names of the involved tokens in a trading pair, and the value is the address information for providing liquidity. For example:
  * To provide liquidity for BTC and DOG•GO•TO•THE•MOON, the environment variable is configured as `POOLS_BTC_DOGGOTOTHEMOON:addr`
  * If BTC and DOG•GO•TO•THE•MOON are provided liquidity from different addresses (e.g. you're using Xverse wallet), the environment variable is configured as `POOLS_BTC_DOGGOTOTHEMOON:addr1,addr2`
  * Multiple trading pairs can be configured, but one address can only be configured for one trading pair.
  * Note that Token names should not contain the • symbol.
* `SINGLE_LIQUIDITY_POOLS_BTC_TOKEN`: Single-sided liquidity pool address configuration. Supports one or two addresses (comma-separated). Example: `SINGLE_LIQUIDITY_POOLS_BTC_USDCSTARKNETTEST: addr1,addr2`
  * Do not use special symbols (such as `•`) in env variable names.
* `TAKER_MNEMONIC`: The wallet mnemonic phrase for allowing the independent Nexus instance to sign transaction and swap.
* `TAKERS_BTC_TOKEN`: Same like `POOLS_BTC_TOKEN`

If `MPC_SIGNER=safeheron`, see [Safeheron Configuration](/dotswap/developers/nexus-protocol/deployment-guide/safeheron-configuration) for the complete variable list and key format options (PEM content or file path).

**Configuration Example**

Pay attention to the indentation level of the YAML configuration to ensure it is correct. If the value of a configuration item is a multi-line string, use `|` or `>` correctly to maintain the format and follow YAML's indentation rules.

```dotenv
services:
  service:
    environment:
      APP_ENV: test
      DOTSWAP_ACCOUNT_ADDRESS: tb1qmlp2ghv2xfv6h2ypmg9gt58uhmegse6c3tyhzq
      DOTSWAP_ACCOUNT_PRIVATE_KEY_HEX: 853ac0c5ba7f629c20a8df8a86ae98e18a47c1262502e8a6ad0d074f3c2cf1af
      MNEMONIC: trumpet ten limb stay exact seven digital verify chronic solve face syrup
      POOLS_BTC_DOGGOTOTHEMOON: tb1qmlp2ghv2xfv6h2ypmg9gt58uhmegse6c3tyhzq
      POOLS_BTC_BILLIONDOLLARCAT: tb1q7qfcw03psf3tla59ahdazu2huh7vru27k24qnl,tb1pau57plr6p56984zq9xlku5ferak2jjux5ljzajlr4t6ks6lm989s6ph428
      SINGLE_LIQUIDITY_POOLS_BTC_USDCSTARKNETTEST: tb1qzn8v9g34zyqsuy2rqnk0nddyffcdgxznr6jqzu,tb1qf00w6ryyfcemvsejne2rhgdcnjl343yp6h4aux
      TAKER_MNEMONIC: trumpet ten limb stay exact seven digital verify chronic solve face syrup
      TAKERS_BTC_DOGGOTOTHEMOON: tb1qf00w6ryyfcemvsejne2rhgdcnjl343yp6h4aux
```

#### Start Service

Check the `docker-compose` version; it needs to be greater than `1.21.0`.

```shell
docker-compose -v
# docker-compose version 1.17.1 ❌
# or
docker compose version
# Docker Compose version v2.32.4 ✅
```

Execute the following command in the terminal to start DOTSWAP DEX:

```shell
# Execute in the command line
docker compose -f docker-compose.yml up --wait --pull always
# or 
docker-compose -f docker-compose.yml up --wait --pull always
```

**Access Service**

After successful startup, you can access it via [http://:17610](https://github.com/DotSwap-Dev/dotswap-doc/blob/doc-en/en/nexus-dex/deployment-guide/http:/%3CYour-Server-IP%3E:17610/README.md).

**Security Operations**

```shell
# Clear environment variables
unset APP_ENV
unset DOTSWAP_HOST
unset ORD_URL
unset NODES_BTC_NODE_CONFIG_HOST
unset NODES_BTC_NODE_CONFIG_USER
unset NODES_BTC_NODE_CONFIG_PASS
unset NODES_BTC_NODE_ZMQ_HOST
unset MPC_SIGNER
unset DOTSWAP_ACCOUNT_PRIVATE_KEY_HEX
unset MNEMONIC
unset TAKER_MNEMONIC

# Clear command history
history -c 
```

**Security Hardening**

After you have confirmed that your node is deployed and running stably, you **must perform the following critical step**:

* **Remove SSH Access Rule:** Return to your firewall settings and **delete or disable** the rule allowing SSH (port 22) access that you created in Stage 1.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(2-1).png" alt=""><figcaption></figcaption></figure>

* **How to manage the server after closing SSH?** You will no longer connect via public SSH. Instead, you should **rely exclusively on the secure, in-browser management tools provided by your cloud provider** (e.g., AWS Session Manager, Linode Lish Console), which is the industry-recommended best practice.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(7).png" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Never expose your private keys/mnemonics. And take the security of your server seriously.
{% endhint %}


# Safeheron Configuration

This page contains the full Safeheron MPC configuration for Nexus deployment.

## When to use

Set `MPC_SIGNER=safeheron` when you want signing to be handled by Safeheron instead of local private keys.

## Key passing mode

Safeheron RSA key fields support both:

* PEM content string
* local PEM file path

Recommended: use file paths (for example `/run/secrets/...`) and make sure those files are mounted and readable in your runtime environment.

## Required consistency

`DOTSWAP_ACCOUNT_ADDRESS` and all addresses in `POOLS_*`, `SINGLE_LIQUIDITY_POOLS_*`, and `TAKERS_*` should belong to the same Safeheron `accountKey + pubKey` derivation set. Otherwise, signing may fail.

## Variables (service runtime)

Set the following `SAFEHERON_*` variables in the running service environment:

* `MPC_SIGNER=safeheron`
* `SAFEHERON_BASE_URL`
* `SAFEHERON_SIGN_API_KEY`
* `SAFEHERON_SIGN_RSA_PRIVATE_KEY` (PEM content or file path)
* `SAFEHERON_SIGN_SAFEHERON_RSA_PUBLIC_KEY` (PEM content or file path)
* `SAFEHERON_ACCOUNT_API_KEY` (optional)
* `SAFEHERON_ACCOUNT_RSA_PRIVATE_KEY` (PEM content or file path, optional)
* `SAFEHERON_ACCOUNT_SAFEHERON_RSA_PUBLIC_KEY` (PEM content or file path, optional)
* `SAFEHERON_ACCOUNT_KEY`
* `SAFEHERON_PUB_KEY`

You can provide PEM content directly for RSA fields, but file paths are recommended for security.

## Example (docker-compose runtime environment mode)

If you edit `docker-compose.yml` environment entries directly, set:

```dotenv
services:
  service:
    environment:
      MPC_SIGNER: safeheron
      SAFEHERON_BASE_URL: https://api.safeheron.com
      SAFEHERON_SIGN_API_KEY: your-safeheron-sign-api-key
      SAFEHERON_SIGN_RSA_PRIVATE_KEY: /run/secrets/safeheron-sign-private.pem
      SAFEHERON_SIGN_SAFEHERON_RSA_PUBLIC_KEY: /run/secrets/safeheron-sign-public.pem
      SAFEHERON_ACCOUNT_API_KEY: your-safeheron-account-api-key
      SAFEHERON_ACCOUNT_RSA_PRIVATE_KEY: /run/secrets/safeheron-account-private.pem
      SAFEHERON_ACCOUNT_SAFEHERON_RSA_PUBLIC_KEY: /run/secrets/safeheron-account-public.pem
      SAFEHERON_ACCOUNT_KEY: your-safeheron-account-key
      SAFEHERON_PUB_KEY: your-safeheron-compressed-pubkey-hex
```

In this manual mode, RSA fields also support direct PEM content.


# Start providing liquidity (CLMM)


# Dual Sided

To add Dual-sided liquidity, you need to provide equal values of BTC and USDC•STARKNET.

### Visit liquidity management portal <a href="#h.8noeklgkd2lq" id="h.8noeklgkd2lq"></a>

1. Access your deployed node in the browser via port 17610. [Click here to learn how to deploy servers and nodes.](/dotswap/developers/nexus-protocol/deployment-guide)

   <kbd>For example:<http://54.86.132.8:17610/></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-6a16172e038c1e952507b53c23cbfbd5cc453d5e%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>
2. Connect your wallet

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2F6EmOco9Cv5Z7PbV3WVye%2Fimage.png?alt=media&amp;token=21c76ad7-c2ac-4f8e-a990-cf2273d9e637" alt=""><figcaption></figcaption></figure>
3. Input the initial price, then enter the amount, and view your LP income rate.

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FuJrBGLVRiXuWP85BOIpE%2Fimage.png?alt=media&amp;token=a78e841c-c8b1-4b12-91b9-c030f5094303" alt=""><figcaption></figcaption></figure>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FxDAodG8auIH0Zd1TRvlK%2Fimage.png?alt=media&amp;token=17aff8cd-225a-43f3-b6d3-51a721d5ea37" alt=""><figcaption></figcaption></figure>
4. Complete the wallet signature, and you will see your liquidity pool here.

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2F5vbkZenw8GUdCVicbNPo%2Fimage.png?alt=media&amp;token=a853d7e1-f8ba-419b-a4dd-35bd502e3ceb" alt=""><figcaption></figcaption></figure>
5. [Click here to begin Dual Sided Pool depoyment](/dotswap/developers/maker/dual-sided-pool/manage-pool)


# Single Sided

To add Single-sided liquidity, you can choose to provide either BTC or USDC•STARKNET individually.

### Visit liquidity management portal <a href="#h.8noeklgkd2lq" id="h.8noeklgkd2lq"></a>

1. Access your deployed node in the browser via port 17610. [Click here to learn how to deploy servers and nodes.](/dotswap/developers/nexus-protocol/deployment-guide)

   <kbd>For example:<http://54.86.132.8:17610/></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FncOzWIBoetIPKxU0Rq72%2Fimage.png?alt=media&amp;token=e81507b9-7ac3-4597-81b8-dc1756a66842" alt=""><figcaption></figcaption></figure>
2. Connect your wallet

   <kbd><mark style="color:red;">Please note that the deployment addresses for single-sided and Dual-sided are different.<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FExGttUwU67NSv202BVbK%2Fimage.png?alt=media&amp;token=58e72b5d-d82a-4f74-a0c5-25fe341f43ba" alt=""><figcaption></figcaption></figure>
3. You can choose different currencies to add single-sided liquidity.

   <kbd><mark style="color:red;">Please note that the addresses for deploying Single-sided liquidity for BTC and USDC are different.<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FWpUC4UCLj7d5wpmJVipD%2Fimage.png?alt=media&amp;token=9ceebca9-73fd-4736-8d29-e84753ae5dc8" alt=""><figcaption></figcaption></figure>
4. Input the initial price, then enter the amount, and view your LP income rate.

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FsyqngAqUBalAJmhOQhDA%2Fimage.png?alt=media&amp;token=c5b82ab5-21cf-489b-812a-b06e354d1f38" alt=""><figcaption></figcaption></figure>
5. Complete the wallet signature, and you will see your liquidity pool here.

   <kbd><mark style="color:red;">After the liquidity pool is automatically matched successfully, its status will change from "Matching" to "Matched".<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2F1aw3HamztnF49sy3GLlz%2Fimage.png?alt=media&amp;token=93afbabe-5e71-47e2-97cc-4f192a477f34" alt=""><figcaption></figcaption></figure>
6. [Click here to begin Single Sided Pool depoyment](/dotswap/developers/maker/single-sided-pool/manage-pool)


# Activate Fast Execution Account


# For Maker

By Turning on "The Fast Trading Account," Makers can achieve much faster transaction processing and enjoy much lower network fees.

1. Turn on "Activate".

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2F7NiiP1g0avsqXnSVI9oX%2Fimage.png?alt=media&amp;token=75c8f033-4af5-4dba-a9ff-1a2b93f4d52b" alt=""><figcaption></figcaption></figure>
2. Enter the amounts of BTC and USDC•STARKNET to authorize.

   <kbd><mark style="color:red;">BTC Maximum Allowance: 0.1218, USDC Maximum Allowance: 11300.39<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FtEmjRYt8iDGskFnXISFI%2Fimage.png?alt=media&amp;token=fd14921b-2c7f-47e6-9be0-3d94fcf001a8" alt=""><figcaption></figcaption></figure>
3. Complete the wallet signature.

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FO3F2i3rtU6CFJfXG6wNg%2Fimage.png?alt=media&amp;token=34153f6c-cf25-461f-9be0-78ebe828a4f8" alt=""><figcaption></figcaption></figure>
4. Wait for the status to change from Activating to Active.

   <kbd><mark style="color:red;">This process requires 2 on-chain confirmations.<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FIW1bJCjDuyV3Bc9bcDef%2Fimage.png?alt=media&amp;token=380157e8-453d-47fb-ae7f-375bef25af50" alt=""><figcaption></figcaption></figure>
5. [Click here to initiate Maker Fast Execution Account deployment.](/dotswap/developers/maker/dual-sided-pool/fast-execution-account)


# For Taker

By Turning on "The Fast Trading Account," Takers can achieve much faster transaction processing and enjoy much lower network fees.

1. Turn on "Activate".

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2F4ZVwHVjBeY89Uazllpq8%2Fimage.png?alt=media&amp;token=dccf66ba-8964-4d55-89f6-6096fb326aaf" alt=""><figcaption></figcaption></figure>
2. Enter the amounts of BTC and USDC•STARKNET to authorize.

   <kbd><mark style="color:red;">BTC Maximum Allowance: 0.1218, USDC Maximum Allowance: 11300.39<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FiL0cbCEXXstVdPELSld2%2Fimage.png?alt=media&amp;token=26899b6f-3bd1-4aac-a5ed-4b700234fc36" alt=""><figcaption></figcaption></figure>
3. Complete the wallet signature.

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FoC8tdOy5qbG7fzLcUGse%2Fimage.png?alt=media&amp;token=4645d1f5-c369-40bf-a785-00832ed50010" alt=""><figcaption></figcaption></figure>
4. Wait for the status to change from Activating to Active.

   <kbd><mark style="color:red;">This process requires 2 on-chain confirmations.<mark style="color:red;"></kbd>

   <figure><img src="https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2FstRUPQ7wllam2aHYvL1n%2Fimage.png?alt=media&amp;token=5cb90818-4ed2-46fb-9eb8-75095b583661" alt=""><figcaption></figcaption></figure>
5. [Click here to initiate Maker Fast Execution Account deployment.](/dotswap/developers/taker/fast-execution-account)


# Global


# Public Configuration

## GET /api/pool/clmm/config

> Global General Configuration

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"security":[],"paths":{"/api/pool/clmm/config":{"get":{"summary":"Global General Configuration","deprecated":false,"description":"","tags":[],"parameters":[{"name":"payer_address","in":"query","description":"","required":false,"schema":{"type":"string"}},{"name":"payer_asset_address","in":"query","description":"","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tick_spacing":{"type":"integer","title":"Tick spacing"},"last_traded_price":{"type":"string","title":"Latest market price"}},"required":["tick_spacing","last_traded_price"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

## POST /api/pool/clmm/get\_system\_message

> Get System Message Interface

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"security":[],"paths":{"/api/pool/clmm/get_system_message":{"post":{"summary":"Get System Message Interface","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{}},"payer_asset_address":{"type":"object","properties":{}}},"required":["payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string"},"message_id":{"type":"string"},"created_at":{"type":"integer"}},"required":["message","message_id","created_at"]},"description":"Whether there is automatic removal"}},"required":["items"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## GET /api/nonce

> Get Nonce

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/nonce":{"get":{"summary":"Get Nonce","deprecated":false,"description":"","tags":[],"parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"nonce":{"type":"string"}},"required":["nonce"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## POST /api/get\_address\_mod

> Check if Address is Taker or Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/get_address_mod":{"post":{"summary":"Check if Address is Taker or Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}},"required":["payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"mod":{"type":"string","description":"taker or maker"}},"required":["tick1","tick2","mod"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```


# Pools Bound to Address

## POST /api/pool/liquid/get\_address\_pools

> Valid pools bound to address

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"tags":[{"name":"DotSwap-ext Nexus Pool Management"},{"name":"DotSwap-ext Nexus Pool Management"}],"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"paths":{"/api/pool/liquid/get_address_pools":{"post":{"summary":"Valid pools bound to address","deprecated":false,"description":"","tags":["DotSwap-ext Nexus Pool Management"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}},"required":["payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"tick1_balance":{"type":"string"},"tick2_balance":{"type":"string"}},"required":["tick1","tick2","tick1_balance","tick2_balance"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```


# Query Pool Rate

This endpoint allows you to retrieve the current swap rate for a selected token and the total liquidity in the pool for that trading pair. Its main uses are:

* Displaying the swap rate to users
* Calculating the estimated amount obtainable from a swap

## POST /api/pool/liquid/liquid\_info

> Get Liquidity Pool Trading Pair Information

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"tags":[{"name":"dotswap-ext/info"}],"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"paths":{"/api/pool/liquid/liquid_info":{"post":{"summary":"Get Liquidity Pool Trading Pair Information","deprecated":false,"description":"","tags":["dotswap-ext/info"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]}},"required":["tick1","tick2"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick1_amount":{"type":"string"},"tick2_amount":{"type":"string"},"liquid_fee_buy_percent":{"type":"string","title":"Buy LP fee rate (a -> b)"},"liquid_fee_sell_percent":{"type":"string","title":"Sell LP fee rate (b -> a)"},"platform_fee_buy_percent":{"type":"string","title":"Buy platform fee rate (a -> b)"},"platform_fee_sell_percent":{"type":"string","title":"Sell platform fee rate (b -> a)"},"tick1_per_tick2":{"type":"string"},"tick2_per_tick1":{"type":"string"}},"required":["tick1","tick2","tick1_amount","tick2_amount","liquid_fee_buy_percent","liquid_fee_sell_percent","platform_fee_buy_percent","platform_fee_sell_percent","tick1_per_tick2","tick2_per_tick1"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

{% hint style="info" %}

1. If you receive a 'LiquidPair not found' error (code: 10180006), it indicates that no liquidity pool exists for this trading pair.
   {% endhint %}


# Maker


# Dual Sided Pool


# List Query

## Query History

You can use this endpoint to query the user's history of creating, adding, and removing liquidity from pools. The `txid` provided can be used to check the on-chain transaction status in the mempool.

## POST /api/pool/liquid/history

> Liquidity operation history

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"tags":[{"name":"DotSwap Nexus Pool History"}],"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"paths":{"/api/pool/liquid/history":{"post":{"summary":"Liquidity operation history","deprecated":false,"description":"","tags":["DotSwap Nexus Pool History"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"page":{"type":"integer"},"page_size":{"type":"integer"},"address":{"type":"string","title":"Ordinals address"},"tick1":{"type":"string"},"tick2":{"type":"string"},"coin_type_1":{"type":"string"},"coin_type_2":{"type":"string"}},"required":["page","page_size","tick1","coin_type_1","tick2","coin_type_2","address"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick1_amount":{"type":"string"},"tick2_amount":{"type":"string"},"op":{"type":"integer","title":"Operation","enum":[0,1,2]},"status":{"type":"integer","title":"Status","enum":[0,1,2,3,4,5,6,7]},"time_at":{"type":"integer","title":"Time"},"address":{"type":"string"},"order_id":{"type":"string"}},"required":["tick1","tick2","tick1_amount","tick2_amount","status","time_at","address","order_id","op"]}},"total":{"type":"integer"}},"required":["items","total"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

1. The list returns an array `txs`. The `txid` field within this array is the transaction hash, which can be used to query the transaction status. Any `status` other than `confirmed` means the transaction is unconfirmed.
2. When adding liquidity fails, the `refundable` field will be `true`, indicating that a refund is possible; otherwise, it will be `false`. {% endhint %}

Use this endpoint to query the history of swaps executed on Dotswap.

## POST /api/pool/liquid/swap\_histories

> Pair swap history

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"tags":[{"name":"DotSwap Nexus Pool History"}],"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"paths":{"/api/pool/liquid/swap_histories":{"post":{"summary":"Pair swap history","deprecated":false,"description":"","tags":["DotSwap Nexus Pool History"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"string"},"coin_type1":{"type":"string"},"tick2":{"type":"string"},"coin_type2":{"type":"string"},"page":{"type":"integer"},"page_size":{"type":"integer"}},"required":["tick1","coin_type1","tick2","coin_type2","page","page_size"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"protocol":{"type":"string"},"op":{"type":"string","description":"Swap"},"tick1":{"type":"string","description":"Token 1"},"tick1_amount":{"type":"string"},"tick1_order_total_amount":{"type":"string","description":"Order total amount"},"tick2":{"type":"string","description":"Token 2"},"tick2_amount":{"type":"string"},"tick2_order_total_amount":{"type":"string","description":"Order total amount"},"time_sec":{"type":"string","description":"Time"},"status":{"type":"string","enum":["0","1","2","3"]},"revenue":{"type":"string","description":"Pool income"}},"required":["tick1_amount","tick2_amount","protocol","tick1_order_total_amount","tick2_order_total_amount","revenue"]}},"total":{"type":"integer"}},"required":["items","total"]}},"required":["code","msg","data"]}}}}}}}}}
```

## Manage Pool

## POST /api/pool/clmm/manage\_list

> CLMM--Manage Pools

```json
{"openapi":"3.0.1","info":{"title":"后端接口","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"本地"}],"security":[],"paths":{"/api/pool/clmm/manage_list":{"post":{"summary":"CLMM--Manage Pools","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"page":{"type":"integer"},"page_size":{"type":"integer"},"address":{"type":"string","title":"默认ordi地址"}},"required":["page","page_size","address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"total":{"type":"integer"},"items":{"type":"array","items":{"type":"object","properties":{"liquidity_pools":{"type":"array","items":{"type":"object","properties":{"price_tick_lower":{"type":"integer"},"price_tick_upper":{"type":"integer"},"tick1_amount":{"type":"string"},"tick2_amount":{"type":"string"},"tick1_fee_income":{"type":"string"},"tick2_fee_income":{"type":"string"},"liquidity":{"type":"string"}},"required":["liquidity"]}},"overview":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"divisibility":{"type":"integer"},"icon":{"type":"string"}},"required":["coin_type","tick","token_id","divisibility","icon"]},"tick1_amount":{"type":"string"},"tick2_amount":{"type":"string"},"lp_buy_fee_per":{"type":"string"},"lp_sell_fee_per":{"type":"string"},"tick1_total_amount":{"type":"string"},"tick2_total_amount":{"type":"string"},"tick1_available_amount":{"type":"string"},"tick2_available_amount":{"type":"string"},"auto_removed":{"type":"boolean"},"last_traded_price":{"type":"string"},"total_tick1_fee_income":{"type":"string"},"total_tick2_fee_income":{"type":"string"}},"required":["tick1","tick2","tick1_amount","tick2_amount","lp_buy_fee_per","lp_sell_fee_per","tick1_total_amount","tick2_total_amount","tick1_available_amount","tick2_available_amount","auto_removed","last_traded_price","total_tick1_fee_income","total_tick2_fee_income"]}}}}},"required":["total","items"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## POST /api/pool/liquid/explorer

> Liquidity Pool List

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/liquid/explorer":{"post":{"summary":"Liquidity Pool List","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"page":{"type":"integer","title":"Current Page"},"page_size":{"type":"integer","title":"Items per Page"},"tick":{"type":"string","description":"search tokens"},"lp_reward_metric":{"type":"string","description":"LP Reward Period Filter 1d,7d,30d"},"volume_metric":{"type":"string","description":"Volume Period Filter 1d,7d,30d"},"apy_metric":{"type":"string","description":"APY Period Filter 1d,7d,30d"},"sort":{"type":"string","description":"tvl，volume，lp_reward"},"desc":{"type":"boolean"}},"required":["page","page_size","tick","lp_reward_metric","volume_metric","sort","desc","apy_metric"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tvl":{"type":"string","title":"TVL"},"volume":{"type":"string","title":"Volume"},"lp_reward":{"type":"string","title":"LP Rewards"},"lp_amount1":{"type":"string","title":"Token 1 Reward Amount"},"lp_amount2":{"type":"string","title":"Token 2 Reward Amount"},"apy":{"type":"string","title":"apy"}},"required":["tick1","tick2","tvl","volume","lp_reward","lp_amount1","lp_amount2","apy"]}},"total":{"type":"integer","title":"Total Amount"}},"required":["items","total"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## POST /api/simplelighting/get\_sl\_asset\_overview

> Get Account Details - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/get_sl_asset_overview":{"post":{"summary":"Get Account Details - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"mod":{"type":"string","description":"taker or maker"},"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"}},"required":["mod","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick":{"type":"string"},"wallet_balance":{"type":"integer"},"channel_balance":{"type":"string"},"wallet_balance_stat_points":{"type":"array","items":{"type":"object","properties":{"balance":{"type":"integer"},"record_time":{"type":"string"}},"required":["balance","record_time"]}}},"required":["tick","wallet_balance","channel_balance","wallet_balance_stat_points"]}}},"required":["items"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```

## POST /api/simplelighting/get\_sl\_asset\_balance\_stat

> Get Account Balance Chart - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/get_sl_asset_balance_stat":{"post":{"summary":"Get Account Balance Chart - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"mod":{"type":"string","description":"taker or maker"},"tick":{"type":"string"},"type":{"type":"string","enum":["1D","1d","7d","7D","30d","30D"]},"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"},"start_time":{"type":"integer"},"end_time":{"type":"integer"}},"required":["mod","tick","type","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"balance":{"type":"string"},"record_time":{"type":"string"}},"required":["balance","record_time"]}}},"required":["items"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```


# Manage Pool (CLMM)

Before submitting any signature-related request, first call `/api/nonce` to retrieve a fresh nonce for anti-replay.

## POST /api/pool/clmm/add

> CLMM - Add Liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"security":[],"paths":{"/api/pool/clmm/add":{"post":{"summary":"CLMM - Add Liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string","title":"Token"},"tick":{"type":"string","title":"Token name"},"token_id":{"type":"string","title":"Token ID"},"amount":{"type":"string","title":"Amount"}},"required":["coin_type","tick","token_id","amount"],"description":"Token 1"},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"amount":{"type":"string"}},"required":["coin_type","tick","token_id","amount"],"description":"Token 2"},"sig_info":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"},"signature":{"type":"string"},"sign_info":{"type":"string"}},"required":["address","public_key","signature","sign_info"]},"service_fee_buy_percentage":{"type":"string","description":"Buying, service fee rate from a to b, a decimal between 0 and 1, only for new pools"},"service_fee_sell_percentage":{"type":"string","description":"Selling, service fee rate from b to a, a decimal between 0 and 1, only for new pools"},"price_tick_lower":{"type":"integer","description":"Lower bound of price tick"},"price_tick_upper":{"type":"integer","description":"Upper bound of price tick"},"price":{"type":"integer","description":"Set price"},"unit_tick":{"type":"string"}},"required":["tick1","tick2","sig_info","service_fee_buy_percentage","service_fee_sell_percentage","price_tick_lower","price_tick_upper","price","unit_tick"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string"},"delta_x":{"type":"string","description":"Actual injected x"},"delta_y":{"type":"string","description":"Actual injected y"}},"required":["order_id","delta_x","delta_y"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## POST /api/pool/clmm/remove

> CLMM - Remove Liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Localhost"}],"security":[],"paths":{"/api/pool/clmm/remove":{"post":{"summary":"CLMM - Remove Liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick2":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"sig_info":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"},"signature":{"type":"string"},"sign_info":{"type":"string"}},"required":["address","public_key","signature","sign_info"]},"percent":{"type":"string","description":"Removal ratio, between 1 - 100"},"price_tick_lower":{"type":"integer"},"price_tick_upper":{"type":"integer"}},"required":["tick1","tick2","sig_info","percent","price_tick_lower","price_tick_upper"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string"}},"required":["order_id"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```


# Fast Execution Account

Before submitting any signature-related request, first call `/api/nonce` to retrieve a fresh nonce for anti-replay.

## POST /api/simplelighting/get\_sl\_config\_list

> Channel Aggregated Information List - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/get_sl_config_list":{"post":{"summary":"Channel Aggregated Information List - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"mod":{"type":"string","description":"taker or maker"},"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"}},"required":["mod","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"sum_init_amount_a":{"type":"integer"},"sum_init_amount_b":{"type":"integer"},"sum_channel_amount_a":{"type":"integer","description":"Channel balance"},"sum_channel_amount_b":{"type":"integer","description":"Channel balance"},"status":{"type":"string","enum":["opening","open","closeing","close"]}},"required":["sum_init_amount_a","sum_init_amount_b","tick_a","sum_channel_amount_a","sum_channel_amount_b","status","tick_b"]}}},"required":["items"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```

## POST /api/simplelighting/get\_open\_limit

> Get Channel Opening Restrictions - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/get_open_limit":{"post":{"summary":"Get Channel Opening Restrictions - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"mod":{"type":"string","description":"taker or maker"}},"required":["tick_a","tick_b","mod"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"not_found_pool":{"type":"boolean","description":"Pool not found on dotswap"},"limit_amount_a":{"type":"integer"},"limit_amount_b":{"type":"integer"},"btc_min_amount":{"type":"integer"},"runes_min_amount":{"type":"integer"},"channel_usage_rates":{"type":"integer"}},"required":["limit_amount_a","limit_amount_b","btc_min_amount","runes_min_amount","channel_usage_rates","not_found_pool"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}}}
```

## POST /api/simplelighting/open\_simple\_lighting

> Open Channel - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/open_simple_lighting":{"post":{"summary":"Open Channel - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_a_amount":{"type":"integer"},"tick_b_amount":{"type":"integer"},"mod":{"type":"string","description":"taker or maker"},"sign_info":{"properties":{"sign_info":{"type":"string"},"address":{"type":"string"},"public_key":{"type":"string"},"signature":{"type":"string"}},"required":["sign_info","address","public_key","signature"],"$ref":"#/components/schemas/SigInfo"}},"required":["tick_a","tick_b","mod","tick_a_amount","tick_b_amount","sign_info"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"success":{"type":"string"}},"required":["success"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"SigInfo":{"type":"object","properties":{"sign_info":{"type":"string"},"address":{"type":"string"},"public_key":{"type":"string"},"signature":{"type":"string"}},"required":["sign_info","address","public_key","signature"]}}}}
```

## POST /api/simplelighting/close\_simple\_lighting

> Manually Close Channel - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/close_simple_lighting":{"post":{"summary":"Manually Close Channel - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"mod":{"type":"string","description":"taker or maker"},"sign_info":{"$ref":"#/components/schemas/sigInfo"},"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"}},"required":["tick_a","tick_b","mod","sign_info","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"success":{"type":"string"}},"required":["success"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature information"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"}},"required":["sign_info","address","public_key","signature"]},"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```

## POST /api/simplelighting/get\_sl\_settle\_infos

> Get Settlement Information List - Maker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/simplelighting/get_sl_settle_infos":{"post":{"summary":"Get Settlement Information List - Maker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"},"mod":{"type":"string","description":"taker or maker"},"settle_type":{"type":"string"},"start_time":{"type":"string"},"end_time":{"type":"string"},"page":{"type":"string"},"page_size":{"type":"string"}},"required":["mod","page","page_size","settle_type","start_time","end_time","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type","token_id"]},"tick_b":{"type":"object","properties":{"tick":{"type":"string"},"coin_type":{"type":"string"},"token_id":{"type":"string"}},"required":["tick","coin_type","token_id"]},"address":{"type":"string"},"record_time":{"type":"integer"},"settle_type":{"type":"string","enum":["account_fee_charged","activate","deactivate","on_chain_settle","reset_allowance","reset_allowance_fail"]},"init_allowance_a":{"type":"integer","description":"Initial allowance value"},"init_allowance_b":{"type":"integer","description":"Initial allowance value"},"on_chain_fee":{"type":"integer","description":"On-chain fee"},"account_usage_fee_a":{"type":"integer","description":"Account usage fee for tick_a"},"account_usage_fee_b":{"type":"string","description":"Account usage fee for tick_b"},"pre_wallet_balance_a":{"type":"integer","description":"Wallet balance before operation for tick_a"},"pre_wallet_balance_b":{"type":"string","description":"Wallet balance before operation for tick_b"},"post_wallet_balance_a":{"type":"string","description":"Wallet balance after operation for tick_a"},"post_wallet_balance_b":{"type":"string","description":"Wallet balance after operation for tick_b"},"pre_channel_balance_a":{"type":"string","description":"Channel balance before operation for tick_a"},"pre_channel_balance_b":{"type":"string","description":"Channel balance before operation for tick_b"},"post_channel_balance_a":{"type":"string","description":"Channel balance after operation for tick_a"},"post_channel_balance_b":{"type":"string","description":"Channel balance after operation for tick_b"},"txid":{"type":"string"},"status":{"type":"string","enum":["success","pending","fail"]}},"required":["address","record_time","settle_type","init_allowance_a","init_allowance_b","on_chain_fee","account_usage_fee_a","pre_wallet_balance_a","pre_wallet_balance_b","post_wallet_balance_a","post_wallet_balance_b","pre_channel_balance_a","pre_channel_balance_b","post_channel_balance_a","post_channel_balance_b","status","tick_a","tick_b","txid","account_usage_fee_b"]}}},"required":["items"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```


# Single Sided Pool


# Manage Pool

This document provides a brief overview of single-sided pools and the related operation APIs.

## Covered APIs

* Get submission limits: `/api/pool/single/add_request_limit`
* Query available balance: `/api/pool/single/balance`
* Get network fee: `/api/pool/single/get_network_fee`
* Submit add-liquidity request: `/api/pool/single/add_liquidity`
* Update add-liquidity request: `/api/pool/single/update_liquidity`
* Cancel matching: `/api/pool/single/cancel`
* Remove liquidity: `/api/pool/single/remove`

## Prerequisites

1. Prepare address fields:

* `payer_address`: BTC address
* `payer_asset_address`: asset address (usually an Ordinals-compatible address, such as for ORDI/Runes assets)

2. Prepare the `sign_info` object:

* `address`
* `public_key`
* `sign_info`
* `signature`
* `nonce` (anti-replay, retrieve from `/api/nonce`)

3. Amount and precision conventions:

* Pass amount fields exactly as defined by each API (most are `string`).
* `price_tick_lower` and `price_tick_upper` define the price range boundaries.
* `unit_tick` defines the base unit for pricing.

4. Identifier convention:

* `pool_id` is passed as `string` in pool management APIs.

## Recommended Call Flow

1. Call `add_request_limit` to get submission constraints (minimum/maximum amount, fee settings, etc.).
2. Call `balance` to confirm available balance.
3. Call `add_liquidity` to submit the matching request.
4. Use `update_liquidity` or `cancel` when needed.
5. Only before calling `remove`, call `get_network_fee` to estimate on-chain cost for liquidity removal.

## Status Reference (Common Pool Statuses)

* `MATCHING`: currently matching
* `MATCHED`: matched
* `MATCHING_ONCHAIN`: matching on-chain in progress
* `REMOVING_LIQUIDITY`: liquidity removal in progress
* `REMOVED`: removed

Before update/cancel/remove operations, query the latest pool status and perform validation checks.

## API Details

## POST /api/pool/single/add\_request\_limit

> Get Add-Liquidity Submission Limits

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/add_request_limit":{"post":{"summary":"Get Add-Liquidity Submission Limits","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"tick_a":{"$ref":"#/components/schemas/tick"},"tick_b":{"$ref":"#/components/schemas/tick"}},"required":["payer_address","payer_asset_address","tick_b","tick_a"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"not_found_pool":{"type":"boolean","description":"DotSwap pool not found"},"tick_a_maximum_value":{"type":"string","description":"Maximum amount for tick_a"},"tick_b_maximum_value":{"type":"string","description":"Maximum amount for tick_b"},"tick_a_minimum_value":{"type":"string","description":"Minimum amount for tick_a"},"tick_b_minimum_value":{"type":"string","description":"Minimum amount for tick_b"},"channel_usage_rates":{"type":"integer","description":"Channel usage fee"},"real_channel_usage_rates":{"type":"number","description":"Effective channel usage fee percentage"}},"required":["tick_a_maximum_value","tick_b_maximum_value","tick_a_minimum_value","tick_b_minimum_value","channel_usage_rates","not_found_pool","real_channel_usage_rates"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## POST /api/pool/single/balance

> Query Available Balance

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/balance":{"post":{"summary":"Query Available Balance","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"address":{"type":"string","description":"Address to query"},"tick":{"type":"string","description":"Token name"},"coin_type":{"type":"string","description":"Token type"},"pool_id":{"type":"string","description":"Pool"}},"required":["address","tick","coin_type"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"balance":{"type":"string","description":"Balance excluding funds in matching"}},"required":["balance"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

## POST /api/pool/single/get\_network\_fee

> Get Estimated Network Fee

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/get_network_fee":{"post":{"summary":"Get Estimated Network Fee","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{}}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"network_fee":{"type":"string","description":"Network fee"}},"required":["network_fee"]}},"required":["code","msg","data"]}}}}}}}}}
```

## POST /api/pool/single/add\_liquidity

> Submit Add-Liquidity Request

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/add_liquidity":{"post":{"summary":"Submit Add-Liquidity Request","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"$ref":"#/components/schemas/tick","description":"Tick1 details"},"tick2":{"$ref":"#/components/schemas/tick","description":"Tick2 details"},"token":{"$ref":"#/components/schemas/tick","description":"Selected token"},"min_amount":{"type":"string","description":"Minimum amount"},"max_amount":{"type":"string","description":"Maximum amount"},"min_fee_rate":{"type":"string","description":"Minimum fee rate"},"sign_info":{"$ref":"#/components/schemas/sigInfo","description":"Signature data"},"price_tick_lower":{"type":"number","description":"Minimum price"},"price_tick_upper":{"type":"number","description":"Maximum price"},"unit_tick":{"type":"string","description":"Tick unit"}},"required":["tick1","max_amount","min_amount","token","tick2","sign_info","min_fee_rate","price_tick_lower","price_tick_upper","unit_tick"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"isSuccess":{"type":"boolean"}},"required":["isSuccess"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]},"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature info"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"},"nonce":{"type":"string","title":"Anti-replay nonce"}},"required":["sign_info","address","public_key","signature","nonce"]}}}}
```

## POST /api/pool/single/update\_liquidity

> Update Liquidity

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/update_liquidity":{"post":{"summary":"Update Liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"min_amount":{"type":"string","description":"Minimum amount"},"max_amount":{"type":"string","description":"Maximum amount"},"min_fee_rate":{"type":"string","description":"Minimum fee rate"},"pool_id":{"type":"string","description":"pool id"},"sign_info":{"$ref":"#/components/schemas/sigInfo","description":"Signature data"},"token":{"$ref":"#/components/schemas/tick","description":"Token to update"},"price_tick_lower":{"type":"number","description":"Minimum price"},"price_tick_upper":{"type":"number","description":"Maximum price"},"unit_tick":{"type":"string","description":"Tick unit"}},"required":["max_amount","min_amount","sign_info","min_fee_rate","pool_id","token","price_tick_upper","price_tick_lower","unit_tick"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"isSuccess":{"type":"boolean"}},"required":["isSuccess"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature info"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"},"nonce":{"type":"string","title":"Anti-replay nonce"}},"required":["sign_info","address","public_key","signature","nonce"]},"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## POST /api/pool/single/cancel

> Cancel Matching

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/cancel":{"post":{"summary":"Cancel Matching","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"pool_id":{"type":"string","description":"pool id"},"sign_info":{"$ref":"#/components/schemas/sigInfo","description":"Signature data"}},"required":["pool_id","sign_info"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"isSuccess":{"type":"boolean"}},"required":["isSuccess"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature info"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"},"nonce":{"type":"string","title":"Anti-replay nonce"}},"required":["sign_info","address","public_key","signature","nonce"]}}}}
```

## POST /api/pool/single/remove

> Remove Liquidity

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/remove":{"post":{"summary":"Remove Liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"pool_id":{"type":"string","description":"pool id"},"sign_info":{"$ref":"#/components/schemas/sigInfo","description":"Signature data"}},"required":["pool_id","sign_info"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"isSuccess":{"type":"boolean"}},"required":["isSuccess"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature info"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"},"nonce":{"type":"string","title":"Anti-replay nonce"}},"required":["sign_info","address","public_key","signature","nonce"]}}}}
```

## Error Handling and Retry Guidance

* Always check `code` and `msg` first, and only use `data` when the request succeeds.
* Show explicit error prompts for signature failures, nonce replay, and out-of-range parameters (minimum/maximum amount).
* For transient network issues and timeouts, use idempotent retries and avoid duplicate submissions for the same business intent.
* Before update/cancel/remove, re-fetch pool status and balance whenever possible.


# Records

This page documents record-related APIs for single-sided pools, including current assets/status and historical records.

## API Scope

* Manage single-sided pool pairs: `/api/pool/single/manage_list`
* Single-sided pool total assets: `/api/pool/single/total_assets`
* Current pool list and status: `/api/pool/single/pool_list`
* Single-sided pool operation history: `/api/pool/single/pool_history`
* Single-sided pool swap history: `/api/pool/single/swap_history`

## Current Assets and Status

## POST /api/pool/single/manage\_list

> Managed Liquidity Pool List

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/manage_list":{"post":{"summary":"Managed Liquidity Pool List","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"apy_metric":{"type":"string"}},"required":["payer_address","payer_asset_address","apy_metric"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"token":{"$ref":"#/components/schemas/tick","description":"Deposited token details"},"tick1":{"$ref":"#/components/schemas/tick","description":"Tick1 details"},"tick2":{"$ref":"#/components/schemas/tick","description":"Tick2 details"},"tick1_amount":{"type":"number","description":"Amount of Tick A in pool"},"tick2_amount":{"type":"number","description":"Amount of Tick B in pool"},"total_tick1_fee_income":{"type":"number","description":"Total fee income of Tick A"},"total_tick2_fee_income":{"type":"number","description":"Total fee income of Tick B"},"apr":{"type":"number","description":"Annualized yield"},"address":{"type":"string","description":"Address of the token"}},"required":["token","tick2","tick1","tick1_amount","tick2_amount","total_tick1_fee_income","total_tick2_fee_income","apr","address"]}},"total":{"type":"number"}},"required":["items","total"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## POST /api/pool/single/total\_assets

> Trade Settlement Total Assets

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/total_assets":{"post":{"summary":"Trade Settlement Total Assets","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}},"required":["payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick":{"$ref":"#/components/schemas/tick","description":"Tick details"},"wallet_balance":{"type":"integer","description":"Wallet balance"},"market_maker_balance":{"type":"string","description":"Market-making balance"},"wallet_balance_stat_points":{"type":"array","items":{"type":"object","properties":{"balance":{"type":"integer"},"record_time":{"type":"string"}},"required":["balance","record_time"]},"description":"Wallet balance trend"}},"required":["tick","wallet_balance","market_maker_balance","wallet_balance_stat_points"]}},"total":{"type":"number"}},"required":["items","total"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## POST /api/pool/single/pool\_list

> Joint Market-Making Pool List

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/pool_list":{"post":{"summary":"Joint Market-Making Pool List","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]},"payer_asset_address":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}},"required":["payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"token":{"$ref":"#/components/schemas/tick","description":"Deposited token"},"tick1":{"$ref":"#/components/schemas/tick","description":"Tick1 details"},"tick2":{"$ref":"#/components/schemas/tick","description":"Tick2 details"},"tick1_amount":{"type":"number","description":"Amount of Tick 1 in pool"},"tick2_amount":{"type":"number","description":"Amount of Tick 2 in pool"},"lp_fee_per":{"type":"string","description":"LP fee percentage"},"dotswap_fee_per":{"type":"string","description":"DotSwap service fee percentage"},"total_tick1_fee_income":{"type":"number","description":"Total fee income of Tick 1"},"total_tick2_fee_income":{"type":"number","description":"Total fee income of Tick 2"},"apy":{"type":"number","description":"Annualized yield"},"apr_1d":{"type":"string"},"apr_7d":{"type":"string"},"apr_30d":{"type":"string"},"status":{"type":"string","description":"Status: MATCHING | MATCHED | MATCHING_ONCHAIN | REMOVING_LIQUIDITY | REMOVED","enum":["MATCHING","MATCHED","MATCHING_ONCHAIN","REMOVING_LIQUIDITY","REMOVED"]},"time_ms":{"type":"number","description":"Timestamp"},"min_amount":{"type":"number","description":"Minimum amount"},"max_amount":{"type":"number","description":"Maximum amount"},"min_fee_rate":{"type":"number","description":"Minimum fee rate"},"pool_id":{"type":"string","description":"pool id"},"tx_id":{"type":"string","description":"tx id "},"price_tick_lower":{"type":"number","description":"Minimum price"},"price_tick_upper":{"type":"number","description":"Maximum price"},"unit_tick":{"type":"string","description":"Tick unit"},"matched_price_tick_lower":{"type":"number","description":"Matched minimum price"},"matched_price_tick_upper":{"type":"number","description":"Matched maximum price"}},"required":["token","tick2_amount","tick2","tick1","tick1_amount","total_tick1_fee_income","dotswap_fee_per","lp_fee_per","total_tick2_fee_income","time_ms","status","apy","min_amount","max_amount","min_fee_rate","pool_id","tx_id","apr_30d","apr_7d","apr_1d","matched_price_tick_upper","matched_price_tick_lower","unit_tick","price_tick_upper","price_tick_lower"]}},"total":{"type":"number"}},"required":["items","total"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## Historical Records

## POST /api/pool/single/pool\_history

> Pool History

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/pool_history":{"post":{"summary":"Pool History","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"page":{"type":"integer"},"page_size":{"type":"integer"},"type":{"type":"string","description":"Operation type"},"status":{"type":"string","description":"Status (Pending | Success | Failed | Rollback)"},"start_time":{"type":"integer"},"end_time":{"type":"integer"},"pool_id":{"type":"string"}},"required":["page","page_size","type","status","start_time","end_time","pool_id"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"total":{"type":"number"},"items":{"type":"array","items":{"type":"object","properties":{"pool_id":{"type":"string"},"type":{"type":"string","description":"Operation type: ADD | REMOVE | STOP_MATCHING | POOL_FEE_CHARGED"},"token":{"$ref":"#/components/schemas/tick","description":"Token type"},"tick1":{"$ref":"#/components/schemas/tick","description":"tick1"},"tick2":{"$ref":"#/components/schemas/tick","description":"tick2"},"lp_buy_fee_per":{"type":"string","description":"Effective fee rate a->b"},"lp_sell_fee_per":{"type":"string","description":"Effective fee rate b->a"},"btc_price":{"type":"string","description":"BTC price (USD)"},"wallet_balance_before_a":{"type":"string","description":"Wallet token A balance before operation"},"wallet_balance_before_b":{"type":"string","description":"Wallet token B balance before operation"},"wallet_balance_after_a":{"type":"string","description":"Wallet token A balance after operation"},"wallet_balance_after_b":{"type":"string","description":"Wallet token B balance after operation"},"pool_tokens_before_a":{"type":"string","description":"Pool token A balance before operation"},"pool_tokens_before_b":{"type":"string","description":"Pool token B balance before operation"},"pool_tokens_after_a":{"type":"string","description":"Pool token A balance after operation"},"pool_tokens_after_b":{"type":"string","description":"Pool token B balance after operation"},"your_pool_tokens_before_a":{"type":"string","description":"Your pool token A balance before operation"},"your_pool_tokens_before_b":{"type":"string","description":"Your pool token B balance before operation"},"your_pool_tokens_after_a":{"type":"string","description":"Your pool token A balance after operation"},"your_pool_tokens_after_b":{"type":"string","description":"Your pool token B balance after operation"},"status":{"type":"string","description":"Status"},"time_ms":{"type":"number","description":"Timestamp"},"tx_id":{"type":"string"},"order_address":{"type":"string","description":"Transaction address"},"min_amount":{"type":"number","description":"Minimum amount"},"max_amount":{"type":"number","description":"Maximum amount"},"min_fee_rate":{"type":"number","description":"Configured fee rate"},"price_tick_lower":{"type":"number","description":"Minimum price"},"price_tick_upper":{"type":"number","description":"Maximum price"},"unit_tick":{"type":"string","description":"Tick unit"},"matched_price_tick_lower":{"type":"number","description":"Matched minimum price"},"matched_price_tick_upper":{"type":"number","description":"Matched maximum price"}},"required":["pool_id","tick2","tick1","type","wallet_balance_before_a","btc_price","lp_buy_fee_per","wallet_balance_after_b","wallet_balance_after_a","wallet_balance_before_b","pool_tokens_after_a","pool_tokens_before_b","pool_tokens_before_a","time_ms","status","pool_tokens_after_b","your_pool_tokens_after_a","your_pool_tokens_before_b","your_pool_tokens_before_a","your_pool_tokens_after_b","order_address","tx_id","token","min_amount","max_amount","min_fee_rate","lp_sell_fee_per","matched_price_tick_upper","matched_price_tick_lower","unit_tick","price_tick_upper","price_tick_lower"]}}},"required":["total","items"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"tick":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}}
```

## POST /api/pool/single/swap\_history

> Trade History

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/api/pool/single/swap_history":{"post":{"summary":"Trade History","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"page":{"type":"integer"},"page_size":{"type":"integer"},"channel":{"type":"string","description":"Channel"},"status":{"type":"string","description":"Status (Pending | Success | Failed | Rollback)"},"start_time":{"type":"integer"},"end_time":{"type":"integer"},"pool_id":{"type":"integer"}},"required":["page","page_size","channel","status","start_time","end_time"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"settle_method":{"type":"string","description":"Settlement method","enum":["wallet","simple_lighting"]},"protocol":{"type":"string","description":"Type"},"op":{"type":"string","description":"Swap operation"},"tick1":{"type":"string","description":"Token 1"},"tick1_amount":{"type":"string"},"tick1_order_total_amount":{"type":"string","description":"Total order amount"},"tick2":{"type":"string","description":"Token 2"},"tick2_amount":{"type":"string"},"tick2_order_total_amount":{"type":"string","description":"Total order amount"},"time_ms":{"type":"string","description":"Timestamp (ms)"},"status":{"type":"string","description":"Status","enum":["Pending","Success","Failed","Rollback"]},"revenue":{"type":"string","description":"Pool revenue"},"channel":{"type":"string","description":"Channel"},"average_price":{"type":"string"},"platform_fee":{"type":"string"},"btc_price_usd":{"type":"string"},"benchmark_token":{"type":"string"},"settlement_address":{"type":"string"},"taker_fee":{"type":"string"},"tvl_before_swap":{"type":"string","description":"TVL before swap"},"tvl_after_swap":{"type":"string","description":"TVL after swap"},"single_side_from_balance_before_swap":{"type":"string","description":"Single-sided from account change before swap"},"single_side_to_balance_before_swap":{"type":"string","description":"Single-sided to account change before swap"},"single_side_from_balance_after_swap":{"type":"string","description":"Single-sided from account change after swap"},"single_side_to_balance_after_swap":{"type":"string","description":"Single-sided to account change after swap"},"single_side_tick_a_fee_income":{"type":"string","description":"Single-sided TickA fee income"},"single_side_tick_b_fee_income":{"type":"string","description":"Single-sided TickB fee income"},"from_balance_before_swap":{"type":"string","description":"From balance before swap"},"to_balance_before_swap":{"type":"string","description":"To balance before swap"},"from_balance_after_swap":{"type":"string","description":"From balance after swap"},"to_balance_after_swap":{"type":"string","description":"To balance after swap"},"address":{"type":"string","description":"Transaction address"},"pool_id":{"type":"string","description":"Poolid"}},"required":["op","tick1","tick2","time_ms","status","tick1_amount","tick2_amount","protocol","tick1_order_total_amount","tick2_order_total_amount","revenue","channel","settle_method","average_price","platform_fee","benchmark_token","btc_price_usd","settlement_address","taker_fee","tvl_before_swap","tvl_after_swap","single_side_from_balance_before_swap","single_side_to_balance_before_swap","single_side_from_balance_after_swap","single_side_to_balance_after_swap","single_side_tick_a_fee_income","single_side_tick_b_fee_income","from_balance_before_swap","to_balance_before_swap","from_balance_after_swap","to_balance_after_swap","address","pool_id"]}},"total":{"type":"integer"}},"required":["items","total"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```


# Taker


# List Query


# Fast Execution Account

Before submitting any signature-related request, first call `/api/nonce` to retrieve a fresh nonce for anti-replay.

## POST /taker/api/simplelighting/get\_open\_limit

> Get Channel Opening Restrictions - Taker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/simplelighting/get_open_limit":{"post":{"summary":"Get Channel Opening Restrictions - Taker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"mod":{"type":"string","description":"taker or maker"}},"required":["tick_a","tick_b","mod"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"not_found_pool":{"type":"boolean","description":"Pool not found on dotswap"},"limit_amount_a":{"type":"integer"},"limit_amount_b":{"type":"integer"},"btc_min_amount":{"type":"integer"},"runes_min_amount":{"type":"integer"},"channel_usage_rates":{"type":"integer"}},"required":["limit_amount_a","limit_amount_b","btc_min_amount","runes_min_amount","channel_usage_rates","not_found_pool"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}}}
```

## POST /taker/api/simplelighting/get\_sl\_config\_list

> Channel Aggregated Information List - Taker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/simplelighting/get_sl_config_list":{"post":{"summary":"Channel Aggregated Information List - Taker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"mod":{"type":"string","description":"taker or maker"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"},"payer_address":{"$ref":"#/components/schemas/addressInfo"}},"required":["mod","payer_asset_address","payer_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"}," msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"sum_init_amount_a":{"type":"integer"},"sum_init_amount_b":{"type":"integer"},"sum_channel_amount_a":{"type":"integer","description":"Channel balance"},"sum_channel_amount_b":{"type":"integer","description":"Channel balance"},"status":{"type":"string","enum":["opening","open","closeing","close"]}},"required":["sum_init_amount_a","sum_init_amount_b","tick_a","sum_channel_amount_a","sum_channel_amount_b","status","tick_b"]}}},"required":["items"]}},"required":["code"," msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```

## POST /taker/api/simplelighting/open\_simple\_lighting

> Open Channel - Taker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/simplelighting/open_simple_lighting":{"post":{"summary":"Open Channel - Taker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_a_amount":{"type":"integer"},"tick_b_amount":{"type":"integer"},"mod":{"type":"string","description":"taker or maker"},"sign_info":{"$ref":"#/components/schemas/sigInfo"}},"required":["tick_a","tick_b","mod","tick_a_amount","tick_b_amount","sign_info"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"success":{"type":"string"}},"required":["success"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature information"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"}},"required":["sign_info","address","public_key","signature"]}}}}
```

## POST /taker/api/simplelighting/close\_simple\_lighting

> Manually Close Channel - Taker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/simplelighting/close_simple_lighting":{"post":{"summary":"Manually Close Channel - Taker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"tick_b":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"mod":{"type":"string","description":"taker or maker"},"sign_info":{"$ref":"#/components/schemas/sigInfo"}},"required":["tick_a","tick_b","mod","sign_info"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"success":{"type":"string"}},"required":["success"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"sigInfo":{"type":"object","properties":{"sign_info":{"type":"string","title":"Signature information"},"address":{"type":"string","title":"Wallet address"},"public_key":{"type":"string","title":"Wallet public key"},"signature":{"type":"string","title":"Signature"}},"required":["sign_info","address","public_key","signature"]}}}}
```

## POST /taker/api/simplelighting/get\_sl\_settle\_infos

> Get Settlement Information List - Taker

```json
{"openapi":"3.0.1","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/simplelighting/get_sl_settle_infos":{"post":{"summary":"Get Settlement Information List - Taker","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"payer_address":{"$ref":"#/components/schemas/addressInfo"},"payer_asset_address":{"$ref":"#/components/schemas/addressInfo"},"mod":{"type":"string","description":"taker or maker"},"settle_type":{"type":"string"},"start_time":{"type":"string"},"end_time":{"type":"string"},"page":{"type":"string"},"page_size":{"type":"string"}},"required":["mod","page","page_size","settle_type","start_time","end_time","payer_address","payer_asset_address"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"tick_a":{"type":"object","properties":{"tick":{"type":"string"},"token_id":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type","token_id"]},"tick_b":{"type":"object","properties":{"tick":{"type":"string"},"coin_type":{"type":"string"},"token_id":{"type":"string"}},"required":["tick","coin_type","token_id"]},"address":{"type":"string"},"record_time":{"type":"integer"},"settle_type":{"type":"string","enum":["account_fee_charged","activate","deactivate","on_chain_settle","reset_allowance","reset_allowance_fail"]},"init_allowance_a":{"type":"integer","description":"Initial allowance value"},"init_allowance_b":{"type":"integer","description":"Initial allowance value"},"on_chain_fee":{"type":"integer","description":"On-chain fee"},"account_usage_fee_a":{"type":"integer","description":"Account usage fee for tick_a"},"account_usage_fee_b":{"type":"string","description":"Account usage fee for tick_b"},"pre_wallet_balance_a":{"type":"integer","description":"Wallet balance before operation for tick_a"},"pre_wallet_balance_b":{"type":"string","description":"Wallet balance before operation for tick_b"},"post_wallet_balance_a":{"type":"string","description":"Wallet balance after operation for tick_a"},"post_wallet_balance_b":{"type":"string","description":"Wallet balance after operation for tick_b"},"pre_channel_balance_a":{"type":"string","description":"Channel balance before operation for tick_a"},"pre_channel_balance_b":{"type":"string","description":"Channel balance before operation for tick_b"},"post_channel_balance_a":{"type":"string","description":"Channel balance after operation for tick_a"},"post_channel_balance_b":{"type":"string","description":"Channel balance after operation for tick_b"},"txid":{"type":"string"},"status":{"type":"string","enum":["success","pending","fail"]}},"required":["address","record_time","settle_type","init_allowance_a","init_allowance_b","on_chain_fee","account_usage_fee_a","pre_wallet_balance_a","pre_wallet_balance_b","post_wallet_balance_a","post_wallet_balance_b","pre_channel_balance_a","pre_channel_balance_b","post_channel_balance_a","post_channel_balance_b","status","tick_a","tick_b","txid","account_usage_fee_b"]}}},"required":["items"]}},"required":["code","msg","data"]}}},"headers":{}}}}}},"components":{"schemas":{"addressInfo":{"type":"object","properties":{"address":{"type":"string"},"public_key":{"type":"string"}},"required":["address","public_key"]}}}}
```


# Trade

The Nexus DEX provides three trading interfaces to accommodate different usage scenarios:

## 1. Two-Step Trading Process

For scenarios requiring quote confirmation before execution:

**Step 1: Get Quote** - Use `/taker/api/swap/quote` to obtain a price quote for your desired trading pair. This endpoint returns a `quote_id` along with detailed information about the exchange rate and amounts.

## POST /taker/api/swap/quote

> Taker Quote

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/swap/quote":{"post":{"summary":"Taker Quote","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Accept","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Host","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Connection","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"symbol":{"type":"string","description":"E.g.: runes-THIRD•THIRD•TEST•TEO/btc-BTC, the latter is the quote currency"},"side":{"type":"string","description":"buy/sell, if runes is at the front, it means buy runes or sell runes"},"quantity":{"type":"string","description":"Quantity"},"enable_channel":{"type":"boolean","description":"Whether to use channel payment"}},"required":["symbol","side","quantity","enable_channel"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"quote_id":{"type":"string"},"symbol":{"type":"string"},"from":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"amount":{"type":"string"}},"required":["coin_type","tick","token_id","amount"]},"to":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"amount":{"type":"string"}},"required":["coin_type","tick","token_id","amount"]},"price":{"type":"string"}},"required":["quote_id","symbol","from","to","price"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

**Step 2: Submit Trade** - Use `/taker/api/swap/submit` with the `quote_id` from step 1 to execute the trade. This allows you to review the quote before committing to the transaction.

## POST /taker/api/swap/submit

> Taker Submit Quote

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/swap/submit":{"post":{"summary":"Taker Submit Quote","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Accept","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Host","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Connection","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"quote_id":{"type":"string"},"fee_rate":{"type":"integer"},"slippage":{"type":"string"},"enable_channel":{"type":"boolean"}},"required":["quote_id","fee_rate","slippage","enable_channel"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string"},"tx_id":{"type":"string"}},"required":["order_id","tx_id"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## 2. Quick Trading

For streamlined trading without separate quote generation:

**Quick Trade** - Use `/taker/api/swap/quick` to get a quote and submit the trade in a single request. This endpoint combines both steps for faster execution when immediate trading is desired.

## POST /taker/api/swap/quick

> Taker Quick Trade

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"http://127.0.0.1:8090","description":"Local"}],"security":[],"paths":{"/taker/api/swap/quick":{"post":{"summary":"Taker Quick Trade","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Accept","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Host","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Connection","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"symbol":{"type":"string","description":"E.g.: runes-THIRD•THIRD•TEST•TEO/btc-BTC, the latter is the quote currency"},"side":{"type":"string","description":"buy/sell, if runes is at the front, it means buy runes or sell runes"},"quantity":{"type":"string","description":"Quantity"},"fee_rate":{"type":"integer"},"slippage":{"type":"string"},"enable_channel":{"type":"boolean","description":"Whether to use channel payment"}},"required":["symbol","side","quantity","enable_channel","fee_rate","slippage"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{}}}},"headers":{}}}}}}}
```


# Global


# Get All Tickers

### Get all tickers

Use this interface to obtain basic information of all tickers that has volume.

<mark style="color:green;">`GET`</mark> [/brc20swap/external/tickers](https://api.dotswap.app/brc20swap/external/tickers)

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

```bash
curl --location --request GET 'https://api.dotswap.app/brc20swap/external/tickers' \
--header 'Pragma: no-cache' \
--header 'Authorization;' \
--header 'User-Id;' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: api.dotswap.app' \
--header 'Connection: keep-alive'
```

{% endtab %}

{% tab title="Response" %}

```json
[
  {
    "ticker_id": "BTC/DOG•GO•TO•THE•MOON",
    "base_currency": "BTC",
    "quote_currency": "DOG•GO•TO•THE•MOON",
    "pool_id": "BTC/DOG•GO•TO•THE•MOON",
    "last_price": "11570090.3290543690443763",
    "base_volume": "5.0186155339877862",
    "quote_volume": "58065835.0550341132474145",
    "liquidity_in_usd": "1072493.0380577594696826811574292917793232"
  },
  {
    "ticker_id": "FB/PSYOPCAT:d1594975888bbd2a0935f0228a0634439436c1a5273690d73f555dc2b0df6a10_0",
    "base_currency": "FB",
    "quote_currency": "PSYOPCAT:d1594975888bbd2a0935f0228a0634439436c1a5273690d73f555dc2b0df6a10_0",
    "pool_id": "FB/PSYOPCAT:d1594975888bbd2a0935f0228a0634439436c1a5273690d73f555dc2b0df6a10_0",
    "last_price": "1941.8609354552722742",
    "base_volume": "19298.5866153690425442",
    "quote_volume": "37475171.457885125741771043",
    "liquidity_in_usd": "162917.8507894370648555614664980891114629"
  }
]
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
FB refers to [Fractal Bitcoin](https://www.fractalbitcoin.io/);

For Runes, BRC20, and ARC20, tickers are unique;

For CAT20, tickers are not unique, so we add token ID (genesis transaction hash followed by output index) to help distinguish them and display it as `ticker:tokenid` .
{% endhint %}


# Get Exchange Rate

> The interface and request parameters for querying token exchange rates are actually the same as those for adding liquidity to the pool.

Through the following interface, you can obtain the current exchange rate of the selected token and the total number of pools in the liquidity pool. The main purpose of this interface in the exchange process is to:

* Display the exchange rate to users
* Calculate the estimated amount that can be exchanged

{% openapi src="/files/uwBOhCZUE51HCr9ecFg4" path="/brc20swap/swap\_info" method="post" %}
[global.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-a3069d4dd3ee104fd54371bb6ae0d122d7d67108%2Fglobal.json?alt=media)
{% endopenapi %}

{% hint style="info" %}

1. If "LiquidPair no found" is prompted, it means that there is no liquidity pool for this token pair.
2. For RUNES, BRC20, and ARC20, the query interfaces are the same, but `send_coin_type` / `receive_coin_type` differ.

**\[2024.04.23 Update]** New: `address` is a required parameter. If the user is not logged in, default to '0'.
{% endhint %}


# Get Token List

{% openapi src="/files/uwBOhCZUE51HCr9ecFg4" path="/brc20swap/search\_ticks" method="post" %}
[global.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-a3069d4dd3ee104fd54371bb6ae0d122d7d67108%2Fglobal.json?alt=media)
{% endopenapi %}

Used to get the list of available tokens for swapping, adding liquidity, etc.

## Swapping

Used for swapping tokens.

Get the complete list of tokens available for swapping, i.e., all tokens that have liquidity pools.

* **usetype:** Use `swap`.

{% hint style="info" %}
**Note:** Only tokens with injected liquidity pools can be swapped.
{% endhint %}

#### Example

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

```json
{
    "page": 1,
    "page_size": 30,
    "keyword": "",
    "usetype": "swap",
    "coin_type": "runes"
}
```

{% endtab %}

{% tab title="cURL Example" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/search_ticks' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"page":1,"page_size":30,"keyword":"","usetype":"swap","coin_type":"runes"}' \
  --compressed
```

{% endtab %}
{% endtabs %}

## Swappable Tokens

Used to get the list of all tokens swappable with a selected token (tick1).

* **tick1:** The name of the selected token.
* **usetype:** Use `gettick2`.

**Example**

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

```typescript
{
    "page": 1,
    "page_size": 30,
    "keyword": "",
    "usetype": "gettick2",
    "coin_type": "runes",
    "tick1": "BTC"
}
```

{% endtab %}

{% tab title="cURL Example" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/search_ticks' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"page":1,"page_size":30,"keyword":"","usetype":"gettick2","coin_type":"runes","tick1":"BTC"}' \
  --compressed
```

{% endtab %}
{% endtabs %}

#### Adding Liquidity

Used to get the list of all tokens available for adding liquidity.

* **usetype:** Use `liquid`.

**Example**

{% tabs %}
{% tab title="Request Body" %}

```json
{
    "page": 1,
    "page_size": 30,
    "keyword": "", 
    "address": "",
    "usetype": "liquid",  
    "coin_type": "runes"
}
```

{% endtab %}

{% tab title="cURL Example" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/search_ticks' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://192.168.10.66:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://192.168.10.66:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"page":1,"page_size":30,"keyword":"","usetype":"liquid","coin_type":"runes"}' \
  --compressed
```

{% endtab %}
{% endtabs %}

## Important Notes:

{% hint style="info" %}
The query interface for RUNES, BRC20, and ARC20 is the same; only the `coin_type` is different.
{% endhint %}


# Data Queries

## Get Mining Points

This endpoint allows querying user liquidity pool shares (lp), mining points (integral), and other data.

{% openapi src="/files/qxt9tJVACipxto9671ZC" path="/brc20swap/manage\_liquid\_info" method="post" %}
[global.data.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-d5b8d0551d1e1d00f983a076657aabe2ca5a4e2c%2Fglobal.data.json?alt=media)
{% endopenapi %}

{% hint style="info" %}

1. The response includes a `protocol` field to indicate the type of pool (brc20, arc20).
   {% endhint %}

## Get Liquidity Change History

This endpoint allows querying the history of user operations related to creating, adding, and removing liquidity pools. The `txid` can be used to query the on-chain transaction status in the mempool.

{% openapi src="/files/qxt9tJVACipxto9671ZC" path="/brc20swap/liquid\_history" method="post" %}
[global.data.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-d5b8d0551d1e1d00f983a076657aabe2ca5a4e2c%2Fglobal.data.json?alt=media)
{% endopenapi %}

{% hint style="info" %}

1. The response includes an array `txs`, where the `txid` field represents the transaction hash for querying transaction status. A status other than `confirmed` indicates the transaction is unconfirmed.
   {% endhint %}

## Liquidity Pool Information List

This endpoint allows querying the Total Value Locked (TVL) of pools.

{% openapi src="/files/qxt9tJVACipxto9671ZC" path="/brc20swap/stat/trade\_info\_list" method="post" %}
[global.data.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-d5b8d0551d1e1d00f983a076657aabe2ca5a4e2c%2Fglobal.data.json?alt=media)
{% endopenapi %}

{% hint style="info" %}

1. Values returned with `_btc` are in BTC units; otherwise, values are in USD.
2. The TVL field includes `pool_locked_amount_btc` and `pool_locked_amount`.
   {% endhint %}

{% openapi src="/files/qxt9tJVACipxto9671ZC" path="/brc20swap/get\_liquid\_address" method="post" %}
[global.data.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-d5b8d0551d1e1d00f983a076657aabe2ca5a4e2c%2Fglobal.data.json?alt=media)
{% endopenapi %}

{% openapi src="/files/qxt9tJVACipxto9671ZC" path="/brc20swap/external/pool/apr" method="post" %}
[global.data.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-d5b8d0551d1e1d00f983a076657aabe2ca5a4e2c%2Fglobal.data.json?alt=media)
{% endopenapi %}


# Get Token Price

> You can use this interface to query the price of the corresponding token on Nexus

## POST /brc20swap/stat/tick\_price

> Get the price information of the token

```json
{"openapi":"3.0.1","info":{"title":"Default Module","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap Test"},{"url":"https://api.dotswap.app","description":"Swap Production"}],"security":[],"paths":{"/brc20swap/stat/tick_price":{"post":{"summary":"Get the price information of the token","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick":{"type":"string"},"coin_type":{"type":"string"}},"required":["tick","coin_type"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"btc_price":{"type":"string","description":"The BTC price corresponding to the token"},"usd_price":{"type":"string","description":"The US dollar price corresponding to the token"}},"required":["btc_price","usd_price"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```


# Spot Exchanges


# tickers

## tickers (Market Info)

> The /tickers endpoint provides 24-hour pricing and volume information on each market pair available on an exchange.

```json
{"openapi":"3.0.1","info":{"title":"后端接口","version":"1.0.0"},"servers":[{"url":"https://api.dotswap.app","description":"swap正式"},{"url":"https://test-api-proxy.ddpurse.com","description":"swap测试"}],"security":[],"paths":{"/dotswap/api/public/tickers":{"get":{"summary":"tickers (Market Info)","deprecated":false,"description":"The /tickers endpoint provides 24-hour pricing and volume information on each market pair available on an exchange.","tags":[],"parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"ticker_id":{"type":"string","description":"Identifier of a ticker with delimiter to separate base/target"},"base_currency":{"type":"string","description":"Symbol of  the base cryptoasset"},"target_currency":{"type":"string","description":"Symbol of the target cryptoasset"},"pool_id":{"type":"string","description":"pool unique ID"},"last_price":{"type":"string","description":"Last transacted price of base currency based on given target currency"},"base_volume":{"type":"string","description":"24 hour trading volume for the pair (unit in base)"},"target_volume":{"type":"string","description":"24 hour trading volume for the pair (unit in target)"},"liquidity_in_usd":{"type":"string","description":"Pool liquidity in USD"}},"required":["ticker_id","base_currency","target_currency","pool_id","last_price","base_volume","target_volume","liquidity_in_usd"]}}}},"headers":{}}}}}}}
```


# Trading


# Bitcoin Channel

## Commit

## POST /brc20swap/create\_deposit\_psbt

> Construct Bitcoin Channel commit PSBT

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/create_deposit_psbt":{"post":{"summary":"Construct Bitcoin Channel commit PSBT","deprecated":false,"description":"","tags":["dotswap/trading"],"parameters":[{"name":"Cookie","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string","title":"Token name"},"value":{"type":"string","title":"Commit amount"},"payer_pub_key":{"type":"string","title":"Wallet public key"},"payer_btc_addr":{"type":"string","title":"Wallet btc address","description":"Reserved for xverse wallets; pass the same address twice if using unisat"},"payer_ord_addr":{"type":"string","title":"Wallet ordinal address"},"fee_rate":{"type":"integer","title":"Fee rate"},"inscription_ids":{"type":"array","items":{"type":"string"},"title":"Transfer inscription","description":"Convenient for constructing psbt"},"  is_multi_sign_trade":{"type":"boolean","title":"Whether to commit to Bitcoin Channel"}},"required":["tick","value","payer_btc_addr","payer_ord_addr","fee_rate","inscription_ids","payer_pub_key","coin_type","  is_multi_sign_trade"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer","additionalProperties":false},"msg":{"type":"string","additionalProperties":false},"data":{"type":"object","properties":{"psbt":{"type":"string","title":"Base64 psbt","additionalProperties":false},"tx_size":{"type":"integer","title":"Tx size","additionalProperties":false},"ins_contain_sats":{"type":"integer","title":"Sum of input inscription satoshis","additionalProperties":false},"ToSignInputs":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer","title":"Vin index","additionalProperties":false},"type":{"type":"string","title":"Address type","description":"Ord: address for storing inscriptions btc: address for storing btc","additionalProperties":false}},"required":["index","type"]}}},"required":["psbt","ToSignInputs","tx_size","ins_contain_sats"]},"req_id":{"type":"string","additionalProperties":false}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

## POST /brc20swap/create\_deposit\_order\_by\_psbt

> Create commit order based on PSBT

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/create_deposit_order_by_psbt":{"post":{"summary":"Create commit order based on PSBT","deprecated":false,"description":"","tags":["dotswap/trading"],"parameters":[{"name":"Cookie","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"psbt":{"type":"string","title":"Signed psbt base64"},"tick":{"type":"string","title":"Btc/brc20 name"},"payer_ord_addr":{"type":"string","title":"Ordinal wallet address"},"inscription_ids":{"type":"array","items":{"type":"string"},"title":"Selected inscription id for brc20 commit"},"amount":{"type":"string","title":"Amount","description":"Used to construct records"},"fee_rate":{"type":"string","title":"Fee rate"},"is_multi_sign_trade":{"type":"boolean","title":"Whether to commit to Bitcoin Channel"}},"required":["psbt","tick","payer_ord_addr","amount","fee_rate","is_multi_sign_trade"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"receiver_addr":{"type":"string"},"order_id":{"type":"string"},"txid":{"type":"string"}},"required":["receiver_addr","order_id","txid"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

## POST /brc20swap/deposit\_records

> Commit records

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/deposit_records":{"post":{"summary":"Commit records","deprecated":false,"description":"","tags":["dotswap/trading"],"parameters":[{"name":"Accept","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Accept-Language","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Connection","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Origin","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Referer","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Dest","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Mode","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Site","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Wallet-Name","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Wallet-Ver","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua-mobile","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua-platform","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Host","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"address":{"type":"string"},"page":{"type":"integer"},"page_size":{"type":"integer"},"is_multi_sign_trade":{"type":"boolean","title":"Query Bitcoin Channel commit records"}},"required":["address","page","page_size"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"total":{"type":"integer"},"records":{"type":"array","items":{"type":"object","properties":{"record_type":{"type":"string"},"coin_type":{"type":"string"},"tick":{"type":"string"},"amount":{"type":"string"},"txid":{"type":"string"},"timestamp":{"type":"integer"},"progress":{"type":"string"}},"required":["record_type","coin_type","tick","amount","txid","timestamp","progress"]}}},"required":["total","records"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

## Reclaim

## POST /brc20swap/get\_trading\_withdraw\_psbt

> Construct Bitcoin Channel reclaim PSBT

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading_account"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/get_trading_withdraw_psbt":{"post":{"summary":"Construct Bitcoin Channel reclaim PSBT","deprecated":false,"description":"","tags":["dotswap/trading_account"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"coin_type":{"type":"string","title":"Brc20/arc20"},"tick":{"type":"string","title":"Brc20/arc20 tick"},"amount":{"type":"string","title":"Reclaim amount"},"payer_btc_address":{"type":"string","title":"BTC reclaim address"},"payer_ord_address":{"type":"string","title":"Ordinals reclaim address"},"user_public_key":{"type":"string","title":"btc:ord"},"fee_rate":{"type":"integer","title":"Fee rate"}},"required":["coin_type","tick","payer_btc_address","fee_rate","amount","user_public_key","payer_ord_address"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string","title":"Order id"},"psbt":{"type":"string","title":"Psbt awaiting user signature"}},"required":["psbt","order_id"]}},"required":["code","msg","data"]}}}}}}}}}
```

## POST /brc20swap/submit\_trading\_withdraw\_psbt

> Signed reclaim PSBT for Bitcoin Channel

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading_account"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/submit_trading_withdraw_psbt":{"post":{"summary":"Signed reclaim PSBT for Bitcoin Channel","deprecated":false,"description":"","tags":["dotswap/trading_account"],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"order_id":{"type":"string","title":"Order id"},"psbt":{"type":"string","title":"Signed psbt"},"is_base64":{"type":"boolean"}},"required":["order_id","psbt","is_base64"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"ID":{"type":"integer"},"OrderId":{"type":"string"},"FeeTxid":{"type":"string"},"FeeAmount":{"type":"integer"},"FeeReceiveAddr":{"type":"string"},"FeeRate":{"type":"integer"},"FeePayMethod":{"type":"string"},"Txid":{"type":"string"},"SenderAddr":{"type":"string"},"ReceiverAddr":{"type":"string"},"Amount":{"type":"string"},"CoinType":{"type":"string"},"Tick":{"type":"string"},"Status":{"type":"string"},"ErrMsg":{"type":"string"},"CreatedAtSec":{"type":"integer"},"UpdatedAtSec":{"type":"integer"}},"required":["ID","OrderId","FeeTxid","FeeAmount","FeeReceiveAddr","FeeRate","FeePayMethod","Txid","SenderAddr","ReceiverAddr","Amount","CoinType","Tick","Status","ErrMsg","CreatedAtSec","UpdatedAtSec"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

## POST /brc20swap/withdraw\_records

> Reclaim records

```json
{"openapi":"3.0.1","info":{"title":"Backend endpoints","version":"1.0.0"},"tags":[{"name":"dotswap/trading"}],"servers":[{"url":"https://api.dotswap.app","description":"Swap main"},{"url":"https://api-testnet4.dotswap.app","description":"Swap test"}],"paths":{"/brc20swap/withdraw_records":{"post":{"summary":"Reclaim records","deprecated":false,"description":"","tags":["dotswap/trading"],"parameters":[{"name":"Accept","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Accept-Language","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Connection","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Origin","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Referer","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Dest","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Mode","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Sec-Fetch-Site","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Wallet-Name","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Wallet-Ver","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua-mobile","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"sec-ch-ua-platform","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Host","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"address":{"type":"string"},"page":{"type":"integer"},"page_size":{"type":"integer"},"is_multi_sign_trade":{"type":"boolean","title":"Query Bitcoin Channel reclaim records"}},"required":["address","page","page_size"]}}}},"responses":{"200":{"description":"Success","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"total":{"type":"integer"},"records":{"type":"array","items":{"type":"object","properties":{"record_type":{"type":"string"},"coin_type":{"type":"string"},"tick":{"type":"string"},"amount":{"type":"string"},"txid":{"type":"string"},"timestamp":{"type":"integer"},"progress":{"type":"string"}},"required":["record_type","coin_type","tick","amount","txid","timestamp","progress"]}}},"required":["total","records"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}}}}}}}}
```

{% hint style="warning" %}
Note: For all the endpoints related to the Bitcoin Channel mentioned above, the parameter `is_multi_sign_trade` must be set to `true`.
{% endhint %}


# CCXT Compatibility

## GET /dotswap/api/fetch\_currencies

> Fetch Currencies List

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap Testing Environment"},{"url":"https://api.dotswap.app","description":"Swap Production Environment"}],"security":[],"paths":{"/dotswap/api/fetch_currencies":{"get":{"summary":"Fetch Currencies List","deprecated":false,"description":"","tags":[],"parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"[token]":{"type":"object","properties":{"id":{"type":"string"},"code":{"type":"string"},"precision":{"type":"integer","description":"Minimum precision"},"name":{"type":"string"},"fee":{"type":"integer"},"active":{"type":"boolean"},"deposit":{"type":"boolean"},"withdraw":{"type":"boolean"},"numeric_id":{"type":"integer"},"type":{"type":"string"},"margin":{"type":"boolean"},"limits":{"type":"object","properties":{"amount":{"type":"object","properties":{}},"withdraw":{"type":"object","properties":{}}},"required":["amount","withdraw"]},"networks":{"type":"null"},"info":{"type":"null"}},"required":["id","code","precision","name","fee","active","deposit","withdraw","numeric_id","type","margin","limits","networks","info"]}},"required":["[token]"]},"req_id":{"type":"string"},"trace_id":{"type":"string"}},"required":["code","msg","data","req_id","trace_id"]}}},"headers":{}}}}}}}
```

## GET /dotswap/api/fetch\_markets

> Fetch Market Information

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap Testing Environment"},{"url":"https://api.dotswap.app","description":"Swap Production Environment"}],"security":[],"paths":{"/dotswap/api/fetch_markets":{"get":{"summary":"Fetch Market Information","deprecated":false,"description":"","tags":[],"parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"symbol":{"type":"string"},"base":{"type":"string"},"quote":{"type":"string"},"active":{"type":"boolean"},"type":{"type":"string"},"precision":{"type":"object","properties":{"amount":{"type":["number","integer"]},"price":{"type":["number","integer"]}},"required":["amount","price"]},"margin_modes":{"type":"object","properties":{"cross":{"type":"boolean"},"isolated":{"type":"boolean"}},"required":["cross","isolated"]},"limits":{"type":"object","properties":{"amount":{"type":"object","properties":{}},"cost":{"type":"object","properties":{}},"leverage":{"type":"object","properties":{}},"price":{"type":"object","properties":{}}},"required":["amount","cost","leverage","price"]}},"required":["id","symbol","base","quote","active","type","precision","margin_modes","limits"]}},"req_id":{"type":"string"},"trace_id":{"type":"string"}},"required":["code","msg","data","req_id","trace_id"]}}},"headers":{}}}}}}}
```

## GET /dotswap/api/fetch\_ticker

> Fetch Ticker Information

```json
{"openapi":"3.1.0","info":{"title":"","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap Testing Environment"},{"url":"https://api.dotswap.app","description":"Swap Production Environment"}],"security":[],"paths":{"/dotswap/api/fetch_ticker":{"get":{"summary":"Fetch Ticker Information","deprecated":false,"description":"","tags":[],"parameters":[{"name":"symbol","in":"query","description":"","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"symbol":{"type":"string"},"timestamp":{"type":"integer"},"datetime":{"type":"string"},"high":{"type":"number"},"low":{"type":"number"},"open":{"type":"number"},"close":{"type":"number"},"change":{"type":"number"},"average":{"type":"number"}},"required":["symbol","timestamp","datetime","high","low","open","close","change","average"]},"req_id":{"type":"string"},"trace_id":{"type":"string"}},"required":["code","msg","data","req_id","trace_id"]}}},"headers":{}}}}}}}
```


# WebSocket Streams

* The base URL for all WSS interfaces listed in this document is: `wss://ws.dotswap.app`
  * The testnet base URL is: `wss://test-api-proxy.ddpurse.com:28910`
* All streams can be accessed directly or as part of combined streams.
* Direct access URL format: `/ws/`
* Combined streams URL format: `/stream?streams=,,`
* When subscribing to combined streams, event payloads are wrapped in this format: `{"stream":"","data":}`
* Each connection to `ws.dotswap.app` has a validity period of no more than 24 hours. Please handle reconnection properly.
* All time and timestamp related fields use milliseconds as the default unit.

## Ticker by Symbol (Single Trading Pair)

**Stream Name**: @trade

```javascript
// Subscribe to DOTSWAP•DOTSWAP/BTC ticker

const wsDSBTC = new WebSocket("wss://ws.dotswap.app/ws/DOTSWAP•DOTSWAP/BTC@trade");

wsDSBTC.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log("DOTSWAP•DOTSWAP/BTC ticker:", data);
};
```

**Payload:**

```json
{
    "e": "trade", // Event type
    "E": 1763975983770, // Event time
    "s": "DOTSWAP•DOTSWAP/BTC", // Trading pair
    "p": "918.209", // Trade price
    "q": "1000", // Trade quantity
    "T": 1763975975000 // Trade time
}
```

## Ticker by Symbol (Multiple Trading Pairs)

**Stream Name**: @trade

```javascript
// Subscribe to DOTSWAP•DOTSWAP/BTC and DOG•GO•TO•THE•MOON/BTC tickers at once

const ws = new WebSocket(
"wss://ws.dotswap.app/stream?streams=DOTSWAP•DOTSWAP/BTC@trade,DOG•GO•TO•THE•MOON/BTC@trade"
);

ws.onmessage = (event) => {
    const message = JSON.parse(event.data);
    console.log("Received data:", message.stream, message.data);
};
```

**Payload:**

```json
{
"stream": "DOTSWAP•DOTSWAP/BTC@trade",
"data": {
  "e": "trade", // Event type
  "E": 1763975983770, // Event time
  "s": "DOTSWAP•DOTSWAP/BTC", // Trading pair
  "p": "918.209", // Trade price
  "q": "1000", // Trade quantity
  "T": 1763975975000 // Trade time
 }
}

```


# API Access

### Access Control

* When using the `/brc20swap/swap_info` interface, the access frequency must be 1 request every 5 seconds or longer.
* If the access frequency limit is violated, a `429` status code will be returned.
* Upon receiving a `429` status code, you are responsible for ceasing further requests and refraining from abusing the API.


# Swap V3

Version V3.0.0 introduces a swap interface that provides swap quotations and supports both AMM and CLMM liquidity pools.


# RUNES

## dotswap V3 Transaction request flow

<figure><img src="https://images.swap.dotwallet.com/web_restrict/ds_api/swap-flowchart.png" alt=""><figcaption></figcaption></figure>

## dotswap V3 Swap interface

## POST /dotswap/api/swap/quote

> aggregate and calculate Swap quotes

```json
{"openapi":"3.0.1","info":{"title":"backend interface","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap production"}],"security":[],"paths":{"/dotswap/api/swap/quote":{"post":{"summary":"aggregate and calculate Swap quotes","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"from_token":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"amount":{"type":"string","description":"When not needed, pass 0；"}},"required":["coin_type","tick"]},"to_token":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"},"amount":{"type":"string","description":"When not needed, pass 0；"}},"required":["coin_type","tick"]},"fee_rate":{"type":"integer","title":"network fee","description":"with a minimum of 1, used to filter pools with no available UTXOs."}},"required":["from_token","to_token","fee_rate"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"quote_id":{"type":"string","title":"Quote ID","description":"used for creating PSBT"},"from_amount":{"type":"string"},"to_amount":{"type":"string"},"swap_method":{"type":"string"},"pool_infos":{"type":"array","items":{"type":"object","properties":{"service_fee":{"type":"number"},"name":{"type":"string"},"third_party_id":{"type":"integer"},"third_party_address":{"type":"string"},"pool_id":{"type":"integer"},"third_pool_id":{"type":"integer"},"pool_url":{"type":"string"},"icon":{"type":"string"},"from_tick":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"to_tick":{"type":"object","properties":{"coin_type":{"type":"string"},"tick":{"type":"string"},"token_id":{"type":"string"}},"required":["coin_type","tick","token_id"]},"from_tick_address":{"type":"string"},"to_tick_address":{"type":"string"},"from_balance":{"type":"string"},"to_balance":{"type":"string"},"from_margin":{"type":"string"},"to_margin":{"type":"string"},"from_to_fee_ratio":{"type":"string"},"to_from_fee_ratio":{"type":"string"},"dex_margin_percent":{"type":"string"},"pool_type":{"type":"string"},"sqrt_price":{"type":"string"},"liquidity":{"type":"null"},"ServiceFeeRatio":{"type":"number"},"deltaAmount":{"type":"string"}}},"description":"There are different scenarios based on the swap_method, which is used to display the swap path."}},"required":["quote_id","from_amount","to_amount","swap_method","pool_infos"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

> Use this interface to obtain the available swap amount.
>
> For example, if you want to check how much `YKO•KKK•KKK•KKK•KKK` you can get for `0.1 BTC`, then set `from_token` to `btc` and `to_token` to `runes`. Input the value of `from_token.amount`, and the interface will return `to_amount`, which represents the amount of `YKO•KKK•KKK•KKK•KKK`.

{% hint style="info" %}
1、Please save the `quote_id` field from the current interface for use in subsequent requests.

2、Note that the `quote_id` is valid for 35 seconds. Please use it within the valid time; otherwise, you need to request a new one.
{% endhint %}

## POST /dotswap/api/swap/create\_psbt

> Aggregate and create Swap PSBT

```json
{"openapi":"3.0.1","info":{"title":"backend interface","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap production"}],"security":[],"paths":{"/dotswap/api/swap/create_psbt":{"post":{"summary":"Aggregate and create Swap PSBT","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"quote_id":{"type":"string","title":"Quote ID","description":"obtained from the calculation interface"},"fee_rate":{"type":"integer","title":"network fee","description":"with a minimum of 1, used for transaction construction."},"btc_address":{"type":"string"},"ord_address":{"type":"string"},"pubkey":{"type":"string"},"slippage":{"type":"integer"},"use_bitcoin_channel":{"type":"boolean"},"inscription":{"type":"array","items":{"type":"string","description":"Inscription ID，如90a78777e3635f392ca460e4422c9d92d20704d363a8ddbe09934f063a75a829i0"},"title":"array of inscription IDs","description":"required only for BRC20."}},"required":["btc_address","ord_address","pubkey","slippage","use_bitcoin_channel","inscription","quote_id","fee_rate"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"request_id":{"type":"string","title":"Request ID","description":"used for order submission"},"psbts":{"type":"array","items":{"type":"string"},"description":"PSBT to be signed"}},"required":["request_id","psbts"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

> 1、The `quote_id` in this interface is the return value obtained from the quotation interface.
>
> 2、Please set `use_bitcoin_channel` to `false` by default, and set `inscription` to an empty array `[]`.

{% hint style="info" %}
Note: The current interface returns a `psbts` array. If the `psbts` array contains more than 0 items, you need to use `signPsbts` for signing. Otherwise, use `signPsbt`.
{% endhint %}

## POST /dotswap/api/swap/submit\_psbt

> Aggregate and create a Swap order

```json
{"openapi":"3.0.1","info":{"title":"backend interface","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap production"}],"security":[],"paths":{"/dotswap/api/swap/submit_psbt":{"post":{"summary":"Aggregate and create a Swap order","deprecated":false,"description":"","tags":[],"parameters":[{"name":"Authorization","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Id","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"User-Agent","in":"header","description":"","required":true,"schema":{"type":"string"}},{"name":"Content-Type","in":"header","description":"","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"request_id":{"type":"string","title":"Request ID","description":"obtained from the PSBT creation"},"psbts":{"type":"array","items":{"type":"string"},"title":"Signed PSBT"},"psbt_is_base64":{"type":"boolean","title":"PSBT serialization type","description":"false:hex true:base64"}},"required":["psbts","request_id"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string"},"tx_id":{"type":"string"}},"required":["order_id","tx_id"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

> 1. The `request_id` is obtained from the `create_psbt` response.
> 2. Please set `psbt_is_base64` according to your signing result; by default, it is usually `false`.


# Swap V2

The V2.0.0 swap interface only supports AMM liquidity pools, and swap amount quotations must be calculated manually.


# Runes

## POST /brc20swap/get\_swap\_psbt2

> Get the unsigned PSBT for exchange

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/get_swap_psbt2":{"post":{"summary":"Get the unsigned PSBT for exchange","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"send_coin_type":{"type":"string","title":"The type of coin to send"},"send_tick":{"type":"string","title":"The tick of the coin to send"},"send_amount":{"type":"string","title":"The amount to send"},"receive_coin_type":{"type":"string","title":"The type of coin to receive"},"receive_tick":{"type":"string","title":"The tick of the coin to receive"},"receive_amount":{"type":"string","title":"The amount to receive"},"address":{"type":"string","title":"Address"},"slipper":{"type":"integer"},"fee_rate":{"type":"integer"},"user_public_key":{"type":"string"},"chl":{"type":"string"},"method":{"type":"string","description":"Non-cross-pool swap, cross-pool pools_swap, just pass 'pools_swap'"},"token":{"type":"string"},"btc_address":{"type":"string"}},"required":["receive_amount","receive_coin_type","receive_tick","send_amount","send_coin_type","send_tick","slipper","fee_rate","token","user_public_key","address","btc_address","chl"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string"},"psbt":{"type":"string"},"check_sign_only":{"type":"boolean"}},"required":["order_id","psbt","check_sign_only"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

#### Important Notes:

{% hint style="info" %}

1. After obtaining the unsigned PSBT, the user must sign it within 30 seconds.
2. Use the same address for both `btc_address` and `address`.
3. For `user_public_key`, provide the parameter as `public_key:public_key` for a wallet with one address, or `btc_public_key:ordi_public_key` for a wallet with two addresses.
4. The `token` must be retrieved from the `/swap-info` endpoint and can only be used once.
   {% endhint %}

## POST /brc20swap/send\_swap\_psbt

> Send the signed PSBT for exchange

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/send_swap_psbt":{"post":{"summary":"Send the signed PSBT for exchange","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"order_id":{"type":"string","title":"Order ID"},"psbt":{"type":"string","title":"Signed PSBT"}},"required":["order_id","psbt"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tx_id":{"type":"string","title":"The txid of the rawtx in PSBT"},"order_id":{"type":"string","title":"The corresponding order ID"},"need_show_task":{"type":"boolean"}},"required":["tx_id"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

After sending the signed PSBT, a successful response indicates that the swap was successful.

### Extending Signing Duration <a href="#extend-sign-duration" id="extend-sign-duration"></a>

If you are using a hardware wallet, the signing process might take longer. To help us identify it being a hardware wallet, you can add the following header to the API requests:

```
Wallet-Type: 'ledger' | 'software'
```

For example:

```javascript
config.headers["Wallet-Type"] = "ledger"; // Setting it to 'ledger' will extend the signing time, please use 'software' by default
```

{% tabs %}
{% tab title="cURL Example" %}

```bash
curl 'https://api.dotswap.app/brc20swap/send_swap_psbt' \
 -H 'Accept: application/json, text/plain, _/_' \
 -H 'Accept-Language: en' \
 -H 'Cache-Control: no-cache' \
 -H 'Connection: keep-alive' \
 -H 'Content-Type: application/json' \
 -H 'Pragma: no-cache' \
 -H 'Sec-Fetch-Dest: empty' \
 -H 'Sec-Fetch-Mode: cors' \
 -H 'Sec-Fetch-Site: cross-site' \
 -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \
 -H 'Wallet-Name: unisat' \
 -H 'Wallet-Type: software' \
 -H 'Wallet-Ver: 1.5.4' \
 -H 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \
 -H 'sec-ch-ua-mobile:?0' \
 -H 'sec-ch-ua-platform: "macOS"' \
 --data-raw '{"order_id":"swap_1071645262503477248","psbt":"70736274ff0100f302000000020a405df30d988160e1c3d3f046e7526e75a2522102e3a6b8dfbdb2fafe38df650600000000ffffffff90295f92edbbabe2ecb25d6f4eba74c91a930ebed4d6d51aac59eaf461328a110000000000ffffffff044a01000000000000225120e3552a2c24a4238a7344f655f04ceb0d14f381fbd9a4b90278d88257125444214a010000000000002251201447eda7459a2ab79ef45fc9173885d84b9604a746f7d2062eef08612536fa3500000000000000000d6a5d0a00c0a23303968ebd0e01e803000000000000225120c01dcf308ab6e8e0791741beda33a700406a94621eb9a1ee22bc95f3ea7bc1e0000000000001012bd20b0000000000002251201447eda7459a2ab79ef45fc9173885d84b9604a746f7d2062eef08612536fa3501084301414da5d08b5d44a76e600e41fb765d9eabe97c11d5bdeb3f2e61141567ac18bcfe1758f833591b24589e818deaa199a597b115cec9d04099c7a9fd2063532676fc010001012b4a01000000000000225120e3552a2c24a4238a7344f655f04ceb0d14f381fbd9a4b90278d8825712544421010304010000000000000000"}'
```

{% endtab %}
{% endtabs %}


# BRC20

When selecting a token pair and clicking swap, if it is a BRC20 token, a pre-swap request is required.

## POST /brc20swap/get\_swap\_psbt\_txsize

> Get the tx size of the PSBT-based exchange

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/get_swap_psbt_txsize":{"post":{"summary":"Get the tx size of the PSBT-based exchange","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"send_coin_type":{"type":"string","title":"The type of coin to send"},"send_tick":{"type":"string","title":"The tick of the coin to send"},"send_amount":{"title":"The amount to send","type":"string"},"receive_coin_type":{"type":"string","title":"The type of coin to receive"},"receive_tick":{"type":"string","title":"The tick of the coin to receive"},"receive_amount":{"type":"string","title":"The amount to receive"},"address":{"type":"string","title":"Address"},"slipper":{"type":"string","title":"Slippage"},"fee_rate":{"type":"integer","title":"Fee rate"},"ins":{"type":"array","items":{"type":"string"},"title":"Inscription ID","description":"Only needed when exchanging with BRC20"},"method":{"type":"string","description":"Non-cross-pool swap, cross-pool pools_swap, just pass 'pools_swap'"}},"required":["send_coin_type","send_tick","send_amount","receive_coin_type","receive_tick","receive_amount","address","fee_rate","slipper","ins","method"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tx_size":{"type":"integer","title":"PSBT tx size","description":"Pass the original value to the get_swap_psbt interface"},"ins_contain_sats":{"type":"integer","description":"The sum of satoshis in the input inscriptions"},"checksum":{"type":"string","description":"Pass the original value to the get_swap_psbt interface"},"vins":{"type":"array","items":{"type":"string"},"description":"Pass the original value to the get_swap_psbt interface"},"usr_cnt":{"type":"integer","description":"Pass the original value to the get_swap_psbt interface"}},"required":["tx_size","vins","usr_cnt"],"nullable":true}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

{% hint style="info" %}
Use the same address for both address and btc\_address.

The response from this endpoint should be passed as is to the get\_swap\_psbt endpoint.

The current slipper (slippage) limit is 12%.
{% endhint %}

## POST /brc20swap/get\_swap\_psbt

> Get the unsigned PSBT for BRC20 exchange

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/get_swap_psbt":{"post":{"summary":"Get the unsigned PSBT for BRC20 exchange","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"send_coin_type":{"type":"string","title":"The type of coin to send"},"send_tick":{"type":"string","title":"The tick of the coin to send"},"send_amount":{"title":"The amount to send","type":"string"},"receive_coin_type":{"type":"string","title":"The type of coin to receive"},"receive_tick":{"type":"string","title":"The tick of the coin to receive"},"receive_amount":{"type":"string","title":"The amount to receive"},"address":{"type":"string","title":"Address"},"slipper":{"type":"string"},"fee_rate":{"type":"integer"},"ins":{"type":"array","items":{"type":"string"},"description":"Only needed when exchanging with BRC20","title":"Inscription ID"},"user_public_key":{"type":"string"},"tx_size":{"type":"integer","description":"Obtained from the get_swap_psbt_txsize interface"},"checksum":{"type":"integer","description":"Obtained from the get_swap_psbt_txsize interface"},"vins":{"type":"array","items":{"type":"string"},"description":"Obtained from the get_swap_psbt_txsize interface"},"usr_cnt":{"type":"integer","description":"Obtained from the get_swap_psbt_txsize interface"},"chl":{"type":"string"},"method":{"type":"string","description":"Non-cross-pool swap, cross-pool pools_swap, just pass 'pools_swap'"}},"required":["send_coin_type","send_tick","send_amount","receive_coin_type","receive_tick","receive_amount","address","fee_rate","slipper","tx_size","checksum","vins","usr_cnt","user_public_key","ins","chl","method"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string","title":"PSBT tx size"},"psbt":{"type":"string"},"check_sign_only":{"type":"boolean"}},"required":["order_id","psbt","check_sign_only"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

> After a successful pre-swap request, obtain the unsigned PSBT. Some request parameters will be from the pre-swap response.

## Important Notes

{% hint style="info" %}

1. After obtaining the unsigned PSBT, the user must sign it within 30 seconds.
2. The `checksum` field should use the value from the previous request, even though the field name may differ.
3. Use the same address for both `btc_address` and `address`.
4. For `user_public_key`, provide the parameter as `public_key:public_key` for a wallet with one address, or `btc_public_key:ordi_public_key` for a wallet with two addresses.
   {% endhint %}

## POST /brc20swap/send\_swap\_psbt

> Send the signed PSBT for exchange

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/send_swap_psbt":{"post":{"summary":"Send the signed PSBT for exchange","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"order_id":{"type":"string","title":"Order ID"},"psbt":{"type":"string","title":"Signed PSBT"}},"required":["order_id","psbt"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"tx_id":{"type":"string","title":"The txid of the rawtx in PSBT"},"order_id":{"type":"string","title":"The corresponding order ID"},"need_show_task":{"type":"boolean"}},"required":["tx_id"]}},"required":["code","msg","data"]}}},"headers":{}}}}}}}
```

Finally, send the signed PSBT. If the response indicates success, the swap is successful.


# CAT20

For testnet, use: <https://test-api-proxy.ddpurse.com/>

For mainet, use: <https://api.dotswap.app/>

Here are the CAT20 API curl examples, will update the docs later:

## V1 deposit

<mark style="color:green;">`POST`</mark> [/brc20swap/create\_deposit\_cat20\_psbtv2](https://test-api-proxy.ddpurse.com/brc20swap/create_deposit_cat20_psbtv2)

Request a deposit transaction to be signed. Example

```
curl --location --request POST 'https://test-api-proxy.ddpurse.com/brc20swap/create_deposit_cat20_psbtv2' \
--header 'Pragma: no-cache' \
--header 'Wallet-Name: unisat' \
--header 'Wallet-Ver: 1.4.10' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: test-api-proxy.ddpurse.com' \
--header 'Connection: keep-alive' \
--data-raw '{
    "tick": "loadrun5:e57683b12e71734a1877bb3d52e0f78aaf99344ee59c82308252a64185dd473e_0",
    "payer_pub_key": "0334634a1d07f69123517540ec1d565fbd9b7775beacb93b41a7937374a06dd685",
    "payer_btc_addr": "bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs",
    "payer_ord_addr": "bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs",
    "fee_rate": 2,
    "coin_type": "cat20",
    "value": "1",
    "token_id": ""
}'
```

Returns PSBTs to be signed, example:

```
{
    "code": 0,
    "msg": "",
    "data": {
        "psbts": [
            {
                "psbt_base64": "cHNidP8BAIkCAAAAAfiYlFv9R8UyjDb6DXYApQZJZsAMSRVkra/JfCfa7HwKAQAAAAD/////AjYWAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZvqGgAAAAAAACJRIEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGbAAAAAAABAStVMgAAAAAAACJRIEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGbAQMEAQAAAAAAAA==",
                "sighash": "",
                "to_sign_inputs": [
                    {
                        "index": 0,
                        "leaf_hash": "",
                        "final_script_witness_length": 0,
                        "not_sign": false
                    }
                ]
            },
            {
                "psbt_base64": "cHNidP8BAKwCAAAAAUZhu1a2vm+9c8EjHTxbeiN+ZUqBXky2q86x08wDPs6eAAAAAAD/////AwAAAAAAAAAAGmoYY2F0AYt2aKBXmE7mcCscWMc+mVc2XKegSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/nETAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZsAAAAAAAEBKzYWAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZsBAwQBAAAAAAAAAA==",
                "sighash": "",
                "to_sign_inputs": [
                    {
                        "index": 0,
                        "leaf_hash": "",
                        "final_script_witness_length": 0,
                        "not_sign": false
                    }
                ]
            },
            {
                "psbt_base64": "cHNidP8BANMCAAAAA506iWPzg8wsV5hxpLkmwD6jzINDC0X6pgbmhXNcW4x/AgAAAAD/////yK2+44akFV53+y2IjivXYFDKlWncKTO/ovY2ppq4OAIBAAAAAP/////Irb7jhqQVXnf7LYiOK9dgUMqVadwpM7+i9jammrg4AgIAAAAA/////wIAAAAAAAAAABpqGGNhdAEoY8xKbazTrYFbBRzxvwFHH5/Sg0oBAAAAAAAAIlEg/a07DGY4ilCMcatXFDriKZMBrPjavB1snu2DmTkrpmsHAAAAAAEBK0oBAAAAAAAAIlEg/a07DGY4ilCMcatXFDriKZMBrPjavB1snu2DmTkrpmsAAQErSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/gABAStxEwAAAAAAACJRIEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGbAAAA",
                "sighash": "",
                "to_sign_inputs": [
                    {
                        "index": 0,
                        "leaf_hash": "cba48905c402c028a95be60fe3b6ff7c59502015e3081337c665c61bf4f1cc22",
                        "final_script_witness_length": 0,
                        "not_sign": false
                    },
                    {
                        "index": 1,
                        "leaf_hash": "",
                        "final_script_witness_length": 9500,
                        "not_sign": true
                    },
                    {
                        "index": 2,
                        "leaf_hash": "",
                        "final_script_witness_length": 0,
                        "not_sign": false
                    }
                ]
            }
        ],
        "leaf_script": "2079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817984c807bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c7bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179879be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179842f40a48df4b2a70c8b4924bf2654661ed3d95fd66a313eb87237597c628e4a031f40a48df4b2a70c8b4924bf2654661ed3d95fd66a313eb87237597c628e4a0310000225120426b76bd26cef82af8a3d4438700e42f693e3e40231d42810082c883f97f9ca322512052f5ec24681512889f765a3313b746a0e92b01df3f4e48404236906a1ff462fe01227901227901227901227901227901227901227901227901227901227901227901227901227901227960795e797e5d797e5c797e5b797e5a797e59797e58797e57797e56797e55797e54797e53797ea8011279787ea85279017f9f695279009c6301006752796878557952797e8801157955797e54798b7e6b6d6d6d6d6d6d6d6d6c775579ad011479011479011479011479011479011479011479011479011479011479012a790125795b795b795b795b795b795b790056766b796c756e7e777755766b796c756e7e777754766b796c756e7e777753766b796c756e7e777752766b796c756e7e777751766b796c756e7e7b756b6d6d6d6c77a852798855796e760087630100776876030000007e527987777777695479537978760087630100776876030000007e527987777777695b795b795b795b795b795b79565c797600a26976569f69948c766b796c756b6d6d6d6c547954797e886d6d6d6d6d6d5a795a795a795a795a795a790124795679567956795679567956790056766b796c756e827752797e7e777755766b796c756e827752797e7e777754766b796c756e827752797e7e777753766b796c756e827752797e7e777752766b796c756e827752797e7e777751766b796c756e827752797e7e7b756b6d6d6d6c77a878886d6d6d75016c79016c79016c79016c79016c79016c7901747901747978827701149d6e7ea9777701487901487901487901487901487901487956007600a26976569f69948c766b796c756b6d6d6d6c0115795879066a1863617401787e77527988577957795779577957795d79007657766b796c75a97e7d7756766b796c75a97e7d7755766b796c75a97e7d7754766b796c75a97e7d7753766b796c75a97e7d77a95279876b6d6d6d6c77695279587958795879587958795557798c7600a26976559f69948c766b796c756b6d6d756c886d6d6d6d755a5f797600a26976569f6994766b796c755d790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790153790132790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790131790116790116797e7601167901167901167901167901167901167955766b796c756b6d6d6d6c7e7d7701167901167901167901167901167901167954766b796c756b6d6d6d6c7e7d7701167901167901167901167901167901167953766b796c756b6d6d6d6c7e7d7701167901167901167901167901167901167952766b796c756b6d6d6d6c7e7d7701167901167901167901167901167901167951766b796c756b6d6d6d6c7e7d7701167901167901167901167901167901167900766b796c756b6d6d6d6c7e7d775f797e775f795f79885d795d795d795d795d795d7955766b796c756b6d6d6d6c58795879587958795879587955766b796c756b6d6d6d6c768277000113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7954766b796c756b6d6d6d6c58795879587958795879587954766b796c756b6d6d6d6c768277510113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7953766b796c756b6d6d6d6c58795879587958795879587953766b796c756b6d6d6d6c768277520113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7952766b796c756b6d6d6d6c58795879587958795879587952766b796c756b6d6d6d6c768277530113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7951766b796c756b6d6d6d6c58795879587958795879587951766b796c756b6d6d6d6c768277540113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7900766b796c756b6d6d6d6c58795879587958795879587900766b796c756b6d6d6d6c768277550113799f637052797e53797e7e547a7572537a537975686d787752797eaa6b6d6d6d6d6d6d6d6d6d6d6d6d6c88011979011979011979011979707e01007e787e6b6d6d6c012f79012f79012f79012f79012f79012f7956011d797600a26976569f69948c766b796c756b6d6d6d6c8801177901197978760087630100776876030000007e52798777777769011479011479011479011479011479011479011479011479011479011479011479011479011479011479011479011479011479011479011479007601147901147901147901147953766b796c756b6d6d6c7e7d7701147901147901147901147952766b796c756b6d6d6c7e7d7701147901147901147901147951766b796c756b6d6d6c7e7d7701147901147901147901147900766b796c756b6d6d6c7e775f795f79885d795d795d795d795d795d7955766b796c756b6d6d6d6c58795879587958795879587955766b796c756b6d6d6d6c768277000113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7954766b796c756b6d6d6d6c58795879587958795879587954766b796c756b6d6d6d6c768277510113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7953766b796c756b6d6d6d6c58795879587958795879587953766b796c756b6d6d6d6c768277520113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7952766b796c756b6d6d6d6c58795879587958795879587952766b796c756b6d6d6d6c768277530113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7951766b796c756b6d6d6d6c58795879587958795879587951766b796c756b6d6d6d6c768277540113799f637052797e53797e7e547a7572537a537975686d755d795d795d795d795d795d7900766b796c756b6d6d6d6c58795879587958795879587900766b796c756b6d6d6d6c768277550113799f637052797e53797e7e547a7572537a537975686d787752797eaa6b6d6d6d6d6d6d6d6d6d6d6c011a798858795879587958795879587956011e797600a26976569f69948c766b796c756b6d6d6d6c7653798778537987786476675168696d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d750167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790167790115790285007902850079012779012e79012e79012e79012e79012e79012e79012a79012a79012a79012a79012a79012a7901167901167901167901167901167901167901167956797657795779577957795779577955766b796c756b6d6d6d6c7e7d7757795779577957795779577954766b796c756b6d6d6d6c7e7d7757795779577957795779577953766b796c756b6d6d6d6c7e7d7757795779577957795779577952766b796c756b6d6d6d6c7e7d7757795779577957795779577951766b796c756b6d6d6d6c7e7d7757795779577957795779577900766b796c756b6d6d6d6c7e7d77a96b6d6d6d6d6c01177901117988765178a978557894000052799f637600a97e77685152799f637600a97e77685252799f637600a97e77685352799f637600a97e77685452799f637600a97e776877777ea9066a1863617401787e777777011f79011f79011f79011f7954007600a26976549f69948c766b796c756b6d6d6c885e7900a069011679011679011679011679011679011679560114797600a26976569f69948c766b796c756b6d6d6d6c5f799d0125790125790125790125790125790125790125790125790125790125790125790125795a795a798800597959795979597953766b796c756b6d6d6c567956795679567953766b796c756b6d6d6c768277005f799f637052797e53797e7e547a7572537a537975686d75597959795979597952766b796c756b6d6d6c567956795679567952766b796c756b6d6d6c768277515f799f637052797e53797e7e547a7572537a537975686d75597959795979597951766b796c756b6d6d6c567956795679567951766b796c756b6d6d6c768277525f799f637052797e53797e7e547a7572537a537975686d75597959795979597900766b796c756b6d6d6c567956795679567900766b796c756b6d6d6c768277535f799f637052797e53797e7e547a7572537a537975686d755c79787e52797eaa6b6d6d6d6d6d6d6c775d011b797600a26976569f6994766b796c7578011b797e8857011b797600a26976569f6994766b796c75012979886d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d75017479630173790173797ea901707988017179017379ad67016f795c0172797600a26976569f6994766b796c75a988686d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d6d7551",
        "control_block": "c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0",
        "leaf_version": 192,
        "total_fee": 5960
    },
    "req_id": "1846823544388632576"
}
```

Then pass it to:

<mark style="color:green;">`POST`</mark> [/brc20swap/create\_deposit\_cat20\_order\_by\_psbt](https://test-api-proxy.ddpurse.com/brc20swap/create_deposit_cat20_order_by_psbt)

```
curl 'https://test-api-proxy.ddpurse.com/brc20swap/create_deposit_cat20_order_by_psbt' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://test-fe.ddpurse.com:17510' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://test-fe.ddpurse.com:17510/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
  -H 'Wallet-Name: unisat' \
  -H 'Wallet-Ver: 1.4.10' \
  -H 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"psbts":["cHNidP8BAIkCAAAAAegkU6zVAAxsviXSWb6mGNOwHVX2AySEAeJFIfkJ7p+MAwAAAAD/////AvQXAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZtSAwAAAAAAACJRIEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGbAAAAAAABASt7HAAAAAAAACJRIEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGbAQMEAQAAAAETQZaCmTEOtBd/Cl1EuujuEAWBmuN5AqGTmPmmSYZNe3usDmlXSRdEPtH8V87uS/TUz8CBAnLgMosgISnxQkBmxn4BARcgNGNKHQf2kSNRdUDsHVZfvZt3db6suTtBp5NzdKBt1oUAAAA=","cHNidP8BAKwCAAAAAUqbMl+TYPsV5aYyVFD7PKL43N0FRJRcX78XlAwdDK5VAAAAAAD/////AwAAAAAAAAAAGmoYY2F0AV5GtuJo1v+Z6hRLWgEoM5DiojMFSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/i8VAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZsAAAAAAAEBK/QXAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZsBAwQBAAAAARNBoICjG8nV1t8da+n83HGtEO3xk4cnIAirZBln/t9mDNXepHXiujNnNXA1bQn4fBg4jQeKmaXFX2TH4rI3IDb4kwEBFyA0Y0odB/aRI1F1QOwdVl+9m3d1vqy5O0Gnk3N0oG3WhQAAAAA=","cHNidP8BAP3+AAIAAAADikqyRJ6tJk5SmiEqX/3nY2BhChnauKHQ0UkoXLnrhtoCAAAAAP////+1ggF3lm3F1+JADE/xRk/De5q9TWSvQTUYTLKXYEZHxwEAAAAA/////7WCAXeWbcXX4kAMT/FGT8N7mr1NZK9BNRhMspdgRkfHAgAAAAD/////AwAAAAAAAAAAGmoYY2F0AeSBe1SBu0pvZj53gpEYH++zs5EESgEAAAAAAAAiUSD9rTsMZjiKUIxxq1cUOuIpkwGs+Nq8HWye7YOZOSuma0oBAAAAAAAAIlEg/a07DGY4ilCMcatXFDriKZMBrPjavB1snu2DmTkrpmsAAAAAAAEBK0oBAAAAAAAAIlEg/a07DGY4ilCMcatXFDriKZMBrPjavB1snu2DmTkrpmtBFEjONwSNAgdma6Fz/wM83S5i2lgoHpZuoHEP7QsGovGby6SJBcQCwCipW+YP47b/fFlQIBXjCBM3xmXGG/TxzCJAqj5aMt65ZWQPidWrYZhmySZ7VuBkRJcnx7NO3P4JleCgZ4Ru8KG8sYVkCyA/m0jazO6+EbiZHrOUqvnEiT+kogABAStKAQAAAAAAACJRIFL17CRoFRKIn3ZaMxO3RqDpKwHfP05IQEI2kGof9GL+AAEBKy8VAAAAAAAAIlEgSM43BI0CB2ZroXP/AzzdLmLaWCgelm6gcQ/tCwai8ZsBE0CsvQw/OqO9posXId0RAw44CnenYwBRHCRF7IMK+1zkBmM1zEKuPecRGJqn13C0+SH10QiJ+iJgZ6H518729g6pARcgNGNKHQf2kSNRdUDsHVZfvZt3db6suTtBp5NzdKBt1oUAAAAA"],"tick":"loadrun5:e57683b12e71734a1877bb3d52e0f78aaf99344ee59c82308252a64185dd473e_0","pubkey":"0334634a1d07f69123517540ec1d565fbd9b7775beacb93b41a7937374a06dd685","payer_btc_addr":"bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs","payer_ord_addr":"bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs","amount":"1","fee_rate":2,"coin_type":"cat20"}'
```

## V1 Liquidity Adding

<mark style="color:green;">`POST`</mark> [/brc20swap/add\_liquid](https://test-api-proxy.ddpurse.com/brc20swap/add_liquid)

Works when you already have V1 balance (FB/BTC and CAT20). Example:

```
curl --location --request POST 'https://test-api-proxy.ddpurse.com/brc20swap/add_liquid' \
--header 'Pragma: no-cache' \
--header 'Wallet-Name: unisat' \
--header 'Wallet-Ver: 1.4.10' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: test-api-proxy.ddpurse.com' \
--header 'Connection: keep-alive' \
--data-raw '{
    "from_tick": "cat:ab308772bc00db30409bca72cec67bc708ea075455f4665fcfc91af03f52db87_0",
    "from_amount": "1",
    "to_amount": "5412597",
    "to_tick": "FB",
    "from_coin_type": "cat20",
    "to_coin_type": "fractal",
    "from_coin_icon_url" : "url",
    "to_coin_icon_url" : "url",
    "address": "bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs",
    "sig_info": {
        "address": "bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs",
        "public_key": "0334634a1d07f69123517540ec1d565fbd9b7775beacb93b41a7937374a06dd685",
        "sign_info": "Address: bc1pfr8rwpydqgrkv6apw0lsx0xa9e3d5kpgr6txagr3plkskp4z7xdsfqaqrs\n\n Add 1cat:ab308772bc00db30409bca72cec67bc708ea075455f4665fcfc91af03f52db87_0, 0.05412597 FB (estimated, actual amount may vary）into cat:ab308772bc00db30409bca72cec67bc708ea075455f4665fcfc91af03f52db87_0/ FB pool, estimated pool shares 50%, service fee income rate 0%（it will be added into the pool automatically）\n      \nTime: 2024-10-17 15:42:53\n\n Timestamp: 1729150973",
        "signature": "H9PStfpgo9hIaBWKmkhYGliLk6LV1SuCiCacTFFIxEB4Lw5uArHGzsmWIpu8yZNYN/LCRQDDZ0K6YGrUZ2vTjvo="
    }
}'
```


# Liquidity Management


# Runes

## POST /brc20swap/v2/create\_add\_liquid\_psbt2

> Build the PSBT for adding liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/v2/create_add_liquid_psbt2":{"post":{"summary":"Build the PSBT for adding liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"string"},"tick2":{"type":"string"},"amount_1":{"type":"string"},"amount_2":{"type":"string"},"slipper":{"type":"string"},"payer_ord_addr":{"type":"string"},"fee_rate":{"type":"string"},"payer_btc_addr":{"type":"string"},"payer_pub_key":{"type":"string"},"coin_type_1":{"type":"string"},"coin_type_2":{"type":"string"},"token":{"type":"string"}},"required":["tick1","coin_type_1","amount_1","tick2","coin_type_2","amount_2","fee_rate","slipper","token","payer_ord_addr","payer_btc_addr","payer_pub_key"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"psbt":{"type":"string","title":"PSBT base64"},"ToSignInputs":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer"},"type":{"type":"string"}},"required":["index","type"]}},"check_sum":{"type":"string"},"tx_size":{"type":"integer"},"usr_cnt":{"type":"integer"},"vins":{"type":"null"},"check_sign_only":{"type":"boolean"}},"required":["ToSignInputs","psbt","check_sum","tx_size","usr_cnt","vins","check_sign_only"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## Important Notest

{% hint style="info" %}

1. Use the same address for both `payer_ord_addr` and `payer_btc_addr`.
   {% endhint %}

## POST /brc20swap/v2/add\_liquid\_by\_psbt

> Add liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/v2/add_liquid_by_psbt":{"post":{"summary":"Add liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"psbt":{"type":"string","title":"PSBT base64"},"tick1":{"type":"string"},"tick2":{"type":"string"},"amount_1":{"type":"string"},"amount_2":{"type":"string"},"slipper":{"type":"string"},"payer_ord_addr":{"type":"string"},"fee_rate":{"type":"string"},"payer_btc_addr":{"type":"string"},"payer_pub_key":{"type":"string"},"check_sum":{"type":"string"},"chl":{"type":"string"},"coin_type_1":{"type":"string"},"coin_type_2":{"type":"string"},"token":{"type":"string"}},"required":["tick1","coin_type_1","amount_1","tick2","coin_type_2","amount_2","fee_rate","slipper","token","payer_ord_addr","payer_btc_addr","payer_pub_key","psbt"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string","title":"Order number"}},"required":["order_id"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

Finally, send the signed PSBT. If the response indicates success, the liquidity has been added/created successfully.

{% hint style="info" %}
The request parameters of the previous interface are inherited, and an additional psbt is passed. export interface SendPoolPsbtBody extends PoolPsbtBody { psbt: string; }
{% endhint %}


# BRC20

When selecting the token pair and clicking to add liquidity, if it is a BRC20 token, you need to first request the pre-add/create interface.

## POST /brc20swap/v2/pre\_add\_liquid

> Pre-add liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/v2/pre_add_liquid":{"post":{"summary":"Pre-add liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"string","title":"Coin name"},"tick2":{"type":"string"},"amount_1":{"type":"string","title":"Injection amount"},"amount_2":{"type":"string"},"tick_1_inscription_ids":{"type":"array","items":{"type":"string"},"title":"Inscription ID","description":"Used when recharging BRC20"},"tick_2_inscription_ids":{"type":"array","items":{"type":"string"}},"payer_ord_addr":{"type":"string","title":"Address"},"payer_btc_addr":{"type":"string"},"payer_pub_key":{"type":"string"},"fee_rate":{"type":"string","title":"Fee rate"},"slipper":{"type":"string","title":"Slippage"}},"required":["tick1","tick2","amount_1","amount_2","slipper","tick_1_inscription_ids","tick_2_inscription_ids","payer_ord_addr","fee_rate","payer_btc_addr","payer_pub_key"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer","additionalProperties":false},"msg":{"type":"string","additionalProperties":false},"data":{"type":"object","properties":{"tx_size":{"type":"integer","title":"Tx size","additionalProperties":false},"ins_contain_sats":{"type":"integer","title":"The sum of satoshis in the input inscriptions","additionalProperties":false},"vins":{"type":"array","items":{"type":"string","additionalProperties":false}},"usr_cnt":{"type":"integer","additionalProperties":false},"net_fee":{"type":"integer","title":"Network fee","additionalProperties":false},"check_sum":{"type":"string","title":"Checksum","additionalProperties":false}},"required":["net_fee","check_sum","tx_size","usr_cnt","vins"]},"req_id":{"type":"string","additionalProperties":false}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## Important Notes

{% hint style="info" %}

1. The result returned from this interface should be passed as is to the `create_add_liquid_psbt` interface.
2. Since liquidity is added based on a ratio and BRC20 needs to be inscribed first, creating BRC20-BRC20 token pair pools is not supported.
3. For the `tick_1_inscription_ids` and `tick_2_inscription_ids` parameters:

   * If `coin_type_1` is BRC20, put the BRC20 inscription ID in the `tick_1_inscription_ids` array and leave `tick_2_inscription_ids` empty.
   * If `coin_type_2` is BRC20, put the BRC20 inscription ID in the `tick_2_inscription_ids` array and leave `tick_1_inscription_ids` empty.

   *For the same token pair, BRC20-BTC and BTC-BRC20, the same pool is created or added to (e.g., ordi-BTC, BTC-ordi), just using different fields for the parameters.*

```
```

{% endhint %}

## POST /brc20swap/v2/create\_add\_liquid\_psbt

> Build the PSBT for adding BRC20 liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/v2/create_add_liquid_psbt":{"post":{"summary":"Build the PSBT for adding BRC20 liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tick1":{"type":"string"},"tick2":{"type":"string"},"amount_1":{"type":"string"},"amount_2":{"type":"string"},"slipper":{"type":"string"},"tick_1_inscription_ids":{"type":"array","items":{"type":"string"}},"tick_2_inscription_ids":{"type":"array","items":{"type":"string"}},"payer_ord_addr":{"type":"string"},"fee_rate":{"type":"string"},"payer_btc_addr":{"type":"string"},"payer_pub_key":{"type":"string"},"check_sum":{"type":"string"},"vins":{"type":"array","items":{"type":"string"}}},"required":["tick1","tick2","amount_1","amount_2","slipper","tick_1_inscription_ids","tick_2_inscription_ids","payer_ord_addr","fee_rate","payer_btc_addr","payer_pub_key","check_sum","vins"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"psbt":{"type":"string","title":"PSBT base64"},"ToSignInputs":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer"},"type":{"type":"string"}},"required":["index","type"]}},"check_sum":{"type":"string"},"tx_size":{"type":"integer"},"usr_cnt":{"type":"integer"},"vins":{"type":"array","items":{"type":"string"}}},"required":["ToSignInputs","psbt","check_sum","tx_size","usr_cnt","vins"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

## Important Notes:

{% hint style="info" %}

1. Upon successful pre-add/create request, obtain the unsigned PSBT. Some of the request parameters will be from the pre-add/create request's return result.
2. Use the same address for both `payer_ord_addr` and `payer_btc_addr`.
   {% endhint %}

## POST /brc20swap/v2/add\_liquid\_by\_psbt

> Add liquidity

```json
{"openapi":"3.0.1","info":{"title":"Backend API","version":"1.0.0"},"servers":[{"url":"https://api-testnet4.dotswap.app","description":"Swap test"},{"url":"https://api.dotswap.app","description":"Swap official"}],"security":[],"paths":{"/brc20swap/v2/add_liquid_by_psbt":{"post":{"summary":"Add liquidity","deprecated":false,"description":"","tags":[],"parameters":[],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"psbt":{"type":"string","title":"PSBT base64"},"tick1":{"type":"string"},"tick2":{"type":"string"},"amount_1":{"type":"string"},"amount_2":{"type":"string"},"slipper":{"type":"string"},"payer_ord_addr":{"type":"string"},"fee_rate":{"type":"string"},"payer_btc_addr":{"type":"string"},"payer_pub_key":{"type":"string"},"check_sum":{"type":"string"},"chl":{"type":"string"},"coin_type_1":{"type":"string"},"coin_type_2":{"type":"string"},"token":{"type":"string"}},"required":["tick1","coin_type_1","amount_1","tick2","coin_type_2","amount_2","fee_rate","slipper","token","payer_ord_addr","payer_btc_addr","payer_pub_key","psbt"]}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"integer"},"msg":{"type":"string"},"data":{"type":"object","properties":{"order_id":{"type":"string","title":"Order number"}},"required":["order_id"]},"req_id":{"type":"string"}},"required":["code","msg","data","req_id"]}}},"headers":{}}}}}}}
```

Finally, send the signed PSBT. If the response indicates success, the liquidity has been added/created successfully.


# Remove Liquidity


# Removing Liquidity

In this guide, we will use an example of Nexus process to show how to remove liquidity from a pool, which includes:

* Removing
  * Pre-remove Request
  * Get Unsigned Remove PSBT
  * Send Signed Remove PSBT
* Get Estimated Remove Amount

> The removing interface for Runes/BRC20/ARC20 is the same, differentiated by `coin_type_*`.

{% openapi src="/files/ebMomft3frkz221TDkVa" path="/brc20swap/v2/pre\_remove\_liquid" method="post" %}
[remove.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-3ac9cec1f64fa55c9e361b89c0bb4a1934a0c36c%2Fremove.json?alt=media)
{% endopenapi %}

### Example

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

```typescript
{
    "tick1": "BTC",
    "tick2": "RUNEONERUNEONE",
    "coin_type_1": "btc",
    "coin_type_2": "runes",
    "payer_ord_addr": "tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e",
    "payer_btc_addr": "tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e",
    "percent": "15",
    "slipper": "12",
    "fee_rate": "57",
    "payer_pub_key": "02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81"
}
```

{% endtab %}

{% tab title="cURL Example (Runes)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/pre_remove_liquid' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"tick1":"BTC","tick2":"RUNEONERUNEONE","coin_type_1":"btc","coin_type_2":"runes","payer_ord_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_btc_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","percent":"15","slipper":"12","fee_rate":"57","payer_pub_key":"02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81"}'
```

{% endtab %}

{% tab title="cURL Example (BRC20)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/pre_remove_liquid' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://192.168.10.66:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://192.168.10.66:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"percent":"10","tick1":"BTC","tick2":"bqbq","coin_type_1":"btc","coin_type_2":"brc20","payer_ord_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_btc_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_pub_key":"02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81","slipper":"12","fee_rate":"11"}' \
  --compressed
```

{% endtab %}

{% tab title="cURL Example (ARC20)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/pre_remove_liquid' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"tick1":"BTC","tick2":"3dbb","coin_type_1":"btc","coin_type_2":"arc20","payer_ord_addr":"tb1qlphav0389832xt8deme0hx2unvw3cjt7fsfuyx","payer_btc_addr":"tb1qlphav0389832xt8deme0hx2unvw3cjt7fsfuyx","percent":"30","slipper":"12","fee_rate":"3","payer_pub_key":"036d9bb5a5cbf1cfb46c6ec79832a53b4f8717751485abb141ba6d595393200ace:036d9bb5a5cbf1cfb46c6ec79832a53b4f8717751485abb141ba6d595393200ace"}'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The returned result should be passed as is to the `create_remove_liquid_psbt` (the following interface).
{% endhint %}

{% openapi src="/files/ebMomft3frkz221TDkVa" path="/brc20swap/v2/create\_remove\_liquid\_psbt" method="post" %}
[remove.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-3ac9cec1f64fa55c9e361b89c0bb4a1934a0c36c%2Fremove.json?alt=media)
{% endopenapi %}

### Example

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

```typescript
{
    "expect_amount1": "1500",
    "expect_amount2": "75",
    "expect_transfer_fee": 20121,
    "check_sum": "D6CCF094281BC79DD4AF6E7A7FBF1CDA",
    "tx_size": 353,
    "usr_cnt": 1,
    "vins": [
        "6cf1c2614a4eaaadf68769909b04687a2ddc4d6082fe4a78654dfad08a9a9323:6"
    ],
    "tick1": "BTC",
    "tick2": "RUNEONERUNEONE",
    "coin_type_1": "btc",
    "coin_type_2": "runes",
    "payer_ord_addr": "tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e",
    "payer_btc_addr": "tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e",
    "percent": "15",
    "slipper": "12",
    "fee_rate": "57",
    "payer_pub_key": "02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81"
}
```

{% endtab %}

{% tab title="cURL Example (Runes)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/create_remove_liquid_psbt' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"expect_amount1":"1500","expect_amount2":"75","expect_transfer_fee":20121,"check_sum":"D6CCF094281BC79DD4AF6E7A7FBF1CDA","tx_size":353,"usr_cnt":1,"vins":["6cf1c2614a4eaaadf68769909b04687a2ddc4d6082fe4a78654dfad08a9a9323:6"],"tick1":"BTC","tick2":"RUNEONERUNEONE","coin_type_1":"btc","coin_type_2":"runes","payer_ord_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_btc_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","percent":"15","slipper":"12","fee_rate":"57","payer_pub_key":"02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81"}' Ex
```

{% endtab %}

{% tab title="cURL Example (BRC20)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/create_remove_liquid_psbt' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://192.168.10.66:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://192.168.10.66:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"expect_amount1":"5075.803216837728754467","expect_amount2":"282.002432596010007297781694096138448","expect_transfer_fee":15798,"check_sum":"8DEFAA3590E994E291F02030EE7BBBE1","usr_cnt":1,"vins":["5fbfbe6ed863c228b8dc77ed2ec55a8b09fcbb8a2767874c12f61c9ce1dbc263:2"],"tx_size":642,"percent":"10","slipper":"12","tick1":"BTC","tick2":"bqbq","coin_type_1":"btc","coin_type_2":"brc20","payer_ord_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_btc_addr":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","payer_pub_key":"02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81:02d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81","fee_rate":"11"}' \
  --compressed
```

{% endtab %}

{% tab title="cURL Example (ARC20)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/create_remove_liquid_psbt' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"expect_amount1":"120383.33777471435486031353079418688523444","expect_amount2":"637.35028437485150273725464254913146868","expect_transfer_fee":1911,"check_sum":"35B665B6AA891953152CC576C5FE125F","tx_size":637,"usr_cnt":1,"vins":["9ad1f5f681637d6d11443b941cfa2f5e0ba4dad2405b88ee8254a34f763969e7:1"],"tick1":"BTC","tick2":"3dbb","coin_type_1":"btc","coin_type_2":"arc20","payer_ord_addr":"tb1qlphav0389832xt8deme0hx2unvw3cjt7fsfuyx","payer_btc_addr":"tb1qlphav0389832xt8deme0hx2unvw3cjt7fsfuyx","percent":"30","slipper":"12","fee_rate":"3","payer_pub_key":"036d9bb5a5cbf1cfb46c6ec79832a53b4f8717751485abb141ba6d595393200ace:036d9bb5a5cbf1cfb46c6ec79832a53b4f8717751485abb141ba6d595393200ace"}'
```

{% endtab %}
{% endtabs %}

{% openapi src="/files/ebMomft3frkz221TDkVa" path="/brc20swap/v2/remove\_liquid\_by\_psbt" method="post" %}
[remove.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-3ac9cec1f64fa55c9e361b89c0bb4a1934a0c36c%2Fremove.json?alt=media)
{% endopenapi %}

### Example

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

```
{
    "psbt": "70736274ff01007d020000000123939a8ad0fa4d65784afe82604ddc2d7a68049b906987f6adaa4e4a61c2f16c0600000000ffffffff02994e00000000000022512054f638dfba2ea8d607a59ec681a1ec479f741b0f505a116fe20172fde877eede52ca040000000000160014464ef3759fcfb1eb3d76f3319ef58ec20301c658000000000001011ffc3a050000000000160014464ef3759fcfb1eb3d76f3319ef58ec20301c65801086b0247304402200b398be45be70f30793de6e31aa9a9007a954f391f82e12b7a72c663af5d94570220230c28c921ca20e94669fab5abb7baf9cc908d121d2a5ffb96643e02c2d529bd012102d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81000000",
    "order_id": "liquid_972788279311073280",
    "checksum": "CAA324EB56C64FA1A6646C9AED0E2BAF",
    "to_sign_inputs": null
}
```

{% endtab %}

{% tab title="cURL Example (Runes)" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/v2/remove_liquid_by_psbt' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"psbt":"70736274ff01007d020000000123939a8ad0fa4d65784afe82604ddc2d7a68049b906987f6adaa4e4a61c2f16c0600000000ffffffff02994e00000000000022512054f638dfba2ea8d607a59ec681a1ec479f741b0f505a116fe20172fde877eede52ca040000000000160014464ef3759fcfb1eb3d76f3319ef58ec20301c658000000000001011ffc3a050000000000160014464ef3759fcfb1eb3d76f3319ef58ec20301c65801086b0247304402200b398be45be70f30793de6e31aa9a9007a954f391f82e12b7a72c663af5d94570220230c28c921ca20e94669fab5abb7baf9cc908d121d2a5ffb96643e02c2d529bd012102d3ac7452920b1cc4653516dd4f4381a2df0a8c0aac6e3446e633a73ea63eee81000000","order_id":"liquid_972788279311073280","checksum":"CAA324EB56C64FA1A6646C9AED0E2BAF","to_sign_inputs":null}'
```

{% endtab %}
{% endtabs %}

{% openapi src="/files/ebMomft3frkz221TDkVa" path="/brc20swap/get\_liquid\_info" method="post" %}
[remove.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-3ac9cec1f64fa55c9e361b89c0bb4a1934a0c36c%2Fremove.json?alt=media)
{% endopenapi %}

### Example

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

```typescript
{
    "address": "tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e",
    "lp_precent": 35,
    "from_tick": "BTC",
    "to_tick": "RUNEONERUNEONE",
    "from_coin_type": "btc",
    "to_coin_type": "runes"
}
```

{% endtab %}

{% tab title="cURL Example" %}

```sh
curl 'https://test-api-proxy.ddpurse.com/brc20swap/get_liquid_info' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:56651' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:56651/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"address":"tb1qge80xavle7c7k0tk7vceaavwcgpsr3jchl0w3e","lp_precent":35,"from_tick":"BTC","to_tick":"RUNEONERUNEONE","from_coin_type":"btc","to_coin_type":"runes"}'
```

{% endtab %}
{% endtabs %}

### Explanation on Fees

The actual amount received by the user will have the key custodial service's fee deducted, which is calculated using the `mutisign_fee_proportion` field returned by the backend (initially 0.3%, and may adjust in the future if the key custodial service changes).

### Fee Calculation

* Removing BTC-BRC20: Fee = BTC satoshi amount \* 0.3%
* Removing BTC-ARC20: Fee = BTC satoshi amount \* 0.3% + ARC20 satoshi amount \* 0.3%
* Removing BRC20-BRC20: Free

Calculation of the Actual Amount Received by the User:

```typescript

if (from_coin_type === "btc") {
  finally_from_amount = from_amount * (1 - mutisign_fee_proportion); 
  if (to_coin_type === "arc20") {
    finally_from_amount =
      finally_from_amount - to_amount * mutisign_fee_proportion;
  }
  finally_to_amount = to_amount;
}
if (to_coin_type === "btc") {
  finally_from_amount = from_amount;
  finally_to_amount = to_amount * (1 - mutisign_fee_proportion);
  if (to_coin_type === "arc20") {
    finally_to_amount =
      finally_to_amount - from_amount * mutisign_fee_proportion;
  }
}

```

{% hint style="info" %}
The estimated amount will change in real-time based on the total token amount in the liquidity pool. Your frontend can perform polling requests to obtain the latest estimate.
{% endhint %}


# CAT20


# Split

> API Base
>
> Test URL: <https://test-api-proxy.ddpurse.com>
>
> Main URL: <https://api-btc.tiertop.io>

You can split the CAT20 assets of a specified address into different addresses through the following interface.

{% openapi src="/files/MfvsVxOYdKQUzrPea6LS" path="/brc20swap/get\_split\_cat20\_psbts" method="post" %}
[cat20.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-9cfdc7d54bba6754204418c069472d543f156ccb%2Fcat20.json?alt=media)
{% endopenapi %}

### Split Users' CAT20

{% tabs %}
{% tab title="Parameter Example" %}

```json
{
  "tick": "dog:b1071ae617c66050d518587f67564885ca1a618b387a15f84001e3fa244ef3d6_0",
  "is_ofc_token": false,
  "user_addr": "bc1pxul8mg4fvx....cxej453h24smw03s0",
  "user_pubkey": "02d3ac7452920b1cc4....0a8c0aac6e3446e633a73ea63eee81",
  "cat_20_output_to_split": "08806ff819db249637a7c1cc762e4f9e29182d7dc658b7571f12c2b539106a1f:2",
  "token_addr": "bc1pxul8mg4fvx....cxej453h24smw03s0",
  "fee_rate": 9,
  "toinfos": [
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    }
  ]
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Regarding `cat_20_output_to_split`, you need to query the corresponding CAT20 UTXO of the corresponding address, find the UTXO you want to split, and then concatenate it with the txId and outputIndex of the corresponding UTXO Query address reference (please replace tokenIdOrTokenAddr and ownerAddrOrPkh)

<img src="https:/images.swap.dotwallet.com/web_restrict/gitbook_api_img/image%20(2).png" alt="" data-size="original">

* [Testnet URL](https://tracker-fractal-testnet/api/tokens/%7BtokenIdOrTokenAddr%7D/addresses/%7BownerAddrOrPkh%7D/utxos)
* [Mainnet URL](https://tracker-fractal-mainnet.catprotocol.org/api/tokens/%7BtokenIdOrTokenAddr%7D/addresses/%7BownerAddrOrPkh%7D/utxos)
  {% endhint %}

### Split Official CAT20

If you're using Nexus's [CAT20 deposit endpoint](/dotswap/developers/l1-swap-and-liquidity-apis/swap_v2/cat20#v1-deposit), you can use these 2 endpoints to split your deposited CAT20 tokens (aka "official CAT20", since they are in Nexus's liquidity pool.)

* When you first call the deposit endpoint `/create_deposit_cat20_psbtv2`, you can set the parameter `not_split:true`.
* If the deposit is succesful, `/create_deposit_cat20_order_by_psbt` will return `receiver_addr` and `txid`.

<figure><img src="https://images.swap.dotwallet.com/web_restrict/gitbook_api_img/image.png" alt=""><figcaption></figcaption></figure>

**Then, you can use the following parameters to call the split endpoint** <mark style="color:green;">`POST`</mark> `/brc20swap/get_split_cat20_psbts`.

{% tabs %}
{% tab title="Parameter Example" %}

```json
{
  // These two parameters should be set to true by default
  "is_ofc_token": true,
  "is_average_split": true,

  // This is the wallet you used for the deposit
  "user_addr": "bc1psx048lgxx9qlgnw2yjn6vw7ndz07f5rdlfxraqpxkr84tqa7670sagd4k8",
  "user_pubkey": "03c22e2f276e66c24e515b24a0c6bcf53852b046b31bbaf98d3f3075c005729691",

  // The token to be split (keep the same as the token name you deposited)
  "tick": "dog:b1071ae617c66050d518587f67564885ca1a618b387a15f84001e3fa244ef3d6_0",

  // This is the txid + :1 returned by the deposit interface (:1 is fixed)
  "cat_20_output_to_split": "3c92ae8ce3fd6377ac9316a28ded9ca5daef835dd3cf2613b8047c1ee9bbf530:1",

  // This is the receiver_addr returned by the deposit interface
  "token_addr": "bc1plsm7wgedgkguhk5xyllhyml2zstu0z7zs353hq7h6jlvu5puf4sqhc2l5t",

  // The number should be greater than 4
  "split_num": 5,

  "fee_rate": 9
}
```

{% endtab %}

{% tab title="cURL Example" %}
{% code overflow="wrap" %}

```bash
curl 'https://test-api-proxy.ddpurse.com/brc20swap/get_split_cat20_psbts' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:60002' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:60002/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"tick":"dog:b1071ae617c66050d518587f67564885ca1a618b387a15f84001e3fa244ef3d6_0","is_ofc_token":true,"user_addr":"bc1psx048lgxx9qlgnw2yjn6vw7ndz07f5rdlfxraqpxkr84tqa7670sagd4k8","user_pubkey":"03c22e2f276e66c24e515b24a0c6bcf53852b046b31bbaf98d3f3075c005729691","cat_20_output_to_split":"3c92ae8ce3fd6377ac9316a28ded9ca5daef835dd3cf2613b8047c1ee9bbf530:1","token_addr":"bc1plsm7wgedgkguhk5xyllhyml2zstu0z7zs353hq7h6jlvu5puf4sqhc2l5t","fee_rate":9,"is_average_split":true,"split_num":5}'
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% openapi src="/files/MfvsVxOYdKQUzrPea6LS" path="/brc20swap/save\_split\_cat20\_psbts" method="post" %}
[cat20.json](https://2330303583-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXEWf0ylbbPQ6t8CoOLdL%2Fuploads%2Fgit-blob-9cfdc7d54bba6754204418c069472d543f156ccb%2Fcat20.json?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Request Parameters" %}

```typescript
// Inherit the parameters of the previous interface
export interface SaveSplitCat20PsbtsBody extends GetSplitCat20PsbtsBody {
  psbts: string[];
}
```

{% endtab %}

{% tab title="Return Result" %}

```typescript
export interface SaveSplitCat20PsbtsRes {
  tx_id: string;
}
```

{% endtab %}

{% tab title="Parameter Example" %}

```json
{
  "tick": "dog:b1071ae617c66050d518587f67564885ca1a618b387a15f84001e3fa244ef3d6_0",
  "is_ofc_token": false,
  "user_addr": "bc1pxul8mg4fvx....cxej453h24smw03s0",
  "user_pubkey": "02d3ac7452920b1cc4....0a8c0aac6e3446e633a73ea63eee81",
  "cat_20_output_to_split": "08806ff819db249637a7c1cc762e4f9e29182d7dc658b7571f12c2b539106a1f:2",
  "token_addr": "bc1pxul8mg4fvx....cxej453h24smw03s0",
  "fee_rate": 9,
  "toinfos": [
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    },
    {
      "to_addr": "bc1pxrvq4n9ud.....587lf3xszyyczr",
      "to_amt": 5
    }
  ],
  "order_id": "",
  "psbts": [
    "cHNidP8BAN8CAAAAAW42i3ZHxnggGQix2qGq0QCVR98cmvoVNLxMbzPUBnJ6AwAAAAD/////BDpmAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIkcAAAAAAAACJRIPHDJ8pFgNQadCvDlFlD2x86fkoECKjpRkGYE7t7okTS8GQAAAAAAAAiUSDxwyfKRYDUGnQrw5RZQ9sfOn5KBAio6UZBmBO7e6JE0hhIAAAAAAAAIlEgNz59oqlhjCWSvFug6GaqBjCay2GnqDP1EP4NmVaRuqsAAAAAAAEBK9mLAQAAAAAAIlEgNz59oqlhjCWSvFug6GaqBjCay2GnqDP1EP4NmVaRuqsBAwQBAAAAARNBrdAMj8AHGH76p3kp379osjZjhI4myNs6mcVRJOeCJgsMk7yKmZQx/enI5MAEsTm2ljWnT6xdajN2i68FvcyQHwEBFyDTrHRSkgscxGU1Ft1PQ4Gi3wqMCqxuNEbmM6c+pj7ugQAAAAAA",
    "cHNidP8BAKwCAAAAAUV4KF9qW9jpts4tPyGS0dmlR0h8+Qz+8Hu6reMArHenAAAAAAD/////AwAAAAAAAAAAGmoYY2F0AZ+Zmft96aoXbolo7Pw2FV21AHtkSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/kheAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIAAAAAAAEBKzpmAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIBCEIBQLp039gq0GzSfhmnOxTJ/Olq+CahVb1dh9WD/Oj+MS0okK7Q4f530iE/UWf12dnCjmvAMjF+yrOfDT1g8BJePqQAAAAA",
    "cHNidP8BAP3+AAIAAAADH2oQObXCEh9Xt1jGfS0YKZ5PLnbMwac3liTbGfhvgAgCAAAAAP////9mPGfKEUTuGJnqnGPraZWC3jjq7U/TopCXuE6bEH4k/QEAAAAA/////2Y8Z8oRRO4YmeqcY+tplYLeOOrtT9OikJe4TpsQfiT9AgAAAAD/////AwAAAAAAAAAAGmoYY2F0AUbowsVb0zIpCtDz3MIBs38VxRfaSgEAAAAAAAAiUSBDEE+mqJWOtyeQgcd/ztVttJrXEBda+i9ohqCbgG4jmkoBAAAAAAAAIlEgQxBPpqiVjrcnkIHHf87VbbSa1xAXWvovaIagm4BuI5oKAAAAAAEBK0oBAAAAAAAAIlEgQxBPpqiVjrcnkIHHf87VbbSa1xAXWvovaIagm4BuI5pBFDc+faKpYYwlkrxboOhmqgYwmsthp6gz9RD+DZlWkbqrdVjd6OouyBa44MKMc7bVjfoVRav7u7i6ftyGud6ukcVAN5QqjFxFp/kZbV8poAFq+U5GcNS7Ptbm4pjQD9DzLGNE69K8T8OWiEayZlclItjv2HSuHkquaUsqKdVkFPFmCgABAStKAQAAAAAAACJRIFL17CRoFRKIn3ZaMxO3RqDpKwHfP05IQEI2kGof9GL+AAEBK0heAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIAAAAA"
  ]
}
```

{% endtab %}

{% tab title="cURL Example" %}
{% code overflow="wrap" %}

```bash
curl 'https://test-api-proxy.ddpurse.com/brc20swap/save_split_cat20_psbts' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Accept-Language: en' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:60002' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://localhost:60002/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \
  -H 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"tick":"dog:b1071ae617c66050d518587f67564885ca1a618b387a15f84001e3fa244ef3d6_0","is_ofc_token":true,"user_addr":"bc1psx048lgxx9qlgnw2yjn6vw7ndz07f5rdlfxraqpxkr84tqa7670sagd4k8","user_pubkey":"03c22e2f276e66c24e515b24a0c6bcf53852b046b31bbaf98d3f3075c005729691","cat_20_output_to_split":"3c92ae8ce3fd6377ac9316a28ded9ca5daef835dd3cf2613b8047c1ee9bbf530:1","token_addr":"bc1plsm7wgedgkguhk5xyllhyml2zstu0z7zs353hq7h6jlvu5puf4sqhc2l5t","fee_rate":9,"is_average_split":true,"split_num":5,"order_id":"","psbts":["cHNidP8BAIkCAAAAARJTZeYyavrM5m1L5sK4rahTDlRR7G1Kgao/c+LUK3IJAwAAAAD/////AqFuAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNJj2WECAAAAACJRIIGfU/0GMUH0Tcokp6Y702if5NBt+kw+gCawz1WDvtefAAAAAAABAStxTWICAAAAACJRIIGfU/0GMUH0Tcokp6Y702if5NBt+kw+gCawz1WDvtefAQMEAQAAAAETQcJ21qTEi6F1QoNEClyyVKH5Npik3n8dvgC9hV1/CjNdXZ4mKhuwEP53G6IHYdcSuCVzgOD1ilAa9/OeA5vIjSYBARcgwi4vJ25mwk5RWySgxrz1OFKwRrMbuvmNPzB1wAVylpEAAAA=","cHNidP8BAKwCAAAAAf5gw44vaKscEIOdEQ1JrGCKx4HfkYbuvXa7LnCZ3s24AAAAAAD/////AwAAAAAAAAAAGmoYY2F0AWRURBrWYrooP0U81DTquW48pBCHSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/q9mAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIAAAAAAAEBK6FuAAAAAAAAIlEg8cMnykWA1Bp0K8OUWUPbHzp+SgQIqOlGQZgTu3uiRNIBCEIBQARHENDsE+fqRt7GqUW/UWzmg9RTq6p41vhjQEty6gWzOgta8ogVNywJrvFUbQm15DMru4/emVjiDwl0GFf0Ys4AAAAA","cHNidP8BAP1/AQIAAAADMPW76R58BLgTJs/TXYPv2qWc7Y2iFpOsd2P944yukjwBAAAAAP////9JK/qTrKEVqJbwYs9WjtfNGKWabamZcE3S8QjHiLkVrAEAAAAA/////0kr+pOsoRWolvBiz1aO180YpZptqZlwTdLxCMeIuRWsAgAAAAD/////BgAAAAAAAAAAGmoYY2F0AZUS1+/sBJzhNQA0cxSuCGe4ipnoSgEAAAAAAAAiUSBDEE+mqJWOtyeQgcd/ztVttJrXEBda+i9ohqCbgG4jmkoBAAAAAAAAIlEgQxBPpqiVjrcnkIHHf87VbbSa1xAXWvovaIagm4BuI5pKAQAAAAAAACJRIEMQT6aolY63J5CBx3/O1W20mtcQF1r6L2iGoJuAbiOaSgEAAAAAAAAiUSBDEE+mqJWOtyeQgcd/ztVttJrXEBda+i9ohqCbgG4jmkoBAAAAAAAAIlEgQxBPpqiVjrcnkIHHf87VbbSa1xAXWvovaIagm4BuI5oDAAAAAAEBK0oBAAAAAAAAIlEgQxBPpqiVjrcnkIHHf87VbbSa1xAXWvovaIagm4BuI5oAAQErSgEAAAAAAAAiUSBS9ewkaBUSiJ92WjMTt0ag6SsB3z9OSEBCNpBqH/Ri/gABASuvZgAAAAAAACJRIPHDJ8pFgNQadCvDlFlD2x86fkoECKjpRkGYE7t7okTSAAAAAAAAAA=="]}'
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Wallet Access Specification


# Specification

### **Required APIs with Examples and Common Error Codes (Using OKX as Example)**

#### Window Global Variable Name

```typescript
// Get OKX wallet instance
const okx = (window as any).okxwallet;

// Get wallet API for different networks
const getWalletApi = (network: "livenet" | "testnet") => {
  const networkAttr = {
    livenet: "bitcoin",
    testnet: "bitcoinTestnet",
  };
  return okx[networkAttr[network]];
};
```

\\

#### Connect Wallet Method

```typescript
interface ConnectParams {
  network: "livenet" | "testnet";
  chain?: "BITCOIN_MAINNET" | "BITCOIN_TESTNET" | "BITCOIN_TESTNET4" | "FRACTAL_BITCOIN_MAINNET" | "FRACTAL_BITCOIN_TESTNET";
  handleMismatchChain?: boolean;
}

interface ConnectResult {
  name: "okx";
  network: "livenet" | "testnet";
  publicKey: string;
  accounts: string[];
  address: string;
  btcAddress: string;
  btcPublicKey: string;
  balance?: {
    confirmed?: number;
    total?: number;
    unconfirmed?: number;
  };
  chain?: string;
}

// Connect wallet
const connect = async (params: ConnectParams): Promise<ConnectResult> => {
  const { network, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    const info = await okx.connect();
    const { publicKey, address, compressedPublicKey } = info;
    
    let balance;
    if (network === "livenet") {
      balance = await okx.getBalance();
    }

    return {
      name: "okx",
      network,
      publicKey,
      accounts: [address],
      address,
      btcAddress: address,
      btcPublicKey: compressedPublicKey,
      balance,
      chain,
    };
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "Connection failed",
      success: false,
    };
  }
};
```

\\

#### Disconnect Wallet Method

```typescript
interface DisconnectParams {
  network: "livenet" | "testnet";
  chain?: string;
  handleMismatchChain?: boolean;
}

const disconnect = async (params: DisconnectParams): Promise<void> => {
  const { network, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    await okx.disconnect();
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "Disconnect failed",
      success: false,
    };
  }
};
```

\\

#### Sign Method

```typescript
interface SignParams {
  network: "livenet" | "testnet";
  msg: string;
  type?: string;
  chain?: string;
  handleMismatchChain?: boolean;
}

const sign = async (params: SignParams): Promise<string> => {
  const { network, msg, type, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    return await okx.signMessage(msg, type);
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "Signing failed",
      success: false,
    };
  }
};
```

\\

#### Sign PSBT Method

```typescript
interface SignPsbtParams {
  psbt: string; // PSBT string in base64 or hex format
  option?: {
    autoFinalized: boolean;
    toSignInputs?: {
      index: number;
      address: string;
      publicKey: string;
      sighashTypes: number[];
      disableTweakSigner: boolean;
    }[];
  };
  network: "livenet" | "testnet";
  data: ConnectResult; // Wallet information
  chain?: string;
  handleMismatchChain?: boolean;
}

const signPsbt = async (params: SignPsbtParams): Promise<string> => {
  const { psbt, option, network, data, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    // Convert to hex format
    let handlePsbt = psbt;
    if (!/^[0-9a-fA-F]+$/.test(psbt)) {
      handlePsbt = Psbt.fromBase64(psbt).toHex();
    }
    
    const res = await okx.signPsbt(handlePsbt, {
      ...option,
      autoFinalized: false,
    });
    
    return res;
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "PSBT signing failed",
      success: false,
    };
  }
};
```

\\

#### Send BTC Method

```typescript
interface SendBitcoinParams {
  from: string; // Sender address
  address: string; // Recipient address
  satoshis: number; // Amount to send (in satoshis)
  option?: {
    feeRate: number; // Fee rate
  };
  network: "livenet" | "testnet";
  chain?: string;
  handleMismatchChain?: boolean;
}

const sendBitcoin = async (params: SendBitcoinParams): Promise<string> => {
  const { from, address, satoshis, option, network, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    const sendOption: any = {
      from,
      to: address,
      value: (satoshis / 100000000).toFixed(8), // Convert to BTC
    };
    
    if (option && option.feeRate) {
      sendOption.fee = option.feeRate;
      sendOption.satBytes = option.feeRate;
    }
    
    const res = await okx.send(sendOption);
    return res.txhash;
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "Send BTC failed",
      success: false,
    };
  }
};
```

\\

#### Sign PSBTs Method

```typescript
interface SignPsbtsParams {
  psbt: string[]; // Array of PSBT strings
  option?: Array<{
    autoFinalized: boolean;
    toSignInputs?: {
      index: number;
      address: string;
      publicKey: string;
      sighashTypes: number[];
      disableTweakSigner: boolean;
    }[];
  }>;
  network: "livenet" | "testnet";
  chain?: string;
  handleMismatchChain?: boolean;
}

const signPsbts = async (params: SignPsbtsParams): Promise<string[]> => {
  const { psbt, option = [], network, chain, handleMismatchChain } = params;
  const okx = getWalletApi(network);
  
  try {
    const handleOptions = option.length === 0
      ? psbt.map(() => ({ autoFinalized: false }))
      : option.map((item) => ({ ...item, autoFinalized: false }));

    const res = await okx.signPsbts(psbt, handleOptions);
    return res;
  } catch (error) {
    throw {
      code: error.code || 1,
      msg: error.msg || error.message || "Batch PSBT signing failed",
      success: false,
    };
  }
};
```

\\

#### Account Switch Monitoring Event

```typescript
interface WalletInfo {
  name: "okx";
  network: "livenet" | "testnet";
  publicKey: string;
  accounts: string[];
  address: string;
  btcAddress: string;
  btcPublicKey: string;
  balance?: {
    confirmed?: number;
    total?: number;
    unconfirmed?: number;
  };
}

const openMonitorOkx = (
  network: "livenet" | "testnet",
  callback?: (data: WalletInfo) => void,
) => {
  const okx = getWalletApi(network);
  
  okx.on("accountsChanged", async (accounts: string[]) => {
    if (accounts && accounts.length > 0) {
      try {
        const info = await okx.connect();
        const { publicKey, address, compressedPublicKey } = info;
        
        let balance;
        if (network === "livenet") {
          balance = await okx.getBalance();
        }

        callback?.({
          name: "okx",
          network,
          publicKey,
          accounts: [address],
          address,
          btcAddress: address,
          btcPublicKey: compressedPublicKey,
          balance,
        });
      } catch (error) {
        console.error("Account switch monitoring failed:", error);
      }
    }
  });
};
```

\\


# Introduction

Bitcoin-backed lending reveals a clear market gap. Borrowers want access to liquidity without losing their long-term Bitcoin exposure, while lenders seek predictable returns without bearing unlimited downside risk. Current models, both centralized and decentralized, fail to reconcile these opposing needs. Centralized custodians introduce counterparty and rehypothecation risks, while decentralized protocols depend on oracle-driven liquidations that penalize borrowers during volatility.

HodlFi emerges to address this unmet demand. By anchoring collateral in borrower-controlled Taproot contracts and replacing liquidations with market-based hedging, HodlFi provides a principled framework that eliminates forced sales, ensures transparent pricing, and keeps custody with the user. This sets the stage for a lending primitive aligned with Bitcoin's ethos of decentralization and trust minimization.


# Rationals

Traditional crypto lending models expose participants to systemic weaknesses that neither protect borrowers nor fully safeguard lenders.

* **Centralized lenders** require users to surrender collateral and often rehypothecate assets, creating exposure to counterparty failures.
* **Decentralized protocols** such as MakerDAO or Aave avoid direct custody but rely on continuous price feeds and liquidation auctions. These mechanisms trigger involuntary liquidations during short-term volatility, frequently punishing solvent borrowers and mispricing collateral.

The core problem is one of **risk misallocation**. Borrowers are forced to shoulder volatility risk, though they lack tools to manage it effectively. Lenders, meanwhile, remain vulnerable to systemic shocks and uncertain recovery from auctions.

HodlFi addresses these issues by redesigning the borrower–lender relationship:

* **Self-Custody & Trust Minimization:** Collateral always remains under borrower control in a Taproot script, removing the need for custodians or discretionary intermediaries.
* **No Mid-Term Liquidations:** Loans run to maturity without margin calls. Borrowers either repay and reclaim their BTC or forfeit it at term, eliminating the stress of forced liquidations.
* **Market-Aligned Hedging:** Downside risk for lenders is absorbed by an embedded hedge purchased in external markets. This shifts volatility away from borrowers and ensures that protection is transparently priced by professional risk markets.

By structuring loans in this way, HodlFi eliminates liquidation as the default risk-control tool and aligns both sides of the transaction with Bitcoin's principles. Borrowers gain liquidity without fear of losing their long-term position, and lenders earn returns with clear, bounded risk exposure. The specifics of pricing mechanics, cost–leverage trade-offs, and scenario analyses are presented in the **Economic Model** section.


# System Architecture

HodlFi's architecture is designed to be trust‑minimized and secure across both the Bitcoin and Ethereum (or other EVM) networks. It is organized in two layers: a contract layer that defines cross‑chain agreements, and a component layer that defines the roles of participants and off‑chain agents. This section highlights the structure, roles, and security boundaries, leaving time‑sequence details to the Loan Lifecycle.


# Contract Layer

At the contract layer, three interlocking agreements bridge the Bitcoin and Ethereum ecosystems to enable lending:

* **Bitcoin Collateral Script (Taproot, hash‑lock with adaptor fallback):** Collateral is locked in a Taproot script with repayment, fallback, and default paths. This ensures borrower control, prevents mid‑term seizure, and guarantees settlement at maturity.
* **Loan Escrow Contract (on Ethereum):** Stablecoin principal is held in an immutable escrow that mirrors the commitments of the Bitcoin script. Funds are released only after proof of collateral lock and repayment, aligning collateral release with repayment fairness.
* **Off‑Chain Hedge Agreement (Options):** Each loan triggers an external BTC put option purchase. This absorbs price risk for the lender and removes the need for on‑chain liquidations.


# Component Layer

At the component layer, four actors interact within clearly defined boundaries:

* **HodlFi Nexus Node (Lender's Node):** Operated by the lender or pool. Manages escrow funding, repayment withdrawal, SPV verification, and hedge execution. Keys are never shared.
* **Trustless Coordinator:** Off‑chain service for assembling commitments, scripts, and proofs. It never holds funds or keys.
* **Chainlink Cosigner (Liveness Oracle):** Provides liveness only in case of unresponsiveness. It cannot move funds independently and all actions are auditable.
* **Borrower's Wallet:** The sole owner of BTC keys. Signs collateral transactions and reclaims collateral after repayment. Also initiates proof submission and repayment on the EVM side.

This structural design ensures asset custody always remains with its rightful owner (borrower for BTC, lender for stablecoins). No centralized entity or even the protocol itself can seize funds. Security comes from cryptography and economic incentives—hash locks, adaptor signatures, timelocks, and SPV proofs—rather than discretionary trust.

<figure><img src="https://3151511913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxm6xnTBWhCVkjhXII1Wh%2Fuploads%2FFe1nqikv8feu1NPapZPi%2Fimage.png?alt=media&amp;token=c5f22506-64e9-4a89-a293-e445f088a0d1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3151511913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxm6xnTBWhCVkjhXII1Wh%2Fuploads%2FnDQteHIgH03xW5AtdfCc%2Fimage.png?alt=media&amp;token=6474d506-e40e-485b-abcf-c47f6022bdda" alt=""><figcaption></figcaption></figure>


# Loan Lifecycle

The Loan Lifecycle describes how a loan progresses over time across Bitcoin and an EVM chain. It complements the structural view above by focusing on the order of interactions.


# Parameters and Commitments

* Commitments: `H(x)`, adaptor commitment `Y = y·G`, maturity `T`.
* Parties: Borrower on Bitcoin, Nexus Node or lender on EVM, Trustless Coordinator for orchestration, Cosigner for liveness only, Options venue for the external hedge.


# Phases

1. **Commit and Deploy** The Coordinator finalizes `H(x)`, `Y`, and `T`. It prepares the Taproot collateral script with repay, fallback, and default paths, and deploys the EVM escrow with mirrored commitments.
2. **Fund Principal on EVM** The Nexus Node funds the escrow with stablecoin principal. Lender keys remain under lender control.
3. **Lock Collateral on Bitcoin** The Borrower sends BTC to the Taproot script. Network confirmations start.
4. **Prove and Disburse** The Borrower submits an SPV proof of the BTC lock to the EVM escrow. After verification, the escrow disburses loan funds to the Borrower.
5. **Quiet Term** No on-chain liquidations occur. The Nexus Node maintains the protective BTC put hedge off chain for the duration of the loan.
6. **Repay on EVM** The Borrower repays principal plus interest to the escrow before or at `T`.
7. **Withdraw and UnlockMain path using hash lock:** The Nexus Node reveals `x` to withdraw on EVM. Once `x` is public, the Borrower uses it to spend the Taproot repay path and reclaim BTC. **Fallback path using adaptor secret:** If `x` is not available, the withdrawal process discloses or enables derivation of `y`. The Borrower completes the Taproot adaptor path with `y` and reclaims BTC. **Liveness assist if required:** If a party is unresponsive beyond the agreed window, the Cosigner assists with liveness according to preset rules. The Cosigner cannot move funds on its own.
8. **Default at Maturity** If repayment is not made by `T`, the lender spends the Taproot default branch after the timelock. The external hedge covers price risk by design.


# Invariants

* Custody separation: Borrower controls BTC. Lender controls funds.
* Atomic alignment: EVM withdrawal and BTC unlock are coupled through `x` for the main path and `y` for the fallback path. `T` defines the default path.
* Oracle minimization: No price feeds are required for liquidation. The Cosigner is liveness only.
* Auditability: SPV proofs, EVM events, and disclosure of `x` or `y` are publicly verifiable.

This time sequence avoids overlap with System Architecture. Architecture explains what components exist and how they are bounded. Lifecycle explains when and how they interact.


# Trust & Security Considerations

HodlFi's trust and security model is grounded in the cryptographic guarantees of Bitcoin and Ethereum. Only a minimal set of additional assumptions is introduced. The design focuses on a few unchanging principles that together ensure fairness, transparency, and resilience.\
The first principle is custody separation. The borrower always retains control over their Bitcoin keys, and the collateral is locked in a Taproot script that only the borrower can unlock upon repayment. At the same time, the lender remains in full control of the stablecoin principal through the escrow contract. No coordinator, cosigner, or external service has the ability to move funds from either side. Custody is never pooled, and no participant has unilateral access to both assets.\
The second principle is atomic alignment. Repayment on the EVM side requires the lender to reveal the secret x. Once revealed, the borrower can use it to unlock the Bitcoin collateral. If x is not provided, the fallback adaptor secret y ensures that the borrower still regains access to their BTC. In the case of default, if repayment has not occurred by the agreed maturity T, the lender can claim the collateral after the timelock. This design ensures that outcomes always resolve, either by repayment and release or by maturity and default, without indefinite lock-up.\
The third principle concerns the cosigner. The cosigner's only function is to preserve liveness in edge cases. If one party has already fulfilled its obligation on one chain but the counterparty is unresponsive, the cosigner can provide a restricted signature to allow the protocol to progress. Crucially, the cosigner cannot seize funds, cannot change outcomes, and cannot act unilaterally. Every action it takes is publicly recorded on-chain, so any deviation or refusal would be immediately observable. This visibility creates strong economic and reputational incentives for honest behavior.\
The final principle is predictability and transparency. All commitments, timelocks, and repayment conditions are established in advance and are visible on-chain. Repayment always aligns with collateral release, defaults always resolve at maturity, and no live price feeds or liquidation triggers are required. This eliminates whole classes of risks such as oracle manipulation, auction failures, or discretionary interventions.\
Taken together, these principles deliver end-to-end trust minimization. Settlement depends on contracts, cryptographic proofs, and market mechanisms rather than on intermediaries. Users can independently verify each step of the process, confident that HodlFi upholds the ethos of Bitcoin: self-custody, transparency, and resilience.


# Economic Model

The economic foundation of HodlFi can be understood by viewing each loan as equivalent to a structured option position. This framing makes clear how risk and return are distributed between borrower and lender, and how the protocol balances both sides without liquidations.

* From the **lender's perspective**, a loan works like selling a cash-secured put option on Bitcoin. The principal is the strike price, and the lender receives interest plus a volatility premium. If repaid, the yield is earned; if defaulted, the lender takes the collateral. With an external protective put, even a deep crash is covered, keeping outcomes predictable and capped.
* From the **borrower's perspective**, interest and the option fee act as an insurance premium. The borrower gains liquidity while keeping the right to reclaim Bitcoin at maturity. There are no margin calls or forced liquidations, since volatility is absorbed off chain. The cost is transparent and varies with external option markets.

This design separates time value from volatility cost. Interest is tied solely to the duration of the loan, while the option fee reflects the level of volatility implied by markets. A higher loan-to-value ratio or a longer tenor raises the premium, because the lender must absorb greater potential risk. Lower LTVs or shorter terms reduce costs. Borrowers can therefore choose their leverage on a continuum, paying proportionally for the protection they require, while lenders are compensated in line with the exposure they underwrite.

The logic becomes clearest when examined through concrete scenarios:

<figure><img src="https://3151511913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxm6xnTBWhCVkjhXII1Wh%2Fuploads%2FY2hNhxPEWPj4lpv8BPed%2Fimage.png?alt=media&amp;token=9cf847e0-30e1-4f0a-af77-df2a147966e5" alt=""><figcaption></figcaption></figure>

* **50-Day Loan Term:** At \~50% LTV, insurance cost is negligible (≈0%). As LTV rises, the premium grows non-linearly, steeply after \~75%. At 95% LTV, the fee is \~4–5% of loan amount for 50 days, reflecting the thin collateral buffer and sharply higher default risk.

<figure><img src="https://3151511913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxm6xnTBWhCVkjhXII1Wh%2Fuploads%2F63QEh2ChC4jCq3BByU5b%2Fimage.png?alt=media&amp;token=65a41cd9-1cad-428b-b190-67b81e161b1f" alt=""><figcaption></figcaption></figure>

* **106-Day (≈3.5 Month) Term:** Longer duration raises volatility risk, so premiums increase across all LTVs versus the 50‑day loan. Around 75% LTV, the premium is \~2% (vs. near 0% for 50 days). Near 100% LTV, the premium reaches \~7–8%. The curve remains gentle at low LTVs then steep after \~75%, showing that high‑LTV, longer loans become much more expensive as time exposure grows.

<figure><img src="https://3151511913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fxm6xnTBWhCVkjhXII1Wh%2Fuploads%2FfvcRa3TLDPheD78DZTe3%2Fimage.png?alt=media&amp;token=a4e7103b-2d14-4151-8eb5-06034c4498ef" alt=""><figcaption></figcaption></figure>

* **288-Day (≈9.5 Month) Term:** For loans approaching a year, insurance costs rise steeply. Even 50–60% LTV may carry a few percent premium. By \~85% LTV, fees reach double digits, and near‑100% LTV over 9 months demands 15–20% upfront. In short, borrowing almost the full BTC value for nearly a year is very costly, reflecting the extreme risk of such leverage.

These examples, based on real option data, highlight the principle that avoiding interim liquidations carries a predictable, market-based cost. High leverage or long maturities demand higher premiums, while conservative borrowing remains inexpensive. Both borrowers and lenders clearly see the trade-offs. Borrowers pay transparent market prices for protection, and lenders earn fixed returns with hedged downside.

What HodlFi provides is flexibility. Borrowers can choose between higher leverage at greater cost or lower leverage at reduced cost, and they may roll or extend loans at suitable times rather than only at maturity. Adding collateral to reduce LTV functions like proactively topping up before a margin call, but the key difference is that the borrower acts by choice rather than under forced liquidation. Traditional margin systems can trigger liquidations during network congestion or volatile crashes, creating systemic risks. By contrast, HodlFi transforms these risks into predictable costs, allowing borrowers to manage positions actively and lenders to remain protected.


# Dynamic Risk Management

Beyond static interest and LTV, HodlFi manages risk dynamically throughout the loan. Instead of rigid liquidation thresholds, it uses market mechanisms to adapt to volatility without altering on‑chain terms. Each loan's risk is hedged and can be rebalanced: the lender's Nexus Node may sell puts if volatility falls or add protection if it rises. These adjustments occur off‑chain, requiring no smart‑contract changes, giving lenders flexibility to manage exposure rather than being locked into initial risk levels.

This dynamic risk management approach yields several important capabilities and benefits:

* **Flexible LTV:** HodlFi does not liquidate at fixed thresholds. LTV affects only cost, which adjusts with hedge prices. Borrowers see LTV as a cost–leverage spectrum, not a cliff; higher LTV means higher premiums, lower LTV means lower fees. Risk rises gradually and is priced continuously.
* **Market‑Responsive Costs:** Interest is fixed by loan term only. Separate fees, tied to live option prices, adapt to volatility: high volatility raises fees, calm markets lower them. This ensures transparent pricing where borrowers pay rates aligned with market risk.
* **Active Hedging:** Lenders can rebalance off‑chain without altering borrower terms, by selling options if risk falls, rolling or add if it rises. This flexibility, absent in typical on‑chain lending, lets each lender manage exposure independently while keeping borrower experience stable.

By embedding risk transfer into the options market instead of rigid on-chain rules, HodlFi turns a static loan into a dynamic instrument. The protocol requires no complex on-chain rebalancing; adaptation happens organically in external markets as lenders adjust hedges. This design allows HodlFi to ride out volatility in real time. Borrowers retain predictable liquidity since collateral is never liquidated mid-term, while lenders earn bounded, market-aligned returns. Dynamic risk management supports the protocol's long-term sustainability: it can absorb bull runs, crashes, and everything in between, evolving with the market rather than breaking under stress. HodlFi is therefore a resilient financial primitive that remains viable across cycles.


# Conclusion

HodlFi represents a clear evolution in Bitcoin-backed lending, offering more than just the removal of liquidations. It establishes a new paradigm where r**isk management is integral to the loan itself.** By combining self-custody, cross-chain interoperability, and option-based hedging, HodlFi allows borrowers to unlock liquidity from their Bitcoin without fearing forced liquidation, while lenders extend credit with confidence that their downside is capped. Borrowers maintain long-term BTC exposure while meeting short-term liquidity needs, and lenders earn predictable returns that are transparently linked to market pricing rather than exposed to unpredictable losses. This produces a balanced outcome supported by smart contracts and market-based mechanisms instead of intermediaries or ad hoc liquidations.\
The model's reliance on real-time option pricing and cryptographic guarantees ensures that HodlFi adapts to evolving market conditions. Dynamic cost structures tied to volatility allow continuous alignment of incentives, while protocol rules remain fixed on-chain. This adaptability supports long-term sustainability and reflects Bitcoin's ethos of decentralization and user empowerment: collateral always stays in the borrower's control, and all processes are auditable.\
By extending Bitcoin's utility into lending without sacrificing its core principles of custody and trust minimization, HodlFi emerges as a versatile financial primitive capable of thriving across cycles. It provides a blueprint for secure, adaptive, and user-centric lending, unlocking liquidity for Bitcoin holders in a manner that is fair, transparent, and resilient for the future of decentralized finance.


# Mediakit

The latest media kit.👉 [Click here](https://drive.google.com/drive/u/3/folders/1NKsZ5zNOgAmQMCfVJlckd1gMzotXUA9v)

[<br>](https://docs.on.nexus/other/links)




---

[Next Page](/llms-full.txt/1)

