# Unizen Overview

Next-Generation DEX Aggregator

<figure><img src="/files/gvvHmpwHQx4eEopPKViR" alt=""><figcaption></figcaption></figure>

Unizen is a next-generation DEX aggregator, offering developers, traders, and businesses the ability to unlock unparalleled token swap capabilities. Powered by groundbreaking innovations such as the Unizen Liquidity Distribution Mechanism (ULDM) and Unizen Interoperability Protocol (UIP), Unizen offers cost-efficient, decentralized, omni-chain swaps across multiple blockchains.

**Why choose Unizen?**

* Superior Trade Execution: ULDM ensures that trades are optimized for slippage reduction, maximum liquidity, and token output.
* Cross-Chain Functionality: Seamlessly swap assets across chains using our UIP, which connects to 10 different interoperability providers for the best route.
* Real-Time Access: Access digital assets immediately once decentralized liquidity is provisioned on any supported blockchain.
* Enterprise-Grade Intelligence: Our Integrators Portal provides advanced API usage analytics, trading volume insights, and full control over API limits and settings.

Below are the core innovations that make Unizen a leading DEX aggregator in the industry:

***

#### **1.** [**Unizen Liquidity Distribution Mechanism (ULDM)**](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm)

At the core of Unizen's performance is the **Unizen Liquidity Distribution Mechanism (ULDM)**, a proprietary algorithm developed in collaboration with leading European universities. ULDM is designed to split and route trades across **hundreds of decentralized exchanges (DEXs)** and **thousands of liquidity pools** on supported networks. This approach ensures maximum token output while minimizing slippage, providing significant performance gains over traditional aggregators.

* **Trade Optimization:** ULDM analyzes liquidity across multiple DEXs in real time and splits trades to avoid slippage and ensure users get the best possible prices.
* **Multi-Network Support:** The algorithm operates across all supported networks, dynamically choosing the best trading routes based on real-time liquidity and market conditions.
* **Next-Generation Aggregation:** By routing trades through multiple pools, ULDM consistently outperforms other aggregators in price execution across all assets.

***

#### **2.** [**Support for Native UTXO Assets**](/api-get-started/utxo-assets-and-cosmos-swap)

Unizen stands out in the market with its ability to support **native UTXO-based assets**, including **Bitcoin (BTC)**, **Bitcoin Cash (BCH)**, **Cosmos (ATOM)**, **Dogecoin (DOGE)**, and more. Unlike most DEX aggregators, which primarily focus on account-based assets, Unizen enables seamless trading of these UTXO-based assets, all in a **fully decentralized and non-custodial** manner. This feature allows developers to integrate UTXO asset trading functionality without compromising security or decentralization.

* **Decentralized UTXO Trading:** Complete non-custodial support for UTXO-based chains ensures full user control of assets at all times.
* **Cross-Asset Trading:** Enables integration of both UTXO-based and account-based assets, broadening trading possibilities for users.

***

#### **3.** [**Seamless Cross-Chain Swaps via 10 Interoperability Providers**](/introduction-to-unizen/unizen-overview/unizen-interoperability-protocol-uip)

Unizen delivers unmatched cross-chain swapping capabilities by aggregating across **10 interoperability providers** to find the fastest, most cost-efficient routes for cross-chain transactions. This allows users to swap assets across different blockchain networks in a **single transaction** while optimizing for both speed and cost.

* **ULDM Cross-Chain Routing:** ULDM splits and routes trades across liquidity pools on both the source and destination networks, ensuring liquidity is maximized for cross-chain swaps.
* **Single Transaction, Multiple Chains:** Users can execute cross-chain swaps with ease, as Unizen handles liquidity aggregation and transaction routing across both networks.
* **Optimized for Efficiency:** Unizen ensures that cross-chain swaps are executed with the lowest possible fees and minimal delays.

***

#### **4. Enterprise-Grade Performance and Business Intelligence**

Unizen is built to scale with the needs of enterprise clients, offering a suite of tools and features that provide deep insights and control over API usage and trading data. Through the **Unizen Integrators Portal**, businesses can manage all aspects of their integration, from API settings to advanced business intelligence on swapping data.

* **Comprehensive Analytics:** Clients can track API traffic, volume, top-traded assets, and more in real-time, allowing for better decision-making and performance optimization.
* **Advanced Reporting:** Access detailed reports on API usage, trading volumes, and liquidity patterns, enabling businesses to optimize their trading strategies and resource allocation.
* **Full Control via Portal:** Developers can manage API limits, monitor performance, and adjust global settings via the user-friendly Integrators Portal.

***

#### **5. Trusted by Top Industry Players**

Unizen is trusted by some of the top-performing wallets and platforms in the industry, providing unparalleled support, security, and scalability to clients. We offer **24/7 support**, enterprise-level security measures, and a highly scalable infrastructure to ensure smooth operations for businesses of any size.

* **24/7 Technical Support:** Dedicated support team available around the clock to assist with integration, troubleshooting, and optimization.
* **Scalability:** Built to handle high transaction volumes and peak demand, ensuring reliable performance for all users.
* **Enterprise-Level Security:** Strong API security features, including IP whitelisting, rate limiting, and secure key management, protect against unauthorized access and ensure safe trading.

***

#### **Conclusion**

Unizen is the leading DEX aggregator for developers and enterprises looking to integrate decentralized trading functionality into their applications. With the **Unizen Liquidity Distribution Mechanism (ULDM)**, native **UTXO asset support**, and industry-leading **cross-chain capabilities**, Unizen provides an unmatched trading experience. Combined with enterprise-grade features and comprehensive analytics, Unizen offers a fully optimized platform that scales with your business needs, delivering performance, security, and innovation.

For more information on integrating Unizen into your product, explore our [**API documentation**](/api-introduction/introduction) and get started with [**Unizen Integrators Portal**](https://unizen.io/developer) today.


# Unizen Liquidity Distribution Mechanism (ULDM)

Minimizing Slippage in Decentralized Trading

**Introduction** \
The Unizen Trade Engine is a decentralized platform that enables users to trade digital assets across multiple blockchains and decentralized exchanges (DEXs) without worrying about the complexities of different protocols and platforms. One of the platform's key features is the Unizen Distributed Liquidity Mechanism (**ULDM**), a unique liquidity aggregation and routing system designed to minimize slippage in decentralized trading.

#### Slippage in Decentralized Trading

In decentralized trading, slippage is a pervasive issue due to the fragmented liquidity across multiple decentralized exchanges (DEXs). When a trader places an order on a DEX, the price of the asset can fluctuate due to market movements or the impact of the trade itself. This results in slippage, where the final execution price deviates from the expected price.

#### Unizen Liquidity Distribution Mechanism (ULDM)

<figure><img src="/files/tNgkzZeBbNUKZ5pg5s8T" alt=""><figcaption><p>ULDMv3.2</p></figcaption></figure>

Unizen addresses slippage through its advanced Unizen Liquidity Distribution Mechanism (ULDM). ULDM is a sophisticated system that integrates Smart Liquidity Routing and a custom trade splitting algorithm to optimize trade execution across fragmented liquidity pools.

**Smart Liquidity Routing**

Smart Liquidity Routing is a dynamic mechanism that scans multiple DEXs to identify the best available liquidity. The routing algorithm considers factors such as liquidity depth, price impact, and transaction costs to determine the optimal path for trade execution. This ensures that trades are executed at the most favorable price by leveraging the optimal liquidity sources.

**Trade Splitting Algorithm**

The trade splitting algorithm minimizes slippage by dividing larger orders into smaller fragments, which are then executed concurrently across multiple DEXs. Advanced statistical models are used to determine the optimal split strategy, minimizing the price impact of each fragment. This parallel execution ensures that large trades do not significantly affect the market price.

#### Private Market Maker (PMM) Liquidity Integration

A recent enhancement to ULDM is the integration of Private Market Maker (PMM) liquidity. This integration allows Unizen to interface with multiple MM orderbooks and settle transactions on-chain. By incorporating PMM liquidity, ULDM can now simultaneously split and route trades across both private MM orderbooks and AMM liquidity pools, significantly improving trade outcomes, especially for deep liquidity pairs like ETH and USDT.

#### Conclusion

Unizen's ULDM is a robust solution addressing slippage in decentralized trading. By combining Smart Liquidity Routing, a custom trade splitting algorithm, and PMM liquidity integration, ULDM enhances trading efficiency and execution precision. This advanced mechanism ensures that trades are executed at the best possible price while minimizing slippage, providing a superior trading experience across multiple blockchains and DEXs.

{% embed url="<https://youtu.be/8Yw4v7oum50>" %}
Community made comparison with 1inch exchange
{% endembed %}


# ULDM Performance

Challenging The Leading DEX Aggregators

{% hint style="info" %}
This study was conducted April 4, 2023
{% endhint %}

**Abstract**\
In this study, we put Unizen Trade's unique liquidity distribution mechanism ([ULDM](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm)) to the test against leading decentralized exchange (DEX) aggregators [1inch ](https://1inch.com)and [Paraswap](https://www.paraswap.io/). By simulating 37 random trades across 7 different blockchains, we demonstrate the efficiency and cost-effectiveness of Unizen Trade as compared to its competitors.

**Introduction**\
Decentralized exchanges (DEXs) have gained immense popularity in recent years as an alternative to traditional centralized exchanges. With the rising interest in DEXs, the competition among DEX aggregators has also intensified. \
\
1inch, and Paraswap are among the leading DEX aggregators, each offering distinct features and benefits to their users. In this article, we compare the performance of Unizen Trade, powered by its unique liquidity distribution mechanism ("[ULDM](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm)"), against [1inch ](https://1inch.com)and [Paraswap ](https://www.paraswap.io/)through a series of simulated trades.

{% hint style="info" %}
None of the trades nor networks was hand picked, nor has the data been manipulated in anyway to accommodate biases.&#x20;
{% endhint %}

**Methodology**\
We conducted a comparison by writing the below script that generated 37 random trades on 7 different blockchains, using an input amount of $10,000. The trades were executed across all platforms, and the results were recorded to evaluate the performance of Unizen Trade, 1inch, and Paraswap.

{% code lineNumbers="true" %}

```javascript
async function main() {
    const X = parseInt(prompt("Enter number of tokens in dataset to be considered "));

    const rawData = fs.readFileSync('tokenlist.json');
    const jsonData = JSON.parse(rawData);
    const tokenList = jsonData.tokens;

    const randomTokens = getRandomTokens(tokenList, X);

    for (let i = 0; i < randomTokens.length - 1; i++) {
        const tokenIn = randomTokens[i].address;
        const tokenOut = randomTokens[i + 1].address;
        const chainId = 1;

        const tokenInDetails = await getTokenDetails(tokenIn, chainId);
        const amountIn = new BigNumber(10000).dividedBy(tokenInDetails.price).multipliedBy(new BigNumber(10).pow(tokenInDetails.decimals)).toFixed(0);

        const result = await getQuotes(tokenIn, tokenOut, amountIn, chainId);
        console.log(`Swapping 10,000 USD worth of ${tokenList.find(token => token.address === tokenIn).symbol} tokens to ${tokenList.find(token => token.address === tokenOut).symbol} will get you:`);
        console.log(`ZCX: ${result.zcx}`);
        console.log(`Paraswap: ${result.paraswap}`);
        console.log(`1inch: ${result.oneInch}`);
    }
}

function getRandomTokens(tokenList, X) {
    const randomTokens = [];

    for (let i = 0; i < X; i++) {
        const randomIndex = Math.floor(Math.random() * tokenList.length);
        randomTokens.push(tokenList[randomIndex]);
    }

    return randomTokens;
}

async function getTokenDetails(tokenAddress, chainId) {
    const apiUrl = ``;
    const response = await axios.get(apiUrl);
    const data = response.data;

    return {
      decimals: data.decimals,
      price: data.price
    };
}

async function getQuotes(tokenIn, tokenOut, amountIn, chainId) {
  const paraswapUrl = `https://apiv5.paraswap.io/prices`;
  const oneInchUrl = `https://api.1inch.io/v5.0/${chainId}/quote`;
  let chainIdToRPC = new Map();

  chainIdToRPC.set(1, "");
  chainIdToRPC.set(137, "");
  chainIdToRPC.set(56, "");
  chainIdToRPC.set(43114, "");
  chainIdToRPC.set(42161, "");
  chainIdToRPC.set(10, "");
  chainIdToRPC.set(250, "");

  const tradeParams = {
    tokenIn: tokenIn,
    tokenOut: tokenOut,
    slippage: 0.03,
    chainId: chainId,
    inNative: false,
    outNative: false,
    deadline: 1679649641,
    isVIP: true,
    amount: amountIn,
  };
  const dexAggr = new DexAggregatorSDK(chainIdToRPC, undefined);
  // fetching zcx quotes
  let uzParams = dexAggr.getBestQuoteCall(
    tradeParams,
    false,
    undefined,
    undefined,
    false,
    true,
    false,
  );
  
  // fetching paraswap
  const paraswapParams = new URLSearchParams({
    srcToken: tokenIn,
    destToken: tokenOut,
    amount: amountIn,
    side: 'SELL',
    network: chainId,
    srcDecimals: 18,
    destDecimals: 18
  });
  // fetching 1inch
  const oneInchParams = new URLSearchParams({
    fromTokenAddress: tokenIn,
    toTokenAddress: tokenOut,
    amount: amountIn
  });
  const paraswapRequest = fetch(`${paraswapUrl}?${paraswapParams}`).then(response => response.json());
  const oneInchRequest = fetch(`${oneInchUrl}?${oneInchParams}`).then(response => response.json());

  const [uzResult, paraswapResult, oneInchResult] = await Promise.all([
    uzParams,
    paraswapRequest,
    oneInchRequest,
  ]);
  // splitting trade for zcx quotes
  let paramsSplit = await dexAggr.getBestQuoteCall(
    tradeParams,
    false,
    undefined,
    undefined,
    false,
    true,
    true,
    uzResult
  );
  let tot = new BigNumber(0)
  for (let i = 0; i < paramsSplit.length; i++) {
    tot = tot.plus(new BigNumber(paramsSplit[i].actualQuote));
  }
  console.log(uzResult[0].actualQuote, tot.toFixed(0))
  const results = {
    tokenIn: tokenIn,
    tokenOut: tokenOut,
    amountIn: amountIn,
    timestamp: Math.floor(Date.now() / 1000),
    chainId: chainId,
    zcx: BigNumber.max(uzResult[0].actualQuote, tot).toFixed(0),
    paraswap: paraswapResult.priceRoute == undefined ? undefined : paraswapResult.priceRoute.destAmount,
    oneInch: oneInchResult.toTokenAmount,
  };
  return results;
}

```

{% endcode %}

**Results**\
The results of the trades indicate a clear advantage for Unizen Trade, thanks to its in-house produced [ULDM](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm). In many instances, Unizen Trade outperformed its competitors by a significant margin, with better exchange rates and improved efficiency. The table below summarizes the results of the trades across all platforms:

<table><thead><tr><th width="111">Sold</th><th width="98">Bought</th><th width="111">Network</th><th width="135">Unizen Out</th><th>Paraswap Out</th><th>1inch Out</th></tr></thead><tbody><tr><td>GTON</td><td>USDC</td><td>Ethereum</td><td>1593</td><td>877</td><td>873</td></tr><tr><td>GTON</td><td>OGN</td><td>Ethereum</td><td>7364</td><td>7141</td><td>7151</td></tr><tr><td>USDC</td><td>OGN</td><td>Ethereum</td><td>81201</td><td>81481</td><td>81212</td></tr><tr><td>ELON</td><td>USDC</td><td>Polygon</td><td>8922</td><td>8247</td><td>8112</td></tr><tr><td>ELON</td><td>TEL</td><td>Polygon</td><td>3571453</td><td>1</td><td>3282245</td></tr><tr><td>USDC</td><td>TEL</td><td>Polygon</td><td>3950712</td><td>1</td><td>4055932</td></tr><tr><td>STRX</td><td>BUSD</td><td>BNB Chain</td><td>9787.6920269854</td><td>9671.2718994656</td><td>9671.4917587943</td></tr><tr><td>STRX</td><td>EVER</td><td>BNB Chain</td><td>105391</td><td>7</td><td>87346</td></tr><tr><td>BUSD</td><td>EVER</td><td>BNB Chain</td><td>0</td><td>0</td><td>0</td></tr><tr><td>SPELL</td><td>USDC</td><td>Fantom</td><td>9266</td><td>9291</td><td>9419</td></tr><tr><td>SPELL</td><td>CREAM</td><td>Fantom</td><td>134</td><td>105</td><td>88</td></tr><tr><td>USDC</td><td>CREAM</td><td>Fantom</td><td>187</td><td>106</td><td>89</td></tr><tr><td>SPA</td><td>USDC</td><td>Arbitrum</td><td>9421</td><td>9512</td><td>3850</td></tr><tr><td>SPA</td><td>SPELL</td><td>Arbitrum</td><td>9044804</td><td>7485484</td><td>4897293</td></tr><tr><td>USDC</td><td>SPELL</td><td>Arbitrum</td><td>12587215</td><td>12540219</td><td>12415396</td></tr><tr><td>YAK</td><td>USDC</td><td>Avalanche</td><td>9629</td><td>9649</td><td>9651</td></tr><tr><td>YAK</td><td>MILK2</td><td>Avalanche</td><td>1075323</td><td>890454</td><td>890454</td></tr><tr><td>USDC</td><td>MILK2</td><td>Avalanche</td><td>1094318</td><td>915633</td><td>915633</td></tr><tr><td>BIT</td><td>USDC</td><td>Ethereum</td><td>9995</td><td>10006</td><td>10006</td></tr><tr><td>BIT</td><td>METIS</td><td>Ethereum</td><td>383</td><td>385</td><td>385</td></tr><tr><td>USDC</td><td>METIS</td><td>Ethereum</td><td>385</td><td>385</td><td>385</td></tr><tr><td>GFI</td><td>USDC</td><td>Polygon</td><td>5779</td><td>4651</td><td>9200</td></tr><tr><td>GFI</td><td>NEXO</td><td>Polygon</td><td>5087</td><td>2780</td><td>4981</td></tr><tr><td>USDC</td><td>NEXO</td><td>Polygon</td><td>5214</td><td>5236</td><td>5236</td></tr><tr><td>SHEESHA</td><td>BUSD</td><td>BNB Chain</td><td>9815.2053875240</td><td>9675.1578566227</td><td>9675.2488882910</td></tr><tr><td>SHEESHA</td><td>TWT</td><td>BNB Chain</td><td>8107</td><td>8171</td><td>8171</td></tr><tr><td>BUSD</td><td>TWT</td><td>BNB Chain</td><td>0</td><td>0</td><td>0</td></tr><tr><td>LINK</td><td>USDC</td><td>Fantom</td><td>9831</td><td>9852</td><td>9838</td></tr><tr><td>LINK</td><td>COVER</td><td>Fantom</td><td>218</td><td>218</td><td>209</td></tr><tr><td>USDC</td><td>COVER</td><td>Fantom</td><td>219</td><td>219</td><td>210</td></tr><tr><td>CELR</td><td>USDC</td><td>Arbitrum</td><td>1284</td><td>644</td><td>2</td></tr><tr><td>OOE</td><td>USDC</td><td>Avalanche</td><td>2074</td><td>1156</td><td>1156</td></tr><tr><td>OOE</td><td>PEFI</td><td>Avalanche</td><td>227208</td><td>127415</td><td>127302</td></tr><tr><td>USDC</td><td>PEFI</td><td>Avalanche</td><td>844622</td><td>862878</td><td>856744</td></tr><tr><td>CELR</td><td>USDC</td><td>Arbitrum</td><td>1285</td><td>645</td><td>2</td></tr><tr><td>CELR</td><td>TUSD</td><td>Arbitrum</td><td>643</td><td>1</td><td>2</td></tr><tr><td>USDC</td><td>TUSD</td><td>Arbitrum</td><td>9992</td><td>10002</td><td>10002</td></tr></tbody></table>

**Percentage Difference in Amount Returned**

For a clearer and more comprehensive representation of the data, we calculated the percentage differences in the amount returned for each trade. These percentages highlight the extent to which trades executed using Unizen Trade's engine outperformed or underperformed compared to those conducted on [1inch ](https://1inch.com)and [Paraswap](https://www.paraswap.io/).

The formula used to calculate the difference in percentage can be seen below.

$$
((Unizen Output - Competitor Output) / Competitor Output) \* 100
$$

{% hint style="info" %}
To avoid errors by zero division, one was used instead to represent the output whenever a zero output was returned. These occurrences are notable where the percentages are very excessive.
{% endhint %}

The instances where Unizen returns higher amounts compared to its competitors are color-coded in <mark style="color:green;">green</mark>. Cases with minimal differences in the amounts returned are highlighted in <mark style="color:orange;">orange</mark>. For situations where the competition returns significantly larger amounts, the color <mark style="color:red;">red</mark> is employed to visually represent these instances.

<table><thead><tr><th width="92.33333333333331">Trade</th><th>Unizen vs Paraswap</th><th>Unizen vs 1inch</th></tr></thead><tbody><tr><td>1</td><td><mark style="color:green;">81.64%</mark></td><td><mark style="color:green;">82.47%</mark></td></tr><tr><td>2</td><td><mark style="color:green;">3.12%</mark></td><td><mark style="color:green;">2.98%</mark></td></tr><tr><td>3</td><td><mark style="color:orange;">-0.34%</mark></td><td><mark style="color:orange;">-0.01%</mark></td></tr><tr><td>4</td><td><mark style="color:green;">8.18%</mark></td><td><mark style="color:green;">9.99%</mark></td></tr><tr><td>5</td><td><mark style="color:green;">357145200.00%</mark></td><td><mark style="color:green;">8.81%</mark></td></tr><tr><td>6</td><td><mark style="color:green;">395071100.00%</mark></td><td><mark style="color:orange;">-2.59%</mark></td></tr><tr><td>7</td><td><mark style="color:green;">1.20%</mark></td><td><mark style="color:green;">1.20%</mark></td></tr><tr><td>8</td><td><mark style="color:green;">1505485.71%</mark></td><td><mark style="color:green;">20.66%</mark></td></tr><tr><td>9</td><td>N/A</td><td>N/A</td></tr><tr><td>10</td><td><mark style="color:orange;">-0.27%</mark></td><td><mark style="color:orange;">-1.62%</mark></td></tr><tr><td>11</td><td><mark style="color:green;">27.62%</mark></td><td><mark style="color:green;">52.27%</mark></td></tr><tr><td>12</td><td><mark style="color:green;">76.42%</mark></td><td><mark style="color:green;">110.11%</mark></td></tr><tr><td>13</td><td><mark style="color:orange;">-0.96%</mark></td><td><mark style="color:green;">144.70%</mark></td></tr><tr><td>14</td><td><mark style="color:green;">20.83%</mark></td><td><mark style="color:green;">84.69%</mark></td></tr><tr><td>15</td><td><mark style="color:green;">0.37%</mark></td><td><mark style="color:green;">1.38%</mark></td></tr><tr><td>16</td><td><mark style="color:orange;">-0.21%</mark></td><td><mark style="color:orange;">-0.23%</mark></td></tr><tr><td>17</td><td><mark style="color:green;">20.76%</mark></td><td><mark style="color:green;">20.76%</mark></td></tr><tr><td>18</td><td><mark style="color:green;">19.51%</mark></td><td><mark style="color:green;">19.51%</mark></td></tr><tr><td>19</td><td><mark style="color:orange;">-0.11%</mark></td><td><mark style="color:orange;">-0.11%</mark></td></tr><tr><td>20</td><td><mark style="color:orange;">-0.52%</mark></td><td><mark style="color:orange;">-0.52%</mark></td></tr><tr><td>21</td><td>0.00%</td><td>0.00%</td></tr><tr><td>22</td><td><mark style="color:green;">24.25%</mark></td><td><mark style="color:red;">-37.18%</mark></td></tr><tr><td>23</td><td><mark style="color:green;">82.99%</mark></td><td><mark style="color:green;">2.13%</mark></td></tr><tr><td>24</td><td><mark style="color:orange;">-0.42%</mark></td><td><mark style="color:orange;">-0.42%</mark></td></tr><tr><td>25</td><td><mark style="color:green;">1.45%</mark></td><td><mark style="color:green;">1.45%</mark></td></tr><tr><td>26</td><td><mark style="color:orange;">-0.78%</mark></td><td><mark style="color:orange;">-0.78%</mark></td></tr><tr><td>27</td><td>N/A</td><td>N/A</td></tr><tr><td>28</td><td><mark style="color:orange;">-0.21%</mark></td><td><mark style="color:orange;">-0.07%</mark></td></tr><tr><td>29</td><td>0.00%</td><td><mark style="color:green;">4.31%</mark></td></tr><tr><td>30</td><td>0.00%</td><td><mark style="color:green;">4.29%</mark></td></tr><tr><td>31</td><td><mark style="color:green;">99.38%</mark></td><td><mark style="color:green;">64100.00%</mark></td></tr><tr><td>32</td><td><mark style="color:green;">79.41%</mark></td><td><mark style="color:green;">79.41%</mark></td></tr><tr><td>33</td><td><mark style="color:green;">78.32%</mark></td><td><mark style="color:green;">78.48%</mark></td></tr><tr><td>34</td><td><mark style="color:orange;">-2.12%</mark></td><td><mark style="color:orange;">-1.41%</mark></td></tr><tr><td>35</td><td><mark style="color:green;">99.22%</mark></td><td><mark style="color:green;">64150.00%</mark></td></tr><tr><td>36</td><td><mark style="color:green;">64200.00%</mark></td><td><mark style="color:green;">32050.00%</mark></td></tr><tr><td>37</td><td><mark style="color:orange;">-0.10%</mark></td><td><mark style="color:orange;">-0.10%</mark></td></tr></tbody></table>

**Conclusion**&#x20;

This analysis showcases the efficacy of Unizen Trade's distinctive liquidity distribution mechanism (ULDM) in delivering a superior trading experience when compared to prominent DEX aggregators like 1inch and Paraswap. By optimally distributing trades across a diverse range of decentralized liquidity pools, Unizen Trade can offer more competitive rates and enhanced efficiency, rendering it an attractive option for traders seeking optimal outcomes for their transactions.

Nevertheless, it is important to note that the trades evaluated in this study were randomly generated, and certain DEX aggregators may outperform others for specific trading pairs under different circumstances. Both 1inch and Paraswap are innovative solutions that offer additional benefits and serve thousands of DeFi traders worldwide. This study was conducted as a competitive analysis to provide deeper insights into ULDM's performance in real-world situations.


# Unizen Interoperability Protocol (UIP)

Zero Touch, Cost Aggregating and Redundant Digital Asset Interoperability

The Unizen Interoperability Protocol (UIP) is a decentralized and trustless protocol that enables seamless traversal of digital assets across multiple blockchains. It is a construct of interoperability aggregation that ensures interoperability operations are cost-efficient, fast, transparent and secure.UIP locates the best interoperability provider based on speed, asset support, and cost. It is currently integrated with cBridge, Axelar, Stargate, ThorChain and LayerZero with many more to come. These providers use a variety of techniques to enable interoperability, including cross-chain bridging, atomic swaps, and token wrapping.

**Architecture**\
UIP is composed of three main layers:<br>

1. **UIP Core:** The UIP Core manages the protocol's resources, including the allocation of interoperability providers.
2. **UIP Registry:** The UIP Registry is a decentralized database that stores information about interoperability providers and their capabilities, including a list of all supported assets, their respective addresses on each blockchain, and the fees associated with each provider.
3. **UIP Client:** The UIP Client communicates with the UIP Core and UIP Registry to initiate interoperability operations using cross-chain bridging, atomic swaps, and token wrapping.

**Interoperability Providers**\
Interoperability providers are third-party services integrated with UIP that enable the traversal of digital assets across multiple blockchains. UIP locates the best interoperability provider based on speed, asset support, and cost. They are responsible for ensuring the secure transfer of assets between blockchains.

**Asset Support**\
UIP's asset support is based on the asset support of the third-party interoperability providers. UIP supports a wide range of digital assets, including cryptocurrencies, tokens, and stablecoins. Each provider has a different set of assets supported.

**Transaction Fees**\
Transaction fees associated with interoperability operations varies between providers, assets and networks. The lowest fees are determined by the UIP Core based on the complexity and duration of the interoperability operation.

**Redundancy**\
UIP integrates multiple interoperability providers, which can work together to facilitate interoperability operations. If one provider experiences an outage or security breach, other providers can continue to operate, ensuring the uninterrupted transfer of assets between blockchains. The UIP Core constantly monitors the performance of interoperability providers and adjusts its allocation of resources accordingly.

**Conclusion**\
The Unizen Interoperability Protocol (UIP) is a decentralized and trustless protocol that enables seamless and efficient traversal of digital assets across multiple blockchains without any manual user intervention. With its integration of multiple interoperability providers, UIP ensures that users always get the best and most cost-efficient option for their specific asset and blockchain destination. Thanks to its support for a wide range of assets, redundancy, and fee aggregation UIP is well-positioned to be a leading protocol for the next generation of decentralized finance.Unizen users can rest assured that there is always a secure and reliable pathway to transfer their assets between blockchains.&#x20;


# LayerZero

LayerZero is the first system to trustlessly enable direct transactions across all chains. Allowing transactions to flow freely between chains provides opportunities for users to consolidate fragmented pockets of liquidity while also making full use of applications on separate chains. LayerZero provides the network fabric underlying the fully-connected omnichain ecosystem of the future.

**LayerZero endpoints**

LayerZero Endpoints are the user-facing interface to LayerZero. Each chain in the LayerZero network has one LayerZero Endpoint implemented as a series of on- chain smart contracts. An Endpoint’s purpose is to allow the user to send a message using the LayerZero protocol backend, guaranteeing valid delivery. A LayerZero Endpoint is split into four modules: Communicator, Validator, Network, and Libraries. The Communicator, Validator, and Network modules comprise the core functionality of the Endpoint, while each new chain supported by LayerZero is added as an additional Library. This design allows Layer 0 to add support for new chains without modifying the three core modules.

**Oracle**

The Oracle is a third-party service that provides a mechanism to, independently of the other LayerZero components, read a block header from one chain and send it to another chain. In theory, this Oracle can be any third-party service that provides this mechanism, but in practice, they expect to use Chainlink, which is the current industry leader for decentralized oracle networks.

**Relayer**

The Relayer is an off-chain service that is similar in function to an Oracle, but instead of fetching block headers, it fetches the proof for a specified transaction. To ensure valid delivery, the only requirement is that for any given message sent using the LayerZero protocol, the Oracle and Relayer must be independent of each other. The protocol itself does not require any specific implementation of a Relayer, and in theory, the users of LayerZero could even implement their own Relayer service. This design allows users to be sure that the Relayer cannot collude with the Oracle, and this independence is what allows us to implement trustless validated delivery. In practice, LayerZero provides the Relayer service while the Oracle is handled by Chainlink’s decentralized oracle network and associated consensus mechanisms.


# DeBridge

**deBridge is** **a** **secure interoperability layer for Web3** that enables decentralized transfers of arbitrary messages and value between various blockchains. The validation of cross-chain transactions is performed by a network of independent validators who are elected by and work for deBridge governance. Validators maintain the blockchain infrastructure and each run a deBridge node to sign all transactions that pass through deBridge smart contracts in different blockchains.&#x20;

[Delegated staking and slashing](broken://pages/-Mf5FVqSjEbcRQKG-JKP) mechanics act as a backbone for protocol security and provide economic disincentives for validators to collude.

The deBridge protocol is an infrastructure platform and a framework for:

* decentralized transfer of arbitrary data and assets
* cross-chain interoperability and composability of smart contracts
* cross-chain swaps
* interoperability and bridging of NFTs&#x20;

Projects can integrate with deBridge infrastructure to tap into the various cross-chain opportunities that we enable. These can for instance be:

* Build own custom bridges for assets and NFTs preserving custom NFT logic (e.g. breeding)&#x20;
* Enable users from other blockchain ecosystems interact with their protocol (enable global accessibility)
* Scale up their protocol to other chains and exchange commands/messages between components of their protocol
* Make their protocol composable with protocols from other ecosystems
* Build new types of cross-chain applications and primitives
* Enable global accessibility by letting users and protocols from other chains seamlessly interact with the protocol


# Stargate

Stargate Finance is, pretty much, a native asset bridge, with a focus on stablecoins.. As a liquidity transport protocol, the platform allows users to add liquidity to various pools, stake assets, and transfer native assets - which reduce the risk of losing a substantial sum of money since their price is pegged to a stable asset.

Even though Stargate Finance was started by LayerZero Labs, it's considered to be a community-driven project. In fact, the exchange aims to provide users with total transparency with documents and white papers that address any potential issues. Users also can earn high returns with unified liquidity pools as well as extensive farming features.

Stargate is the first bridge to solve the bridging trilemma. Existing bridges are forced to make trade-offs on the following core bridge features:

* **Instant Guaranteed Finality:** Users & Applications can trust that when they successfully commit a transaction on the source chain, it will arrive on the destination chain.
* **Native Assets:** Users & Applications swap in native assets as opposed to wrapped assets that require additional swaps to acquire the desired asset and corresponding fees.
* **Unified Liquidity:** Shared access of a single liquidity pool across multiple chains creates deeper liquidity for users & applications that trust in the bridge's reliability.


# Celer

Short summary of architectural benefits, for users and for liquidity providers.

cBridge (Celer Bridge) introduces the best-in-class cross-chain token bridging experience with deep liquidity for users, highly efficient and easy-to-use liquidity management for both cBridge node operators and Liquidity Providers who do not want to operate cBridge nodes and new exciting developer-oriented features such as general message bridging for cases like cross-chain DEX and NFTs. All of the above is made possible by extending the existing functionality and services provided by the Celer State Guardian Network (SGN) powered by validators and stakers in the system with value capture.

* **Deep liquidity:** supports much larger transfer sizes.
* **Simpler to use:** offer an option to reduce two-step operations to a single click.
* **Native gas token unwrapping:** e.g. transfer WETH from BSC to unwrapped ETH on Arbitrum.
* Extend to even more tokens and chains
* **Insured bridge node Service Level:** did you initiate a transfer but the bridge node was not available? Slash cBridge node’s bond to cover your opportunity cost!
* **White-label frontend SDK:** Allows multi-chain dApp to have a built-in cross-chain experience.
* **Cross-chain messaging for NFT and more:** Allows developers to build applications beyond simple cross-chain asset transfers, including cross-chain DEX and NFT cross-chain minting.


# Axelar

Axelar delivers secure cross-chain communication for Web3. Secure means Axelar is built on proof-of-stake, the battle-tested approach used by Ethereum, Cosmos, Avalanche, and more. Cross-chain communication means you can build a complete experience for users that lets them interact with any asset, any application, on any chain with one click.

**Gateway smart contracts**

Gateway smart contracts allow Axelar to communicate messages across all connected chains. For each EVM chain connected to Axelar network, a Gateway contract is deployed to that chain. This Gateway contract is used to pass messages from the Axelar network to the connected chain, and the Gateway contract is controlled by a key, which is held jointly by all the Axelar validators. This is accomplished through a multi-party cryptography scheme, where the key is divided into many pieces, called key shares. Each validator holds many key shares, and the amount of shares is dictated by the amount of staked AXL tokens the validator has. The Gateway can only execute actions on the external chain if the number of validators holding key shares who authorize the action reaches a set threshold.

**Validators**

First, the validators participate in consensus on the Axelar network, producing blocks and validating transactions as with other proof-of-stake chains. Specifically, they perform the generic duties expected from validators of all Cosmos SDK-based chains.

Beyond this, Axelar validators also have additional duties as they are responsible for verifying all cross-chain activity being processed by the network. This requires validators to run nodes for Axelar-supported chains, and observe those external chains for activity. For example, in an asset transfer flow moving tokens from chain A to chain B, the user requesting the transfer must deposit tokens to a deposit address on chain A, and wait for Axelar network to confirm this deposit. This confirmation is done by the validators. A vote is started on the Axelar network, asking each validator to observe their chain A nodes for the deposit transaction made by the user. The validators then cast votes on whether or not the deposit transaction was observed on their chain A node. The votes are tallied and if the number of confirmation votes surpasses a set threshold, the deposit transaction is considered confirmed by the Axelar network.

At this point, Axelar's multi-party cryptography scheme kicks in. If destination chain B has an Axelar Gateway deployed, the tokens transferred must be minted by the Gateway smart contract and transferred to the user's chain B deposit address. Each Gateway contract is controlled by a key that is able to issue commands to the Gateway and approve transactions by signing. Each Axelar validator holds a piece of this key, called a key share. Validators agree through their confirmation votes to confirm a deposit and sign a transaction transferring the tokens to the user's address on chain B, which completes the asset transfer. Once enough key shares have agreed, the transaction can proceed.

\
**Relayer services**

Relayer services are a type of optional convenience service provided by Axelar. These are tasks that can be performed by anyone, and no form of trust is required to authorize or complete the task. These tasks are still important, as they must be done by someone to enable successful cross-chain communication. Because relayer services do not require any element of trust, and can be implemented by anyone, app developers within the Axelar community can choose to build their own version of existing relayer services for their app to use, instead of using the existing Axelar relayer services.

\
**Gas receiver**

The Gas Receiver is a smart contract that accepts tokens as payment to cover costs of contract execution for general message passing transactions. First, send funds to the Gas Receiver on the source chain, and specify the general message passing transaction that should be covered, as well as the payment token and amount. Axelar relayer services will confirm the gas payment on the source chain, then automatically execute the smart contract call on the destination chain when it gets approved.


# Thorchain

THORChain observes incoming user deposits to vaults, executes business logic (swap, add/remove liquidity), and processes outbound transactions. THORChain is primarily a leaderless vault manager, ensuring that every stage of the process is byzantine-fault-tolerant.

THORChain's key objective is to be resistant to centralization and capture whilst facilitating cross-chain liquidity. THORChain only secures the assets in its vaults, and has economic guarantees that those assets are safe.

THORChain is an independent blockchain that operates as a Layer 1 cross-chain decentralized exchange (DEX). Built using the Cosmos SDK, THORChain enables the exchange of assets across disparate blockchains in a non-custodial manner. THORChain is the backend for many user interfaces.

Key selling points of THORChain are:

* the ability to swap Layer 1, or native, assets across multiple chains - e.g. native BTC to ETH swap.
* No user-registration required - simply send a transaction and THORChain will execute it.
* No wrapped assets - all assets are natively secured.
* Transparent, fair prices, without relying on centralized third-parties.
* Continuous Liquidity Pools that maximise the efficiency of the protocol.

**Value capture**

The fees need to capture value from those accessing the resource and pay it to those providing the resource, and in this case, the resource is liquidity. However, liquidity is relative to the size of the transaction that demands it over the depth of the market that will service it. A small transaction in a deep pool has less demand for liquidity than a large transaction in a small pool.

**Access control**

The other reason for fees is access-control; a way to throttle demand for a fixed resource and let natural market forces take over. If there is too much demand for a resource, fees must rise commensurately. The resource in this case is liquidity, not market depth, thus fees must be proportional to liquidity.

**Resource subsidization**

Every swap on THORChain consumes resources (Disk, CPU, Network and Memory resources from validators). These costs are fixed in nature. In addition, every outgoing transaction demands resources on connected chains, such as paying the Bitcoin mining fee or Ethereum gas cost. As such, THORChain charges a single flat fee on every transaction that pays for internal and external resources.


# Unizen Dashboard

<figure><img src="/files/O8wIVbEUabnMCqwd6GIp" alt=""><figcaption></figcaption></figure>

The Unizen Dashboard provides users with a comprehensive overview of their assets, trades, and transaction history across all supported blockchains. It leverages the [Unizen Omni-Chain Data Pool ](/introduction-to-unizen/unizen-explore/unizen-omni-chain-data-pool)to automatically collect data and present it in an easy-to-read format, complete with graphs and diagrams.&#x20;

The dashboard is built on top of a robust backend infrastructure that allows for fast and accurate data retrieval. It also integrates with the Unizen Trade Engine, enabling users to monitor and manage their cross-chain portfolio from a single location.&#x20;

The dashboard provides users with an unparalleled view of the Web3 ecosystem, allowing them to view all of their NFTs, DeFi assets, and more across their favorite blockchains. They can also track and explore new and old NFTs, view their favorite assets, those trending, or a custom list.&#x20;

With the Unizen Dashboard, users no longer need to manually enter data or visit multiple block explorers to track their assets. They can view their entire portfolio and transaction history in one place, making it easier to make informed investment decisions.&#x20;

Overall, the Unizen Dashboard provides a powerful tool for users to monitor and manage their assets in the Web3 ecosystem. It simplifies the process of tracking investments and provides a comprehensive view of asset holdings and performance across all supported blockchains.


# General

Dashboard should be considered as your homepage, with some general data, shortcuts to other parts of Unizen ecosystem, a chart of ZCX supply, and announcements.


# Portfolio

Portfolio shows which tokens user is holding, on which networks, and also if the user has locked tokens in a known staking contracts on-chain. Great for asset awarness.&#x20;

<figure><img src="/files/WTydntz21u5Q6KLKMsc5" alt=""><figcaption><p>Example of Portfolio</p></figcaption></figure>


# History

History shows any on-chain interactions as it relates to the connected wallet. History is also a quick way to dive deeper into wallets, transactions, swaps and more.

<figure><img src="/files/4J4ueCtwlYcv1zkLM7ER" alt=""><figcaption><p>Example of History</p></figcaption></figure>

&#x20;


# Unizen Trade

Access Decentralized Liquidity Across Multiple Blockchains

<figure><img src="/files/SJk4UWyMwdWvsWkkq83G" alt=""><figcaption></figcaption></figure>

Unizen Trade is a decentralized trading platform that provides immediate access to decentralized liquidity across hundreds of DEXs deployed across all supported blockchains. Any asset is accessible from the moment of IDO on any of the supported blockchains on Unizen Trade - no matter the network liquidity has been provisioned to.

<figure><img src="/files/IFI5FwktQiHSSEIEmLZZ" alt=""><figcaption><p>Trade panel</p></figcaption></figure>

The Unizen Trade Engine is powered by the [Unizen Liquidity Distribution Mechanism (ULDM)](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm) which is a merger of Smart Liquidity Routing and our custom "trade splitting" algorithm developed by researchers at prominent European Universities. This enables the trade engine to minimize slippage significantly for all assets with decentralized liquidity provisioned across all of our supported blockchains and DEXs.&#x20;

ULDM ensures that orders are executed with the best available price across multiple liquidity sources in a trustless and decentralized manner. By splitting the trade order into smaller portions and routing them through different DEXs and liquidity pools, the ULDM optimizes the trade execution to reduce slippage and maximize returns.&#x20;

{% embed url="<https://youtu.be/8Yw4v7oum50>" %}
Community made comparison with 1inch exchange
{% endembed %}

A data driven [competitive analysis](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm/uldm-performance) was conducted for single-chain trades on April 4th, 2023 to see how [ULDM ](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm)performs in real world scenarios against leading DEX Aggregators. This analysis showcases the efficacy of Unizen Trade's distinctive liquidity distribution mechanism ([ULDM](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm)) in delivering a superior trading experience when compared to prominent DEX aggregators like 1inch and Paraswap.

In addition to the benefits provided by the ULDM, the Unizen Trade Engine also utilizes the [Unizen Interoperability Protocol (UIP)](/introduction-to-unizen/unizen-overview/unizen-interoperability-protocol-uip), which allows for seamless access to assets on all supported blockchains with no manual user intervention. The UIP is integrated into the trade engine to automatically handle any necessary conversions or swaps between assets on different chains, allowing users to easily trade and manage their assets without having to worry about the technical details of cross-chain interoperability. This integration greatly simplifies the user experience and allows users to easily take advantage of the diverse range of assets and liquidity available across all supported chains.&#x20;

Unizen Trade also supports fiat conversions to crypto with credit card, Apple Pay and Google Pay. With every fiat purchase, the Unizen Trade Engine finds the best on-ramp provider to maximize returns.&#x20;

The architecture of the Unizen Trade Engine is completely non-custodial, meaning that users maintain full control over their assets throughout the trading process. This ensures that the platform is secure and reliable, and that users can trade with peace of mind.


# Fees

Access Paths and Fee Breakdown

There are two (2) pathways for users to access Unizen Trade:

1. The user comes directly to the [Unizen Trade](https://docs.unizen.io/introduction-to-unizen/unizen-trade) application via [zcx.com](https://zcx.com/); and
2. The user accesses Unizen’s trade aggregator through a third party Web3 application that has integrated its services to Unizen via the Unizen Trade API.&#x20;

There are two key components to the fees:

1. **Integrator Fee**: The fee set by the integrator for each trade conducted using the Unizen API.
2. **Unizen’s Share**: The percentage of the integrator’s fee that is shared with Unizen.

Both values are determined by the selected API plan. Depending on the plan, you may have the flexibility to adjust the fee percentage or, in some cases, there may be no revenue sharing with Unizen at all.

**Direct Access**

Unizen doesn't charge any trading fees from its end-users directly. &#x20;

**API Access**

Third-party integrators connecting to Unizen through the Unizen Trade API can choose an API plan tailored to their specific needs. Each plan outlines the conditions for setting fees and the percentage shared with Unizen. Below is an overview of each plan:

* **Free Plan**: Integrators have complete flexibility to set their own fee percentage. This fee can be adjusted in the settings tab of the integrator's portal. Unizen will retain 20% of the fee set by the integrator.
* **Starter Plan**: This plan follows the same conditions as the Free plan, with integrators free to set their fee percentage, and Unizen retaining 20%.
* **Growth Plan**: In this plan, integrators can set any desired fee, and Unizen does not take any portion of the fee. The fee settings can be managed through the integrator's portal.
* **Custom Plan**: For this plan, a fixed trading fee is agreed upon between the third party and Unizen. Unizen retains a fixed percentage of that fee, as stipulated in the agreement.


# Unizen Explore

Search, Track, and Analyze Single- and Cross-Chain Activity

<figure><img src="/files/oMkFwk1r8BrlZbFKH86k" alt=""><figcaption></figcaption></figure>

Unizen Explore is a powerful omni-chain enabled block explorer that provides users with easy access to on-chain data across multiple blockchains in the Unizen ecosystem. Powered by the Unizen Omni-Chain Data Pool, Unizen Explore provides deep integration with eight blockchains and eliminates the need for users to rely on external block explorers.&#x20;

<figure><img src="/files/UgXYVVqGx34uz6b6BmWy" alt=""><figcaption><p>Unizen explorer search</p></figcaption></figure>

Unizen Explore allows users to search and explore various types of on-chain data with an intuitive user interface. Users can easily track cross-chain trades and bridge operations across all supported blockchains, providing a complete view of their cross-chain activity. Here are some example of queries that can be made.

* [Wallets](https://zcx.com/explorer/address/0xaf951f7a4aa4e2a033b034af0897273ed553e8c3/)
* [Smart Contracts](https://zcx.com/explorer/contract/0x078f188810ad3f2506a4fd76a982f281f4df15f2/137)
* [Transactions](https://zcx.com/explorer/transaction/0x44c8a8b3f607298c3c6b986041bf3fe6b9dac5cb3699540b5a2b0214fda66265/1)
* [Block numbers](https://zcx.com/explorer/block/25947989/56)
* [Single](https://zcx.com/explorer/transaction/0x1d8e1470d24f20d9cdc21c82838de0b183047c1aaebdf42575ec29f48b78c39a/1) & [cross-chain trades](https://zcx.com/explorer/transaction/0x9e8ba069fd7084ea8fda8ff8d4f5a65b1f1161b9de9e78476b9379d5a77291c6/250)
* [NFTs](https://zcx.com/explorer/nft/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d/contract_address=0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d\&chainID=eth-main\&tokenID=1004\&exchange=opensea) & [NFT collections](https://zcx.com/explorer/nft_collection/0x9e4cea1ba3f1fdc80dd2b6ceb20628d03a1b1aea/contract_address=0x9e4cea1ba3f1fdc80dd2b6ceb20628d03a1b1aea\&exchange=opensea\&key=anatomy-pudgy-penguins\&chainId=1)
* [ERC-20](https://zcx.com/explorer/token/0xc52c326331e9ce41f04484d3b5e5648158028804/1) & [BEP-20 tokens](https://zcx.com/explorer/token/0xb8c77482e45f1f44de1745f52c74426c631bdd52/1)

One of the unique benefits of Unizen Explore is its deep integration with the [Unizen Omni-Chain Data Pool](/introduction-to-unizen/unizen-explore/unizen-omni-chain-data-pool), which eliminates cut paper trails and makes on-chain data easily accessible at all times across the entire ecosystem. Users no longer need to rely on third-party block explorers, which streamlines the process of interacting with multiple blockchains.&#x20;

Unizen Explore provides a streamlined and efficient experience for users, making it a valuable tool for those interacting with decentralized applications through Unizen.&#x20;

Overall, Unizen Explore is a powerful tool for exploring on-chain data across multiple blockchains in the Unizen ecosystem, with deep integration, streamlined accessibility, and powerful search capabilities.


# Unizen Omni-Chain Data Pool

The Unizen Omni-Chain Data Pool is a deep storage of on-chain data across all supported blockchains in the Unizen ecosystem. It is designed to provide developers and users with easy access to on-chain data and simplify cross-chain interactions.

The data pool is pieced together across hundreds of data sources, and provides a robust infrastructure for accurate and fast queries. This means that users can easily search for and access on-chain data related to various types of transactions, wallets, NFTs, and more.

Under the hood, the Unizen Omni-Chain Data Pool leverages a number of different technologies to provide its functionality. These include:<br>

1. **Data Integration:** The Unizen Omni-Chain Data Pool integrates data from multiple blockchains in a way that allows users to search for data across all of them. This is achieved through a process of normalizing data from various blockchain sources and storing it in a format that is easily searchable.
2. **Data Storage:** The data pool uses a distributed database to store all of the on-chain data. This allows for easy scalability and ensures that the data is available to users at all times.
3. **Data Indexing:** The Unizen Omni-Chain Data Pool uses indexing techniques to speed up queries and provide fast access to data. This is achieved through a combination of pre-processing and caching techniques.
4. **Data Retrieval:** The data pool provides an API for accessing the stored data. The API is designed to be easy to use, and provides a variety of different search and retrieval methods for different types of data.

One of the key benefits of the Unizen Omni-Chain Data Pool is that it simplifies cross-chain interactions by eliminating the need for users to rely on external block explorers. This reduces the complexity of interacting with different blockchains, and provides a seamless experience for users.

Overall, the Unizen Omni-Chain Data Pool is an important component of the Unizen ecosystem, and provides developers and users with easy access to on-chain data from multiple blockchains. Its deep integration with Unizen Explore and other Unizen products makes it a powerful tool for simplifying web3 interactions and unlocking the potential of decentralized technologies.&#x20;


# Unizen Earn

Stake with Confidence and Flexibility

<figure><img src="/files/QGix0vwBG3dbCGwvEOrq" alt=""><figcaption></figcaption></figure>

Unizen Earn is a staking application on the Polygon blockchain and the Unizen platform that provides users with a flexible and profitable way to earn rewards in various cryptocurrencies. One of the unique features of Unizen Earn is that it allows users to stake their ZCX and earn rewards in multiple cryptocurrencies, not just one.&#x20;

{% embed url="<https://www.youtube.com/watch?v=76rZOlrquYs>" %}

The rewards offered to stakers on Unizen Earn are in various cryptocurrencies from vetted up-and-coming projects with high growth potential. These projects are carefully selected and vetted by ZenX Labs, the research and incubation arm of Unizen, to ensure their quality and potential for growth. \
\
Unizen Earn is designed to be user-friendly, with a simple and intuitive interface that allows users to easily stake their ZCX and track their rewards. The platform does not lock up staked ZCX, so users can deposit or withdraw their ZCX at any time without any penalties or restrictions. This provides users with maximum flexibility, as they can use their ZCX for other purposes if needed. \
\
Unizen Earn offers highly competitive APR rates that can vary depending on market conditions and the assets being rewarded. The APR rates are transparently displayed on the platform, allowing users to make informed decisions about their staking strategies. The platform also provides users with a range of tools and analytics to help them optimize their staking performance. This includes real-time data on the assets being staked, historical performance charts, and customizable alerts and notifications available on the Unizen Dashboard. \
\
Unizen Earn also provides stakers with additional benefits, such as exposure to up-and-coming projects and joint marketing ventures. Projects that participate in Unizen Earn campaigns are featured on the Unizen platform, which can help to create awareness for their brand and the products they build. This has led to increased visibility and growth potential for these projects historically.


# Token Utility

Ever-growing Utility

ZCX is the native utility token powering the Unizen platform. It's an ERC-20 token minted on the Ethereum Network.<br>

The utility of ZCX currently includes the following:

* Hyper-deflationary
* Staking on Unizen Earn
* Pro Membership Purchases
* DAO Utility<br>

**Hyper-deflationary 🔥**

With every trade executed on Unizen Trade or through a Unizen SDK integration, a portion of the trade's USD equivalent will be set aside for a scheduled token burn. In Unizen's terminology, these reserved ZCX assets are referred to as "earmarked" ZCX.

The token burn process is directly linked to the trading volume. Specifically, Unizen will earmark 0.5% of the value of every single-chain trade and 1% of any cross-chain trade.

To put it simply, if Unizen achieves a daily trade volume of $1 million in single-chain trades, then $5,000 worth of circulating ZCX tokens will be scheduled for burning each day.

It's important to note that the timing of these token burns is entirely randomized to ensure compliance with regulatory requirements, hence the use of the term "earmarked."

The buy-back-burn is our **secondary** mechanism of burning, beyond even the burn reserve pool, whereby we utilize fees from our total, aggregate SDK integrations to buy-back and then burn ZCX off the open market, from willing sellers. This takes us from a strong deflationary project to one which we class as having hyper-deflationary tokenomics. Herein, we are following in the footsteps of BTC itself as our foundation and building upon that with the buy-back-burn mechanism.

\
**Staking on Unizen Earn**&#x20;

The ZCX token is used in the Unizen Earn program, a multi-asset rewards program. Users stake their ZCX on the platform to earn a plethora of chain-agnostic rewards in up-and-coming projects that are sourced through ZenX Labs, Unizen’s full-service incubator. The more ZCX that are staked, the higher is the level of rewards a user secures.<br>

**Pro Membership Purchases**

By spending $50 worth of ZCX, users acquire Pro membership on the Unizen platform. Pro membership unlocks the pro trading features that are part of Unizen's UI/UX. The ZCX are subsequently sent to a burn address, which is one element of the token’s hyper-deflationary design.\
\
**DAO Utility**\
\
ZCX now plays a governance role in Unizen’s evolving DAO framework, currently implemented through the [**DEXE platform**](https://app.dexe.io/dao/0x230c939d76000e7fd13b030701828a6f7e6d08bb/dao-proposals/all).

* **Voting Power** is based on **ZCX balances** at the time of a proposal snapshot.
* **Voting is conducted off-chain**, ensuring wide participation without gas cost barriers.
* Governance decisions currently live on the **BNB Chain**, with the system designed to remain lightweight and efficient in early stages.
* Proposals have already been successfully passed through this mechanism, showcasing early community involvement in decision-making.

This governance model allows ZCX holders to participate meaningfully in platform decisions without technical overhead — with plans for deeper on-chain integration in future phases.<br>


# Tokenomics

### Basic Metrics

{% hint style="info" %}
The moving variables of this data is reflected as per 4th of February, 2024. Real time tracking is available at [unizen.io](https://unizen.io)
{% endhint %}

| Circulating supply             | 557.92M ZCX |
| ------------------------------ | ----------- |
| Total supply                   | 948.94M     |
| % Staked                       | 19.45 %     |
| Supply burnt                   | 51.06M ZCX  |
| Supply earmarked for burn      | 349.18k ZCX |
| Circ supply scheduled for burn | 50M ZCX     |

### Allocation

Total number of tokens on TGE: 1 billion, subject to deflationary actions

**Private Sale Tokens:** 16% (Fully circulating)

All tokens have been distributed as of Sep 2022 and are fully vested

**Foundation Tokens:** 28.5% (Partially circulating)

16 million were released as of November 25, 2022

For the remaining tokens an 18-month linear vesting started on January 1, 2023&#x20;

**Partners and Advisors:** 5.5% (Locked)

60-month vesting starting from August 1, 2023,&#x20;

**Team:** 20% (Locked)

* 50% of Team tokens will be unlocked and released after a 36-month lock-up that started July 15, 2022.&#x20;
* The remaining 50% will be unlocked and released in equal portions every calendar month over a period of twenty-four (24) months

**Ecosystem Reserve:** 30% (Fully circulating)

100 million of the 300 million Ecosystem Reserve funds have been sent to a burn reserve contract fueling the burn mechanisms across the Unizen ecosystem

The remaining 200 million is divided into two categories

* 50 million is dedicated to a market making reserve
* 150 million is controlled by the upcoming Unizen Decentralised Autonomous Protocol (uDAP)

###

### Vesting Schedule

**Foundation**

In terms of circulating Foundation tokens, as previously disclosed, 75,600,499.75 and 14,076,445.2 (89,676,944.95 in total) were previously allocated to strategic institutions. An additional 6,066,426.9 in total have been allocated to market making, liquidity, and exchange listings.&#x20;

The remaining Foundation tokens total 189,256,628.15. Of this total, 16 million Foundation tokens were released into circulation as of November 25, 2022. For the remaining Foundation tokens, a 18-month linear vesting period began on January 1, 2023.\
\
As such, 16,000,000 tokens and two months of vested tranches of 9,625,368.2 was added to the circulating supply in November 25, 2022.&#x20;

**Team**

The entire allocation of Team tokens is currently locked and not in circulation. 50% of the Team tokens will be unlocked and released after a 36-month lock-up that began on July 15, 2022. Following this initial lock-up period, the remaining 50% of the Team tokens will be unlocked and released over a period of twenty-four (24) months on a linear basis, ending in July 2027.

**Partners & Advisors**&#x20;

The entire allocation of Partners & Advisors tokens is currently locked and not in circulation. The release of these tokens into circulation shall follow a 60-month linear vesting period that starts on August 1, 2023.

**Ecosystem Reserve**

Is a 300 million token allocation that's fully circulating. However, it will not be directly sold and shall only be used to expand and reinforce the Unizen ecosystem within the two categories specified below.&#x20;

1. **Hyperdeflationary Tokenomics** **Reserve**. 100 million of the 300 million Ecosystem Reserve funds have been sent to a burn reserve contract fueling the burn mechanisms across the Unizen ecosystem. These assets can be withdrawn by the team, distributed or sold as insurance in the highly unlikely event of a hack of the platform. To retain the freedom to act quickly in such an event, these assets are also to be considered circulating. This brings the total of our hyperdeflationary tokenomics reserve to 100,000,000 ZCX in total.<br>
2. **Ecosystem Reserve (Airdrop/Burn/DAO)**. The remaining 200 million in the Ecosystem Reserve allocation will be made circulating to fund marketing and platform growth initiatives, of which 50 million will be dedicated to a market making reserve. The remaining 150 million tokens will be controlled by the upcoming Unizen Decentralised Autonomous Protocol (uDAP). The Unizen team retains the freedom to access these assets prior to the uDAP deployment in two specific cases, namely, an airdrop or a burn.

<br>


# Introduction

Empowering Web3 Builders with Unbeatable Token Swaps

{% hint style="info" %}
Request an API key by filling out this form: <https://www.unizen.io/api-application>
{% endhint %}

<figure><img src="/files/Sya3BZuCLeNDmX18bEIq" alt=""><figcaption></figcaption></figure>

Integrating the Unizen Trade API into your platform unlocks unparalleled value for your users, thanks to our groundbreaking innovations like [Unizen Liquidity Distribution Mechanism](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm/uldm-performance) and [Unizen Interoperability Protocol](/introduction-to-unizen/unizen-overview/unizen-interoperability-protocol-uip). As a proven solution that consistently outperforms leading DEX aggregators, the Unizen Trade API is the go-to choice for Web3 builders offering token swaps in their products.

### Why choose the Unizen Trade API?

Enable the most cost efficient, most accessible and seamless omni-chain enabled decentralized swaps for the users of your product or platform.&#x20;

**Superior Performance**

In a [study of 37 randomly selected single-chain trades](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm/uldm-performance) worth $10k each, Unizen Trade provided approximately $238,073 more value in total compared to the two leading DEX Aggregators.

<figure><img src="/files/Pl90XH5oxSQGTawdtbbS" alt=""><figcaption><p>Unizen Liquidity Distribution Mechanism (ULDM)</p></figcaption></figure>

This superior performance can be accredited to ULDM, an in-house innovation developed in conjunction with top research institutions. ULDM addresses the problem of slippage by combining two key elements: Smart Liquidity Routing and a custom "trade splitting" algorithm.&#x20;

**Seamless Interoperability**

<figure><img src="/files/obSQteh8lhDLzBTXxSM6" alt=""><figcaption><p>Unizen Interoperability Protocol (UIP)</p></figcaption></figure>

[Unizen Interoperability Protocol](/introduction-to-unizen/unizen-overview/unizen-interoperability-protocol-uip) enables the fastest, seamless, zero-touch cross-chain interactions at the lowest cost possible for all assets. This groundbreaking technology further sets Unizen Trade apart from the competition, providing users with an unmatched trading experience.

**Instant Access**

<figure><img src="/files/N5T7WEmuPHGrRlA10P2D" alt=""><figcaption></figcaption></figure>

The moment decentralized liquidity is provisioned on any of the supported blockchains, digital assets immediately become accessible on the Unizen Trade API. Unizen Trade Engine holds access to millions of digital assets across multiple blockchains, including native Bitcoin.&#x20;

**Flexible Fee Structure**

<figure><img src="/files/5whysSFdSQ7lB1BZkphH" alt=""><figcaption></figcaption></figure>

Partners who integrate with Unizen through the Unizen Trade API can opt to charge a fee to their users, with flexibility in the fee structure. The API agreement allows partners to determine the fee to be charged, with Unizen retaining a percentage of the fee or positive slippage based on specific conditions. This ensures a fair and balanced relationship between Unizen and its partners.

Learn more about Unizen's revenue share model [here](/introduction-to-unizen/unizen-trade/fees).

### How does it work?

Unizen Trade API is a superior-grade DEX aggregation and intelligent order routing API. By leveraging this API, developers can effortlessly and dependably access aggregated omni-chain DEX liquidity.&#x20;

Unizen Trade API secures the most optimal execution price across more than 150 liquidity sources, including public Automated Market Makers (AMMs) and private professional market makers, spread across eight diverse blockchains.

<figure><img src="/files/YeZT5VpcMmjpHqdkXXiP" alt=""><figcaption></figcaption></figure>

The process of making a trade on Unizen involves a number of steps.

1. Integrators request a quote from the Unizen API.
2. Once the request data is received, the Unizen API proceeds to call the Unizen Trade Engine, which retrieves a quote from all supported DEX (AMM CDEX).
3. The Unizen Trade Engine then returns the requested data to the Unizen API.
4. The Unizen API then takes over and handles the data based on Integrator requirements. Afterwards, it returns all supported DEX for this trade, with the best trade on top. This stage is crucial because it helps Integrators make an informed decision on the best trade to make.
5. Once Integrators have made a decision, they send a request to the Unizen API to generate data for a transaction with the selected DEX.
6. The Unizen API then generates transaction data, estimates gas, and returns it to the Integrators. This stage is important as it helps Integrators plan ahead and avoid any unforeseen issues that may arise.
7. Once Integrators have received the data, they use it to send the transaction to the Unizen trade contract. This is the final step of the trade.

After that, the Unizen API continues to support the API to track the transaction status, ensuring that Integrators remain updated on the status of their trades.

### Under the Hood: Using the Unizen Trade Aggregator API

To execute trades using the Unizen Trade Aggregator API, follow these steps:

1. Request a quote from the Unizen API by calling the `/quote/single` or `/quote/cross` API. The `/quote/single` API is used for single-chain trades, while the `/quote/cross` API is used for cross-chain trades.
2. The Unizen API will handle the request data and call the Unizen Trade Engine to retrieve a quote from all supported DEXs.
3. The Unizen API will return the requested data to you, allowing you to make an informed decision on the best trade to execute.
4. Once you have decided on the trade you want to execute, call the `/trade/v1/{chainId}/swap/single` or `/trade/v1/{chainId}/swap/cross` API to generate transaction data for the selected DEX.
   1. You can avoid calling the swap endpoint by using the quote endpoint instead. Simply pass the user's wallet address as the `sender` parameter and set `disableEstimate` to `true`. This way, you'll receive the same information as you would from the swap endpoint, saving one transaction in the process. However, this approach only works for the best quote. If you wish to select a different quote, you'll need to call the swap endpoint with the details of that specific quote.
5. The Unizen API will generate the transaction data, estimate gas, and return it to you.
6. Send the transaction to the Unizen trade contract using the data generated by the Unizen API.
7. The Unizen API will continue to support the API to track the transaction status, ensuring that you remain updated on the status of your trades.

By following these steps, you can easily execute trades across multiple DEXs without having to interact with each one individually. This provides a seamless user experience for multi-chain trading and asset management.


# Before you get started

Good to know

{% hint style="info" %}
Here's an example project built with Next.js. Its purpose is to demonstrate how to integrate the Unizen API for single-chain and cross-chain trade: <https://github.com/unizen-io/unizen-dex-aggregator-example>
{% endhint %}

For security reasons, our API does not return contract addresses. Instead, you can obtain Trade Aggregator addresses using either of the following methods:

1. Install the npm package: <https://www.npmjs.com/package/@unizen-io/unizen-contract-addresses> and use the JSON file from `@unizen-io/unizen-contract-addresses/production.json`
2. Configure the JSON file provided below for your project.

```

  {
  "v1": {
    "ethereum": "0xd3f64BAa732061F8B3626ee44bab354f854877AC",
    "bsc": "0x880E0cE34F48c0cbC68BF3E745F17175BA8c650e",
    "polygon": "0x07d0ac7671D4242858D0cebcd34ec03907685947",
    "avax": "0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7",
    "fantom": "0xBE2A77399Cde40EfbBc4e89207332c4a4079c83D",
    "arbitrum": "0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7",
    "optimism": "0xad1D43efCF92133A9a0f33e5936F5ca10f2b012E",
    "base": "0x4F68248ecB782647D1E5981a181bBe1bfFee1040"
  },
  "v2": {
    "ethereum": "0xf140bE1825520F773Ff0F469786FCA65c876885f",
    "bsc": "0x12067e4473a1f00e58fa24e38e2cf3e53e21a33d",
    "polygon": "0x85f8fb7ac814d0a6a0b16bc207df5bbc631f1ca6",
    "avax": "0x468ae09BD4c8B4D9f7601e37B6c061776FeCFE3B",
    "fantom": "0xD38559966E53B651794aD4df6DDc190d2235180E",
    "arbitrum": "0x9660b95fcDBA4B0f5917C47b703179E03a28bf27",
    "optimism": "0x3ce6e87922e62fc279152c841102eb2bf5497010"
  },
  "v3": {
    "ethereum": "0xCf2DBA4e5C9f1B47AC09dc712A0F7bD8eE31A15d",
    "bsc": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "polygon": "0xCf2DBA4e5C9f1B47AC09dc712A0F7bD8eE31A15d",
    "avax": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "arbitrum": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "optimism": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "base": "0xa9c430de6a91132330A09BE41f9f19bf45702f74"
  }
}
```

This file contains the addresses of our production contracts. The version, indicated by "v1" or "v2" or "v3", corresponds to the trade and can be obtained from the quote data of the respective trade using the /quote API.<br>

### How to set the fees

The fees for each integrator can vary based on the selected API plan and, for custom plans, are determined by the fee and revenue-sharing percentage agreed upon with Unizen. Additionally, each trade quote includes a `feePercentage` parameter, allowing integrators to specify different fees based on the trade. For custom plans, the `feePercentage` must fall within the predefined range agreed upon with Unizen.

For more detailed information, please refer to [here](/introduction-to-unizen/unizen-trade/fees).

### Make sure you grasp the concepts of Price Impact and Slippage

We have written an article diving into the concepts and protective measures that should be put in place to protect users from conducting trades with high price impact or slippage. \
\
This article can be found [here](/api-introduction/before-you-get-started/understanding-price-impact-and-price-slippage-in-token-swaps).&#x20;


# Understanding Price Impact and Price Slippage in Token Swaps

This section clarifies the concepts of price impact and price slippage within the context of token swaps facilitated by the API.

## **Price Impact**

Price impact refers to the **immediate difference** in the execution price of a swap compared to the quoted price at the time the order is submitted. It arises due to the following factors:

* **Trade Size:** Larger trade sizes can significantly affect the price within a liquidity pool, leading to a less favorable execution price compared to the quoted price.
* **Liquidity:** Swapping tokens within a pool with low liquidity can cause a higher price impact. This is because there might not be enough sellers or buyers readily available to fulfill your order at the quoted price.

## **Price Slippage**

Price slippage signifies the **potential difference** between the quoted price and the final execution price of a swap. It arises due to external market movements that occur **between the time the order is submitted and the time it is executed**. Unlike price impact, slippage is independent of the trade size itself.

**Minimizing Negative Price Impact**

The API offers mechanisms to minimize negative price impact:

* **Trade Size Optimization:** [ULDM](/introduction-to-unizen/unizen-overview/unizen-liquidity-distribution-mechanism-uldm) allow splitting trades into smaller chunks and routing these across multiple liquidity pools, effectively reducing the impact on the pool's price.
* **Liquidity Checks:** The API checks for pool liquidity before executing a swap, preventing trades with high price impact in illiquid pools. This is a configurable setting in the Integrators Portal.

**Important Considerations**

* It's crucial to acknowledge that the API cannot entirely eliminate price impact, especially for illiquid token pairs.
* Developers integrating the API should advise users to carefully review the estimated execution price before confirming a swap, considering both the quoted price and potential price slippage.

## **How is price impact calculated in our system?**

This section explains how our DEX aggregator calculates price impact for both single-chain and cross-chain trades. We leverage USD as the standard unit for this calculation, offering several key benefits:

* **Universal Comparison:** USD provides a consistent metric, simplifying the comparison of price impact across different trades, regardless of the specific cryptocurrencies involved.
* **User Familiarity:** Expressing price impact in USD allows users to assess the potential effects on their portfolio in a familiar and stable currency, aiding in informed decision-making.
* **Cross-Chain Consistency:** For cross-chain trades involving assets from different blockchains, USD eliminates the complexities of comparing diverse native tokens, ensuring a universal benchmark.
* **Financial Relevance:** USD's widespread use as a reference point in finance allows users to seamlessly understand and compare the impact of cross-chain trades, fostering a more intuitive user experience.

**Calculation Example:**

Let's consider a trade where the input is 100 ETH, equivalent to $224,509.65 USD, and the expected output is 224,183.2629 USDT, approximately equal to $224,242.41 USD.

<figure><img src="/files/oB1vF0pjbXM8BlndGJct" alt="" width="462"><figcaption></figcaption></figure>

We calculate the price impact using the following formula:

**Price Impact = 1 - `(Expected Output / Input)`**

Substituting the values derived from the screenshot:

**Price Impact = 1 - `(224,242.41 USD / 224,509.65 USD)`**

**Price Impact ≈ 0.00119032745**

Expressed as a percentage, the price impact is approximately **0.119%**.

In essence, using USD as the common denominator for price impact calculations enhances user experience, transparency, and accessibility across our DEX aggregator platform.

## **Prioritizing User Protection**

**Slippage Protection in the Quote API:**

The Quote API offers built-in slippage protection for trades through the `slippageProtectionPercentage` parameter. The default value is 0.5 (50%), but integrators can customize this based on their users' needs and risk tolerance.

Here's how it works:

* **Configurable Threshold:** By adjusting the `slippageProtectionPercentage` parameter, integrators can ensure the Quote API only considers DEXs with valid slippage protection mechanisms.
* **Accuracy and Risk Minimization:** This approach helps maintain the accuracy of trade execution and minimizes the risk of slippage, reducing the difference between the expected and actual trade price for users.

This revised version uses more concise language and emphasizes the user's perspective. It also clarifies how the `slippageProtectionPercentage` parameter functions within the Quote API.

<figure><img src="/files/l7SQqniauOnMUz6gwVBO" alt=""><figcaption></figcaption></figure>

**Slippage Transparency:** We clearly inform users about potential slippage through warnings and prompts. This empowers them to understand the risks and confirm their trades with full awareness.

**Price Impact Protection in the Quote API:**

The Quote API provides integrators with an additional layer of protection – price impact filtering. We strive to provide accurate results, so when we can calculate price impact estimates, the API filters out DEXs with invalid or unrealistic price impacts. This ensures users are presented with a list of DEXs that offer a more reliable execution experience.

Similar to slippage protection, integrators can customize the threshold for price impact filtering using the `priceImpactProtectionPercentage` parameter. This allows them to tailor the API's behavior to their specific needs and risk tolerance.

<figure><img src="/files/PgYbY9uvm59PYIlzg3MN" alt=""><figcaption></figcaption></figure>


# Token Allowance Management for Non-updatable Allowance Tokens

**Overview**

In the context of ERC-20 tokens, allowance management is a critical aspect of ensuring that tokens can be securely and efficiently traded. An allowance is a pre-approved limit of tokens that an account (usually a smart contract) can transfer on behalf of another account. However, certain tokens, such as Tether (USDT) on Ethereum, do not support updating an existing allowance amount directly. This means that if the approved allowance is not sufficient for a trade, you must revoke the current allowance and then set a new one.

**Token Allowance Management for USDT**

**Key Points**

* **Non-Updatable Allowance**: USDT on Ethereum does not allow incrementing or decrementing an existing allowance. Instead, the allowance must be set to zero before it can be changed.
* **Allowance Process**: To increase the allowance for a spender, you must first revoke the current allowance by setting it to zero and then approve the new desired amount.
* **Security Considerations**: This process ensures that partial updates to allowances do not inadvertently create security risks or inconsistencies in token management.

**Steps for Managing Allowance**

1. **Revoke Current Allowance**:\
   await usdtContract.approve(spender, 0);&#x20;
2. **Approve New Allowance**:

   await usdtContract.approve(spender, amount);\
   amount can be the exact amount you want to approve, or MaxUnit<br>

For more information, you can check USDT on Ethereum smart contract source code here: <https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7#code>


# Tokens with taxes

For tokens subject to taxes, specific adaptations are essential in trading workflows:

1. **Disable Exact Out Feature**:
   * Disable the exact out feature for these tokens since they are predominantly traded with the exact in trade type. Trade involving taxed tokens and using Exact Out will result in an error message.
2. **Increase Slippage**:
   * Elevate the slippage tolerance to compensate for reduced proceeds when selling taxed tokens.
   * Recommend increasing slippage directly on the UI when dealing with taxed tokens, with adjustments corresponding to the tax rates.
   * Dynamically adjust slippage based on the tax amount provided for each token in the trade to ensure successful transactions despite the tax implications (we provide a recommended slippage on each quote, as we describe at the end of this article)

**Tax Information is included in Quotes Endpoint and Information Endpoints**:

Tax details for each token involved in a trade are included in the quotes endpoint response. Attributes such as buyTax and sellTax for each tokenFrom and tokenTo are present in the information, facilitating users' understanding of tax implications and aiding informed decision-making.

For instance, when querying the quotes endpoint, the UI should will return tax-related information for each token involved, such as buyTax and sellTax. Additionally, the UI should dynamically adapt the slippage settings based on the tax amount associated with each token, promoting seamless trading experiences despite tax considerations.

```json
"tokenFrom": {
      "name": "ZCX",
      "symbol": "ZCX",
      "decimals": 18,
      "contractAddress": "0xc52c326331e9ce41f04484d3b5e5648158028804",
      "chainId": 1,
      "buyTax": 0,
      "sellTax": 0
    }
```

You can also find the tax information in the endpoints that return information about tokens (popular tokens, search, token information).

**A recommended slippage value is included with each quote**

We’ve added a *recommendedSlippage* field, allowing you to see the suggested slippage for a specific token pair. By default, the recommended slippage is set to 0.5%. However, if token taxes apply, this value may be adjusted to prevent failed trades caused by insufficient amounts.

**Setting the Appropriate Slippage Before Requesting a Quote**

To ensure a correct slippage value before making a quote request, you can calculate it directly using the token information, rather than waiting for a recommendation from the API. The process involves checking the tax information for both the token you are sending (tokenFrom) and the token you are receiving (tokenTo):

1. **Check Token Taxes**:
   * For the **tokenFrom**, you need to inspect the `sellTax`.
   * For the **tokenTo**, look at the `buyTax`.
2. **Calculate Slippage**:

   * If either token has taxes applied, you can calculate a proper slippage based on the sum of the buy and sell taxes. For example:

   ```typescript
   const tokenToHasTax = tokenToBuyTax > 0;
   const isNeedOneTimeSlippage = tokenFromHasTax || tokenToHasTax;
   const recommendedSlippage = isNeedOneTimeSlippage 
       ? 0.5 + (tokenFromSellTax + tokenToBuyTax) * 100 
       : defaultSlippage;
   ```

   * If taxes are present, the slippage should be set higher to account for these fees, starting with a base value of `0.5%` plus the combined taxes from both tokens. If no taxes are applied, the **default slippage** is used.

By calculating slippage this way, you ensure that your transaction has enough tolerance to account for token taxes and prevent failed swaps. In the example code, the slippage increases by adding the tax percentages to a base of **0.5%** when taxes are applied.


# Wrapping and Unwrapping Native Tokens

Sometimes, users may want to swap a wrapped native token into the actual native token, a process known as "unwrapping." Conversely, converting a native token into its wrapped version is called "wrapping." Essentially, these are the same token, but wrapping the native token transforms it into an ERC-20 token, which provides additional functionality not supported by native tokens, such as integration with smart contracts or DeFi protocols.

In our API, we cannot facilitate these swaps, as they are not real trades. There are no quotes involved, and the conversion is always a 1:1 ratio since it's the same underlying asset. We recommend that integrators handle this directly in their UI and utilize the chain’s native wrap/unwrap methods (for EVM networks) to perform the conversion.


# Quote expiration deadline

By default, quotes do not have an expiration date. Instead, the market determines whether a quote is still valid. If a user delays confirming the trade and market conditions change, the trade may fail due to insufficient amounts, as the previously calculated quote may no longer be executable.

However, each quote may include an optional field called *quoteDeadline*. This field specifies the expiration time for the quote. If the quote is confirmed after this deadline, the trade will fail. Therefore, integrators must pay attention to this field and display it appropriately in the UI to help prevent failed trades for users.

If the *quoteDeadline* field is absent, it indicates there is no expiration for the quote.


# Security Best Practices for Integrating Unizen

Ensuring that your Unizen integration is secure is essential for protecting both your application and your users. Below are best practices to follow when working with Unizen’s API.

**API Key Management**

* Use Environment Variables: Store API keys securely in environment variables. Never hard-code API keys in your source code or share them publicly.
* Rotate API Keys Regularly: Regularly rotate your API keys to reduce the risk of compromised credentials.
* IP Whitelisting: Enable IP whitelisting to ensure that only authorized IP addresses can make API requests to your Unizen integration.

**Securing API Endpoints**

* Disable CORS: Ensure that your API is configured to disable Cross-Origin Resource Sharing (CORS) to prevent unauthorized access.
* Use HTTPS: All requests to the Unizen API should be made over HTTPS to protect sensitive data in transit.
* Enable Rate Limiting: Implement rate limiting to prevent abuse and denial-of-service (DoS) attacks.

**Example: Setting up IP Whitelisting**

You can restrict API access to certain IPs by configuring IP whitelisting in the Unizen Integrator’s Portal. This helps ensure that only requests from your servers are processed.

By providing concrete steps and examples on how to secure API keys, handle sensitive data, and configure IP whitelisting, this article becomes more actionable and useful for developers.

<br>

###


# Why disable CORS

#### 1. **Protection Against Direct Requests:**

CORS is designed to control how web pages in one domain can request resources from another domain. By disabling CORS, we prevent direct requests to our API endpoints from web pages or applications hosted on different domains. This restriction is intentional to minimize the risk of unauthorized access and potential misuse of sensitive data.

#### 2. **Forcing the Use of Reverse Proxy:**

Disabling CORS acts as a deliberate measure to encourage integrators to adopt a reverse proxy approach. Instead of making direct requests from client-side applications, integrators are prompted to route their API requests through a reverse proxy. This adds an extra layer of security by hiding API keys and minimizing exposure to potential security threats.

### The Role of Reverse Proxy:

#### 1. **Concealing API Keys:**

A reverse proxy serves as an intermediary between client applications and API servers. By utilizing a reverse proxy, API keys are hidden from direct exposure to client-side code, mitigating the risk of key compromise and unauthorized access.

#### 2. **Centralized Security Control:**

Leveraging a reverse proxy allows for centralized security controls. Security configurations, including key handling and access policies, can be managed and monitored from a single point. This centralization streamlines security management, reducing the likelihood of misconfigurations.

#### 3. **Enhanced Monitoring and Logging:**

Reverse proxies provide robust monitoring and logging capabilities for API traffic. Integrators can benefit from comprehensive logs, gaining insights into usage patterns and potential security threats. This enhanced visibility ensures timely detection and response to any suspicious activities.


# How to integrate with a reverse proxy

### How to Integrate with a Reverse Proxy:

#### 1. **Selecting a Reverse Proxy Solution:**

Integrators are encouraged to choose a reliable reverse proxy solution that aligns with their specific requirements. Popular options include Nginx, Apache HTTP Server, and cloud-based solutions like AWS API Gateway.

#### 2. **Configuring API Key Handling:**

Proper configuration of the reverse proxy is essential for secure API key handling. Integrators should follow best practices for configuring the proxy to conceal API keys and enforce access controls.

#### 3. **Implementing Secure Communication:**

Ensure that communication between client applications and the reverse proxy, as well as between the proxy and API servers, is secured using HTTPS. This safeguards data in transit and prevents potential eavesdropping.

Disabling CORS in our API endpoints is a deliberate choice aimed at fortifying the security of our digital infrastructure. We advocate the use of a reverse proxy as a secure and effective means to handle API requests, concealing API keys and centralizing security controls. Integrators are encouraged to follow best practices outlined in this documentation to ensure a secure and reliable integration with our API.

By embracing these security measures, we reinforce our commitment to protecting sensitive data, maintaining the trust of our users and integrators, and creating a robust foundation for secure API-driven applications.


# Version 2 of our smart contracts

We are excited to introduce Version 2 of our smart contract, bringing significant enhancements to improve security, efficiency, and user experience.

**What’s New in Version 2?**

* **Gasless Trades** – Users can now execute trades without needing to pay gas fees in the native token. This eliminates the requirement to hold native tokens for transactions, improving accessibility and user profitability.
* **Permit2 Integration** – This version implements **Permit2**, a more secure and cost-efficient alternative to the traditional allowance system, reducing approval costs and enhancing security.
* **Unified approval address and executor** – In **Version 2**, approvals are now simplified with a **single address**—the **Unizen Router**.

  * No more handling approvals across multiple smart contracts (`v1`, `v2`, `v3`).
  * Users only need to approve the **Unizen Router** once, streamlining the trading experience.
  * This reduces complexity for integrators and improves efficiency for end users.

  With this update, managing approvals is easier, faster, and more consistent across all trades.
* **Optimized Gas Usage** – Internal improvements have reduced overall gas costs, making transactions more efficient.
* **Enhanced Fee Flexibility** – Version 2 provides better handling of integrator fees, allowing for more customization and adaptability.
* **New chains** - you will be able to swap on newly added chains like Unichain and Berachain.

#### **Migration & Adoption**

We **strongly recommend** using Version 2 of the smart contract:

* **New Integrators:** If you are integrating for the first time, you should use **Version 2** from the start.
* **Existing Integrators:** If you are currently using the previous version, we highly encourage you to **migrate** to Version 2. The migration process is straightforward and will allow you to take full advantage of the new features.

By upgrading, you ensure better efficiency, lower costs, and improved user experience for your platform.


# Migration to smart contract v2

Upgrading your current Unizen API implementation to Version 2 is a simple process. Follow these steps to seamlessly transition to the new version and take advantage of its improved features.

**Migration Steps**

1. **Enable Version 2 in Quote Requests**
   * In your **quote** endpoint, include the parameter `version=v2`.
   * This ensures that our system utilizes the latest version of the smart contracts.
2. **Update the Unizen Contract Addresses Package**
   * Upgrade to the latest [**Unizen contract addresses package**](https://www.npmjs.com/package/@unizen-io/unizen-contract-addresses) to retrieve the new `unizenRouter` address.
   * This is the **only address** needed for approvals—no more version-specific handling.
3. **Use the Unizen Router for Transaction Execution**
   * When executing a transaction from the user's wallet (for non-gasless trades), use the **Unizen Router address**.
   * The **swap** endpoint will continue to return the correct contract details, including the necessary approval information (if applicable, unless it’s a **Permit2** trade).

#### **That's It!**

With just these simple steps, your integration will be fully compatible with **Version 2** of Unizen’s API. By upgrading, you ensure improved efficiency, reduced costs, and enhanced functionality.


# QuickStart guide

1. Sign Up: [Request an API key](https://www.unizen.io/developer). Choose the plan or contact us to discuss about your needs.
2. Fetch a Single-Chain Swap Quote: just a simple call to our api passing the api key as header.

```bash
curl -X 'GET' \
  'https://api.zcx.com/trade/v1/56/quote/single?fromTokenAddress=0x0000000000000000000000000000000000000000&toTokenAddress=0x55d398326f99059ff775485246999027b3197955&amount=10000000000000000000&sender=0x54c47034887C582Fc1Af4a9a3b68180a8a9eF2d2&receiver=0x54c47034887C582Fc1Af4a9a3b68180a8a9eF2d2&slippage=0.005&excludedDexes=%7B%0A%20%20%221%22%3A%20%5B%0A%20%20%20%20%220x0000000000000%22%0A%20%20%5D%0A%7D&priceImpactProtectionPercentage=0.5&slippageProtectionPercentage=0.5' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer <YOUR API KEY>'
```

3. The response is an array of quotes, choose the desired quote (the first is the best in terms of amount out) and take the transactionData and just a few fields and call the swap endpoint.

```bash
curl -X 'POST' \
  'https://api.zcx.com/trade/v1/56/swap/single' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer <YOUR API KEY>' \
  -H 'Content-Type: application/json' \
  -d '{
  "transactionData": {
      "info": {
        "feePercent": 0,
        "sharePercent": 0,
        "srcToken": "0x0000000000000000000000000000000000000000",
        "dstToken": "0x55d398326f99059fF775485246999027B3197955",
        "deadline": 1728640582,
        "slippage": 0.005,
        "tokenHasTaxes": false,
        "path": [
          "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c",
          "0x55d398326f99059ff775485246999027b3197955"
        ],
        "v3Path": "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c00006455d398326f99059ff775485246999027b3197955",
        "tradeType": 0,
        "amountIn": "10000000000000000000",
        "amountOutMin": "5646899008721574387295",
        "actualQuote": "5675275385649823504819",
        "uuid": "UNIZEN-CLI",
        "apiId": "17",
        "userPSFee": 0
      },
      "call": [
        {
          "targetExchange": "0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",
          "targetExchangeID": "pancakev3",
          "sellToken": "0x0000000000000000000000000000000000000000",
          "buyToken": "0x55d398326f99059fF775485246999027B3197955",
          "amountDelta": "5646899008721574387295",
          "amount": "10000000000000000000",
          "data": "0xb858183f00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000080000000000000000000000000880e0ce34f48c0cbc68bf3e745f17175ba8c650e0000000000000000000000000000000000000000000000008ac7230489e800000000000000000000000000000000000000000000000001321e7759e10ae35e5f000000000000000000000000000000000000000000000000000000000000002bbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c00006455d398326f99059ff775485246999027b3197955000000000000000000000000000000000000000000"
        }
      ]
    },
  "nativeValue": "10000000000000000000",
  "account": "0xF0Fbf42C54Ac40dA016003baD35E5AefaC6E1CE1",
  "receiver": "0xF0Fbf42C54Ac40dA016003baD35E5AefaC6E1CE1",
  "tradeType": 0
}'
```

4. Finally in the response of this swap endpoint you have the data to conduct the trade on the user's wallet.

Check out our full API documentation in the next sections.

<br>


# Information endpoints

The information that you need to perform the best swaps.

{% hint style="info" %}
Here's an example project built with Next.js. Its purpose is to demonstrate how to integrate the Unizen API for single-chain and cross-chain trade: <https://github.com/unizen-io/unizen-dex-aggregator-example>
{% endhint %}

A list of endpoints that returns information needed for other endpoints  to perform a trade:

1. `/trade/v1/info/chains`: This endpoint provides a list of chains available within the API.
2. `/trade/v1/info/sources`: This endpoint returns a list of exchanges available for each chain.
3. `/trade/v1/info/cross-providers`: It returns information of the different cross-providers enabled on our system.
4. `/trade/v1/info/token/search`: This endpoint allows users to perform search of tokens within the API. It typically accepts search parameters and returns results a list of tokens that match the specified criteria.&#x20;
5. `/trade/v1/info/token/popular`: This endpoint returns a list of popular tokens. A chain id can be sent as optional param.
6. `/trade/v1/info/token/{chainId}/{tokenAddress}`: This endpoint returns the information of a concrete token given its contract address and chain id where it is deployed.
7. `/trade/v1/info/tokenLogo/{chainId}/{tokenAddress}`: This endpoint returns the token logo of a given token. It's an image.
8. `/trade/v1/info/thorchain-inbound-address:`This endpoint returns the contract addresses of the smart contracts that involves BTC trading .
9. `/trade/v1/info/trade/{txHash}`: This endpoint returns the information of a cross chain trade given its transaction hash in the chain from.
10. `/trade/v1/info/trade/{chainId}/{txHash}`This endpoint returns the information of a trade conducted using our API. It can be single or cross chain. For cross chain trades, the txHash has to be the on on the origin chain.

These endpoints are interconnected, with `/chains` providing an overview of available chains, `/sources` identifying the exchanges available in our API on each chain, and `/search` enabling users to query and retrieve specific information of tokens based on their requirements. The combination of these endpoints helps users navigate and access the desired data efficiently.


# GET /trade/v1/info/chains

Get list of supported chains in Unizen Aggregator SDK.

{% openapi src="/files/2IU9blsEv6mdn2LEvNd6" path="/trade/v1/info/chains" method="get" expanded="true" %}
[docs-json (10).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE9UaVFYfsiou7DHQncB4%2Fdocs-json%20\(10\).json?alt=media\&token=fc4c45ca-79ee-45a0-95f4-142613db6867)
{% endopenapi %}


# GET /trade/v1/info/sources

Get list of decentralized exchanges for each supported chain in Unizen Aggregator SDK.

{% openapi src="/files/2IU9blsEv6mdn2LEvNd6" path="/trade/v1/info/sources" method="get" expanded="true" %}
[docs-json (10).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE9UaVFYfsiou7DHQncB4%2Fdocs-json%20\(10\).json?alt=media\&token=fc4c45ca-79ee-45a0-95f4-142613db6867)
{% endopenapi %}


# GET/v1/info/cross-providers

It returns cross-chain providers information

{% openapi src="/files/9osqBn3W6crgDTw6PsgP" path="/v1/info/cross-providers" method="get" expanded="true" fullWidth="true" %}
[docs json (1).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2Fj9HgIoOjl5uKtJ6QGcI0%2Fdocs%20json%20\(1\).json?alt=media)
{% endopenapi %}


# GET /trade/v1/info/token/search

Get list of tokens and their information given a search term.

{% openapi src="/files/2IU9blsEv6mdn2LEvNd6" path="/trade/v1/info/token/search" method="get" expanded="true" %}
[docs-json (10).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE9UaVFYfsiou7DHQncB4%2Fdocs-json%20\(10\).json?alt=media\&token=fc4c45ca-79ee-45a0-95f4-142613db6867)
{% endopenapi %}


# GET /v1/info/token/popular

Get a list of popular tokens.

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/v1/info/token/popular" method="get" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# GET /trade/v1/info/token/{chainId}/{tokenAddress}

Get information of a token given a chain id and the contract address of the token.

{% openapi src="/files/xyXcyJFj7gpZw8zVrlvo" path="/trade/v1/info/token/{chainId}/{tokenAddress}" method="get" expanded="true" %}
[docs-json (7).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FpX0oNr2akUWL3w1iQ4Cw%2Fdocs-json%20\(7\).json?alt=media\&token=3e8a8888-55df-4435-9f07-38ad272bcf4b)
{% endopenapi %}


# GET /trade/v1/info/tokenLogo/{chainId}/{tokenAddress}

This endpoint returns the token logo of a given token. It's an image.

{% openapi src="/files/MczrvqsUY5q5EBHwcyvc" path="/v1/info/tokenLogo/{chainId}/{tokenAddress}" method="get" expanded="true" %}
[docs-json (3).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FI19gjAAV6b8xrJugXmWa%2Fdocs-json%20\(3\).json?alt=media\&token=29656672-d4ab-4e6d-84e4-c36d4099622f)
{% endopenapi %}


# GET /info/thorchain-inbound-address

Get information of a BTC cross-chain trade

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/info/thorchain-inbound-address" method="get" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# GET /trade/v1/info/tx/{txHash}

Get information of a cross chain trade given a transaction hash (it has to be the transaction hash on the origin chain)

{% openapi src="/files/Ln0NPsTXlO0x0y5xoapW" path="/v1/info/tx/{txHash}" method="get" expanded="true" fullWidth="false" %}
[docs-json (4).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FmrEmmN4SYdb91bKtRAY9%2Fdocs-json%20\(4\).json?alt=media\&token=4ea60b66-48f4-4cf4-aedc-0830546748f7)
{% endopenapi %}


# GET /trade/v1/info/trade/{chainId}/{txHash}

Get information of a trade conducted in Unizen API.

{% openapi src="/files/Ln0NPsTXlO0x0y5xoapW" path="/v1/info/trade/{chainId}/{txHash}" method="get" expanded="true" fullWidth="false" %}
[docs-json (4).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FmrEmmN4SYdb91bKtRAY9%2Fdocs-json%20\(4\).json?alt=media\&token=4ea60b66-48f4-4cf4-aedc-0830546748f7)
{% endopenapi %}


# GET /trade/v1/info/trades

Get information of the trades conducted in Unizen API, by the company of the api key used.

{% openapi src="/files/P1uQ7IUGeYHFOtMBlfT0" path="/v1/info/trades" method="get" expanded="true" %}
[docs-json (5).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FSQRjaBg8bLu1JxWKwY70%2Fdocs-json%20\(5\).json?alt=media\&token=fcd9b4e1-1a79-4433-acff-93f44f35d74b)
{% endopenapi %}


# Approval

The approval endpoints facilitate the authorization process required for conducting trades on the Unizen smart contract. These endpoints provide essential functionality for managing permissions and ensuring secure and efficient trade execution on the Unizen platform. While it's not mandatory to use these endpoints, they offer convenient and streamlined methods for handling approvals.

**1. `/trade/v1/{chainId}/approval/spender`:**

**Method: `GET`**

**Description:**

This endpoint retrieves the address of the Unizen DEX Aggregator, which is essential for performing approval actions. Users need to approve this address to authorize the DEX Aggregator to spend funds on their behalf during trades.

**2. `/trade/v1/{chainId}/approval/transaction`:**

**Method: `GET`**

**Description:**

This endpoint generates the data required to call the Unizen smart contract, facilitating the approval process for allowing the Unizen DEX Aggregator to spend funds. It streamlines the process by providing the necessary transaction data for executing approvals efficiently.

**3. `/trade/v1/{chainId}/approval/allowance`:**

**Method: `GET`**

**Description:**

This endpoint retrieves the number of tokens that the Unizen DEX Aggregator is currently allowed to spend on behalf of the user. It offers transparency and visibility into the approved token allowance, enabling users to monitor and manage their permissions effectively.

**Usage:**

Developers and users can utilize these endpoints to handle approval actions conveniently and securely. By leveraging these endpoints, users can streamline the authorization process and ensure smooth and efficient trade execution on the Unizen platform.

**Note:**

While direct operations on the blockchain using the address from the `@unizen-io/unizen-contract-addresses` package are possible, utilizing these endpoints provides a more user-friendly and integrated approach to managing approvals. They offer a centralized and standardized method for handling authorization, enhancing the overall trading experience on Unizen.


# GET /trade/v1/{chainId}/approval/spender

Address of Unizen DEX Aggregator that must be trusted to spend funds.

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/v1/{chainId}/approval/spender" method="get" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# GET /trade/v1/{chainId}/approval/transaction

It generates the data needed for calling the contract in order to allow Unizen DEX Aggregator to spend funds.

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/v1/{chainId}/approval/transaction" method="get" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# GET /trade/v1/{chainId}/approval/allowance

Get the number of tokens that the Unizen DEX Aggregator is allowed to spend.

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/v1/{chainId}/approval/allowance" method="get" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# Single-Chain Swap

Unizen API for Dex Aggregator Single-Chain Transaction

This document provides an overview of the Unizen API for single-chain transactions via the Unizen DEX aggregator. The API provides access to all available quotes for a trade from supported DEXes, as well as the ability to generate transaction data for a trade.

Unizen's trading architecture is decentralized, providing access to over 20,000 digital assets across more than 160 decentralized exchanges and 7 blockchains. This allows users to get the most out of their trades and easily access digital assets on any supported blockchain.

**Available Endpoints**

The Unizen API for single-chain transactions provides the following endpoints:

* `GET /trade/v1/{chainId}/quote/single`: Find all available quotes for a single-chain trade via the Unizen DEX aggregator.
* `GET /trade/v1/{chainId}/swap/single`: Generate transaction data for a single-chain trade via the Unizen DEX aggregator.

| Network             | Quote Endpoint               | Swap Endpoint               |
| ------------------- | ---------------------------- | --------------------------- |
| Ethereum (Mainnet)  | /trade/v1/1/quote/single     | /trade/v1/1/swap/single     |
| Polygon             | /trade/v1/137/quote/single   | /trade/v1/137/swap/single   |
| Binance Smart Chain | /trade/v1/56/quote/single    | /trade/v1/56/swap/single    |
| Optimism            | /trade/v1/10/quote/single    | /trade/v1/10/swap/single    |
| Fantom              | /trade/v1/250/quote/single   | /trade/v1/250/swap/single   |
| Avalanche           | /trade/v1/43114/quote/single | /trade/v1/43114/swap/single |
| Arbitrum            | /trade/v1/42161/quote/single | /trade/v1/42161/swap/single |

**Using the Unizen API for Single-Chain Transactions**

1. Call `GET /trade/v1/{chainId}/quote/single` to get all available quotes for a single-chain trade via the Unizen DEX aggregator.
2. Call `GET /trade/v1/{chainId}/swap/single` to generate transaction data for a single-chain trade via the Unizen DEX aggregator.
3. Send the transaction to the DEX aggregator contract using the `sendTransaction` function, passing in the `from` address, `to` address, `data`, `gasPrice`, `gasLimit`, and `value` parameters.

**Note**: you can avoid calling the 2nd step (swap call) if you pass the sender and the parameter disableEstimateGas=false to the quote endpoint, so you will get the gas estimation and the transaction data to conduct the trade

**Minimum Trade Amount**:

* The minimum amount to trade is $1 (in USD value of tokens). Trades with amounts below this limit are not allowed.

**Solana**

You can get quotes and execute trades on supported EVM chains (Ethereum, BSC, Polygon, Berachain, etc.) as well as on Solana. The process is identical for both, except for the final step—sending the confirmation to the user's wallet. This step requires different handling depending on whether the chain is EVM-based or Solana. The details are explained in the following articles.

**Important**: the chain id for Solana is -846853820


# GET /trade/v1/{chainId}/quote/single

Find all available quotes for single-chain trade via Unizen DEX Aggregator

{% openapi src="/files/P1uQ7IUGeYHFOtMBlfT0" path="/v1/{chainId}/quote/single" method="get" expanded="true" %}
[docs-json (5).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FSQRjaBg8bLu1JxWKwY70%2Fdocs-json%20\(5\).json?alt=media\&token=fcd9b4e1-1a79-4433-acff-93f44f35d74b)
{% endopenapi %}


# GET /trade/v1/{chainId}/swap/single

Generate transaction data for single-chain trade via Unizen DEX Aggregator

{% openapi src="/files/Ln0NPsTXlO0x0y5xoapW" path="/v1/{chainId}/swap/single" method="post" %}
[docs-json (4).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FmrEmmN4SYdb91bKtRAY9%2Fdocs-json%20\(4\).json?alt=media\&token=4ea60b66-48f4-4cf4-aedc-0830546748f7)
{% endopenapi %}


# Send transaction in evm chains

Send the transaction to the DEX Aggregator contract.

#### Example <a href="#example" id="example"></a>

```typescript
library.getSigner().sendTransaction({ from: account, to: contractAddress, data: data, gasPrice: userGasPrice?.value, // optional gasLimit: estimateGas, // optional value: nativeValue });
```

#### Parameters <a href="#parameters" id="parameters"></a>

With data from /quote/single API (contractAddress, data, nativeValue, estimateGas)

* `library`: [ethers.providers.Web3Provider](https://docs.ethers.org/v4/cookbook-providers.html#metamask)
* `account`: the address of the wallet sending the transaction
* `data`: the transaction data to be sent
* `contractAddress`: the address of the contract to which the transaction is being sent
* `userGasPrice` (optional): the gas price set by the user
* `estimateGas` (optional): the estimated amount of gas needed for the transaction
* `currencyInIsNative`: a boolean value that indicates whether the currency being used is native to the blockchain or not
* `nativeValue`: the value of the native currency being sent with the transaction

#### Return Value <a href="#return-value" id="return-value"></a>

This function returns a promise that resolves to a transaction hash. The format data can be found here: [Signers](https://docs.ethers.org/v5/api/signer/#Signer-sendTransaction)

**ContractAddress**

When you are preparing to send a transaction, it is essential to reference the correct version of the smart contract. This version is specified within the `transactionData` of the swap endpoint. Alternatively, if you have the `disableEstimate` parameter set to false, you would refer to the quote endpoint instead. Once you have identified the correct version, you can obtain the associated address by referring to our npm package that contains all our smart contract addresses.

The `transactionData` will also provide a field known as `contractAddress`. This field reflects the same address where the transaction must be directed. However, for enhanced security and to minimize potential risks, we strongly advise retrieving the contract address through our npm package instead of solely relying on the address provided in the `transactionData`. This recommendation is made to safeguard against any inadvertent security vulnerabilities that could arise from using incorrect or outdated address information.


# Send transaction in Solana

Here's how you can send a Solana transaction to execute the trade.

**Steps to Send a Transaction on Solana**

1. Set up a Solana connection.
2. Create transaction instructions.
3. Fetch the latest blockhash.
4. Create a `TransactionMessage`.
5. Use Address Lookup Tables (ALTs) if available.
6. Compile and create a `VersionedTransaction`.
7. Sign and send the transaction.
8. Return the transaction signature.

***

**Code Example (Without Hooks)**

```ts
import { 
  Connection, PublicKey, TransactionInstruction, TransactionMessage, 
  VersionedTransaction, AddressLookupTableAccount 
} from '@solana/web3.js';

// 1️⃣ Initialize Solana connection
const connection = new Connection('https://api.mainnet-beta.solana.com');

// 2️⃣ Function to create and send a transaction
async function sendSolanaTransaction(wallet, instructionsData, addressLookupTableAccounts) {
  if (!wallet?.publicKey) {
    throw new Error("Wallet is not connected");
  }

  // 3️⃣ Convert instruction data into TransactionInstructions
  const instructions = instructionsData.map((instruction) => new TransactionInstruction({
    keys: instruction.keys.map(key => ({
      pubkey: new PublicKey(key.pubkey),
      isSigner: key.isSigner,
      isWritable: key.isWritable
    })),
    programId: new PublicKey(instruction.programId),
    data: Buffer.from(instruction.data)
  }));

  // 4️⃣ Fetch the latest blockhash
  const { blockhash } = await connection.getLatestBlockhash('confirmed');

  // 5️⃣ Handle Address Lookup Tables (if available)
  const lookupTables = addressLookupTableAccounts?.map(alta => new AddressLookupTableAccount({
    key: new PublicKey(alta.key),
    state: {
      addresses: alta.state.addresses.map(addr => new PublicKey(addr)),
      authority: new PublicKey(alta.state.authority),
      deactivationSlot: BigInt(alta.state.deactivationSlot),
      lastExtendedSlot: alta.state.lastExtendedSlot,
      lastExtendedSlotStartIndex: alta.state.lastExtendedSlotStartIndex
    }
  }));

  // 6️⃣ Create a TransactionMessage
  const messageV0 = new TransactionMessage({
    payerKey: wallet.publicKey,
    recentBlockhash: blockhash,
    instructions: instructions
  });

  // 7️⃣ Compile to VersionedTransaction
  const messageV0Compiled = messageV0.compileToV0Message(lookupTables);
  const transaction = new VersionedTransaction(messageV0Compiled);

  // 8️⃣ Sign and send the transaction
  const signature = await wallet.signAndSendTransaction(transaction);
  
  console.log("Transaction Signature:", signature);
  return signature;
}
```

***

#### **How to Use This Function**

```ts
// Example wallet object (Replace with actual wallet provider)
const wallet = {
  publicKey: new PublicKey("YourWalletPublicKeyHere"),
  signAndSendTransaction: async (tx) => {
    console.log("Signing and sending transaction...");
    return "mock_signature"; // Replace with actual wallet signing logic
  }
};

// Example transaction instructions (Replace with real data)
const transactionInstructions = [
  {
    keys: [{ pubkey: "TargetAddressHere", isSigner: false, isWritable: true }],
    programId: "ProgramIdHere",
    data: "Base64EncodedDataHere"
  }
];

// Example Address Lookup Tables (Replace with real ALTs)
const addressLookupTableAccounts = [];

// Send transaction
sendSolanaTransaction(wallet, transactionInstructions, addressLookupTableAccounts)
  .then(sig => console.log("Transaction sent with signature:", sig))
  .catch(err => console.error("Transaction failed:", err));
```

***

#### **Explanation**

* **Creates a transaction** from provided instructions.
* **Fetches the latest blockhash** to ensure validity.
* **Uses Address Lookup Tables (ALTs)** for optimized transactions.
* **Compiles the transaction** into a `VersionedTransaction`.
* **Signs and sends the transaction** using the connected wallet.


# Cross-Chain Swap

Unizen API for Dex Aggregator Cross-Chain Transaction

Cross-chain swaps allow users to trade assets across different blockchain ecosystems without needing to rely on centralized exchanges. Unizen provides a unique advantage by leveraging the Unizen Liquidity Distribution Mechanism (ULDM) to optimize both the source and destination network liquidity.

This document provides an overview of the Unizen API for cross-chain transactions via the Unizen DEX aggregator. The API provides access to all available quotes for a trade from supported DEXes across different blockchains, as well as the ability to generate transaction data for a trade.

With Unizen's trading architecture, users can easily access and trade over 20,000 digital assets across more than 160 decentralized exchanges and 7 blockchains, making it a powerful tool for cross-chain trading and asset management.

#### Available Endpoints <a href="#available-endpoints" id="available-endpoints"></a>

The Unizen API for cross-chain transactions provides the following endpoints:

* `GET /trade/v1/{chainId}/quote/cross`: Find all available quotes for a cross-chain trade via the Unizen DEX aggregator.
* `GET /trade/v1/{chainId}/swap/cross`: Generate transaction data for a cross-chain trade via the Unizen DEX aggregator.

| Network             | Quote Endpoint              | Swap Endpoint              |
| ------------------- | --------------------------- | -------------------------- |
| Ethereum (Mainnet)  | /trade/v1/1/quote/cross     | /trade/v1/1/swap/cross     |
| Polygon             | /trade/v1/137/quote/cross   | /trade/v1/137/swap/cross   |
| Binance Smart Chain | /trade/v1/56/quote/cross    | /trade/v1/56/swap/cross    |
| Optimism            | /trade/v1/10/quote/cross    | /trade/v1/10/swap/cross    |
| Fantom              | /trade/v1/250/quote/cross   | /trade/v1/250/swap/cross   |
| Avalanche           | /trade/v1/43114/quote/cross | /trade/v1/43114/swap/cross |
| Arbitrum            | /trade/v1/42161/quote/cross | /trade/v1/42161/swap/cross |
| Base                | /trade/v1/8453/quote/cross  | /trade/v1/8453/swap/cross  |

#### How it works. Using the Unizen API for Cross-Chain Transactions <a href="#using-the-unizen-api-for-cross-chain-transactions" id="using-the-unizen-api-for-cross-chain-transactions"></a>

1. Call `GET /trade/v1/{chainId}/quote/cross` to get all available quotes for a cross-chain trade via the Unizen DEX aggregator.
2. Call `GET /trade/v1/{chainId}/swap/cross` to generate transaction data for a cross-chain trade via the Unizen DEX aggregator.
3. Send the transaction to the DEX aggregator contract using the `sendTransaction` function, passing in the `from` address, `to` address, `data`, `gasPrice`, `gasLimit`, and `value` parameters.

**Note**: you can avoid calling the 2nd step (swap call) if you pass the sender and the parameter disableEstimateGas=false to the quote endpoint, so you will get the gas estimation and the transaction data to conduct the trade

**Cost Calculation for Cross-Chain Swaps**:

* **When Trading with Native Currency**:
  * **Total Spend** = `nativeValue` + `native Fee` (from our quote API) + `transaction fee` (gas limit \* gas price)
* **When Trading with Tokens**:
  * **Total Spend** = `amount of token to trade` + `native Fee` (from our quote API, payable in native ETH, BNB, MATIC, etc.) + `transaction fee` (gas limit \* gas price)

Here you have some more clarifications:

* **`nativeValue`**: This represents the gas cost on the origin chain. It is calculated based on a gas estimation performed on that chain.
* **`nativeFee`**: This is the total fee charged by the interoperability provider. It includes both the provider's fee and the gas cost incurred on the destination chain.
* **Cross-Chain Quote Endpoint**: By default, the `nativeFee` is returned. If the parameter `disableEstimate` is set to `false`, the response will also include the `nativeValue` and the gas estimation details.
* **Swap Endpoint**: This endpoint returns all values (`nativeFee`, `nativeValue`, and gas estimation) by default.

**Handling Trade Failures on Destination Chain**:

* In cross-chain trades, the trade on the destination chain can sometimes fail due to market conditions.
* If the trade fails and the funds (in stablecoins) have already been sent to the destination chain using an interoperability provider, the user will receive these funds in stablecoins.
* Trade failures can occur because the trade on the destination chain is executed after the trade on the origin chain and the interoperability provider's execution, during which market conditions may change.
* Use the information endpoints related to trades to monitor and know the status of a trade.

**Minimum Trade Amount**:

* The minimum amount to trade is $10 (in USD value of tokens). Trades with amounts below this limit are not allowed.


# GET /trade/v1/{chainId}/quote/cross

Find all available quotes for cross-chain trade via Unizen DEX Aggregator

{% openapi src="/files/P1uQ7IUGeYHFOtMBlfT0" path="/v1/{chainId}/quote/cross" method="get" expanded="true" %}
[docs-json (5).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FSQRjaBg8bLu1JxWKwY70%2Fdocs-json%20\(5\).json?alt=media\&token=fcd9b4e1-1a79-4433-acff-93f44f35d74b)
{% endopenapi %}


# GET /trade/v1/{chainId}/swap/cross

Generate transaction data for single-chain trade via Unizen DEX Aggregator

{% openapi src="/files/2IU9blsEv6mdn2LEvNd6" path="/trade/v1/{chainId}/swap/cross" method="post" expanded="true" fullWidth="false" %}
[docs-json (10).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE9UaVFYfsiou7DHQncB4%2Fdocs-json%20\(10\).json?alt=media\&token=fc4c45ca-79ee-45a0-95f4-142613db6867)
{% endopenapi %}


# Send transaction

Send the transaction to the DEX Aggregator contract.

#### Example <a href="#example.1" id="example.1"></a>

```typescript
library.getSigner().sendTransaction({
  from: account,
  to: contractAddress,
  data: data,
  gasPrice: userGasPrice?.value, // optional
  gasLimit: estimateGas, // optional
  value: nativeValue
});
```

#### Parameters <a href="#parameters" id="parameters"></a>

With data from /quote/cross API (contractAddress, data, nativeValue, estimateGas)

* library: [ethers.providers.Web3Provider](https://docs.ethers.org/v4/cookbook-providers.html#metamask)
* account: the address of the wallet sending the transaction
* data: the transaction data to be sent
* contractAddress: the address of the contract to which the transaction is being sent
* userGasPrice (optional): the gas price set by the user
* estimateGas (optional): the estimated amount of gas needed for the transaction
* currencyInIsNative: a boolean value that indicates whether the currency being used is native to the blockchain or not
* nativeValue: the value of the native currency being sent with the transaction

#### Return Value <a href="#return-value" id="return-value"></a>

This function returns a promise that resolves to a transaction hash. The format data can be found here: [Signers](https://docs.ethers.org/v5/api/signer/#Signer-sendTransaction)

**ContractAddress**

When you are preparing to send a transaction, it is essential to reference the correct version of the smart contract. This version is specified within the `transactionData` of the swap endpoint. Alternatively, if you have the `disableEstimate` parameter set to false, you would refer to the quote endpoint instead. Once you have identified the correct version, you can obtain the associated address by referring to our npm package that contains all our smart contract addresses.

The `transactionData` will also provide a field known as `contractAddress`. This field reflects the same address where the transaction must be directed. However, for enhanced security and to minimize potential risks, we strongly advise retrieving the contract address through our npm package instead of solely relying on the address provided in the `transactionData`. This recommendation is made to safeguard against any inadvertent security vulnerabilities that could arise from using incorrect or outdated address information.


# Gasless orders

These endpoints facilitate you the creation of gasless orders, to be conducted on our system.&#x20;

### List of endpoints

#### **1. Create Gasless Order**

**Endpoint**: `POST /v1/gasless/create`

**Description**: Initiates a new gasless order by submitting the necessary trade details along with the user's signature.

**Request Body**:

```json
{
  "signature": "string",        // User's digital signature
  "tokenFrom": "string",        // Address of the source token
  "tokenTo": "string",          // Address of the destination token
  "amount": "string",           // Amount to be traded (in smallest units)
  "chainFrom": "integer",       // Source blockchain chain ID
  "chainTo": "integer",         // Destination blockchain chain ID
  "bestDex": "string"           // Preferred decentralized exchange
}
```

**Response**:

```json
{
  "success": true,
  "orderId": "string"           // Unique identifier for the created order
}
```

***

#### **2. Retrieve Typed Data for Signing**

**Endpoint**: `POST /v1/gasless/typed-data`

**Description**: Generates the structured data that the user needs to sign, ensuring the integrity and authorization of the gasless transaction.

**Request Body**:

```json
{
  "tokenFrom": "string",        // Address of the source token
  "tokenTo": "string",          // Address of the destination token
  "amount": "string",           // Amount to be traded (in smallest units)
  "chainFrom": "integer",       // Source blockchain chain ID
  "chainTo": "integer",         // Destination blockchain chain ID
  "bestDex": "string"           // Preferred decentralized exchange
}
```

**Response**:

```json
{
  "success": true,
  "typedData": {
    // Structured data object for user signature
  }
}
```

***

#### **3. Cancel Gasless Order**

**Endpoint**: `POST /v1/gasless/cancel`

**Description**: Allows the user to cancel a previously created gasless order, provided it hasn't been processed yet.

**Request Body**:

```json
{
  "orderId": "string"           // Unique identifier of the order to be cancelled
}
```

**Response**:

```json
{
  "success": true,
  "message": "Order cancelled successfully"
}
```

***

#### **4. Check Gasless Order Status**

**Endpoint**: `GET /v1/gasless/status/{orderId}`

**Description**: Retrieves the current status of a specific gasless order, enabling users to monitor its progress.

**Path Parameter**:

* `orderId`: Unique identifier of the order whose status is being queried.

**Response**:

```json
{
  "success": true,
  "orderId": "string",
  "status": "string",           // Current status (e.g., pending, processing, completed, cancelled, failed)
  "message": "string"           // Additional information about the order status
}
```

***

#### **5. Estimate Gas for Gasless Transaction**

**Endpoint**: `POST /v1/gasless/estimate`

**Description**: Provides an estimation of the gas costs associated with a proposed gasless transaction, aiding in understanding potential fees.

**Request Body**:

```json
{
  "tokenFrom": "string",        // Address of the source token
  "tokenTo": "string",          // Address of the destination token
  "amount": "string",           // Amount to be traded (in smallest units)
  "chainFrom": "integer",       // Source blockchain chain ID
  "chainTo": "integer",         // Destination blockchain chain ID
  "bestDex": "string"           // Preferred decentralized exchange
}
```

**Response**:

```json
{
  "success": true,
  "gasEstimation": "string",    // Estimated gas units required
  "feeEquivalent": "string"     // Equivalent fee in the specified token (if applicable)
}
```

***

These endpoints facilitate the creation, management, and monitoring of gasless orders, streamlining the trading process by covering gas fees on behalf of the user.

For detailed information and additional parameters, please refer to the official API documentation at <https://api.zcx.com/trade/docs#/Gasless%20Orders>.


# POST /trade/v1/gasless/typed-data

{% openapi src="/files/oI7ZvQDqvKYMWN19sLxG" path="/v1/gasless/typed-data" method="post" %}
[docs-json (7).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FadjH63Iardf9TAJ0bnKu%2Fdocs-json%20\(7\).json?alt=media\&token=d16ad084-b3fa-4119-9fb4-dfcdd4a07e1a)
{% endopenapi %}


# POST /v1/gasless/estimate

{% openapi src="/files/oI7ZvQDqvKYMWN19sLxG" path="/v1/gasless/estimate" method="post" %}
[docs-json (7).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FadjH63Iardf9TAJ0bnKu%2Fdocs-json%20\(7\).json?alt=media\&token=d16ad084-b3fa-4119-9fb4-dfcdd4a07e1a)
{% endopenapi %}


# POST /v1/gasless/create

{% openapi src="/files/1Majq2yC8sNs9rlThT6t" path="/v1/gasless/create" method="post" %}
[docs json (6).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE1XRSz4INp6cunl7GVwE%2Fdocs%20json%20\(6\).json?alt=media)
{% endopenapi %}


# POST /v1/gasless/cancel

{% openapi src="/files/1Majq2yC8sNs9rlThT6t" path="/v1/gasless/cancel" method="post" %}
[docs json (6).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE1XRSz4INp6cunl7GVwE%2Fdocs%20json%20\(6\).json?alt=media)
{% endopenapi %}


# GET /trade/v1/gasless/status/{orderId}

{% openapi src="/files/1Majq2yC8sNs9rlThT6t" path="/v1/gasless/status/{orderId}" method="get" %}
[docs json (6).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE1XRSz4INp6cunl7GVwE%2Fdocs%20json%20\(6\).json?alt=media)
{% endopenapi %}


# GET /v1/gasless/orderByAddress/{address}

{% openapi src="/files/1Majq2yC8sNs9rlThT6t" path="/v1/gasless/ordersByAddress/{address}" method="get" %}
[docs json (6).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FE1XRSz4INp6cunl7GVwE%2Fdocs%20json%20\(6\).json?alt=media)
{% endopenapi %}


# UTXO Assets and Cosmos Swap

Unizen extends support to UTXO-based assets like Bitcoin, Bitcoin Cash, Cosmos, and Dogecoin—a feature that sets Unizen apart from most DEX aggregators that typically focus on account-based assets.

**UTXO vs. Account-Based Trading**

* UTXO Model: In a UTXO-based system (e.g., Bitcoin), the amount available for a transaction is derived from "unspent transaction outputs" rather than balances stored in accounts.
* Account-Based Model: In systems like Ethereum, tokens are stored in accounts, making transactions simpler to manage.

This document provides an overview of the Unizen API for UTXO Assets and Cosmos trade via the Unizen DEX aggregator and Thorchain.

For UTXO Assets and Cosmos trade, currently we only support trading:&#x20;

* All currencies on Ethereum, Avax, Binance Smart Chain networks -> UTXO Assets and Cosmos
* UTXO Assets and Cosmos -> Native Currency on Ethereum, Avax, Binance Smart Chain
* UTXO Assets and Cosmos -> UTXO Assets and Cosmos

**Available Endpoints**

The Unizen API for cross-chain transactions also includes UTXO Assets and Cosmos trade, but it differs from EVM cross-chain trade.

`GET /trade/v1/{chainId}/quote/cross`: Fetches the UTXO Assets and Cosmos trade data.

`GET /trade/v1/{chainId}/swap/cross`: Generates transaction data for UTXO Assets and Cosmos trade via Thorchain.

**How it works. Using the Unizen API for native UTXO assets and Cosmos trade**

1. Call `GET /trade/v1/{chainId}/quote/cross` to retrieve all available quotes for a cross-chain trade via the Unizen DEX aggregator.
2. Call `GET /trade/v1/{chainId}/swap/cross` to generate transaction data for a cross-chain trade via the Unizen DEX aggregator.
3. Send the transaction with the user fund to the Unizen DEX aggregator contract.

You can test it here: <https://github.com/unizen-io/unizen-dex-aggregator-example>. This example project also includes all steps for the integration.&#x20;


# GET /trade/v1/{chainId}/quote/cross 1

**For UTXO Assets and Cosmos trade, currently we only support trading:**&#x20;

* All currencies on Ethereum, Avax, Binance Smart Chain networks -> UTXO Assets and Cosmos
* UTXO Assets and Cosmos -> Native Currency on Ethereum, Avax, Binance Smart Chain
* UTXO Assets and Cosmos -> UTXO Assets and Cosmos

**List of chain id and decimals for UTXO and Cosmos**

* BTC: chainId: -3980891822, decimals 8
* BCH: chainId: -174457306, decimals 8
* LTC: chainId: -33463083, decimals 8
* DOGE: chainId: -3143381382, decimals 8
* GAIA (Cosmos) : chainId: -978111860, decimals 6

**Parameters**

**This is the list of important params for UTXO and Cosmos trade**

| Name                 | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| fromTokenAddress\*   | <p>The address of the token being traded. If native, use address zero: 0x0000000000000000000000000000000000000000.</p><p>For UTXO or Cosmos assets, use Address Zero</p><p>Example: 0x0000000000000000000000000000000000000000</p>                                                                                                                                                                                                                                                      |
| toTokenAddress\*     | Zero address, as we only support trade from native UTXO or Cosmos to Ethereum on the Ethereum mainnet, Avax on the Avax, and BNB on Binance Smart Chain network. Example: 0x0000000000000000000000000000000000000000                                                                                                                                                                                                                                                                    |
| amount\*             | Amount of tokens being traded. Example: 1 BTC → 100000000, 1 ETH → 1000000000000000000                                                                                                                                                                                                                                                                                                                                                                                                  |
| destinationChainId\* | <p>The chain ID of the destination network<br>Available values: 1, 56, 43114, -3980891822, -174457306, -33463083, -3143381382, -978111860 </p>                                                                                                                                                                                                                                                                                                                                          |
| sender\*             | The address of the sender. If trading from UTXO or Cosmos to EVM, the sender is your UTXO or Cosmos address. If trading from EVM to UTXO or Cosmos, the sender is your EVM address.                                                                                                                                                                                                                                                                                                     |
| receiver\*           | <p>The address of the receiver. If trading from UTXO or Cosmos to EVM, the receiver is your EVM address. If trading from EVM to UTXO or Cosmos, the receiver is your UTXO or Cosmos address. <br>Example: <br>- BTC: bc1qf7cd6pvs9sqnkr0nadsuhgecy8prnc9t8k0jny<br>- BCH: qpg6w46s2l25d2mehycfay8hrntwz4l4ty8cuju0np<br>- DOGE: DGcwfQ8tb6BXK4nv2wE28Vs9Aw56LaEV28<br>- LTC: ltc1q08tx4wsj2vmdttz7tys0275a7wrenlqpqcw8zc<br>- Cosmos: cosmos1aac5zxrt2xj39pujq5594w86ywntkal5skju7w</p> |
|                      |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| isExactOut           | For UTXO assets and Cosmos trade, we don't support exact out trade. isExactOut is false for this trade                                                                                                                                                                                                                                                                                                                                                                                  |
| chainId\*            | <p>The chain ID of the chain to quote on. <br>Available values: 1, 56, 43114, -3980891822, -174457306, -33463083, -3143381382, -978111860</p>                                                                                                                                                                                                                                                                                                                                           |

Response

200: OK The response is an array of objects. Currently, we only support Thorchain for native UTXO assets and Cosmos trade, so this array will have only one item for Thorchain.

```
{
    "srcTradeList": [
        {
            "fee": "0",
            "toTokenAmountWithoutFee": "100895388037136513049",
            "fromTokenAmount": "100000000000000000000",
            "toTokenAmount": "100895388037136513049",
            "deltaAmount": "100695474535918293668",
            "tokenFrom": {
                "name": "USDC",
                "symbol": "USDC",
                "decimals": 18,
                "contractAddress": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "priceInUsd": 0.9999971484215191,
                "chainId": 56,
                "buyTax": 0,
                "sellTax": 0
            },
            "tokenTo": {
                "name": "Tether USDt",
                "symbol": "USDT",
                "decimals": 18,
                "contractAddress": "0x55d398326f99059fF775485246999027B3197955",
                "priceInUsd": 1.000470720675468,
                "chainId": 56,
                "buyTax": 0,
                "sellTax": 0
            },
            "tradeType": 0,
            "protocol": [
                {
                    "name": "PancakeSwap Stable",
                    "logo": "https://pancakeswap.finance/favicon.ico",
                    "route": [
                        "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                        "0x55d398326f99059fF775485246999027B3197955"
                    ],
                    "percentage": 100
                }
            ],
            "transactionData": {
                "info": {
                    "feePercent": 0,
                    "sharePercent": 0,
                    "srcToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                    "dstToken": "0x55d398326f99059fF775485246999027B3197955",
                    "deadline": 1723712648,
                    "slippage": 0.002,
                    "tokenHasTaxes": false,
                    "path": [
                        "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                        "0x55d398326f99059fF775485246999027B3197955"
                    ],
                    "tradeType": 0,
                    "amountIn": "100000000000000000000",
                    "amountOutMin": "99756837107886218311",
                    "actualQuote": "99956750609104427165",
                    "uuid": "UNIZEN-CLI",
                    "apiId": "17",
                    "userPSFee": 0
                },
                "call": [
                    {
                        "targetExchange": "0xC6665d98Efd81f47B03801187eB46cbC63F328B0",
                        "targetExchangeID": "pancakeStable",
                        "sellToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                        "buyToken": "0x55d398326f99059fF775485246999027B3197955",
                        "amountDelta": "99756837107886218311",
                        "amount": "100000000000000000000",
                        "data": "0xa6cbf4170000000000000000000000008ac76a51cc950d9822d68b83fe1ad97b32cd580d00000000000000000000000055d398326f99059ff775485246999027b31979550000000000000000000000000000000000000000000000056bc75e2d6310000000000000000000000000000000000000000000000000000568677ad0b4105c470000000000000000000000000000000000000000000000000000000000000000"
                    }
                ]
            },
            "nativeValue": "0",
            "contractVersion": "v1",
            "gasPrice": "1000000000"
        },
    ],
    "dstTradeList": [],
    "srcTrade": {
        "fee": "0",
        "toTokenAmountWithoutFee": "100895388037136513049",
        "fromTokenAmount": "100000000000000000000",
        "toTokenAmount": "100895388037136513049",
        "deltaAmount": "100695474535918293668",
        "tokenFrom": {
            "name": "USDC",
            "symbol": "USDC",
            "decimals": 18,
            "contractAddress": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
            "priceInUsd": 0.9999971484215191,
            "chainId": 56,
            "buyTax": 0,
            "sellTax": 0
        },
        "tokenTo": {
            "name": "Tether USDt",
            "symbol": "USDT",
            "decimals": 18,
            "contractAddress": "0x55d398326f99059fF775485246999027B3197955",
            "priceInUsd": 1.000470720675468,
            "chainId": 56,
            "buyTax": 0,
            "sellTax": 0
        },
        "tradeType": 0,
        "protocol": [
            {
                "name": "PancakeSwap Stable",
                "logo": "https://pancakeswap.finance/favicon.ico",
                "route": [
                    "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                    "0x55d398326f99059fF775485246999027B3197955"
                ],
                "percentage": 100
            }
        ],
        "transactionData": {
            "info": {
                "feePercent": 0,
                "sharePercent": 0,
                "srcToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "dstToken": "0x55d398326f99059fF775485246999027B3197955",
                "deadline": 1723712648,
                "slippage": 0.002,
                "tokenHasTaxes": false,
                "path": [
                    "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                    "0x55d398326f99059fF775485246999027B3197955"
                ],
                "tradeType": 0,
                "amountIn": "100000000000000000000",
                "amountOutMin": "99756837107886218311",
                "actualQuote": "99956750609104427165",
                "uuid": "UNIZEN-CLI",
                "apiId": "17",
                "userPSFee": 0
            },
            "call": [
                {
                    "targetExchange": "0xC6665d98Efd81f47B03801187eB46cbC63F328B0",
                    "targetExchangeID": "pancakeStable",
                    "sellToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                    "buyToken": "0x55d398326f99059fF775485246999027B3197955",
                    "amountDelta": "99756837107886218311",
                    "amount": "100000000000000000000",
                    "data": "0xa6cbf4170000000000000000000000008ac76a51cc950d9822d68b83fe1ad97b32cd580d00000000000000000000000055d398326f99059ff775485246999027b31979550000000000000000000000000000000000000000000000056bc75e2d6310000000000000000000000000000000000000000000000000000568677ad0b4105c470000000000000000000000000000000000000000000000000000000000000000"
                }
            ]
        },
        "nativeValue": "0",
        "contractVersion": "v1",
        "gasPrice": "1000000000"
    },
    "dstTrade": {
        "toTokenAmount": "161293",
        "deltaAmount": "161293",
        "tokenTo": {
            "name": "BTC",
            "symbol": "BTC",
            "decimals": 8,
            "contractAddress": "0x0000000000000000000000000000000000000000",
            "chainId": -3980891822,
            "priceInUsd": 60914.241350926735,
            "buyTax": 0,
            "sellTax": 0
        }
    },
    "transactionData": {
        "inbound_address": "0x9c4c8387b447364e788acaa36ed921c0c6195507",
        "outbound_delay_blocks": 0,
        "outbound_delay_seconds": 0,
        "fees": {
            "asset": "BTC.BTC",
            "affiliate": "414",
            "outbound": "3641",
            "liquidity": "165",
            "total": "4220",
            "slippage_bps": 9,
            "total_bps": 249
        },
        "slippage_bps": 9,
        "streaming_slippage_bps": 9,
        "router": "0xb30ec53f98ff5947ede720d32ac2da7e52a5f56b",
        "expiry": 1723627149,
        "warning": "Do not cache this response. Do not send funds after the expiry.",
        "notes": "Base Asset: Send the inbound_address the asset with the memo encoded in hex in the data field. Tokens: First approve router to spend tokens from user: asset.approve(router, amount). Then call router.depositWithExpiry(inbound_address, asset, amount, memo, expiry). Asset is the token contract address. Amount should be in native asset decimals (eg 1e18 for most tokens). Do not send to or from contract addresses.",
        "recommended_min_amount_in": "5831301363",
        "recommended_gas_rate": "7",
        "gas_rate_units": "gwei",
        "memo": "=:BTC.BTC:bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt::zcx-com:25",
        "expected_amount_out": "161293",
        "expected_amount_out_streaming": "",
        "max_streaming_quantity": 0,
        "streaming_swap_blocks": 0,
        "amount": "100895388037136513049",
        "tradeProtocol": "CROSS_CHAIN_THORCHAIN",
        "params": {
            "uuidPercentage": 0,
            "sharePercent": 0
        },
        "call": [
            {
                "targetExchange": "0xC6665d98Efd81f47B03801187eB46cbC63F328B0",
                "targetExchangeID": "pancakeStable",
                "sellToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "buyToken": "0x55d398326f99059fF775485246999027B3197955",
                "amountDelta": "99756837107886218311",
                "amount": "100000000000000000000",
                "data": "0xa6cbf4170000000000000000000000008ac76a51cc950d9822d68b83fe1ad97b32cd580d00000000000000000000000055d398326f99059ff775485246999027b31979550000000000000000000000000000000000000000000000056bc75e2d6310000000000000000000000000000000000000000000000000000568677ad0b4105c470000000000000000000000000000000000000000000000000000000000000000"
            }
        ],
        "info": {
            "feePercent": 0,
            "sharePercent": 0,
            "srcToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
            "dstToken": "0x55d398326f99059fF775485246999027B3197955",
            "deadline": 1723712648,
            "slippage": 0.002,
            "tokenHasTaxes": false,
            "path": [
                "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "0x55d398326f99059fF775485246999027B3197955"
            ],
            "tradeType": 0,
            "amountIn": "100000000000000000000",
            "amountOutMin": "99756837107886218311",
            "actualQuote": "99956750609104427165",
            "uuid": "UNIZEN-CLI",
            "apiId": "17",
            "userPSFee": 0,
            "memo": "=:BTC.BTC:bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt::zcx-com:25",
            "vault": "0x9c4c8387b447364e788acaa36ed921c0c6195507"
        }
    },
    "nativeValue": "0",
    "nativeFee": "0",
    "tradeProtocol": "CROSS_CHAIN_THORCHAIN",
    "sourceChainId": 56,
    "destinationChainId": -3980891822,
    "contractVersion": "v1",
    "providerInfo": {
        "name": "Thorchain",
        "logo": "https://thorchain.org/images/logos/full-dark.png",
        "website": "https://thorchain.org/",
        "docsLink": "https://thorchain.org/integrate",
        "description": "THORChain is a network that facilitates native asset settlement between Bitcoin, Ethereum, BNB Chain, Avalanche, Cosmos Hub, Dogecoin, Bitcoin Cash & Litecoin"
    },
    "tradeParams": {
        "sender": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "receiver": "bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt",
        "tokenIn": "0x55d398326f99059ff775485246999027b3197955",
        "tokenOut": "0x0000000000000000000000000000000000000000",
        "amount": "100895388037136513049",
        "srcChainId": 56,
        "dstChainId": -3980891822,
        "inNative": true,
        "outNative": true,
        "deadline": 1723627149,
        "tokenInfo": [
            {
                "name": "USDT",
                "symbol": "USDT",
                "decimals": 18,
                "contractAddress": "0x55d398326f99059ff775485246999027b3197955",
                "chainId": 56,
                "buyTax": 0,
                "sellTax": 0
            },
            {
                "name": "BTC",
                "symbol": "BTC",
                "decimals": 8,
                "contractAddress": "0x0000000000000000000000000000000000000000",
                "chainId": -3980891822,
                "priceInUsd": 60914.241350926735,
                "buyTax": 0,
                "sellTax": 0
            }
        ]
    }
}

```


# GET /trade/v1/{chainId}/swap/cross

Parameters

| Name       | Description                                                                                                                        |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| chainId \* | The chain ID of the chain to quote on. Available values: 1, 56, 43114, -3980891822, -174457306, -33463083, -3143381382, -978111860 |

**Request body**

The transaction data for the cross-chain trade.

<pre><code>{  
 "transactionData": {},// transactionData is transactionData object from quote API 
<strong> "nativeValue": "29422186306758765852",   
</strong><strong> "account": "0xF0Fbf42C54Ac40dA016003baD35E5AefaC6E1CE1" 
</strong><strong>}
</strong></code></pre>

For example:&#x20;

```
{
    transactionData: {
        "inbound_address": "0x9c4c8387b447364e788acaa36ed921c0c6195507",
        "outbound_delay_blocks": 0,
        "outbound_delay_seconds": 0,
        "fees": {
            "asset": "BTC.BTC",
            "affiliate": "412",
            "outbound": "2427",
            "liquidity": "164",
            "total": "3003",
            "slippage_bps": 9,
            "total_bps": 179
        },
        "slippage_bps": 9,
        "streaming_slippage_bps": 9,
        "router": "0xb30ec53f98ff5947ede720d32ac2da7e52a5f56b",
        "expiry": 1723627398,
        "warning": "Do not cache this response. Do not send funds after the expiry.",
        "notes": "Base Asset: Send the inbound_address the asset with the memo encoded in hex in the data field. Tokens: First approve router to spend tokens from user: asset.approve(router, amount). Then call router.depositWithExpiry(inbound_address, asset, amount, memo, expiry). Asset is the token contract address. Amount should be in native asset decimals (eg 1e18 for most tokens). Do not send to or from contract addresses.",
        "recommended_min_amount_in": "5845355010",
        "recommended_gas_rate": "7",
        "gas_rate_units": "gwei",
        "memo": "=:BTC.BTC:bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt::zcx-com:25",
        "expected_amount_out": "161754",
        "expected_amount_out_streaming": "",
        "max_streaming_quantity": 0,
        "streaming_swap_blocks": 0,
        "amount": "100408321618356225713",
        "tradeProtocol": "CROSS_CHAIN_THORCHAIN",
        "params": {
            "uuidPercentage": 0,
            "sharePercent": 0
        },
        "call": [
            {
                "targetExchange": "0xC6665d98Efd81f47B03801187eB46cbC63F328B0",
                "targetExchangeID": "pancakeStable",
                "sellToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "buyToken": "0x55d398326f99059fF775485246999027B3197955",
                "amountDelta": "99756837107886218311",
                "amount": "100000000000000000000",
                "data": "0xa6cbf4170000000000000000000000008ac76a51cc950d9822d68b83fe1ad97b32cd580d00000000000000000000000055d398326f99059ff775485246999027b31979550000000000000000000000000000000000000000000000056bc75e2d6310000000000000000000000000000000000000000000000000000568677ad0b4105c470000000000000000000000000000000000000000000000000000000000000000"
            }
        ],
        "info": {
            "feePercent": 0,
            "sharePercent": 0,
            "srcToken": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
            "dstToken": "0x55d398326f99059fF775485246999027B3197955",
            "deadline": 1723712898,
            "slippage": 0.002,
            "tokenHasTaxes": false,
            "path": [
                "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "0x55d398326f99059fF775485246999027B3197955"
            ],
            "tradeType": 0,
            "amountIn": "100000000000000000000",
            "amountOutMin": "99756837107886218311",
            "actualQuote": "99956750609104427165",
            "uuid": "UNIZEN-CLI",
            "apiId": "17",
            "userPSFee": 0,
            "memo": "=:BTC.BTC:bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt::zcx-com:25",
            "vault": "0x9c4c8387b447364e788acaa36ed921c0c6195507"
        }
    },
    "nativeValue": "100000000",
    "account": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791" //your account on source chain. if it's UTXO, account is your UTXO address
}

```

**Response**

Response for trade from UTXO asset or Cosmos to EVM:

```
{
    "data": {
        "method": "transfer",
        "params": [
            {
                "from": "bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt",
                "recipient": "bc1qkttu0a6gljrrswzyw3rwp59sunjep7zfqgyvr9",
                "asset": "BTC.BTC",
                "feeRate": 5,
                "amount": {
                    "amount": "100000000",
                    "decimals": 8
                },
                "memo": "=:ETH.ETH:0x207ca4370639120f9A049aF9CAB4fCaa608F2445::zcx-com:25"
            }
        ]
    }
}

```

Response for trade from EVM to BTC:

```
{
    "to": "0x0f0ae95b14adb4b5abb75448ffd34753078b1e63",
    "data": "0x3d3a4254432e4254433a62633171647032633568736b396c776c64756d35766d327878363564786163777a7878797932793477743a3a7a63782d636f6d3a3235",
    "nativeValue": "1000000000000000000"
}
```


# Sending transactions

Sending a transaction to the inbound address.

{% hint style="warning" %}
**Important things you need to check before sending transactions:** \
1\. Never cache this response and **do not** send funds after the expiry.
{% endhint %}

Send the transaction: using our response data from /swap endpoint

* From UTXO : For example, if you are using the XDeFi wallet on the UTXO assets: \
  For more information related to sending transaction with UTXO and Cosmos, you can read from your wallet documentation. \
  For example, if you are using xDeFi wallet, you can check: <https://developers.xdefi.io/developers/extension-wallet>

```
(window as any).xfi.bitcoin?.request({
        "method": "transfer",
        "params": [
            {
                "from": "bc1qdp2c5hsk9lwldum5vm2xx65dxacwzxxyy2y4wt",
                "recipient": "bc1qkttu0a6gljrrswzyw3rwp59sunjep7zfqgyvr9",
                "asset": "BTC.BTC",
                "feeRate": 5,
                "amount": {
                    "amount": "100000000",
                    "decimals": 8
                },
                "memo": "=:ETH.ETH:0x207ca4370639120f9A049aF9CAB4fCaa608F2445::zcx-com:25"
            }
        ]
    }
)

```

* From EVM to BTC&#x20;

```
provider?.getSigner(account)?.sendTransaction({
        to: swapData.to,
        data: swapData.data,
        value: swapData.nativeValue
      });
```


# Efficient Quote Retrieval with Batch Processing

Our platform provides a streamlined method for obtaining quotes, enhancing your trading experience. We recommend utilizing our dedicated endpoint designed for batch processing to effortlessly gather multiple quotes at once.

**Endpoint: `/trade/v1/{chainId}/batch_quote/single`**

**Method: `GET`**

**Description:**

By leveraging this endpoint, users can efficiently access a comprehensive array of quotes for their trades from our supported Decentralized Exchanges (DEXs). This batch processing approach simplifies the quote retrieval process, allowing users to gather all available quotes with just one request.

**Parameters:**

* `{chainId}`: Identifies the blockchain or chain instance.

**Usage:**

Simply pass the required parameters to the endpoint, and receive all available quotes for the trade from our supported DEXs. It's important to note that the retrieved quotes serve as an orientation for the trade passed, and do not include information to conduct the trade. Another call to the quote endpoint is necessary to confirm the quote and proceed with the trade.

**Note:**

The quotes obtained through this endpoint are intended as guidance for users in making informed trading decisions. To execute a trade based on a specific quote, users must confirm the quote and conduct the trade through an additional call to the quote endpoint.

**Recommendation:**

We highly recommend utilizing this endpoint as a batch process for quote retrieval. Its efficiency and convenience significantly improve the trading experience, enabling users to make well-informed decisions while navigating the cryptocurrency market landscape.


# GET /trade/v1/{chainId}/batch\_quote/single

By passing in the params, you will receive all available quotes for the trade from our supported DEXs.

{% openapi src="/files/3JMkNwtEVLyggw0naX9p" path="/v1/{chainId}/batch\_quote/single" method="post" expanded="true" fullWidth="true" %}
[docs-json (2).json](https://1510373414-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7JXcB8KHgOrQ0aFkHXeg%2Fuploads%2FtuMHMOKaueiVatrpgEBD%2Fdocs-json%20\(2\).json?alt=media\&token=29006e80-e511-46a0-961e-d70150460b91)
{% endopenapi %}


# Error Messages

This document provides a list of error messages, along with their explanations, that integrators may encounter when working with the Unizen API. These error messages are designed to provide detailed information about the specific issues that may arise during trading. It is important for integrators to understand these error messages in order to effectively handle and communicate them to users.

Additionally, these error messages are also meant to be displayed to users when they encounter issues while using our application. By providing clear and informative error messages, we aim to assist users in understanding the cause of the problem and guide them towards potential solutions or actions to take.

We believe that transparent and user-friendly error messages are crucial for a seamless user experience. By addressing potential errors proactively and providing meaningful explanations, we strive to enhance user confidence and satisfaction with our application.

1. **Trade call issue with external DEX**: This error occurs when there is an issue while calling an external DEX to trade. It can happen due to various reasons, such as the rate changing, the DEX stopping trading, the DEX changing the function being called, or the DEX killing their contract.

2. **Return amount is not enough**: Trade amount lower than expected. This error occurs when the amount returned after the trade execution on the chain is lower than the expected amount.

3. **Insufficient contract allowance or disallowed data.** This error occurs when the user hasn't approved enough allowance to our trade smart contract or when the token contract doesn't allow the call with data.

4. **Not enough funds for the transaction**. This error occurs when there are insufficient funds available for sending the transaction.

5. **Gas limit exceeded or contract issues**. This error can occur in situations such as when the exact gas limit is exceeded during trading, when the contract has been upgraded but the frontend/sdk has not been updated, or when sending a transaction to the wrong contract address.

6. **Trade amount is 0**. This error occurs when the trade amount specified is zero.

7. **Trade on an unapproved DEX**. This error occurs when attempting to trade at a DEX that hasn't been whitelisted yet.

8. **No data provided to the contract**. This error occurs when no data is passed to the contract.

9. **Insufficient native currency sent**. This error occurs when the user trades using the native currency but doesn't send enough amount to the contract.

10. **ERC20 token amount is 0**. This error occurs when the user trades with an ERC20 token, but the amount specified is 0.

11. **Incorrect receiver address**. This error occurs when the receiver address specified in the trade information is either address(0) or doesn't match the user address or our contract address.

12. **Sender and user addresses must match**. This error occurs when the sender and user addresses specified are not the same, which is done to prevent hacking attempts from other contracts.

13. **Negative trade amount after execution**. This error occurs when trading **exactIn**, and after the trade execution, the amount in the contract becomes less than 0.

14. **Cross-chain pool not added yet**. This error occurs when a user trades cross-chain, but the pool from Stargate has not been added yet.

15. **Destination chain address not set**. This error occurs when a user trades cross-chain and the address of our application on the destination chain has not been set yet. Sending assets to address(0) on the destination chain will result in the loss of funds forever.


# Obtaining gasless quotes

This document provides a step-by-step guide on how to retrieve gasless quotes using the quote single endpoint in the ZCX API.

> What is a gasless trade?&#x20;
>
> A **gasless trade** is a transaction where the user does not directly pay for the gas fees (the computational cost of executing a transaction on a blockchain). Instead, these fees are typically covered by a third party (us) to enhance the user experience. The user doesn't need native to pay the gas!

#### **How to Enable Gasless Trades**

To perform gasless trades, you can use the same **quote endpoint** as regular trades, with two additional parameters to enable the gasless feature:

**Required Parameters**

* **`version=v2`**:\
  This specifies the use of the second version of our smart contract, which introduces the gasless trading feature. This version also supports additional enhancements such as:
  * **Permit2** for streamlined approvals.
  * The ability to specify a **feeReceiver**.
  * Other advanced functionalities.
* **`isGasless=true`**:\
  This explicitly requests a gasless quote where Unizen will cover the gas fees.

***

#### **How Gasless Quotes Work**

* When you request a gasless quote, **Unizen** pays the gas fees on behalf of the user.
* To offset the gas cost, the returned quote amount is slightly reduced by an amount equivalent to the gas cost.
* The quote response structure remains identical to that of regular trades, so no changes are needed to parse or handle the quote.

***

#### **Steps to Conduct a Gasless Trade**

1. **Get a Gasless Quote**:
   * Use the quote endpoint with the additional parameters:

     ```bash
     GET /quote?version=v2&isGasless=true&...otherParameters
     ```
   * The response will include the same fields as regular quotes.
2. **Generate typed data for sign gasless trade**: Use the `transactionData` from step 1 to create the typed data needed for confirming and signing a gasless order. **Important**: this endpoint returns an updated transactionData. This new data is the one to be used to submit the trade.&#x20;
3. **Optional Step**: Call the `estimateGas` endpoint to simulate the transaction and determine whether it will succeed or fail.
4. **Submit the Trade**:

* To execute the trade, you must call the **Create Order** endpoint and provide the required trade details.
* **Important**: use the transactionData (call field) returned by the typed-data endpoint, not the one obtained in the quote endpoint.
* Our system processes the order and conducts the trade on behalf of the user.

***

#### **Benefits of Gasless Trades**

* **No Gas Fees for Users**: Users do not need to pay gas fees or hold native tokens for the transaction.
* **Streamlined Integration**: The same quote structure and swap flow as regular trades make integration straightforward.
* **Simplified User Experience**: Reduces friction for users, especially those new to blockchain transactions.

***

#### **Additional Notes**

* Ensure the `version=v2` parameter is included, as gasless trades are only supported in the second version of our smart contracts.
* Gasless trades is enabled only for single chain trades, for now.
* The reduced quote amount accounts for the gas costs covered by Unizen.

By following these steps, you can seamlessly integrate gasless trading into your workflow. Let us know if further assistance is needed! 🚀


# Gas estimation

#### **Gas Estimation for Gasless Quotes**

To retrieve the gas estimation for a gasless quote, use the following endpoint:

**Endpoint:**

`/v1/gasless/estimate`

***

#### **Description**

This endpoint provides an estimate of the gas costs associated with executing a gasless quote. It helps you understand the gas fee that will be covered by the system on behalf of the user.

***

#### **Usage Example**

**Request**:

```bash
POST /v1/gasless/estimate
Content-Type: application/json
{
  "parameters": {
    // Add necessary parameters for estimation
  }
}
```

**Success response:**&#x20;

```
1137450 // estimate of the gas costs associated with executing a gasless quote
```

**Error Response**:

```json
{
    "status": 500,
    "message": "Internal Server Error",
    "requestId": "6b130836-3b52-4035-8399-464cdd78bc2f",
    "error": {
        "error": "Internal Server Error",
        "description": "execution reverted: ERC20: transfer amount exceeds balance\n",
        "statusCode": 500,
        "meta": []
    }
}
```

***

#### **Key Points**

* **Gas Coverage**: The gas fees are paid by the system for gasless trades, and this endpoint helps estimate the cost.
* **Parameters**: Ensure all required parameters are included in the request for accurate estimation.

For further details, refer to the full API documentation.


# Executing the trade

The gasless trade has to be executed by us, given that we pay the gas instead of the user

#### **Gasless Trading Flow**

To perform a gasless trade, follow these steps using the gasless endpoints:

***

#### **1. Retrieve Typed Data**

**Endpoint**: `/v1/gasless/typed-data`\
Send a request with the trade details to this endpoint to retrieve the structured data required for the user to sign.

**Request:**

```json
{
    "transactionData": {
        "info": {
            "feeReceiver": "0xf4AA7a82B1d7f30Ca22D306c5eC429CF8AF160ef",
            "feePercent": 0,
            ...
        },
        "call": [
            {
                "targetExchange": "0x1F721E2E82F6676FCE4eA07A5958cF098D339e18",
                "targetExchangeID": "camelotv3",
                "sellToken": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
                "buyToken": "0x0000000000000000000000000000000000000000",
                "amountDelta": "1972679740777741",
                "amount": "6603531",
                "data": "0xac9650d80000...00000000000000000"
            }
        ],
        "version": "v2",
        "amountInAfterFee": "6603531",
        "amountInBeforeFee": "6623429",
        "fee": "19898"
    },
    "sender": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
    "chainId": 42161
}
```

**Response:**

```json
{
    "account": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
    "domain": {
        "name": "GasLessExecutor",
        "version": "1",
        "chainId": 42161,
        "verifyingContract": "0x9BCd841436ef4f85dacefB1aEc772aF71619024e"
    },
    "types": {
        "UnizenGasLessOrder": [
            {
                "name": "user",
                "type": "address"
            },
            ...
        ]
    },
    "primaryType": "UnizenGasLessOrder",
    "message": {
        "user": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "receiver": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "srcToken": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
        "dstToken": "0x0000000000000000000000000000000000000000",
        "amountIn": "6623429",
        "fee": "19898",
        "amountOutMin": "1972679740777741",
        "deadline": 1734963690,
        "tradeHash": "0x8748ade4edde06...e40b4dbc11fa47"
    }
}
```

***

#### **2. User Signs the Typed Data**

After receiving the `typedData` structure, the user must sign it using their wallet or signing tool (e.g., MetaMask, hardware wallets). This signature proves the user’s intent to perform the trade.

***

#### **3. Create the Order**

**Endpoint**: `/v1/gasless/create`\
Send the signature obtained from the user, along with the trade details, to this endpoint to create the order.

**Request:**

```json
{
    "chainFrom": 42161,
    "order": { // result of /v1/gasless/typed-data (message object)
        "user": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "receiver": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "srcToken": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
        "dstToken": "0x0000000000000000000000000000000000000000",
        "amountIn": "6623429",
        "fee": "19898",
        "amountOutMin": "1972679740777741",
        "deadline": 1734963690,
        "tradeHash": "0x8748ade4edde06...e40b4dbc11fa47"
    },
    "call": [ // call array from transactionData object of the quote 
        {
            "targetExchange": "0x1F721E2E82F6676FCE4eA07A5958cF098D339e18",
            "targetExchangeID": "camelotv3",
            "sellToken": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
            "buyToken": "0x0000000000000000000000000000000000000000",
            "amountDelta": "1972679740777741",
            "amount": "6603531",
            "data": "0xac9650d8000000000000000000000...00000000"
        }
    ],
    "permitData": { // if use Permit2
        "user": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
        "amount": "6623429",
        "deadline": 1734963223,
        "nonce": 569626219515420,
        "sign": "0xb43dbbcdcf610ff77fd17ab0630d5e85391086...04121f1b"
    },
    "signature": "0x2728c5bd1d666623533d899f6f6...7387b9e41c" // signature from step 2
}
```

**Response:**

```json
{"orderId":"561e1e2f-c32b-48c7-bb85-b9bc599d4d91"}
```

Once the order is created, it will be processed by our gasless trade processor. The system will cover the gas fees and execute the trade on behalf of the user.

***

#### **4. Cancel the Order (Optional)**

If the order has not been processed yet (this typically happens very quickly), it can be cancelled.

**Endpoint**: `/v1/gasless/cancel`

**Request:**

```json
{
  "orderId": "12345"
}
```

**Response:**

```json
{
  "success": true,
  "message": "Order cancelled successfully"
}
```

***

#### **Summary of Workflow**

1. **Call `/v1/gasless/typed-data`**: Retrieve the structured data for the user to sign.
2. **User Signs the Data**: Obtain a valid signature from the user.
3. **Call `/v1/gasless/create`**: Create the gasless order using the signature and trade details.
4. **(Optional) Cancel the Order**: If necessary, call `/v1/gasless/cancel` to cancel the order before it is processed.

***

#### **Key Notes**

* **Speed**: Orders are typically processed very quickly, minimizing the need for cancellations.
* **Security**: User signatures ensure the trade is authorized and secure.
* **Gasless Execution**: All gas fees are handled by the system, simplifying the process for the user.

For further details or troubleshooting, refer to the full API documentation or contact support. 🚀


# Following the orders

#### **Tracking the Status of a Gasless Order**

To monitor the status of a gasless order and provide updates to the user, use the following endpoint:

**Endpoint:**

`/v1/gasless/status/{orderId}`

***

#### **Description**

This endpoint allows you to query the status of an order created via the gasless trading flow. It provides real-time information about the order's current state, enabling you to keep the user informed.

***

#### **How to Use**

1. **Call the Endpoint**:\
   Replace `{orderId}` with the unique identifier of the order you want to track:

   ```bash
   GET /v1/gasless/status/12345
   ```
2. **Response**:\
   The endpoint returns the current status of the order. Example response:

   ```json

   {
       "response": {
           "id": "561e1e2f-c32b-48c7-bb85-b9bc599d4d91",
           "address": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
           "chainFrom": 42161,
           "tokenFrom": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
           "chainTo": 0,
           "tokenTo": "0x0000000000000000000000000000000000000000",
           "amount": "6623429",
           "fee": "19898",
           "amountOutMin": "1972679740777741",
           "swapCall": "{\"order\":{\"user\":\"0x2472d3...6bacb2526197387b9e41c\"}",
           "status": "completed", // Possible values: "pending", "processing", "completed", "cancelled", "faile
           "createdAt": "2024-12-23T13:51:34.188129Z",
           "deadLineAt": "2024-12-23T14:21:30Z",
           "canceledAt": null,
           "completedAt": "2024-12-23T13:51:38.019587Z",
           "failedAt": null,
           "signatureCreated": "0x2728c5bd1d666623533d899f6f60d4a49a0d597d4ba1fc7e24079e1cea8d9db26f8b9b63f927f9614060fcafaef60f0ca769a7a77f2af6bacb2526197387b9e41c",
           "signatureCancel": null,
           "failureMsg": null,
           "txCompleted": "0x49fdec98eac1fd27...9361b375", // tx hash when the order is created 
           "apiKey": 17,
           "amountDeducted": "19898",
           "gasPrice": "20000000",
           "estimatedGas": "1304999",
           "gasUsed": "1117733",
           "nativeUsdPrice": "3312.41"
       }
   }
   ```

***

#### **Possible Status Values**

| Status       | Description                                              |
| ------------ | -------------------------------------------------------- |
| `pending`    | The order has been created and is awaiting processing.   |
| `processing` | The order is currently being executed by the system.     |
| `completed`  | The order has been successfully processed and finalized. |
| `cancelled`  | The order was cancelled before it could be executed.     |
| `failed`     | The order could not be processed due to an error.        |

***

#### **Key Notes**

* **Real-Time Updates**: Poll this endpoint to get real-time updates about the order status.
* **Order Information**: Use the `orderId` provided when the order was created to query its status.
* **User Feedback**: Use the returned status and message to display appropriate feedback to the user.

This endpoint ensures transparency and allows you to keep users informed about the progress of their gasless trades. 🚀


# Integration with Unizen Contracts for Token Swapping

By following these steps, you can seamlessly interact with Unizen’s API and integrate token swapping functionality into your smart contract. This guide provides a comprehensive approach, ensuring both

### Step-by-Step Integration with Unizen Contracts for Token Swapping

Integrating with the Unizen platform for token swapping within your smart contracts requires a structured approach. Here’s a detailed guide to help you perform token swaps using Unizen’s APIs.

#### Step 1: Retrieve a Quote

The first step in this integration is to obtain a quote for the token swap.

**Endpoint:**

```bash
/v1/{chainId}/quote/single
```

Replace `{chainId}` with the appropriate blockchain ID (e.g., Ethereum, BSC). This request to the Unizen API returns a quote, which includes essential details such as the estimated gas cost and the token amounts necessary to perform the swap.

#### Step 2: Call the Unizen Swap API

Once you have a quote, you can initiate the token swap by calling the Unizen Swap API.

**Endpoint:**

```bash
/v1/{chainId}/swap/single
```

**Parameters:**

* `account`: This is the contract address of your integrator contract interacting with Unizen.
* `receiver`: Specify the receiver of the swapped tokens:
  * For direct delivery to a user's address, enter the user's address.
  * If the tokens should return to your contract, set this parameter to the `account` address.

**Example Response:**

```json
{
  "data": "0xbfaa0506000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000001e0000000000000000000000000e6b9bb7257b7c0801794f7f37b51390e3d5156950000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000be4a43f000000000000000000000000000000000000000000000000000000000bf3f0f8900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000a554e495a454e2d434c49000000000000000000000000000000000000000000000000000000000000000000000000..."
}
```

This response contains data necessary to proceed with the swap transaction.

**Note:** If you already know the receiver address at the time of obtaining the quote, you can skip the call to the swap endpoint, simplifying the integration process. Assuming you also know the account address of the smart contract that will interact with the Unizen contract, you can pass the receiver address directly in the quote request. Additionally, by setting the `disableEstimate` parameter to `true`, the response will include both a gas estimation and the necessary transaction data, allowing you to proceed directly to transaction execution without the intermediate swap API call. This can streamline the process, saving resources and reducing the number of API interactions required.

#### Executing the Swap in Solidity

After receiving the response data from Unizen, you can execute the token swap in your Solidity smart contract. Follow one of these methods based on the token type being swapped.

**For Native Token Swaps**

If swapping from a native token like ETH, use the following code:

```solidity
(bool success, ) = UnizenContractAddress.call{value: swapAmount}(data);
require(success, "Swap failed");
```

* **`swapAmount`**: The amount of the native token (e.g., ETH) to swap.
* **`data`**: The `data` from the Unizen API response.

**For ERC20 Token Swaps**

When swapping an ERC20 token, make sure to approve the Unizen contract to spend the tokens on cridyour behalf before executing the swap. Then use the following code:

```solidity
ERC20(sellToken).safeApprove(UnizenContractAddress, swapAmount);
(bool success, ) = UnizenContractAddress.call{value: 0}(data);
require(success, "Swap failed");
ERC20(sellToken).safeApprove(UnizenContractAddress, 0);  // Reset allowance
```

* **`sellToken`**: The ERC20 token address you want to swap.
* **`swapAmount`**: The amount of the ERC20 token to be swapped.
* **`data`**: The response data from the Unizen API.

**Security Note:** Resetting the token allowance back to zero (`safeApprove(UnizenContractAddress, 0)`) after the swap is a best practice for security, as it prevents excessive approvals that could pose risks if the contract’s security is compromised.


# Registering Errors on Smart Contract Calls

Since we cannot determine if a gas estimation fails on the integrator's side—particularly when called from the integrator's smart contract—we provide an endpoint to register errors that occur during on-chain calls. This information is highly valuable to us for maintaining service quality, allowing us to analyze and review failed trades (e.g., tokens involved, DEX used, and other relevant details).

**Endpoint: `POST /api/register-error`**

This endpoint allows clients to register errors that occur during smart contract calls when conducting a trade. The provided information can include various transaction-related details, though all fields are optional.

***

#### **Request**

* **Method**: `POST`
* **Content-Type**: `application/json`

**Request Body Parameters**

| Field              | Type     | Description                                                                         |
| ------------------ | -------- | ----------------------------------------------------------------------------------- |
| `input_data`       | `string` | (Optional) The raw input data of the transaction.                                   |
| `value`            | `string` | (Optional) The value of the transaction in wei (smallest unit of the native token). |
| `sender`           | `string` | (Optional) The address of the sender initiating the transaction (`0x...`).          |
| `to_address`       | `string` | (Optional) The address to which the transaction is sent (`0x...`).                  |
| `api_key`          | `string` | (Optional) The API key for authentication and tracking.                             |
| `chain_id`         | `number` | (Optional) The ID of the blockchain network where the transaction was conducted.    |
| `block_number`     | `number` | (Optional) The block number where the transaction was attempted.                    |
| `transaction_hash` | `string` | (Optional) The hash of the transaction (`0x...`).                                   |

***

#### **Response**

**Successful Response**

* **HTTP Status**: `200 OK`
* **Response Body**:

  ```json
  {
    "status": "success",
    "message": "Error registered successfully."
  }
  ```

**Error Response**

* **HTTP Status**: `400 Bad Request`
* **Response Body** (example):

  ```json
  {
    "status": "error",
    "message": "Invalid request body."
  }
  ```

***

#### **Example Request**

**Request Body**

```json
{
  "input_data": "0xa9059cbb000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
  "value": "1000000000000000000",
  "sender": "0xAbcd1234Ef567890abcd1234Ef567890Abcd1234",
  "to_address": "0xDefg5678Gh901234defg5678Gh901234Defg5678",
  "api_key": "my-secret-api-key",
  "chain_id": 1,
  "block_number": 12345678,
  "transaction_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```

**Response**

```json
jsonCopiar código{
  "status": "success",
  "message": "Error registered successfully."
}
```

***

#### **Notes**

1. **Optional Fields**: All fields in the request are optional; the backend should handle missing fields gracefully.
2. **Error Logging**: This endpoint is used to collect transaction details when an error occurs, providing valuable insights for debugging and analytics.
3. **Authentication**: If the `api-key` is required for security, ensure it is validated against your system.
4. **Chain-Specific Handling**: The `chainId` should correspond to the appropriate blockchain network (e.g., Ethereum Mainnet = `1`).

This documentation entry provides clear guidelines for developers to use the `POST /api/register-error` endpoint effectively.


# What is Permit2?

#### **What is Permit2?**

**Permit2** is an advanced token approval mechanism introduced to streamline and enhance the user experience for decentralized token transactions. Building on the foundations of the ERC-20 token standard and EIP-2612 (Permit), Permit2 enables users to grant token allowances to smart contracts without requiring multiple on-chain approvals. This innovation allows for improved efficiency, reduced gas costs, and enhanced flexibility in decentralized trading.

Permit2 is particularly beneficial for DeFi applications and trading protocols, as it simplifies the process of granting token approvals, making the workflow more user-friendly and cost-effective.

***

#### **How Permit2 Works**

Permit2 leverages off-chain signatures to authorize token spending, enabling users to delegate token approvals to a specific smart contract or relayer. Instead of requiring users to send on-chain approval transactions, Permit2 allows:

1. **Off-Chain Authorization**:
   * The user signs a message (a "permit") off-chain authorizing a specific spender (e.g., a trading protocol) to spend a certain amount of tokens on their behalf.
2. **On-Chain Execution**:
   * The relayer or smart contract submits the signed permit to the blockchain, executing the transaction without the need for a separate approval step.
3. **Enhanced Features**:
   * Permit2 supports additional features such as allowance transfers, bulk approvals, and precise allowance expiration times, providing greater control over token approvals.

***

#### **Key Benefits of Permit2 for Trading**

1. **Gas Cost Savings**:
   * Traditional ERC-20 token approvals require a separate transaction for each allowance, incurring gas fees. Permit2 eliminates the need for these redundant approval transactions, saving users gas costs.
2. **Simplified User Experience**:
   * Users can sign a single message off-chain instead of interacting with the blockchain twice (approval + transaction). This reduces complexity and enhances accessibility, especially for new users.
3. **Reduced Approval Risks**:
   * Traditional token approvals often involve granting large or unlimited allowances to smart contracts, exposing users to potential security risks. Permit2 enables users to set:
     * **Custom Allowance Limits**: Users can specify exact amounts to be approved.
     * **Time-Limited Approvals**: Permissions can expire automatically after a defined period, reducing exposure.
4. **Cross-Platform Compatibility**:
   * Permit2 is designed to work seamlessly across multiple decentralized applications (dApps) and protocols. This makes it a versatile solution for trading platforms, DeFi protocols, and wallet integrations.
5. **Batch Operations**:
   * Permit2 allows bulk approvals and transfers in a single transaction, optimizing workflows for advanced use cases such as portfolio management and multi-token swaps.

***

#### **Use Cases in Trading**

1. **Decentralized Exchanges (DEXs)**:
   * Traders can sign a Permit2 authorization once, enabling seamless trades across multiple tokens without additional approvals.
2. **Aggregators**:
   * Trading aggregators can leverage Permit2 to simplify routing trades through multiple liquidity sources without requiring repeated token approvals.
3. **Gasless Transactions**:
   * Protocols can use Permit2 in combination with relayers to enable gasless trading experiences, where users do not need to pay for gas fees directly.
4. **Lending and Yield Farming**:
   * Users can authorize lending protocols or yield farms to manage token allowances more dynamically and securely, improving operational efficiency.

***

#### **Comparison: Permit vs. Permit2**

| Feature                | Permit (EIP-2612)                   | Permit2                             |
| ---------------------- | ----------------------------------- | ----------------------------------- |
| Approval Methodology   | Off-chain signature + on-chain call | Off-chain signature + on-chain call |
| Gas Savings            | Yes                                 | Yes, with bulk operations support   |
| Time-Limited Approvals | Yes                                 | Yes                                 |
| Batch Approvals        | No                                  | Yes                                 |
| Transfer Allowances    | No                                  | Yes                                 |
| Compatibility          | Specific to token implementation    | Works across all ERC-20 tokens      |

***

#### **Conclusion**

Permit2 is a significant step forward in enhancing the efficiency, security, and user experience of token approvals for decentralized trading. By reducing gas costs, simplifying workflows, and offering advanced features such as batch operations and time-limited allowances, Permit2 provides a powerful tool for DeFi protocols and traders alike.

For developers and platforms, integrating Permit2 into their systems can unlock better user experiences while optimizing transaction workflows. Permit2 is set to become a foundational component in the next generation of decentralized finance.


# Usage in our api

#### **Using `permitData` to Enhance Permit2 in the Trading API**

This document explains how to leverage the `permitData` field with the Permit2 mechanism in the trading API for efficient and secure token approvals. The endpoint in focus is:

**Endpoint**: `GET /single-chain/swap`

***

#### **What is `permitData`?**

`permitData` is an advanced feature provided by the API to facilitate gas-efficient and user-friendly token approvals. By utilizing Permit2, `permitData` enables off-chain signatures for token allowances, which can be submitted on-chain without requiring the user to send a separate approval transaction.

This eliminates the need for traditional ERC-20 `approve` calls, streamlining the trading experience while saving gas costs and improving security.

***

#### **How `permitData` Works**

1. **Off-Chain Signature**: The user signs a `permit` message off-chain authorizing the trading contract to spend their tokens.
2. **On-Chain Execution**: The signed `permitData` is sent along with the swap request to the `/single-chain/swap` endpoint.
3. **Token Allowance**: The contract uses Permit2 to verify the signature and execute the swap, avoiding a separate on-chain approval step.

***

#### **Workflow to Use `permitData`**

**1. Retrieve `permitData` Structure**

To generate the `permitData` that the user needs to sign, follow these steps:

1. **Prepare the Request Payload**:
   * Prepare the data required for Permit2 signed typed data, including `token`, `amount`, `spender`, `nonce`, and `deadline`. Generate the typed data for signing using either [`@uniswap/permit2-sdk`](https://www.npmjs.com/package/@uniswap/permit2-sdk) or any method of your choice.
   * Ensure the token being approved supports Permit2.
   * Ensure that you sent version=v2 on the quote request endpoint, as this feature it's only available in v2 version of our smart contract.
2. **User Signs the Data**:

   * Obtain the user’s signature on the `permitData` using a wallet (e.g., MetaMask or hardware wallet). (for example: <https://viem.sh/docs/actions/wallet/signTypedData.html>)
   * with the signature after sign, this is the permitData format:

   ```
   "permitData": {
       "user": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791", // user address
       "amount": "8018856", // amount to trade
       "deadline": 1734451256, // deadline for the permit2 signature
       "nonce": 3791859555499801, // random nonce https://github.com/shonentropy3/cdeer/blob/15faa9d33e6ded2cececf3ecf3e1c07b99b58943/front/pages/order.js#L134
       "sign": "0xbdd2d80ced…7a1c" // result of signTypedData
   }
   ```

***

**2. Call the Swap Endpoint with `permitData`**

Send the signed `permitData` to the `/single-chain/swap` endpoint along with the other required parameters:

**Request Example**:

```json
{
  "transactionData": {},
  "nativeValue": "0",
  "amount": "1000000000000000000", // Amount in smallest units (e.g., wei)
  "account":  "0xF0Fbf42C54Ac40dA016003baD35E5AefaC6E1CE1",
  "receiver":  "0xF0Fbf42C54Ac40dA016003baD35E5AefaC6E1CE1",
  "tradeType" : "0",
  "permitData": {
    "user": "0x2472d3EF4bF71af00c3dE490a5a53A99CbAC0791",
    "amount": "8018856",
    "deadline": 1734451256,
    "nonce": 3791859555499801,
    "sign": "0xbdd2d80ced…7a1c
  }
}
```

**Response Example**:

```json
{
  "data": {},
  "contractVersion": "v1",
  "estimateGas": "11231133211313",
  "estimateGasError": "Execution reverted",
  "nativeValue": "0",
  "allowance": "56442235035",
  "insufficientFunds": false,
  "insufficientAllowance": false,
  "insufficientGas": false,
  "maxFeePerGas": "20748300881",
  "maxPriorityFeePerGas": "maxPriorityFeePerGas",
  "gasPrice": "56442235035",
  "estimateGasRawError": "Error: invalid BigNumber string (argument=\"value\", value=\"\", code=INVALID_ARGUMENT, version=bignumber/5.7.0)"
}
```

***

#### **Benefits of Using `permitData`**

1. **Gas Savings**:
   * Eliminates the need for a separate approval transaction, reducing gas costs.
2. **Enhanced Security**:
   * Users can provide time-limited and amount-specific allowances, minimizing exposure to potential exploits.
3. **Streamlined UX**:
   * Allows users to sign once off-chain and execute swaps seamlessly without additional approval steps.
4. **Batch Approvals**:
   * Permit2 enables batch approvals and allowances for multiple tokens, optimizing multi-token swaps.

***

#### **Best Practices**

1. **Validate `permitData` Before Execution**:
   * Ensure the `permitData` signature is valid and corresponds to the intended swap parameters.
2. **Handle Expiry Gracefully**:
   * Monitor the `deadline` field in the `permitData` to ensure it hasn’t expired before sending the transaction.
3. **Test with Supported Tokens**:
   * Verify that the tokens involved in the swap support Permit2. Tokens without Permit2 support will require traditional approvals.

***

#### **Key Notes**

* Permit2 is only supported on compatible tokens and networks.
* Ensure that the `spender` address matches the contract that will execute the swap.
* Keep the signed `permitData` secure and ensure it is only used for the intended transaction.

By incorporating `permitData` and Permit2 into your trading workflow, you can enhance user experience, save gas, and improve transaction efficiency. For additional details, refer to the full API documentation at <https://api.zcx.com/trade/docs#/Single%20chain%20methods/SwapSingleController_getSingleSwap>.


# Embed the Unizen Widget

Integrating the Unizen Widget into Your WebApp

To integrate the Unizen widget into your web application using an iframe, follow these steps. This guide will walk you through the process of embedding the widget and customizing its parameters.

**Important Notice:** Please notify us to whitelist your site before integrating our widget.<br>

Unizen Playground URL: <https://www.unizen.io/widget>

**Step-by-Step Guide**

1. **Set Up Parameters:**<br>

   You can customize the widget by changing the values in the `params` object. Here’s a brief explanation of each parameter:\
   **Trade params**&#x20;

   * **uuid**: Your uuid.
   * **apiKeyId**: Your API key ID.
   * **themeName**: The theme of the widget (dark or light).
   * **inputCurrency**: The input currency address, for native currency, use Zero Address.
   * **outputCurrency**: The output currency address, for native currency, use Zero Address.
   * **inputChainId**: The chain ID of the input currency.
   * **outputChainId**: The chain ID of the output currency.
   * **tokenFromAmount**: The amount of the input currency, if you want to trade exact in. For example, if you want to trade 1.1 ETH => tokenFromAmount = '1.1'. NOTE: if exact out trade, leave it empty.
   * **tokenToAmount**: The amount of the output currency, if you want to trade exact out. NOTE: if exact in trade, leave it empty.

   **Theme params**

   * **primaryTextColorLight**: Primary text color in light mode.
   * **primaryTextColorDark**: Primary text color in dark mode.
   * **secondaryTextColor**: Secondary text color.
   * **interactiveColorLight**: Interactive color in light mode.
   * **interactiveColorDark**: Interactive color in dark mode.
   * **accentColorLight**: Accent color in light mode.
   * **accentColorDark**: Accent color in dark mode.
   * **containerCardColorLight**: Container card color in light mode.
   * **containerCardColorDark**: Container card color in dark mode.
   * **dialogColorLight**: Dialog background color in light mode.
   * **dialogColorDark**: Dialog background color in dark mode.
   * **cardRadius**: Border radius for cards.
   * **buttonRadius**: Border radius for buttons.
   * **tokenLogoShadowSize**: The size of the shadow applied to token logos, for example: '0 0 0 0'
   * **font**: The font used in the widget. It should match one of the available font classes. This is available font list: 'fira-code', 'baloo', 'poppins', 'lato', 'nunito', 'raleway', 'montserrat', 'oswald', 'playfair', 'barlow', 'rubik', 'cormorant', 'noto', 'alegreya', 'inter'<br>

   <figure><img src="/files/FHh9Jx5q8H5fXmKGHOZE" alt=""><figcaption></figcaption></figure>

   **Other params**

   * **networkSelector**: Represents the UI option for selecting a network, usually a dropdown or selector. (string: 'true' or 'false')
   * **categorySelector**: Represents the UI option for selecting a category currency:  (string: 'true' or 'false')
   * **networks**: A comma-separated list of supported networks. For example: 137,56

   Example params for trade from 1000 USDT to ETH on Ethereum: <br>

   ```typescriptreact
   const params = {
       uuid: 'your uuid',
       apiKeyId: 'your apiKeyId',
       themeName: 'dark',
       inputCurrency: '0xdac17f958d2ee523a2206206994597c13d831ec7', // USDT address
       outputCurrency: '0x0000000000000000000000000000000000000000', // ETH address (native currency)
       inputChainId: '1', // Ethereum mainnet chain ID
       outputChainId: '1', // Ethereum mainnet chain ID
       tokenFromAmount: '1000', // Exact in amount of 1000 USDT
       tokenToAmount: '', // Leave empty for exact in trade
       primaryTextColorLight: 'red',
       primaryTextColorDark: 'blue',
       secondaryTextColor: 'blue',
       interactiveColorLight: 'orange',
       interactiveColorDark: 'purple',
       accentColorLight: 'pink',
       accentColorDark: 'cyan',
       containerCardColorLight: 'yellow',
       containerCardColorDark: 'yellow',
       dialogColorLight: 'green',
       dialogColorDark: 'green',
       cardRadius: '10px',
       buttonRadius: '5px'
     };
   ```
2. **Generate Widget URL:**\
   Construct the URL for the widget by appending the parameters to the base URL. \
   ``const WIDGET_URL = `https://zcx.com/widget?${new URLSearchParams(params)}`;``
3. **Embed the Widget in an iframe:**

   ```typescriptreact
     <iframe
           src={WIDGET_URL}
           title='Unizen Exchange Widget'
           className={clsx(
             'w-[600px]',
             'h-[600px]',
             'border-2'
           )}>
         </iframe>
   ```


# Smart Contracts

A Collection of Unizen Smart Contract Addresses Across Networks

**Ethereum**

| Unizen Bridge       | `0x59679AB495079334488a48Dedb6AEF6F7a81A192` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator    | `0xd3f64BAa732061F8B3626ee44bab354f854877AC` |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |
| Unizen Earn         | `0xb202CCbeBB4C472657f16F30bF277d3BE7F4781a` |

**Polygon**

| Unizen Bridge       | `0x42ab28B4fB1722399BbceB3197A31db8860b1293` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator    | `0x07d0ac7671D4242858D0cebcd34ec03907685947` |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |
| Unizen Earn         | `0x078f188810ad3F2506a4FD76a982F281f4df15F2` |

#### **BNB Chain** <a href="#binance-smart-chain" id="binance-smart-chain"></a>

| Trade Aggregator    | `0x880E0cE34F48c0cbC68BF3E745F17175BA8c650e` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator v2 | 0x42479c390270cBa049A2D10F63bF75d9D0B7a742   |

#### **Avax** <a href="#avax" id="avax"></a>

| Trade Aggregator    | `0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |

#### **Fantom** <a href="#fantom" id="fantom"></a>

| Trade Aggregator    | `0xBE2A77399Cde40EfbBc4e89207332c4a4079c83D` |
| ------------------- | -------------------------------------------- |
| Trade aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |

#### **Arbitrum** <a href="#arbitrum" id="arbitrum"></a>

| Trade Aggregator    | `0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |

#### **Optimism** <a href="#optimism" id="optimism"></a>

| Trade Aggregator    | `0xad1D43efCF92133A9a0f33e5936F5ca10f2b012E` |
| ------------------- | -------------------------------------------- |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22   |

#### **Base** <a href="#optimism" id="optimism"></a>

| Trade Aggregator    | 0x4F68248ecB782647D1E5981a181bBe1bfFee1040 |
| ------------------- | ------------------------------------------ |
| Trade Aggregator v2 | 0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22 |

#### **Berachain** <a href="#optimism" id="optimism"></a>

| Trade Aggregator v2 | 0x433dA70E79861C265E07953Dde9ce8629a57a589 |
| ------------------- | ------------------------------------------ |

#### **Unichain** <a href="#optimism" id="optimism"></a>

| Trade Aggregator v2 | 0x4039942b38241D62cA8460Ea54A096a5B3e2bf61 |
| ------------------- | ------------------------------------------ |

#### Solana

<table data-header-hidden><thead><tr><th></th><th></th><th data-hidden></th></tr></thead><tbody><tr><td>Solana Aggregator</td><td>zcxP3rDDcrPN6H3dk7mR9YGPFHZRbcMzPHLZzEhtGsN</td><td></td></tr></tbody></table>

1. Install the npm package: <https://www.npmjs.com/package/@unizen-io/unizen-contract-addresses> and use the JSON file from `@unizen-io/unizen-contract-addresses/production.json`
2. Configure the JSON file provided below for your project.

```json
{
  "v1": {
    "ethereum": "0xd3f64BAa732061F8B3626ee44bab354f854877AC",
    "bsc": "0x880E0cE34F48c0cbC68BF3E745F17175BA8c650e",
    "polygon": "0x07d0ac7671D4242858D0cebcd34ec03907685947",
    "avax": "0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7",
    "fantom": "0xBE2A77399Cde40EfbBc4e89207332c4a4079c83D",
    "arbitrum": "0x1C7F7e0258c81CF41bcEa31ea4bB5191914Bf7D7",
    "optimism": "0xad1D43efCF92133A9a0f33e5936F5ca10f2b012E",
    "base": "0x4F68248ecB782647D1E5981a181bBe1bfFee1040"
  },
  "v2": {
    "ethereum": "0xf140bE1825520F773Ff0F469786FCA65c876885f",
    "bsc": "0x12067e4473a1f00e58fa24e38e2cf3e53e21a33d",
    "polygon": "0x85f8fb7ac814d0a6a0b16bc207df5bbc631f1ca6",
    "avax": "0x468ae09BD4c8B4D9f7601e37B6c061776FeCFE3B",
    "fantom": "0xD38559966E53B651794aD4df6DDc190d2235180E",
    "arbitrum": "0x9660b95fcDBA4B0f5917C47b703179E03a28bf27",
    "optimism": "0x3ce6e87922e62fc279152c841102eb2bf5497010"
  },
  "v3": {
    "ethereum": "0xCf2DBA4e5C9f1B47AC09dc712A0F7bD8eE31A15d",
    "bsc": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "polygon": "0xCf2DBA4e5C9f1B47AC09dc712A0F7bD8eE31A15d",
    "avax": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "arbitrum": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "optimism": "0xa9c430de6a91132330A09BE41f9f19bf45702f74",
    "base": "0xa9c430de6a91132330A09BE41f9f19bf45702f74"
  },
  "unizenRouter": {
    "ethereum": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "bsc": "0x42479c390270cBa049A2D10F63bF75d9D0B7a742",
    "polygon": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "avax": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "arbitrum": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "optimism": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "base": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "fantom": "0xef58B643240178c2BC37681f8d4E50d7Ec37Ee22",
    "berachain": "0x433dA70E79861C265E07953Dde9ce8629a57a589",
    "unichain": "0x4039942b38241D62cA8460Ea54A096a5B3e2bf61"
  }
}
```

**Note**: The Solana aggregator address isn't included in the npm package because the transaction data already specifies the address for Solana


# Security Audits

The entire Unizen infrastructure, code base and smart contracts has been audited multiple times both internally and through reputable third-party auditors.&#x20;

The audit reports can be found below.

[Hacken Unizen\_Solana\_Aggregator Feb 2025](https://github.com/unizen-io/unizen-stratosphere-sc/blob/main/audit-report/Hacken_Unizen_%5BSCA%5D%20Unizen%20_%20Unizen-Solana-Swap%20_%20Jan2025_P-2025-1478_2_20250212%2015_41.pdf)

[Verichains Unizen\_Solana\_Aggregator Feb 2025](https://github.com/unizen-io/unizen-stratosphere-sc/blob/main/audit-report/Verichains_Public_Report_Unizen_Solana_Aggregator_Program_v1_1.pdf)

[Beosin Unizen\_Solana\_Aggregator Feb 2025](https://github.com/unizen-io/unizen-stratosphere-sc/blob/main/audit-report/unizen-solana-swap_202502061212.pdf)

[Beosin audit report June 2024](https://github.com/unizen-io/unizen-audits/blob/main/Beosin_Audit_24June21.pdf)

[Verichain audit report June 2024](https://github.com/unizen-io/unizen-audits/blob/main/Verichains_audit_24June27.pdf)

[Beosin audit report April 2024](https://github.com/unizen-io/unizen-audits/blob/main/Unizen%20Trade_202404031610.pdf)

[Verichain audit report April 2024](https://github.com/unizen-io/unizen-audits/blob/main/Verichains%20Public%20Report%20-%20Unizen.pdf)

[Beosin audit report April 2024 (V3 contracts, swap cross-chain via Debridge/Meson)](https://github.com/unizen-io/unizen-audits/blob/main/Smart%20contract%20security%20audit%20report%20-%20Unizen%20Trade.pdf)

[Halborn](https://github.com/unizen-io/unizen-audits/blob/main/REP-Halborn-Unizen-DexAggregator-2022-09-09.pdf)\
[Verichain](https://github.com/unizen-io/unizen-audits/blob/main/REP-Verichains-Unizen-DexAggregator-2022-12-29.pdf)\
[Certik](https://github.com/unizen-io/unizen-audits/blob/main/REP-unizen-2021-07-13.pdf)<br>

<br>


# Roadmap

What We're Building

#### **ULDM v3.5 with AI/ML**

* Integrate ML models to optimize trade routes in real time
* Predict slippage, gas costs, bridge risks, and trade reliability
* Use historical and live data to train routing optimizing AI models
* Begin transition toward partial automation (shadow mode → active)

#### Limit Orders

* Full limit order support with on-chain settlement
* Partial fill support
* Gas abstraction and relayer support for ease of use
* Modular architecture to plug into ULDM routing

#### Earn 2.0

* Incentivized liquidity provisioning with dual-purpose rewards
* LP token staking with IL-mitigating mechanics
* Designed for long-term depth and stickier liquidity
* Integrated analytics to track performance and rewards

#### Custom Liquidity Pools

* Deploy native Unizen pools for top-traded assets
* Ultra-efficient routing and deep liquidity pairing with ULDM
* Custom curves optimized for specific trade flows
* Built for ZCX, ETH, BTC, stablecoins, and other top performing assets

#### TWAP Orders

* Time-weighted average price orders for large trades
* Split execution across defined time windows
* Dynamic sizing based on liquidity depth and volatility
* Integrated fallback logic in case of sharp market moves

#### Unizen DAO (Powered by DEXE)

* Deployed governance layer using DEXE’s DAO framework
* Token holders can propose and vote on protocol changes

#### **Multi-Regional Kubernetes Deployment**

* Deploy and manage Kubernetes clusters in multiple regions (APAC, US, EU)
* Reduce response times for users in latency-sensitive regions
* Enable geo-based routing and failover
* Use cloud-native tools (e.g., GKE multi-cluster, AWS EKS, Cloudflare) to manage traffic

#### **Scalability Improvements**

* Auto-scaling based on traffic spikes and region-specific demand
* Isolate workloads per region to reduce cross-zone latency
* Optimize container scheduling and caching per region
* Shared global state where needed (e.g., Redis, DBs with read replicas)

#### **Reliability Enhancements**

* Active-active setup with health checks and failover
* Region-level fault isolation to reduce blast radius
* Real-time monitoring and observability using Prometheus + Grafana
* Log and trace aggregation for faster debugging

#### More (Not Yet Announced)

* Ongoing R\&D
* Tactical innovations aligned with protocol and ecosystem strategy\ <br>

### Ongoing Priorities

#### More Networks

* EVM-first: Monad, Linea, Scroll, Mode, ZetaChain, zkSync, Blast, Polygon zkEVM
* Consider high-TVL non-EVMs if safe bridging and aggregator support exists
* Native ZenChain routing once mainnet is live

#### More Interoperability Providers

* Expand bridge coverage: CCIP, Squid, Across and StargateV2
* Evaluate bridge risk dynamically with scoring models
* Integrate bridges deeper into ULDM for optimized cross-chain flow

#### More Solvers

* Deploy Unizen as solver on major intent-based architectures
* Follow developments in SUAVE, Anoma, Essential, etc.
* Build internal solver engine aligned with ULDM logic
* Focus on gas efficiency, bundling, and MEV resistance

#### More Liquidity

* Onboard more DEXs and PMMs per network weekly
* Partner with LPs, protocols, and treasuries to deepen liquidity
* Monitor and reroute around thin or volatile pools
* Use AI to detect anomalies and shift volume to safer paths

#### **Global Rollout of Performance-Critical Services**

* Gradual expansion of ULDM routing, analytics, and limit order services into regional clusters
* Shared memory/cache coordination for consistency across regions
* Prioritize services handling live routing, trade execution, and bridge interactions

#### **Improved Latency**

* Monitor regional response times and adjust routing rules
* Benchmark API latencies under real-world trade scenarios
* Optimize DNS and CDN config for faster edge resolution

<br>


