# About 31Third

## Introduction

31Third is a blockchain-based asset management infrastructure radically optimizing on-chain trade execution and portfolio management.

## Product

Our first product is batch trading, which enables users to trade with two or more assets or rebalance an entire portfolio in a single transaction. Batch trading reduces transaction costs, results in better prices, saves execution time and ensures more accurate portfolio weights.

If the S\&P 500 had been available in an on-chain environment, our infrastructure could rebalance all the 500 underlying assets in one go, resulting in up to 30% reduction in transaction fees.

## Algorithmic Smart Order Routing (ASOR)

Our algorithmic smart order router is the heart of our infrastructure. When you execute a batch trade, our algorithm finds the best prices and deepest liquidity not only across exchanges and market makers but also across each traded asset.&#x20;

This linear optimization results in hundreds of more newly analyzed trade routes for users, which can yield radically better prices.

#### Case Study

For example, look at the DeFi Pulse Index, the largest on-chain ETF with ten underlying assets weighted based on market capitalization.&#x20;

Existing smart order routers are limited to one-to-one trades, which means that liquidity is compared only for a single pair. With traditional routers, the traders receive quotes for ten separate one-to-one traders in the best case.

In contrast, our algorithmic smart order router calculates 90 possible combinations across the portfolio $$f(n) = \binom{n}{2} \* 2$$ ; this is close to 10x more variations analyzed.

## Benefits

#### Zero Slippage

We offer the deepest liquidity network with direct access to market makers and DEXs.

#### Advanced API

Access our entire product suite via simple APIs, enabling full integration with other platforms, automated trading systems, and OMS.

#### Protocol Integrations

Trade with yield baring tokens via our direct integrations to Aave, Curve, Lido, and more.

#### Self Custody

Access all our features via any wallet or custody provider.


# Use cases

## Background

Every tenth consecutive on-chain trade is from the same wallet address. By executing these together, traders could optimize billions of trading volumes, save millions in fees, and reduce execution time by days while achieving better prices.

## **Portfolio Rebalancing**

Portfolio rebalancing is a many-to-many transaction batched into a single trade. Traders can pre-define their portfolio's target allocation, and our algorithmic smart order router achieves the desired portfolio weights in seconds.

The solution is a game-changer for on-chain ETFs and those actively managing their assets based on a pre-defined strategy. On top of achieving substantially better prices and laser-sharp portfolio weights, our infrastructure saves all the manual calculations and removes the potential for error for the trader.

{% embed url="<https://www.youtube.com/watch?v=MiT3Lv91DTk>" %}
Batch Execution / Multi Asset Swap Demo
{% endembed %}

## **Many-to-One**

Many-to-one execution enables traders to liquidate selected tokens or their entire portfolio into a single asset.

The order simplifies the execution of a concentrated position, the liquidation of risk-on assets into stables, and the redemption of portfolio tokens with multiple underlying assets.

#### Example: All In SHIB

Exchange all your assets into a single token. The function is available for tokens set up in our backend. If you want us to set up a token for you, fill out this form. The below example shows the transaction for SHIB.

<https://app.31third.com/rebalance/allin/shib>

#### **Example: Liquidiate to Stables**

Liquidate your risky assets into stablecoins in times of volatility.

<https://app.31third.com/rebalance/index/allout>&#x20;

## One-to-Many

One-to-many execution enables traders to enter multiple positions and initiate a portfolio from a single asset.

#### **Example: Issue a Portfolio**

Trade your asset(s) into an index tracked by 31Third.

10 Largest DeFi Market Cap: <https://app.31third.com/rebalance/index/defi10>

5 MidCap: <https://app.31third.com/rebalance/index/midcap5>

Stabelcoin Staking Index: <https://app.31third.com/rebalance/index/staking>

#### Example: Follow a Wallet

Follow the trades of a wallet. The below example shows the function for [Light Wallet](https://www.whalestats.com/ethereum-address/0x72a53cdbbcc1b9efa39c834a540550e23463aacb-Light-wallet).

<https://app.31third.com/rebalance/wallet/0x72a53cdbbcc1b9efa39c834a540550e23463aacb>


# 0x Labs Collaboration

We are collaborating with 0x Labs, the category leader in decentralized exchange aggregators.

Our batch execution engine is multiple recipients of the 0x DAO Grants Program. We are excited to contribute to the 0x ecosystem with a product with profound benefits for a wide variety of users and protocols.

From the technical perspective, the 0x API enables us to offer the deepest liquidity network with direct access to market makers and DEXs. In other words, when trading via our front-end or relying on our batch execution API, you will benefit from the entire product suite of 0x Labs.


# Architecture

31Third provides a fully-fledged system based on three components. An API that uses on-chain and external data to prepare optimal rebalancings, a set of smart contracts enabling batched execution of token actions, such as trades, wrapping, and staking, and a frontend that allows the rebalancings of wallets, SetProtocol portfolio tokens or Enzyme vaults.

The usage of our frontend is optional. It is also possible to directly integrate our API and smart contracts into existing systems.

<figure><img src="/files/ZiAlyc76j3ILWdoRckZZ" alt=""><figcaption><p>31Third Stack</p></figcaption></figure>

## 31Third API

The 31Third API's primary purpose is to calculate rebalancings for wallets, SetProtocol tokens, Enzyme vaults, and other frameworks in the future.

Our algorithmic smart order router (ASOR) is the heart of our infrastructure. When you calculate a rebalancing, our algorithm finds the best prices and deepest liquidity not only across exchanges and market makers but also across each traded asset.

The algorithm fetches prices from different price sources for various DEXs and market makers. It analyses trade efficiency factors like depth of liquidity, slippage, price impact, multi-hop abilities, and more to calculate the optimal route from any base to any target allocation.

More on the 31Third API can be found below.

{% content-ref url="/pages/fa2iz2i85r9aBXYNLVZp" %}
[31Third API](/31third-api/overview)
{% endcontent-ref %}

## 31Third protocol

The 31Third protocol is a set of smart contracts allowing the execution of multiple token on-chain operations like trading, wrapping, staking, and others in one go, batched together in a single transaction.

More on the 31Third protocol can be found below.

{% content-ref url="/pages/SG4K5fjq88sRYe73NSip" %}
[Protocol](/protocol/overview)
{% endcontent-ref %}

## 31Third Frontend

We provide an easy-to-use UI for traders and asset managers to manage their portfolios. Just configure the desired target allocation, let our API calculate the optimal rebalancing, check if you are satisfied with the result, and execute the whole rebalancing within one transaction. This not only saves you time and nerves but also spares substantial gas fees. [Gas cost analysis](/protocol/statistics/gas-cost-analysis).

<figure><img src="/files/Uf0kzT2rCzpx8bYC4bOm" alt=""><figcaption><p>31Third portfolio rebalancing</p></figcaption></figure>

## External Integrator

Instructions on accessing our API and using the protocol can be found in the specific sections. If you have any questions, we are happy to assist. Reach out via mail or [Discord](https://discord.gg/TZ3GBBgnf9).

{% content-ref url="/pages/fa2iz2i85r9aBXYNLVZp" %}
[31Third API](/31third-api/overview)
{% endcontent-ref %}

{% content-ref url="/pages/SG4K5fjq88sRYe73NSip" %}
[Protocol](/protocol/overview)
{% endcontent-ref %}


# Team

<table data-header-hidden><thead><tr><th width="203"></th><th></th></tr></thead><tbody><tr><td><img src="/files/z4kYLiHozihVvwSVm4zZ" alt="" data-size="original"></td><td><p><strong>Manuel</strong> </p><p>... holds a Master's degree in Management and IT and boasts over two decades of leadership experience as a serial entrepreneur. He previously founded a mobile marketing startup that catered to over a thousand B2B clients. Additionally, he spent seven years working for Erste Group Bank and Erste Asset Management, managing various digital projects.</p></td></tr></tbody></table>

<table data-header-hidden><thead><tr><th width="204"></th><th></th></tr></thead><tbody><tr><td><img src="/files/SwNeFGAMvYEfkOCR3wUy" alt="" data-size="original"></td><td><p><strong>Philipp</strong></p><p>... is an experienced full-stack software developer with a deep knowledge of blockchain technology. Philipp studied software engineering and focused on blockchain during his master's degree, where he wrote an insightful thesis on DeFi. With over 7 years of experience in the industry, Philipp has worked with both established companies like Cloudflight, as well as innovative startups. Passionate about creating cutting-edge solutions, Philipp is dedicated to driving innovation in the field of technology.</p></td></tr></tbody></table>

<table data-header-hidden><thead><tr><th width="204"></th><th></th></tr></thead><tbody><tr><td><img src="/files/A13fzMVw6UsmTZQf8jHj" alt="" data-size="original"></td><td><p><strong>Koppany</strong></p><p>... comes from the hedge fund group of Morgan Stanley. He has a deep understanding of DeFi both on a financial and technical level. Koppany studied at the FHWN and the London School of Economics. He is a lecturer at his former university.</p></td></tr></tbody></table>

<table data-header-hidden><thead><tr><th width="203"></th><th></th></tr></thead><tbody><tr><td><img src="/files/vtHEVEgulFIYRIKst5Zd" alt=""></td><td><p><strong>Johannes</strong></p><p>... is a highly skilled blockchain and full-stack developer with over seven years of experience. After completing his degree in software engineering, Johannes has advanced to become a team lead and a certified Scrum Master. With his expertise in software design, Johannes is dedicated to creating innovative software solutions and driving the development process forward.</p></td></tr></tbody></table>


# Overview

{% hint style="info" %}
Every request requires specifying the following headers:

* x-api-key
* chain-id

[Get your API key](mailto:dev@31third.com)
{% endhint %}

The 31Third API is available under <https://api.31third.com/1.3>.&#x20;

Swagger documentations can be found under:

* General: <https://api.31third.com/1.3/api>
* Enzyme: <https://api.31third.com/1.3/api/enzyme>

The following chains are currently supported:

| Name             | Id      |
| ---------------- | ------- |
| Ethereum Mainnet | 0x1     |
| Polygon Mainnet  | 0x89    |
| OP Mainnet       | 0xa     |
| \[SOON] Base     | 0x2105  |
| Arbitrum One     | 0xa4b1  |
| \[SOON] Blast    | 0x13e31 |
| BNB Smart Chain  | 0x38    |

## 31Third Basket Trade API flow

The API flow for integrators looks as follows. All the steps are described in more details below.&#x20;

Please note that the endpoints used in the picture are for basic wallet rebalancings, however similar endpoints exist for Enzyme vaults as well.

<figure><img src="/files/iij2cEnBqTT1Y455w0an" alt=""><figcaption><p>31Third API flow</p></figcaption></figure>

### Step 1: Assets

You can either use your own or some external service to load token/asset data or use 31Third's asset endpoints. If you use some external source keep in mind that what don't support all existing tokens, so a rebalancing calculation might fail.

More details on assets:

* [Wallet](/31third-api/assets/wallet)
* [Enzyme](/31third-api/basket-trade-m-n-swap/enzyme)

### Step 2: Settings

(COMING SOON)

31Third supports multiple liquidity sources. The available sources can be fetched and then be used to configure the rebalancing calculation.

More details on settings:

* COMING SOON

### Step 3: Configure rebalancing

This can either be done by a user via an UI or through a script.

### Step 4: Calculate rebalancing

Calculate the rebalancing with the 31Third API. It's possible to calculate rebalancings for wallets or protocol contracts (e.g. Enzyme vaults).

More details on rebalancings:

* [Wallet](/31third-api/basket-trade-m-n-swap/wallet)
* [Enzyme](/31third-api/basket-trade-m-n-swap/enzyme)

#### Step 4.1: async

The calculation of rebalancings might take some seconds depending on how many assets are involved. Therefore all rebalancing endpoints have the option to calculate them async, show the progress to the user and then receive the rebalancing when the calculation is done.

More details on async:

* [async](/31third-api/basket-trade-m-n-swap/async)&#x20;

### Step 5: Show rebalancing

Show rebalancing with details to the user. Or if you use a script maybe do some checks or analysis on top.

### Step 6: Refresh Quotes

After you calculated a rebalancing it might be that you have to refresh quotes. For example if you have a user interface and user don't directly execute received rebalancings.&#x20;

More details on refreshing quotes:

* [Refresh Quotes](/31third-api/refresh-quotes)

### Step 7: Sign and execute

Users can now sign and execute the rebalancing on-chain. The following 3 params may be used for that:

<table><thead><tr><th width="146"></th><th></th></tr></thead><tbody><tr><td><code>txHandler</code></td><td>the <code>contract address</code> where the the data should be sent to</td></tr><tr><td><code>txData</code></td><td>the <code>calldata</code> to send to the contract</td></tr><tr><td><code>txValue</code></td><td>the native currency <code>value</code> sent with the tx (optional)</td></tr></tbody></table>


# Assets

Depending if you want to do rebalancings for wallets or protocols (e.g. Enzyme vaults) there are different options to load assets:

* [Wallet](/31third-api/assets/wallet)
* [Enzyme](/31third-api/assets/enzyme)


# Wallet

Data from both endpoints can be used for the SELL and BUY side, however if you also want to show the current balances of a wallet you should go with the second endpoint.&#x20;

## /asset

Load a list of assets containing token and price information for wallet rebalancings

## GET /1.3/asset

> Get list of assets (token + price)

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"asset","description":"Load asset data"}],"paths":{"/1.3/asset":{"get":{"operationId":"AssetController_getAssets","summary":"Get list of assets (token + price)","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListResponseDto"},{"properties":{"items":{"description":"List of assets","type":"array","items":{"$ref":"#/components/schemas/AssetDto"}}}}]}}}}},"tags":["asset"]}}},"components":{"schemas":{"ListResponseDto":{"type":"object","properties":{}},"AssetDto":{"type":"object","properties":{"token":{"description":"Underlying token of the asset","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"balance":{"format":"int64","type":"integer","description":"Balance of this asset on the specified address"},"priceInNativeCurrency":{"format":"int64","type":"integer","description":"Price of this asset in native currency (wei)"},"priceInUsd":{"type":"number","description":"Price of this asset in USD"},"priceInEur":{"type":"number","description":"Price of this asset in EUR"},"valueInNativeCurrency":{"format":"int64","type":"integer","description":"Value of this asset in ETH (wei)"},"valueInUsd":{"type":"number","description":"Value of this asset in USD"},"valueInEur":{"type":"number","description":"Value of this asset in EUR"},"cmcRank":{"type":"number","description":"CoinMarketCap rank of this token"},"isTradeable":{"type":"boolean","description":"Determines if this asset is tradeable in general"},"isSellable":{"type":"boolean","description":"Determines if this asset is sellable by the connected account (E.g. it could be the case that the account just holds an amount worth 0.000001$ and is this case its not sellable)"}},"required":["token","balance","priceInNativeCurrency","priceInUsd","priceInEur","valueInNativeCurrency","valueInUsd","valueInEur","cmcRank","isTradeable","isSellable"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]}}}}
```

## /asset/{address}

Load a list of assets containing token, price and balance information for wallet rebalancings

## Get list of assets (token + price + balance for passed address)

> Also contains assets for all other supported tokens with a balance of zero

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"asset","description":"Load asset data"}],"paths":{"/1.3/asset/{address}":{"get":{"operationId":"AssetController_getAssetsForAccount","summary":"Get list of assets (token + price + balance for passed address)","description":"Also contains assets for all other supported tokens with a balance of zero","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}},{"name":"address","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListResponseDto"},{"properties":{"items":{"description":"List of assets","type":"array","items":{"$ref":"#/components/schemas/AssetDto"}}}}]}}}}},"tags":["asset"]}}},"components":{"schemas":{"ListResponseDto":{"type":"object","properties":{}},"AssetDto":{"type":"object","properties":{"token":{"description":"Underlying token of the asset","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"balance":{"format":"int64","type":"integer","description":"Balance of this asset on the specified address"},"priceInNativeCurrency":{"format":"int64","type":"integer","description":"Price of this asset in native currency (wei)"},"priceInUsd":{"type":"number","description":"Price of this asset in USD"},"priceInEur":{"type":"number","description":"Price of this asset in EUR"},"valueInNativeCurrency":{"format":"int64","type":"integer","description":"Value of this asset in ETH (wei)"},"valueInUsd":{"type":"number","description":"Value of this asset in USD"},"valueInEur":{"type":"number","description":"Value of this asset in EUR"},"cmcRank":{"type":"number","description":"CoinMarketCap rank of this token"},"isTradeable":{"type":"boolean","description":"Determines if this asset is tradeable in general"},"isSellable":{"type":"boolean","description":"Determines if this asset is sellable by the connected account (E.g. it could be the case that the account just holds an amount worth 0.000001$ and is this case its not sellable)"}},"required":["token","balance","priceInNativeCurrency","priceInUsd","priceInEur","valueInNativeCurrency","valueInUsd","valueInEur","cmcRank","isTradeable","isSellable"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]}}}}
```


# Enzyme

## /asset/enzyme/{vault}

Load a list of assets containing token, price and balance information for Enzyme rebalancings. Should be used for the BUY side.

## Get list of all Enzyme assets (incl. balance for passed vault)

> Also contains asset entries for all other supported tokens with a balance of zero

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"asset","description":"Load asset data"}],"paths":{"/1.3/asset/enzyme/{vault}/{testnet}":{"get":{"operationId":"EnzymeAssetController_getAssetsForVault","summary":"Get list of all Enzyme assets (incl. balance for passed vault)","description":"Also contains asset entries for all other supported tokens with a balance of zero","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}},{"name":"vault","required":true,"in":"path","schema":{"type":"string"}},{"name":"testnet","required":true,"in":"path","schema":{"type":"boolean"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListResponseDto"},{"properties":{"items":{"description":"List of supported assets with balance of passed vault","type":"array","items":{"$ref":"#/components/schemas/AssetDto"}}}}]}}}}},"tags":["asset"]}}},"components":{"schemas":{"ListResponseDto":{"type":"object","properties":{}},"AssetDto":{"type":"object","properties":{"token":{"description":"Underlying token of the asset","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"balance":{"format":"int64","type":"integer","description":"Balance of this asset on the specified address"},"priceInNativeCurrency":{"format":"int64","type":"integer","description":"Price of this asset in native currency (wei)"},"priceInUsd":{"type":"number","description":"Price of this asset in USD"},"priceInEur":{"type":"number","description":"Price of this asset in EUR"},"valueInNativeCurrency":{"format":"int64","type":"integer","description":"Value of this asset in ETH (wei)"},"valueInUsd":{"type":"number","description":"Value of this asset in USD"},"valueInEur":{"type":"number","description":"Value of this asset in EUR"},"cmcRank":{"type":"number","description":"CoinMarketCap rank of this token"},"isTradeable":{"type":"boolean","description":"Determines if this asset is tradeable in general"},"isSellable":{"type":"boolean","description":"Determines if this asset is sellable by the connected account (E.g. it could be the case that the account just holds an amount worth 0.000001$ and is this case its not sellable)"}},"required":["token","balance","priceInNativeCurrency","priceInUsd","priceInEur","valueInNativeCurrency","valueInUsd","valueInEur","cmcRank","isTradeable","isSellable"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]}}}}
```


# Swap

31Third swap API.

## Get started

{% content-ref url="/pages/wQ01uwG4EUGbkHOQLHIA" %}
[Get started](/31third-api/swap/get-started)
{% endcontent-ref %}

***

## API reference

{% content-ref url="/pages/v3aBRgpDybwqxqbGV9GJ" %}
[price](/31third-api/swap/price)
{% endcontent-ref %}

{% content-ref url="/pages/sPTF07oV1zu47nqBZq1m" %}
[quote](/31third-api/swap/quote)
{% endcontent-ref %}


# Get started

## Step 0: Get 31Third API key

Request an API key via <dev@31third.com>.&#x20;

## Step 1: Get an indicative price

Use `/swap/price` to fetch an indicative price.&#x20;

{% content-ref url="/pages/v3aBRgpDybwqxqbGV9GJ" %}
[price](/31third-api/swap/price)
{% endcontent-ref %}

You'll receive indicative information about:

* buy amount
* conversion price
* price impact estimation.

## Step 2: Get quote

Use `/swap/quote` to fetch a quote.&#x20;

{% content-ref url="/pages/sPTF07oV1zu47nqBZq1m" %}
[quote](/31third-api/swap/quote)
{% endcontent-ref %}

You'll receive information about:

* buy amount
* minimal buy amount
* conversion price
* guaranteed conversion price
* price impact
* maximal price impact
* **raw transaction**

## Step 3: Send transaction

The quote response contains a raw transaction.

```
RawTransaction {
  to: string;
  data: string;
  value: string;
  gasLimit?: string; // Not always present
  gasPrice?: string; // Not always present
}
```

This transaction can be broadcasted to execute the swap.

### Ethers.js example

The raw transaction can be passed into [ethers signer.sendTransaction](https://docs.ethers.org/v5/api/signer/#Signer-sendTransaction) as follows:

```typescript
signer.sendTransaction(rawTransaction);
```


# price

API reference to fetch an indicative price for a swap.

## GET /1.3/swap/price

> Get indicative price for a swap

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"swap","description":"Calculate swaps"}],"paths":{"/1.3/swap/price":{"get":{"operationId":"SwapController_getSwapPrice","summary":"Get indicative price for a swap","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}},{"name":"sellToken","required":true,"in":"query","description":"Address of the sell token","schema":{"type":"string"}},{"name":"buyToken","required":true,"in":"query","description":"Address of the buy token","schema":{"type":"string"}},{"name":"sellAmount","required":true,"in":"query","description":"Sell amount in token base units (e.g. Wei for ETH)","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SwapPriceDto"}}}}},"tags":["swap"]}}},"components":{"schemas":{"SwapPriceDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated swap price."},"sellToken":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"buyToken":{"description":"Buy token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"sellAmount":{"format":"int64","type":"integer","description":"Amount to sell. (In sell token units)"},"buyAmount":{"format":"int64","type":"integer","description":"Estimated buy amount. (In buy token units)"},"price":{"type":"number","description":"Price of the <code>buy</code> token in <code>sell</code> token. E.g. 1 BTC = 100.000 USD; you sell WBTC and buy USDC; the price is 0.000001"},"priceImpactBps":{"type":"number","description":"Estimated price impact in basis points. [-10_000;10_000]. > 0 = value loss. < 0 = value gain","minimum":-10000,"maximum":10000}},"required":["id","sellToken","buyToken","sellAmount","buyAmount","price","priceImpactBps"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]}}}}
```


# quote

API reference to fetch a quote for a swap.

{% hint style="info" %}
**Enzyme**

To execute swap with your Enzyme vault note the following:

* taker: Address of your Enzyme vault
* txOrigin: Address of the authorized "Manager" or "Asset Manager"
* encodingType: Set to "enzyme-vault"
  {% endhint %}

## GET /1.3/swap/quote

> Get quote for a swap

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"swap","description":"Calculate swaps"}],"paths":{"/1.3/swap/quote":{"get":{"operationId":"SwapController_getSwapQuote","summary":"Get quote for a swap","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}},{"name":"sellToken","required":true,"in":"query","description":"Address of the sell token","schema":{"type":"string"}},{"name":"buyToken","required":true,"in":"query","description":"Address of the buy token","schema":{"type":"string"}},{"name":"sellAmount","required":true,"in":"query","description":"Sell amount in token base units (e.g. Wei for ETH)","schema":{"type":"string"}},{"name":"taker","required":true,"in":"query","description":"Address which holds the sellToken. (Allowance has to be set before execution)","schema":{"type":"string"}},{"name":"txOrigin","required":false,"in":"query","description":"Address of the external account that executed the tx. (Only needed if taker is a contract)","schema":{"type":"string"}},{"description":"(WIP) Liquidity sources types","required":false,"name":"types","in":"query","schema":{"type":"array"}},{"description":"Configuration allows three strategies: empty, include or exclude.\n - Empty: all sources are enabled. \n - Include (Whitelisting): only the given sources are enabled. \n - Exclude (Blacklisting): all sources except the given ones are enabled.","oneOf":[{"$ref":"#/components/schemas/IncludeLiquiditySourcesDto"},{"$ref":"#/components/schemas/ExcludeLiquiditySourcesDto"}],"required":false,"name":"sources","in":"query","schema":{}},{"name":"maxSlippageBps","required":false,"in":"query","description":"Maximum allowed slippage for the swap. (in basis points)","schema":{"minimum":0,"maximum":10000,"default":50,"type":"number"}},{"name":"maxPriceImpactBps","required":false,"in":"query","description":"Max price impact for the swap. (in basis points)","schema":{"minimum":0,"maximum":10000,"default":10000,"type":"number"}},{"name":"priceImpactExceedsError","required":false,"in":"query","description":"If true an error is returned if the price impact is exceeded. Otherwise an issue (warning) is added to the response. Defaults to false.","schema":{"default":false,"type":"boolean"}},{"name":"minExpirySec","required":false,"in":"query","description":"Min quote expiry. (in seconds)\nRFQ/OTC quotes from market makers have hard expiries between 40-90 seconds. If minExpiry is set higher then MM expiries these MMs are excluded. (Keep in mind that MM pricing might be better than DEX pricing, especially if quantity is high)","schema":{"minimum":10,"maximum":120,"default":35,"type":"number"}},{"name":"skipSimulation","required":false,"in":"query","description":"Skip Tenderly simulation","schema":{"default":false,"type":"boolean"}},{"name":"skipChecks","required":false,"in":"query","description":"Skip balance and allowance checks","schema":{"default":false,"type":"boolean"}},{"name":"encodingType","required":false,"in":"query","description":"Encoding type for the returned raw transaction.","schema":{"default":"basic","enum":["basic","enzyme-vault"],"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SwapQuoteDto"}}}}},"tags":["swap"]}}},"components":{"schemas":{"IncludeLiquiditySourcesDto":{"type":"object","properties":{"include":{"type":"object","description":"Sources to include. Default for all others is disabled. (Whitelisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["include"]},"SubLiquiditySourceSelectionDto":{"type":"object","properties":{"subSources":{"type":"object","description":"Map of sub-source identifiers to an empty object marker, signifying selection.","additionalProperties":{"type":"object","description":"An empty object {} marker."}}}},"ExcludeLiquiditySourcesDto":{"type":"object","properties":{"exclude":{"type":"object","description":"Sources to exclude. Default for all others is enabled. (Blacklisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["exclude"]},"SwapQuoteDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated swap price."},"sellToken":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"buyToken":{"description":"Buy token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"sellAmount":{"format":"int64","type":"integer","description":"Amount to sell. (In sell token units)"},"buyAmount":{"format":"int64","type":"integer","description":"Estimated buy amount. (In buy token units)"},"price":{"type":"number","description":"Price of the <code>buy</code> token in <code>sell</code> token. E.g. 1 BTC = 100.000 USD; you sell WBTC and buy USDC; the price is 0.000001"},"priceImpactBps":{"type":"number","description":"Estimated price impact in basis points. [-10_000;10_000]. > 0 = value loss. < 0 = value gain","minimum":-10000,"maximum":10000},"minBuyAmount":{"format":"int64","type":"integer","description":"Minimal buy amount. (In buy token units)"},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>buy</code> token in <code>sell</code> token."},"maxPriceImpactBps":{"type":"number","description":"Maximum price impact in basis points. [-10_000;10_000]. > 0 = value loss. < 0 = value gain","minimum":-10000,"maximum":10000},"expiresAt":{"format":"date-time","type":"string","description":"If the swap contains RFQ/OTC fills this is a hard deadline. If not this can be considered as soft deadline. (Can be null if all fills are DEX based.)\nA new swap should be calculated every 20 - 30 seconds since market prices might change quickly."},"transaction":{"description":"Raw transaction.","allOf":[{"$ref":"#/components/schemas/RawTransactionDto"}]},"issues":{"description":"Balance and allowance check results.","allOf":[{"$ref":"#/components/schemas/SwapIssuesDto"}]},"tenderlySimulation":{"description":"Tenderly simulation results.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","sellToken","buyToken","sellAmount","buyAmount","price","priceImpactBps","minBuyAmount","guaranteedPrice","maxPriceImpactBps","expiresAt","transaction"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"RawTransactionDto":{"type":"object","properties":{"to":{"type":"string","description":"Address of the contract to send the tx to. In most cases this is the 31Third BatchTrade contract.\nIf encodingType is set to \"enzyme-vault\" on the request, this will bethe accessor of the Enzyme vault."},"data":{"type":"string","description":"The encoded tx data.\nSet encodingType to \"enzyme-vault\" if you want the calldata to be encodedfor an Enzyme vault."},"value":{"format":"int64","type":"integer","description":"The amount of native currency (e.g., Wei for Ethereum) to be transferred with the transaction, represented as a string to handle large numbers precisely."},"gasLimit":{"type":"string","description":"Estimated gasLimit. (Just returned if simulation is enabled and possible. Simulation might not be possible if there are outstanding approvals)"},"gasPrice":{"type":"string","description":"Suggested gasPrice. (Just returned if available)"}},"required":["to","data","value"]},"SwapIssuesDto":{"type":"object","properties":{"balance":{"description":"Not enough balance","allOf":[{"$ref":"#/components/schemas/SwapBalanceIssueDto"}]},"allowance":{"description":"Not enough allowance","allOf":[{"$ref":"#/components/schemas/SwapAllowanceIssueDto"}]},"priceImpact":{"description":"Max price impact exceeded","allOf":[{"$ref":"#/components/schemas/SwapPriceImpactIssueDto"}]}}},"SwapBalanceIssueDto":{"type":"object","properties":{"token":{"description":"Token the balance check was done for (sellToken)","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"actual":{"format":"int64","type":"integer","description":"Actual balance of the taker"},"required":{"format":"int64","type":"integer","description":"Required balance of the taker"}},"required":["token","actual","required"]},"SwapAllowanceIssueDto":{"type":"object","properties":{"token":{"description":"Token the allowance check was done for (sellToken)","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"spender":{"type":"string","description":"Token the balance check was done for (sellToken)"},"actual":{"format":"int64","type":"integer","description":"Actual allowance the taker has approved to the spender"},"required":{"format":"int64","type":"integer","description":"Required allowance the taker has to approve to the spender"}},"required":["token","spender","actual","required"]},"SwapPriceImpactIssueDto":{"type":"object","properties":{"sellToken":{"description":"Sell token","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"buyToken":{"description":"Buy token","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"actual":{"type":"number","description":"Actual price impact in BPS (including slippage)"},"max":{"type":"number","description":"Max requested price impact in BPS"}},"required":["sellToken","buyToken","actual","max"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```


# Basket Trade (m:n swap)

Basket trades or m:n swaps allow you to rebalance a portfolio of assets in one go. This means you can specify a base allocation (m) consisting of one or many assets and a target allocation (n) with one or many assets. M and n can be the same assets in a different percentual allocation but also completely different assets.

For specific use-case specific descriptions see:

* [Wallet](/31third-api/basket-trade-m-n-swap/wallet)
* [Enzyme](/31third-api/basket-trade-m-n-swap/enzyme)
* [SetProtocol](/31third-api/basket-trade-m-n-swap/setprotocol)

### Usage example with ethers.js

The API returns a DTO containing the following properties:

```typescript
export interface RebalancingResponseDto extends BaseEntityModel {
  ...
  txHandler: Address;    // address of deployed BatchTrade
  txData: string;        // calldata containing encoded Trades and BatchTradeConfig
  txValue: BigNumberDto; // value native currency sent for trading
  ...
}
```

which can be passed into [ethers signer.sendTransaction](https://docs.ethers.org/v5/api/signer/#Signer-sendTransaction) as follows:

```typescript
signer.sendTransaction({
  to: rebalancing.txHandler,
  data: rebalancing.txData,
  value: rebalancing.txValue,
});
```


# async

The calculation of rebalancings might take some seconds depending on how many assets are involved. Therefore all rebalancing endpoints have the option to calculate them async. If `async` is set to `true` you receive an `id` for your rebalancing and you can then periodically fetch the progress of the rebalancing. If its done, `percent` will have the value `100` and you will also receive the rebalancing.

## /rebalancing/calculation-progress/{id}

Fetch the current progress or receive the final rebalancing if it's done.

## Get calculation progress

> Returns progress state of running rebalancing

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing (common)","description":"Execute common rebalancing actions"}],"paths":{"/1.3/rebalancing/calculation-progress/{id}":{"get":{"operationId":"RebalancingCommonController_getCalculationProgress","summary":"Get calculation progress","description":"Returns progress state of running rebalancing","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"id","required":true,"in":"path","schema":{"type":"string"}},{"name":"accept-language","required":true,"in":"header","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CalculationProgressDto"}}}}},"tags":["rebalancing (common)"]}}},"components":{"schemas":{"CalculationProgressDto":{"type":"object","properties":{"percent":{"type":"number","description":"Progress in percent"},"message":{"type":"string","description":"Progress status message or error message"},"failed":{"type":"boolean","description":"Indicates if rebalancing failed"},"rebalancing":{"description":"If finished. Rebalancing result is found here","allOf":[{"$ref":"#/components/schemas/RebalancingResponseDto"}]}},"required":["percent","message","failed","rebalancing"]},"RebalancingResponseDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated rebalancing."},"creationDate":{"format":"date-time","type":"string","description":"Rebalancing creation timestamp"},"baseValueInUsd":{"type":"number","description":"Total value of assets in the rebalancing base allocation. (in USD)"},"sellValueInUsd":{"type":"number","description":"The proportion of value that is taken out for trades, meaning sold. (in USD)"},"estimatedValueLossInUsd":{"type":"number","description":"Estimated loss of total portfolio value. (in USD; fees are already included in this value)"},"estimatedTargetValueInUsd":{"type":"number","description":"Estimated total value of the rebalancing target allocation. (in USD; fees are already included in this value)"},"estimatedReceiveValueInUsd":{"type":"number","description":"Estimated value of assets received after all trades. (in USD; fees are already included in this value)"},"minReceiveValueInUsd":{"type":"number","description":"Minimal total portfolio value after the rebalancing. (in USD; slippage and fees are included in this value)"},"estimatedImpact":{"type":"number","description":"Estimated impact. (0.01 = 1%; fees are already included in this value)"},"maxImpact":{"type":"number","description":"Maximal impact. (0.01 = 1%; slippage and fees are included in this value)"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for the rebalancing. (in WEI)"},"estimatedGasFeesInUsd":{"type":"number","description":"Estimated gas fees for the rebalancing. (in USD)"},"estimatedProtocolFeesInUsd":{"type":"number","description":"Estimated protocol fees for the rebalancing. (in USD)"},"requiredAllowances":{"description":"List of tokens for which the allowance has to be increased before executing the rebalancing. (List based on the wallet passed in the rebalancing request.)","type":"array","items":{"$ref":"#/components/schemas/AllowanceDto"}},"trades":{"description":"List of trades which will be executed to fulfill the rebalancing.","type":"array","items":{"$ref":"#/components/schemas/TradeDto"}},"txHandler":{"type":"string","description":"[Just if a batch trade is requested, otherwise use txHandler per trade] Address of the contract to send the txData to. It will be our <b>batch trade</b> contract if it is a rebalancing transaction. However, in some special cases, it may also be a different contract, for example, in the case of wrapping ETH into WETH."},"txData":{"type":"object","description":"[Just if a batch trade is requested, otherwise use txData per trade] Call data to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"txValue":{"format":"int64","type":"integer","description":"Call value to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"tokensWithoutPricePair":{"type":"string","description":"List of tokens for which no price pair could be found."},"executable":{"type":"boolean","description":"Is executable based on wallet permissions for smart contracts"},"expirationTimestamp":{"format":"date-time","type":"string","description":"If the rebalancing contains RFQ/OTC trades this is a hard deadline.If not this can be considered as soft deadline. A new rebalancing should be calculated since after some time market prices might have changed in a way that another composition of trades might be better."},"earliestRefreshQuotesTimestamp":{"format":"date-time","type":"string","description":"Earliest timestamp when quotes for this rebalancing can be refreshed"},"suggestedRefreshQuotesTimestamp":{"format":"date-time","type":"string"},"tenderlySimulation":{"description":"Tenderly simulation result.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","creationDate","baseValueInUsd","sellValueInUsd","estimatedValueLossInUsd","estimatedTargetValueInUsd","estimatedReceiveValueInUsd","minReceiveValueInUsd","estimatedImpact","maxImpact","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedGasFeesInUsd","estimatedProtocolFeesInUsd","requiredAllowances","trades","txHandler","txData","txValue","tokensWithoutPricePair","executable","expirationTimestamp","earliestRefreshQuotesTimestamp","suggestedRefreshQuotesTimestamp","tenderlySimulation"]},"AllowanceDto":{"type":"object","properties":{"token":{"description":"Token address that needs allowance","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"allowanceTarget":{"type":"string","description":"Exchange proxy to set the allowance on"},"neededAllowance":{"format":"int64","type":"integer","description":"Allowance needed to execute rebalancing"},"currentAllowance":{"format":"int64","type":"integer","description":"Current allowance set on target"},"resetNeeded":{"type":"boolean","description":"Reset allowance to 0 before setting new one"}},"required":["token","allowanceTarget","neededAllowance","currentAllowance","resetNeeded"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"TradeDto":{"type":"object","properties":{"from":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"to":{"description":"Receive token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"fromAmount":{"format":"int64","type":"integer","description":"Amount of the <code>from</code> token to sell. (In from token units)"},"toAmount":{"format":"int64","type":"integer","description":"Amount of the <code>to</code> token to receive. (In to token units; liquidity source fees are already included in this value)"},"minToReceiveBeforeFees":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In to token units; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceive":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive. (In to token units; slippage, liquidity source fees and protocol fees are included in this value)"},"fromValueInUsd":{"type":"number","description":"Value of the <code>from</code> token to sell. (in USD)"},"toValueInUsd":{"type":"number","description":"Value of the <code>to</code> token to receive. (in USD; liquidity source fees are already included in this value)"},"minToReceiveBeforeFeesInUsd":{"type":"number","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In USD; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceiveInUsd":{"type":"number","description":"Minimal value of the <code>to</code> token to receive. (in USD; slippage, liquidity source fees and protocol fees are included in this value)"},"estimatedPriceImpact":{"type":"number","description":"Estimated price impact in percent. [-1;1]. > 0 = value loss. < 0 = value gain","minimum":-1,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage used for the calculation of this trade. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"price":{"type":"number","description":"Price of the <code>to</code> token in <code>from</code> token. Does not included slippage."},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>to</code> token in <code>from</code> token including slippage."},"previouslyRequiredTrades":{"description":"List of IDs of the trades that have to be executed before this trade.","type":"array","items":{"type":"string"}},"allowanceTarget":{"type":"string","description":"Allowance target to set the allowance to if <code>allowanceNeeded</code> is <code>true</code>"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"estimatedFees":{"format":"int64","type":"integer","deprecated":true,"description":"[USE estimatedGasFees INSTEAD] Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"expirationTimestamp":{"format":"date-time","type":"string","description":"Shows an approximate expiration estimation for this trade. When a trade is expired, <code>/rebalancing/refresh-expired-quotes</code> can be used to refresh the quote for this trade. Alternatively, a new rebalancing can be calculated."},"transactions":{"type":"array","items":{"type":"string"}},"fill":{"$ref":"#/components/schemas/FillDto"}},"required":["from","to","fromAmount","toAmount","minToReceiveBeforeFees","minToReceive","fromValueInUsd","toValueInUsd","minToReceiveBeforeFeesInUsd","minToReceiveInUsd","estimatedPriceImpact","maxSlippage","price","guaranteedPrice","previouslyRequiredTrades","allowanceTarget","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedFees","expirationTimestamp","transactions","fill"]},"FillDto":{"type":"object","properties":{"liquiditySource":{"$ref":"#/components/schemas/SimpleLiquiditySourceDto"},"proportionInBps":{"type":"number"},"from":{"$ref":"#/components/schemas/SimpleTokenDto"},"to":{"$ref":"#/components/schemas/SimpleTokenDto"},"subFills":{"type":"array","items":{"type":"string"}}},"required":["liquiditySource","proportionInBps","from","to","subFills"]},"SimpleLiquiditySourceDto":{"type":"object","properties":{"identifier":{"type":"string"},"readableName":{"type":"string"},"iconUrl":{"type":"string"},"enabled":{"type":"boolean"}},"required":["identifier","readableName","iconUrl","enabled"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```

## /rebalancing/cancel/{id}

Cancel the calculation of a requested rebalancing.

## Cancel rebalancing

> Cancel async rebalancing with id

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing (common)","description":"Execute common rebalancing actions"}],"paths":{"/1.3/rebalancing/cancel/{id}":{"get":{"operationId":"RebalancingCommonController_cancelRebalancing","summary":"Cancel rebalancing","description":"Cancel async rebalancing with id","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"walletAddress","required":true,"in":"query","schema":{"type":"string"}},{"name":"id","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":""}},"tags":["rebalancing (common)"]}}}}
```


# Wallet

Calculate a rebalancing for a wallet. The minimal params are:

* signer: Address
* wallet: Address
* baseEntries
* targetEntries

## Request a rebalancing for an arbitrary set of tokens

> Sell tokens are passed with amounts, buy tokens are passed as percentage allocation

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing/wallet","description":"Calculate rebalancings for wallets"}],"paths":{"/1.3/rebalancing/wallet":{"post":{"operationId":"RebalancingWalletController_calculateOptimalRebalancing","summary":"Request a rebalancing for an arbitrary set of tokens","description":"Sell tokens are passed with amounts, buy tokens are passed as percentage allocation","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingWalletQueryDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingResponseDto"}}}}},"tags":["rebalancing/wallet"]}}},"components":{"schemas":{"RebalancingWalletQueryDto":{"type":"object","properties":{"signer":{"type":"string","description":"The wallet that is used to sign the rebalancing and send it on-chain."},"baseEntries":{"description":"List of base entries (token and amount)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAmountEntryDto"}},"targetEntries":{"description":"List of target entries (token and allocation)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAllocationEntryDto"}},"maxDeviationFromTarget":{"type":"number","description":"Maximum deviation from the target allocation. (0.01 = 1%)","minimum":0.001,"default":0.005,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage for the calculated trades. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"maxPriceImpact":{"type":"number","description":"Max price impact for the calculated basket trade. (0.01 = 1%)","minimum":0,"default":0.01,"maximum":1},"priceImpactExceedsError":{"type":"boolean","description":"If true an error is returned if the price impact is exceeded. Otherwise an issue (warning) is added to the response. Defaults to false.","default":false},"minExpirySec":{"type":"number","description":"Min quote expiry. (in seconds)\nRFQ/OTC quotes from market makers have hard expiries between 40-90 seconds. If minExpiry is set higher then MM expiries these MMs are excluded. (Keep in mind that MM pricing might be better than DEX pricing, especially if quantity is high)","minimum":10,"default":35,"maximum":120},"minTradeValue":{"type":"number","description":"Min trade value. (in USD)\nThe smart order router ignores potential trades with a value smaller than minTradeValue. Super small value trades often lead to execution issues, therefore we skip trades smaller than $1 by default.","minimum":0,"default":1},"liquiditySourceSettings":{"description":"(COMING SOON) Settings for liquidity sources (DEXs, market makers, DeFi protocols)","deprecated":true,"allOf":[{"$ref":"#/components/schemas/LiquiditySourceSettingsDto"}]},"liquiditySourceConfig":{"description":"Configure liquidity sources. Whitelisting or blacklisting is available on a source level but also on a type level.","allOf":[{"$ref":"#/components/schemas/LiquiditySourceConfigDto"}]},"batchTrade":{"type":"boolean","description":"Describes if batch trading should be enabled (if not trades can be executed one-by-one)","default":true},"revertOnError":{"type":"boolean","description":"Describes if the batch execution should revert if one trade fails. Otherwise the already positive executed trades are settled.","default":true},"skipBalanceValidation":{"type":"boolean","description":"Describes if balance check should be skipped. (Can be useful for testing).","default":false},"failOnMissingPricePair":{"type":"boolean","description":"If true, an exception is thrown, indicating that no price pair can be found for at least one of the tokens. (Only assets with a balance greater than 0 are considered.) If false, the rebalancing is still calculated without considering the tokens with no pairs.","default":true},"async":{"type":"boolean","description":"If true the rebalancing will be calculated asynchronously. The progress can be checked with the responded id","default":false},"simulationTxOrigin":{"type":"string","description":"[FOR TENDERLY SIMULATION] Address that should be used instead of <code>signer</code>. Can be useful for Tenderly simulation if simulating an Enzyme vault you're not the owner of."},"wallet":{"type":"string","description":"Wallet for which the rebalancing is calculated."}},"required":["signer","baseEntries","targetEntries","simulationTxOrigin","wallet"]},"RebalancingAmountEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in base allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\".)"},"amount":{"type":"string","description":"Amounts of the base token to sell (in WEI)"}},"required":["tokenAddress","amount"]},"RebalancingAllocationEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in target allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")."},"allocation":{"type":"number","description":"Allocation of the token in percent summing up to 1.00. (0.01 = 1%)"}},"required":["tokenAddress","allocation"]},"LiquiditySourceSettingsDto":{"type":"object","properties":{"decentralizedExchangeSettings":{"description":"Settings for DEXs","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DecentralizedExchangeSettingsDto"}]},"marketMakerSettings":{"description":"Settings for market makers","deprecated":true,"allOf":[{"$ref":"#/components/schemas/MarketMakerSettingsDto"}]},"deFiProtocolSettings":{"description":"Settings for DeFi protocols","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DeFiProtocolSettings"}]}}},"DecentralizedExchangeSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if decentralized exchange liquidity (e.g.: Uniswap, SushiSwap) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"MarketMakerSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if market maker liquidity (e.g.: 0x RFQ, Hashflow) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"DeFiProtocolSettings":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if DeFi protocols (e.g.: Aave, Compound) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"LiquiditySourceConfigDto":{"type":"object","properties":{"types":{"description":"(WIP) Liquidity sources types","type":"array","items":{"type":"string"}},"sources":{"description":"Configuration allows three strategies: empty, include or exclude.\n - Empty: all sources are enabled. \n - Include (Whitelisting): only the given sources are enabled. \n - Exclude (Blacklisting): all sources except the given ones are enabled.","oneOf":[{"$ref":"#/components/schemas/IncludeLiquiditySourcesDto"},{"$ref":"#/components/schemas/ExcludeLiquiditySourcesDto"}]}}},"IncludeLiquiditySourcesDto":{"type":"object","properties":{"include":{"type":"object","description":"Sources to include. Default for all others is disabled. (Whitelisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["include"]},"SubLiquiditySourceSelectionDto":{"type":"object","properties":{"subSources":{"type":"object","description":"Map of sub-source identifiers to an empty object marker, signifying selection.","additionalProperties":{"type":"object","description":"An empty object {} marker."}}}},"ExcludeLiquiditySourcesDto":{"type":"object","properties":{"exclude":{"type":"object","description":"Sources to exclude. Default for all others is enabled. (Blacklisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["exclude"]},"RebalancingResponseDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated rebalancing."},"creationDate":{"format":"date-time","type":"string","description":"Rebalancing creation timestamp"},"baseValueInUsd":{"type":"number","description":"Total value of assets in the rebalancing base allocation. (in USD)"},"sellValueInUsd":{"type":"number","description":"The proportion of value that is taken out for trades, meaning sold. (in USD)"},"estimatedValueLossInUsd":{"type":"number","description":"Estimated loss of total portfolio value. (in USD; fees are already included in this value)"},"estimatedTargetValueInUsd":{"type":"number","description":"Estimated total value of the rebalancing target allocation. (in USD; fees are already included in this value)"},"estimatedReceiveValueInUsd":{"type":"number","description":"Estimated value of assets received after all trades. (in USD; fees are already included in this value)"},"minReceiveValueInUsd":{"type":"number","description":"Minimal total portfolio value after the rebalancing. (in USD; slippage and fees are included in this value)"},"estimatedImpact":{"type":"number","description":"Estimated impact. (0.01 = 1%; fees are already included in this value)"},"maxImpact":{"type":"number","description":"Maximal impact. (0.01 = 1%; slippage and fees are included in this value)"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for the rebalancing. (in WEI)"},"estimatedGasFeesInUsd":{"type":"number","description":"Estimated gas fees for the rebalancing. (in USD)"},"estimatedProtocolFeesInUsd":{"type":"number","description":"Estimated protocol fees for the rebalancing. (in USD)"},"requiredAllowances":{"description":"List of tokens for which the allowance has to be increased before executing the rebalancing. (List based on the wallet passed in the rebalancing request.)","type":"array","items":{"$ref":"#/components/schemas/AllowanceDto"}},"trades":{"description":"List of trades which will be executed to fulfill the rebalancing.","type":"array","items":{"$ref":"#/components/schemas/TradeDto"}},"txHandler":{"type":"string","description":"[Just if a batch trade is requested, otherwise use txHandler per trade] Address of the contract to send the txData to. It will be our <b>batch trade</b> contract if it is a rebalancing transaction. However, in some special cases, it may also be a different contract, for example, in the case of wrapping ETH into WETH."},"txData":{"type":"object","description":"[Just if a batch trade is requested, otherwise use txData per trade] Call data to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"txValue":{"format":"int64","type":"integer","description":"Call value to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"tokensWithoutPricePair":{"type":"string","description":"List of tokens for which no price pair could be found."},"executable":{"type":"boolean","description":"Is executable based on wallet permissions for smart contracts"},"expirationTimestamp":{"format":"date-time","type":"string","description":"If the rebalancing contains RFQ/OTC trades this is a hard deadline.If not this can be considered as soft deadline. A new rebalancing should be calculated since after some time market prices might have changed in a way that another composition of trades might be better."},"earliestRefreshQuotesTimestamp":{"format":"date-time","type":"string","description":"Earliest timestamp when quotes for this rebalancing can be refreshed"},"suggestedRefreshQuotesTimestamp":{"format":"date-time","type":"string"},"tenderlySimulation":{"description":"Tenderly simulation result.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","creationDate","baseValueInUsd","sellValueInUsd","estimatedValueLossInUsd","estimatedTargetValueInUsd","estimatedReceiveValueInUsd","minReceiveValueInUsd","estimatedImpact","maxImpact","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedGasFeesInUsd","estimatedProtocolFeesInUsd","requiredAllowances","trades","txHandler","txData","txValue","tokensWithoutPricePair","executable","expirationTimestamp","earliestRefreshQuotesTimestamp","suggestedRefreshQuotesTimestamp","tenderlySimulation"]},"AllowanceDto":{"type":"object","properties":{"token":{"description":"Token address that needs allowance","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"allowanceTarget":{"type":"string","description":"Exchange proxy to set the allowance on"},"neededAllowance":{"format":"int64","type":"integer","description":"Allowance needed to execute rebalancing"},"currentAllowance":{"format":"int64","type":"integer","description":"Current allowance set on target"},"resetNeeded":{"type":"boolean","description":"Reset allowance to 0 before setting new one"}},"required":["token","allowanceTarget","neededAllowance","currentAllowance","resetNeeded"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"TradeDto":{"type":"object","properties":{"from":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"to":{"description":"Receive token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"fromAmount":{"format":"int64","type":"integer","description":"Amount of the <code>from</code> token to sell. (In from token units)"},"toAmount":{"format":"int64","type":"integer","description":"Amount of the <code>to</code> token to receive. (In to token units; liquidity source fees are already included in this value)"},"minToReceiveBeforeFees":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In to token units; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceive":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive. (In to token units; slippage, liquidity source fees and protocol fees are included in this value)"},"fromValueInUsd":{"type":"number","description":"Value of the <code>from</code> token to sell. (in USD)"},"toValueInUsd":{"type":"number","description":"Value of the <code>to</code> token to receive. (in USD; liquidity source fees are already included in this value)"},"minToReceiveBeforeFeesInUsd":{"type":"number","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In USD; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceiveInUsd":{"type":"number","description":"Minimal value of the <code>to</code> token to receive. (in USD; slippage, liquidity source fees and protocol fees are included in this value)"},"estimatedPriceImpact":{"type":"number","description":"Estimated price impact in percent. [-1;1]. > 0 = value loss. < 0 = value gain","minimum":-1,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage used for the calculation of this trade. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"price":{"type":"number","description":"Price of the <code>to</code> token in <code>from</code> token. Does not included slippage."},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>to</code> token in <code>from</code> token including slippage."},"previouslyRequiredTrades":{"description":"List of IDs of the trades that have to be executed before this trade.","type":"array","items":{"type":"string"}},"allowanceTarget":{"type":"string","description":"Allowance target to set the allowance to if <code>allowanceNeeded</code> is <code>true</code>"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"estimatedFees":{"format":"int64","type":"integer","deprecated":true,"description":"[USE estimatedGasFees INSTEAD] Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"expirationTimestamp":{"format":"date-time","type":"string","description":"Shows an approximate expiration estimation for this trade. When a trade is expired, <code>/rebalancing/refresh-expired-quotes</code> can be used to refresh the quote for this trade. Alternatively, a new rebalancing can be calculated."},"transactions":{"type":"array","items":{"type":"string"}},"fill":{"$ref":"#/components/schemas/FillDto"}},"required":["from","to","fromAmount","toAmount","minToReceiveBeforeFees","minToReceive","fromValueInUsd","toValueInUsd","minToReceiveBeforeFeesInUsd","minToReceiveInUsd","estimatedPriceImpact","maxSlippage","price","guaranteedPrice","previouslyRequiredTrades","allowanceTarget","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedFees","expirationTimestamp","transactions","fill"]},"FillDto":{"type":"object","properties":{"liquiditySource":{"$ref":"#/components/schemas/SimpleLiquiditySourceDto"},"proportionInBps":{"type":"number"},"from":{"$ref":"#/components/schemas/SimpleTokenDto"},"to":{"$ref":"#/components/schemas/SimpleTokenDto"},"subFills":{"type":"array","items":{"type":"string"}}},"required":["liquiditySource","proportionInBps","from","to","subFills"]},"SimpleLiquiditySourceDto":{"type":"object","properties":{"identifier":{"type":"string"},"readableName":{"type":"string"},"iconUrl":{"type":"string"},"enabled":{"type":"boolean"}},"required":["identifier","readableName","iconUrl","enabled"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```


# Enzyme

Calculate a rebalancing for an Enzyme vault. The minimal params are:

* signer: Address
* vault: Address
* baseEntries (If an empty array is passed all vault tokens are considered as base allocation)
* targetEntries

## POST /1.3/rebalancing/enzyme

> Request a rebalancing for an enzyme vault with a target allocation.

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing/enzyme","description":"Calculate rebalancings for Enzyme vaults"}],"paths":{"/1.3/rebalancing/enzyme":{"post":{"operationId":"RebalancingEnzymeController_calculateOptimalEnzymeRebalancing","summary":"Request a rebalancing for an enzyme vault with a target allocation.","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingEnzymeVaultQueryDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingResponseDto"}}}}},"tags":["rebalancing/enzyme"]}}},"components":{"schemas":{"RebalancingEnzymeVaultQueryDto":{"type":"object","properties":{"signer":{"type":"string","description":"The wallet that is used to sign the rebalancing and send it on-chain."},"baseEntries":{"description":"List of base entries (token and amount). (If an empty array is passed all vault tokens are considered as base allocation. Tokens with a value < $0.01 are ignored.)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAmountEntryDto"}},"targetEntries":{"description":"List of target entries (token and allocation)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAllocationEntryDto"}},"maxDeviationFromTarget":{"type":"number","description":"Maximum deviation from the target allocation. (0.01 = 1%)","minimum":0.001,"default":0.005,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage for the calculated trades. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"maxPriceImpact":{"type":"number","description":"Max price impact for the calculated basket trade. (0.01 = 1%)","minimum":0,"default":0.01,"maximum":1},"priceImpactExceedsError":{"type":"boolean","description":"If true an error is returned if the price impact is exceeded. Otherwise an issue (warning) is added to the response. Defaults to false.","default":false},"minExpirySec":{"type":"number","description":"Min quote expiry. (in seconds)\nRFQ/OTC quotes from market makers have hard expiries between 40-90 seconds. If minExpiry is set higher then MM expiries these MMs are excluded. (Keep in mind that MM pricing might be better than DEX pricing, especially if quantity is high)","minimum":10,"default":35,"maximum":120},"minTradeValue":{"type":"number","description":"Min trade value. (in USD)\nThe smart order router ignores potential trades with a value smaller than minTradeValue. Super small value trades often lead to execution issues, therefore we skip trades smaller than $1 by default.","minimum":0,"default":1},"liquiditySourceSettings":{"description":"(COMING SOON) Settings for liquidity sources (DEXs, market makers, DeFi protocols)","deprecated":true,"allOf":[{"$ref":"#/components/schemas/LiquiditySourceSettingsDto"}]},"liquiditySourceConfig":{"description":"Configure liquidity sources. Whitelisting or blacklisting is available on a source level but also on a type level.","allOf":[{"$ref":"#/components/schemas/LiquiditySourceConfigDto"}]},"batchTrade":{"type":"boolean","description":"Describes if batch trading should be enabled (if not trades can be executed one-by-one)","default":true},"revertOnError":{"type":"boolean","description":"Describes if the batch execution should revert if one trade fails. Otherwise the already positive executed trades are settled.","default":true},"skipBalanceValidation":{"type":"boolean","description":"Describes if balance check should be skipped. (Can be useful for testing).","default":false},"failOnMissingPricePair":{"type":"boolean","description":"If true, an exception is thrown, indicating that no price pair can be found for at least one of the tokens. (Only assets with a balance greater than 0 are considered.) If false, the rebalancing is still calculated without considering the tokens with no pairs.","default":false},"async":{"type":"boolean","description":"If true the rebalancing will be calculated asynchronously. The progress can be checked with the responded id","default":false},"simulationTxOrigin":{"type":"string","description":"[FOR TENDERLY SIMULATION] Address that should be used instead of <code>signer</code>. Can be useful for Tenderly simulation if simulating an Enzyme vault you're not the owner of."},"vault":{"type":"string","description":"Vault for which the rebalancing is calculated."},"testnet":{"type":"boolean","description":"Activate testnet. (Just for Polygon)","default":false}},"required":["signer","baseEntries","targetEntries","simulationTxOrigin","vault"]},"RebalancingAmountEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in base allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\".)"},"amount":{"type":"string","description":"Amounts of the base token to sell (in WEI)"}},"required":["tokenAddress","amount"]},"RebalancingAllocationEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in target allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")."},"allocation":{"type":"number","description":"Allocation of the token in percent summing up to 1.00. (0.01 = 1%)"}},"required":["tokenAddress","allocation"]},"LiquiditySourceSettingsDto":{"type":"object","properties":{"decentralizedExchangeSettings":{"description":"Settings for DEXs","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DecentralizedExchangeSettingsDto"}]},"marketMakerSettings":{"description":"Settings for market makers","deprecated":true,"allOf":[{"$ref":"#/components/schemas/MarketMakerSettingsDto"}]},"deFiProtocolSettings":{"description":"Settings for DeFi protocols","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DeFiProtocolSettings"}]}}},"DecentralizedExchangeSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if decentralized exchange liquidity (e.g.: Uniswap, SushiSwap) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"MarketMakerSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if market maker liquidity (e.g.: 0x RFQ, Hashflow) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"DeFiProtocolSettings":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if DeFi protocols (e.g.: Aave, Compound) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"LiquiditySourceConfigDto":{"type":"object","properties":{"types":{"description":"(WIP) Liquidity sources types","type":"array","items":{"type":"string"}},"sources":{"description":"Configuration allows three strategies: empty, include or exclude.\n - Empty: all sources are enabled. \n - Include (Whitelisting): only the given sources are enabled. \n - Exclude (Blacklisting): all sources except the given ones are enabled.","oneOf":[{"$ref":"#/components/schemas/IncludeLiquiditySourcesDto"},{"$ref":"#/components/schemas/ExcludeLiquiditySourcesDto"}]}}},"IncludeLiquiditySourcesDto":{"type":"object","properties":{"include":{"type":"object","description":"Sources to include. Default for all others is disabled. (Whitelisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["include"]},"SubLiquiditySourceSelectionDto":{"type":"object","properties":{"subSources":{"type":"object","description":"Map of sub-source identifiers to an empty object marker, signifying selection.","additionalProperties":{"type":"object","description":"An empty object {} marker."}}}},"ExcludeLiquiditySourcesDto":{"type":"object","properties":{"exclude":{"type":"object","description":"Sources to exclude. Default for all others is enabled. (Blacklisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["exclude"]},"RebalancingResponseDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated rebalancing."},"creationDate":{"format":"date-time","type":"string","description":"Rebalancing creation timestamp"},"baseValueInUsd":{"type":"number","description":"Total value of assets in the rebalancing base allocation. (in USD)"},"sellValueInUsd":{"type":"number","description":"The proportion of value that is taken out for trades, meaning sold. (in USD)"},"estimatedValueLossInUsd":{"type":"number","description":"Estimated loss of total portfolio value. (in USD; fees are already included in this value)"},"estimatedTargetValueInUsd":{"type":"number","description":"Estimated total value of the rebalancing target allocation. (in USD; fees are already included in this value)"},"estimatedReceiveValueInUsd":{"type":"number","description":"Estimated value of assets received after all trades. (in USD; fees are already included in this value)"},"minReceiveValueInUsd":{"type":"number","description":"Minimal total portfolio value after the rebalancing. (in USD; slippage and fees are included in this value)"},"estimatedImpact":{"type":"number","description":"Estimated impact. (0.01 = 1%; fees are already included in this value)"},"maxImpact":{"type":"number","description":"Maximal impact. (0.01 = 1%; slippage and fees are included in this value)"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for the rebalancing. (in WEI)"},"estimatedGasFeesInUsd":{"type":"number","description":"Estimated gas fees for the rebalancing. (in USD)"},"estimatedProtocolFeesInUsd":{"type":"number","description":"Estimated protocol fees for the rebalancing. (in USD)"},"requiredAllowances":{"description":"List of tokens for which the allowance has to be increased before executing the rebalancing. (List based on the wallet passed in the rebalancing request.)","type":"array","items":{"$ref":"#/components/schemas/AllowanceDto"}},"trades":{"description":"List of trades which will be executed to fulfill the rebalancing.","type":"array","items":{"$ref":"#/components/schemas/TradeDto"}},"txHandler":{"type":"string","description":"[Just if a batch trade is requested, otherwise use txHandler per trade] Address of the contract to send the txData to. It will be our <b>batch trade</b> contract if it is a rebalancing transaction. However, in some special cases, it may also be a different contract, for example, in the case of wrapping ETH into WETH."},"txData":{"type":"object","description":"[Just if a batch trade is requested, otherwise use txData per trade] Call data to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"txValue":{"format":"int64","type":"integer","description":"Call value to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"tokensWithoutPricePair":{"type":"string","description":"List of tokens for which no price pair could be found."},"executable":{"type":"boolean","description":"Is executable based on wallet permissions for smart contracts"},"expirationTimestamp":{"format":"date-time","type":"string","description":"If the rebalancing contains RFQ/OTC trades this is a hard deadline.If not this can be considered as soft deadline. A new rebalancing should be calculated since after some time market prices might have changed in a way that another composition of trades might be better."},"earliestRefreshQuotesTimestamp":{"format":"date-time","type":"string","description":"Earliest timestamp when quotes for this rebalancing can be refreshed"},"suggestedRefreshQuotesTimestamp":{"format":"date-time","type":"string"},"tenderlySimulation":{"description":"Tenderly simulation result.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","creationDate","baseValueInUsd","sellValueInUsd","estimatedValueLossInUsd","estimatedTargetValueInUsd","estimatedReceiveValueInUsd","minReceiveValueInUsd","estimatedImpact","maxImpact","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedGasFeesInUsd","estimatedProtocolFeesInUsd","requiredAllowances","trades","txHandler","txData","txValue","tokensWithoutPricePair","executable","expirationTimestamp","earliestRefreshQuotesTimestamp","suggestedRefreshQuotesTimestamp","tenderlySimulation"]},"AllowanceDto":{"type":"object","properties":{"token":{"description":"Token address that needs allowance","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"allowanceTarget":{"type":"string","description":"Exchange proxy to set the allowance on"},"neededAllowance":{"format":"int64","type":"integer","description":"Allowance needed to execute rebalancing"},"currentAllowance":{"format":"int64","type":"integer","description":"Current allowance set on target"},"resetNeeded":{"type":"boolean","description":"Reset allowance to 0 before setting new one"}},"required":["token","allowanceTarget","neededAllowance","currentAllowance","resetNeeded"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"TradeDto":{"type":"object","properties":{"from":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"to":{"description":"Receive token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"fromAmount":{"format":"int64","type":"integer","description":"Amount of the <code>from</code> token to sell. (In from token units)"},"toAmount":{"format":"int64","type":"integer","description":"Amount of the <code>to</code> token to receive. (In to token units; liquidity source fees are already included in this value)"},"minToReceiveBeforeFees":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In to token units; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceive":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive. (In to token units; slippage, liquidity source fees and protocol fees are included in this value)"},"fromValueInUsd":{"type":"number","description":"Value of the <code>from</code> token to sell. (in USD)"},"toValueInUsd":{"type":"number","description":"Value of the <code>to</code> token to receive. (in USD; liquidity source fees are already included in this value)"},"minToReceiveBeforeFeesInUsd":{"type":"number","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In USD; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceiveInUsd":{"type":"number","description":"Minimal value of the <code>to</code> token to receive. (in USD; slippage, liquidity source fees and protocol fees are included in this value)"},"estimatedPriceImpact":{"type":"number","description":"Estimated price impact in percent. [-1;1]. > 0 = value loss. < 0 = value gain","minimum":-1,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage used for the calculation of this trade. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"price":{"type":"number","description":"Price of the <code>to</code> token in <code>from</code> token. Does not included slippage."},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>to</code> token in <code>from</code> token including slippage."},"previouslyRequiredTrades":{"description":"List of IDs of the trades that have to be executed before this trade.","type":"array","items":{"type":"string"}},"allowanceTarget":{"type":"string","description":"Allowance target to set the allowance to if <code>allowanceNeeded</code> is <code>true</code>"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"estimatedFees":{"format":"int64","type":"integer","deprecated":true,"description":"[USE estimatedGasFees INSTEAD] Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"expirationTimestamp":{"format":"date-time","type":"string","description":"Shows an approximate expiration estimation for this trade. When a trade is expired, <code>/rebalancing/refresh-expired-quotes</code> can be used to refresh the quote for this trade. Alternatively, a new rebalancing can be calculated."},"transactions":{"type":"array","items":{"type":"string"}},"fill":{"$ref":"#/components/schemas/FillDto"}},"required":["from","to","fromAmount","toAmount","minToReceiveBeforeFees","minToReceive","fromValueInUsd","toValueInUsd","minToReceiveBeforeFeesInUsd","minToReceiveInUsd","estimatedPriceImpact","maxSlippage","price","guaranteedPrice","previouslyRequiredTrades","allowanceTarget","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedFees","expirationTimestamp","transactions","fill"]},"FillDto":{"type":"object","properties":{"liquiditySource":{"$ref":"#/components/schemas/SimpleLiquiditySourceDto"},"proportionInBps":{"type":"number"},"from":{"$ref":"#/components/schemas/SimpleTokenDto"},"to":{"$ref":"#/components/schemas/SimpleTokenDto"},"subFills":{"type":"array","items":{"type":"string"}}},"required":["liquiditySource","proportionInBps","from","to","subFills"]},"SimpleLiquiditySourceDto":{"type":"object","properties":{"identifier":{"type":"string"},"readableName":{"type":"string"},"iconUrl":{"type":"string"},"enabled":{"type":"boolean"}},"required":["identifier","readableName","iconUrl","enabled"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```


# SetProtocol

Calculate a rebalancing for an Enzyme vault. The minimal params are:

* signer: Address
* setToken: Address
* baseEntries (If an empty array is passed all vault tokens are considered as base allocation)
* targetEntries

## POST /1.3/rebalancing/set-protocol

> Request a rebalancing for a set token with a target allocation.

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing/set-protocol","description":"Calculate rebalancings for SetProtocol Set tokens"}],"paths":{"/1.3/rebalancing/set-protocol":{"post":{"operationId":"RebalancingSetProtocolController_calculateOptimalSetTokenRebalancing","summary":"Request a rebalancing for a set token with a target allocation.","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingSetProtocolQueryDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingSetProtocolResponseDto"}}}}},"tags":["rebalancing/set-protocol"]}}},"components":{"schemas":{"RebalancingSetProtocolQueryDto":{"type":"object","properties":{"signer":{"type":"string","description":"The wallet that is used to sign the rebalancing and send it on-chain."},"baseEntries":{"description":"List of base entries (token and amount)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAmountEntryDto"}},"targetEntries":{"description":"List of target entries (token and allocation)","type":"array","items":{"$ref":"#/components/schemas/RebalancingAllocationEntryDto"}},"maxDeviationFromTarget":{"type":"number","description":"Maximum deviation from the target allocation. (0.01 = 1%)","minimum":0.001,"default":0.005,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage for the calculated trades. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"maxPriceImpact":{"type":"number","description":"Max price impact for the calculated basket trade. (0.01 = 1%)","minimum":0,"default":0.01,"maximum":1},"priceImpactExceedsError":{"type":"boolean","description":"If true an error is returned if the price impact is exceeded. Otherwise an issue (warning) is added to the response. Defaults to false.","default":false},"minExpirySec":{"type":"number","description":"Min quote expiry. (in seconds)\nRFQ/OTC quotes from market makers have hard expiries between 40-90 seconds. If minExpiry is set higher then MM expiries these MMs are excluded. (Keep in mind that MM pricing might be better than DEX pricing, especially if quantity is high)","minimum":10,"default":35,"maximum":120},"minTradeValue":{"type":"number","description":"Min trade value. (in USD)\nThe smart order router ignores potential trades with a value smaller than minTradeValue. Super small value trades often lead to execution issues, therefore we skip trades smaller than $1 by default.","minimum":0,"default":1},"liquiditySourceSettings":{"description":"(COMING SOON) Settings for liquidity sources (DEXs, market makers, DeFi protocols)","deprecated":true,"allOf":[{"$ref":"#/components/schemas/LiquiditySourceSettingsDto"}]},"liquiditySourceConfig":{"description":"Configure liquidity sources. Whitelisting or blacklisting is available on a source level but also on a type level.","allOf":[{"$ref":"#/components/schemas/LiquiditySourceConfigDto"}]},"batchTrade":{"type":"boolean","description":"Describes if batch trading should be enabled (if not trades can be executed one-by-one)","default":true},"revertOnError":{"type":"boolean","description":"Describes if the batch execution should revert if one trade fails. Otherwise the already positive executed trades are settled.","default":true},"skipBalanceValidation":{"type":"boolean","description":"Describes if balance check should be skipped. (Can be useful for testing).","default":false},"failOnMissingPricePair":{"type":"boolean","description":"If true, an exception is thrown, indicating that no price pair can be found for at least one of the tokens. (Only assets with a balance greater than 0 are considered.) If false, the rebalancing is still calculated without considering the tokens with no pairs.","default":true},"async":{"type":"boolean","description":"If true the rebalancing will be calculated asynchronously. The progress can be checked with the responded id","default":false},"simulationTxOrigin":{"type":"string","description":"[FOR TENDERLY SIMULATION] Address that should be used instead of <code>signer</code>. Can be useful for Tenderly simulation if simulating an Enzyme vault you're not the owner of."},"setToken":{"type":"string","description":"Set token the rebalancing should be calculated for"}},"required":["signer","baseEntries","targetEntries","simulationTxOrigin","setToken"]},"RebalancingAmountEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in base allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\".)"},"amount":{"type":"string","description":"Amounts of the base token to sell (in WEI)"}},"required":["tokenAddress","amount"]},"RebalancingAllocationEntryDto":{"type":"object","properties":{"tokenAddress":{"type":"string","description":"Address of the token in target allocation. (Ethereum is passed as \"ETH\" or \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")."},"allocation":{"type":"number","description":"Allocation of the token in percent summing up to 1.00. (0.01 = 1%)"}},"required":["tokenAddress","allocation"]},"LiquiditySourceSettingsDto":{"type":"object","properties":{"decentralizedExchangeSettings":{"description":"Settings for DEXs","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DecentralizedExchangeSettingsDto"}]},"marketMakerSettings":{"description":"Settings for market makers","deprecated":true,"allOf":[{"$ref":"#/components/schemas/MarketMakerSettingsDto"}]},"deFiProtocolSettings":{"description":"Settings for DeFi protocols","deprecated":true,"allOf":[{"$ref":"#/components/schemas/DeFiProtocolSettings"}]}}},"DecentralizedExchangeSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if decentralized exchange liquidity (e.g.: Uniswap, SushiSwap) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"MarketMakerSettingsDto":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if market maker liquidity (e.g.: 0x RFQ, Hashflow) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"DeFiProtocolSettings":{"type":"object","properties":{"disable":{"type":"boolean","description":"Describes if DeFi protocols (e.g.: Aave, Compound) should be disabled","default":false},"include":{"description":"Whitelisting. Just include the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>exclude</code>)","default":[],"type":"array","items":{"type":"string"}},"exclude":{"description":"Blacklisting. Exclude the given sources. (Cannot be combined with <code>disable</code> set to <code>true</code> or <code>include</code>)","default":[],"type":"array","items":{"type":"string"}}}},"LiquiditySourceConfigDto":{"type":"object","properties":{"types":{"description":"(WIP) Liquidity sources types","type":"array","items":{"type":"string"}},"sources":{"description":"Configuration allows three strategies: empty, include or exclude.\n - Empty: all sources are enabled. \n - Include (Whitelisting): only the given sources are enabled. \n - Exclude (Blacklisting): all sources except the given ones are enabled.","oneOf":[{"$ref":"#/components/schemas/IncludeLiquiditySourcesDto"},{"$ref":"#/components/schemas/ExcludeLiquiditySourcesDto"}]}}},"IncludeLiquiditySourcesDto":{"type":"object","properties":{"include":{"type":"object","description":"Sources to include. Default for all others is disabled. (Whitelisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["include"]},"SubLiquiditySourceSelectionDto":{"type":"object","properties":{"subSources":{"type":"object","description":"Map of sub-source identifiers to an empty object marker, signifying selection.","additionalProperties":{"type":"object","description":"An empty object {} marker."}}}},"ExcludeLiquiditySourcesDto":{"type":"object","properties":{"exclude":{"type":"object","description":"Sources to exclude. Default for all others is enabled. (Blacklisting)","additionalProperties":{"$ref":"#/components/schemas/SubLiquiditySourceSelectionDto"}}},"required":["exclude"]},"RebalancingSetProtocolResponseDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated rebalancing."},"creationDate":{"format":"date-time","type":"string","description":"Rebalancing creation timestamp"},"baseValueInUsd":{"type":"number","description":"Total value of assets in the rebalancing base allocation. (in USD)"},"sellValueInUsd":{"type":"number","description":"The proportion of value that is taken out for trades, meaning sold. (in USD)"},"estimatedValueLossInUsd":{"type":"number","description":"Estimated loss of total portfolio value. (in USD; fees are already included in this value)"},"estimatedTargetValueInUsd":{"type":"number","description":"Estimated total value of the rebalancing target allocation. (in USD; fees are already included in this value)"},"estimatedReceiveValueInUsd":{"type":"number","description":"Estimated value of assets received after all trades. (in USD; fees are already included in this value)"},"minReceiveValueInUsd":{"type":"number","description":"Minimal total portfolio value after the rebalancing. (in USD; slippage and fees are included in this value)"},"estimatedImpact":{"type":"number","description":"Estimated impact. (0.01 = 1%; fees are already included in this value)"},"maxImpact":{"type":"number","description":"Maximal impact. (0.01 = 1%; slippage and fees are included in this value)"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for the rebalancing. (in WEI)"},"estimatedGasFeesInUsd":{"type":"number","description":"Estimated gas fees for the rebalancing. (in USD)"},"estimatedProtocolFeesInUsd":{"type":"number","description":"Estimated protocol fees for the rebalancing. (in USD)"},"requiredAllowances":{"description":"List of tokens for which the allowance has to be increased before executing the rebalancing. (List based on the wallet passed in the rebalancing request.)","type":"array","items":{"$ref":"#/components/schemas/AllowanceDto"}},"trades":{"description":"List of trades which will be executed to fulfill the rebalancing.","type":"array","items":{"$ref":"#/components/schemas/SetProtocolTradeDto"}},"txHandler":{"type":"string","description":"[Just if a batch trade is requested, otherwise use txHandler per trade] Address of the contract to send the txData to. It will be our <b>batch trade</b> contract if it is a rebalancing transaction. However, in some special cases, it may also be a different contract, for example, in the case of wrapping ETH into WETH."},"txData":{"type":"object","description":"[Just if a batch trade is requested, otherwise use txData per trade] Call data to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"txValue":{"format":"int64","type":"integer","description":"Call value to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"tokensWithoutPricePair":{"type":"string","description":"List of tokens for which no price pair could be found."},"executable":{"type":"boolean","description":"Is executable based on wallet permissions for smart contracts"},"expirationTimestamp":{"format":"date-time","type":"string","description":"If the rebalancing contains RFQ/OTC trades this is a hard deadline.If not this can be considered as soft deadline. A new rebalancing should be calculated since after some time market prices might have changed in a way that another composition of trades might be better."},"earliestRefreshQuotesTimestamp":{"format":"date-time","type":"string","description":"Earliest timestamp when quotes for this rebalancing can be refreshed"},"suggestedRefreshQuotesTimestamp":{"format":"date-time","type":"string"},"tenderlySimulation":{"description":"Tenderly simulation result.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","creationDate","baseValueInUsd","sellValueInUsd","estimatedValueLossInUsd","estimatedTargetValueInUsd","estimatedReceiveValueInUsd","minReceiveValueInUsd","estimatedImpact","maxImpact","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedGasFeesInUsd","estimatedProtocolFeesInUsd","requiredAllowances","trades","txHandler","txData","txValue","tokensWithoutPricePair","executable","expirationTimestamp","earliestRefreshQuotesTimestamp","suggestedRefreshQuotesTimestamp","tenderlySimulation"]},"AllowanceDto":{"type":"object","properties":{"token":{"description":"Token address that needs allowance","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"allowanceTarget":{"type":"string","description":"Exchange proxy to set the allowance on"},"neededAllowance":{"format":"int64","type":"integer","description":"Allowance needed to execute rebalancing"},"currentAllowance":{"format":"int64","type":"integer","description":"Current allowance set on target"},"resetNeeded":{"type":"boolean","description":"Reset allowance to 0 before setting new one"}},"required":["token","allowanceTarget","neededAllowance","currentAllowance","resetNeeded"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"SetProtocolTradeDto":{"type":"object","properties":{"from":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"to":{"description":"Receive token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"fromAmount":{"format":"int64","type":"integer","description":"Amount of the <code>from</code> token to sell. (In from token units)"},"toAmount":{"format":"int64","type":"integer","description":"Amount of the <code>to</code> token to receive. (In to token units; liquidity source fees are already included in this value)"},"minToReceiveBeforeFees":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In to token units; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceive":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive. (In to token units; slippage, liquidity source fees and protocol fees are included in this value)"},"fromValueInUsd":{"type":"number","description":"Value of the <code>from</code> token to sell. (in USD)"},"toValueInUsd":{"type":"number","description":"Value of the <code>to</code> token to receive. (in USD; liquidity source fees are already included in this value)"},"minToReceiveBeforeFeesInUsd":{"type":"number","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In USD; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceiveInUsd":{"type":"number","description":"Minimal value of the <code>to</code> token to receive. (in USD; slippage, liquidity source fees and protocol fees are included in this value)"},"estimatedPriceImpact":{"type":"number","description":"Estimated price impact in percent. [-1;1]. > 0 = value loss. < 0 = value gain","minimum":-1,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage used for the calculation of this trade. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"price":{"type":"number","description":"Price of the <code>to</code> token in <code>from</code> token. Does not included slippage."},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>to</code> token in <code>from</code> token including slippage."},"previouslyRequiredTrades":{"description":"List of IDs of the trades that have to be executed before this trade.","type":"array","items":{"type":"string"}},"allowanceTarget":{"type":"string","description":"Allowance target to set the allowance to if <code>allowanceNeeded</code> is <code>true</code>"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"estimatedFees":{"format":"int64","type":"integer","deprecated":true,"description":"[USE estimatedGasFees INSTEAD] Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"expirationTimestamp":{"format":"date-time","type":"string","description":"Shows an approximate expiration estimation for this trade. When a trade is expired, <code>/rebalancing/refresh-expired-quotes</code> can be used to refresh the quote for this trade. Alternatively, a new rebalancing can be calculated."},"transactions":{"type":"array","items":{"type":"string"}},"fill":{"$ref":"#/components/schemas/FillDto"},"fromAmountPositionUnits":{"format":"int64","type":"integer","description":"(Only for methode \"set-token\") Amount of the <code>from</code> token to sell. (In position units)"},"minToReceivePositionUnits":{"format":"int64","type":"integer","description":"(Only for methode \"set-token\") Amount of the <code>from</code> token to sell. (In position units)"},"setProtocolTxHandler":{"type":"string","description":"Address of the contract to send the <code>setProtocolTxData</code> to. Usually, this is the SetProtocol TradeModule."},"setProtocolTxData":{"type":"object","description":"Call data to execute this single trade. (Must be sent to the <code>setProtocolTxHandler</code> contract address.)"}},"required":["from","to","fromAmount","toAmount","minToReceiveBeforeFees","minToReceive","fromValueInUsd","toValueInUsd","minToReceiveBeforeFeesInUsd","minToReceiveInUsd","estimatedPriceImpact","maxSlippage","price","guaranteedPrice","previouslyRequiredTrades","allowanceTarget","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedFees","expirationTimestamp","transactions","fill","fromAmountPositionUnits","minToReceivePositionUnits","setProtocolTxHandler","setProtocolTxData"]},"FillDto":{"type":"object","properties":{"liquiditySource":{"$ref":"#/components/schemas/SimpleLiquiditySourceDto"},"proportionInBps":{"type":"number"},"from":{"$ref":"#/components/schemas/SimpleTokenDto"},"to":{"$ref":"#/components/schemas/SimpleTokenDto"},"subFills":{"type":"array","items":{"type":"string"}}},"required":["liquiditySource","proportionInBps","from","to","subFills"]},"SimpleLiquiditySourceDto":{"type":"object","properties":{"identifier":{"type":"string"},"readableName":{"type":"string"},"iconUrl":{"type":"string"},"enabled":{"type":"boolean"}},"required":["identifier","readableName","iconUrl","enabled"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```


# Refresh Quotes

After you calculated a rebalancing it might be that you have to refresh quotes. For example if you have a user interface and user don't directly execute received rebalancings.&#x20;

Currently we consider rebalancings to be valid for 5 minutes however quotes should be refresed more often. A good starting point would be 20 or 30 seconds. (Make sure to not fire refresh calls to our API every second or you might get blocked.)

## GET /1.3/rebalancing/refresh-expired-quotes

> Refresh the quotes of a previously calculated rebalancing

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"rebalancing (common)","description":"Execute common rebalancing actions"}],"paths":{"/1.3/rebalancing/refresh-expired-quotes":{"get":{"operationId":"RefreshExpiredQuotesController_refreshExpiredQuotes","summary":"Refresh the quotes of a previously calculated rebalancing","parameters":[{"name":"x-api-key","in":"header","description":"31Third API key (Request via dev@31third.com)","schema":{"type":"string"}},{"name":"chain-id","in":"header","description":"Chain ID as hex string. (e.g.: 0x1 for Ethereum mainnet)","schema":{"type":"string"}},{"name":"rebalancingId","required":true,"in":"query","description":"ID of a previously calculated rebalancing","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RebalancingResponseDto"}}}}},"tags":["rebalancing (common)"]}}},"components":{"schemas":{"RebalancingResponseDto":{"type":"object","properties":{"id":{"type":"string","description":"Unique ID of the calculated rebalancing."},"creationDate":{"format":"date-time","type":"string","description":"Rebalancing creation timestamp"},"baseValueInUsd":{"type":"number","description":"Total value of assets in the rebalancing base allocation. (in USD)"},"sellValueInUsd":{"type":"number","description":"The proportion of value that is taken out for trades, meaning sold. (in USD)"},"estimatedValueLossInUsd":{"type":"number","description":"Estimated loss of total portfolio value. (in USD; fees are already included in this value)"},"estimatedTargetValueInUsd":{"type":"number","description":"Estimated total value of the rebalancing target allocation. (in USD; fees are already included in this value)"},"estimatedReceiveValueInUsd":{"type":"number","description":"Estimated value of assets received after all trades. (in USD; fees are already included in this value)"},"minReceiveValueInUsd":{"type":"number","description":"Minimal total portfolio value after the rebalancing. (in USD; slippage and fees are included in this value)"},"estimatedImpact":{"type":"number","description":"Estimated impact. (0.01 = 1%; fees are already included in this value)"},"maxImpact":{"type":"number","description":"Maximal impact. (0.01 = 1%; slippage and fees are included in this value)"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for the rebalancing. (in WEI)"},"estimatedGasFeesInUsd":{"type":"number","description":"Estimated gas fees for the rebalancing. (in USD)"},"estimatedProtocolFeesInUsd":{"type":"number","description":"Estimated protocol fees for the rebalancing. (in USD)"},"requiredAllowances":{"description":"List of tokens for which the allowance has to be increased before executing the rebalancing. (List based on the wallet passed in the rebalancing request.)","type":"array","items":{"$ref":"#/components/schemas/AllowanceDto"}},"trades":{"description":"List of trades which will be executed to fulfill the rebalancing.","type":"array","items":{"$ref":"#/components/schemas/TradeDto"}},"txHandler":{"type":"string","description":"[Just if a batch trade is requested, otherwise use txHandler per trade] Address of the contract to send the txData to. It will be our <b>batch trade</b> contract if it is a rebalancing transaction. However, in some special cases, it may also be a different contract, for example, in the case of wrapping ETH into WETH."},"txData":{"type":"object","description":"[Just if a batch trade is requested, otherwise use txData per trade] Call data to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"txValue":{"format":"int64","type":"integer","description":"Call value to execute the rebalancing. (Must be sent to the <code>txHandler</code> contract address.)"},"tokensWithoutPricePair":{"type":"string","description":"List of tokens for which no price pair could be found."},"executable":{"type":"boolean","description":"Is executable based on wallet permissions for smart contracts"},"expirationTimestamp":{"format":"date-time","type":"string","description":"If the rebalancing contains RFQ/OTC trades this is a hard deadline.If not this can be considered as soft deadline. A new rebalancing should be calculated since after some time market prices might have changed in a way that another composition of trades might be better."},"earliestRefreshQuotesTimestamp":{"format":"date-time","type":"string","description":"Earliest timestamp when quotes for this rebalancing can be refreshed"},"suggestedRefreshQuotesTimestamp":{"format":"date-time","type":"string"},"tenderlySimulation":{"description":"Tenderly simulation result.","allOf":[{"$ref":"#/components/schemas/TenderlySimulationDto"}]}},"required":["id","creationDate","baseValueInUsd","sellValueInUsd","estimatedValueLossInUsd","estimatedTargetValueInUsd","estimatedReceiveValueInUsd","minReceiveValueInUsd","estimatedImpact","maxImpact","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedGasFeesInUsd","estimatedProtocolFeesInUsd","requiredAllowances","trades","txHandler","txData","txValue","tokensWithoutPricePair","executable","expirationTimestamp","earliestRefreshQuotesTimestamp","suggestedRefreshQuotesTimestamp","tenderlySimulation"]},"AllowanceDto":{"type":"object","properties":{"token":{"description":"Token address that needs allowance","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"allowanceTarget":{"type":"string","description":"Exchange proxy to set the allowance on"},"neededAllowance":{"format":"int64","type":"integer","description":"Allowance needed to execute rebalancing"},"currentAllowance":{"format":"int64","type":"integer","description":"Current allowance set on target"},"resetNeeded":{"type":"boolean","description":"Reset allowance to 0 before setting new one"}},"required":["token","allowanceTarget","neededAllowance","currentAllowance","resetNeeded"]},"SimpleTokenDto":{"type":"object","properties":{"address":{"type":"string","description":"Address of the token"},"name":{"type":"string","description":"Name of the token"},"symbol":{"type":"string","description":"Symbol of the token"},"imageUrl":{"type":"string","description":"Url of the token icon"},"decimals":{"type":"number","description":"Decimals of the token"},"sliderColor":{"type":"string","description":"Color based on the icon that can be used for elements in the frontend"},"chain":{"description":"Chain on which the token is deployed","allOf":[{"$ref":"#/components/schemas/ChainDto"}]},"tags":{"description":"Tags categorizing the token","type":"array","items":{"type":"string"}},"deflationary":{"type":"boolean","description":"Describes if this token is deflationary (e.g.: transfer fees)"}},"required":["address","name","symbol","imageUrl","decimals","sliderColor","chain","tags","deflationary"]},"ChainDto":{"type":"object","properties":{"name":{"type":"string","description":"Name of the chain"},"identifier":{"type":"string","description":"ID of the EVM base chain as hex value"},"enabled":{"type":"boolean","description":"Describes if rebalancings are enabled"},"batchTradeSupported":{"type":"boolean","description":"Describes if batch trade is supported"},"batchTradeAddress":{"type":"string","description":"Address of the deployed 31third-protocol BatchTrade contract"},"blockExplorerLink":{"type":"string","description":"Link of the most common block explorer"},"nativeTokenAddress":{"type":"string","description":"(Pseudo)-address of the chains native token"},"wrappedNativeTokenAddress":{"type":"string","description":"Address of the chains wrapped native token"},"tokenHelperAddress":{"type":"string","description":"Address of a helper contract capable of doing batch reads"},"portfolioEnabled":{"type":"boolean","description":"Describes if portfolio feature is enabled"}},"required":["name","identifier","enabled","batchTradeSupported","batchTradeAddress","blockExplorerLink","nativeTokenAddress","wrappedNativeTokenAddress","tokenHelperAddress","portfolioEnabled"]},"TradeDto":{"type":"object","properties":{"from":{"description":"Sell token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"to":{"description":"Receive token.","allOf":[{"$ref":"#/components/schemas/SimpleTokenDto"}]},"fromAmount":{"format":"int64","type":"integer","description":"Amount of the <code>from</code> token to sell. (In from token units)"},"toAmount":{"format":"int64","type":"integer","description":"Amount of the <code>to</code> token to receive. (In to token units; liquidity source fees are already included in this value)"},"minToReceiveBeforeFees":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In to token units; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceive":{"format":"int64","type":"integer","description":"Minimal amount of the <code>to</code> token to receive. (In to token units; slippage, liquidity source fees and protocol fees are included in this value)"},"fromValueInUsd":{"type":"number","description":"Value of the <code>from</code> token to sell. (in USD)"},"toValueInUsd":{"type":"number","description":"Value of the <code>to</code> token to receive. (in USD; liquidity source fees are already included in this value)"},"minToReceiveBeforeFeesInUsd":{"type":"number","description":"Minimal amount of the <code>to</code> token to receive excluding fees. (In USD; slippage and liquidity source fees are included in this value; protocol fees are excluded)"},"minToReceiveInUsd":{"type":"number","description":"Minimal value of the <code>to</code> token to receive. (in USD; slippage, liquidity source fees and protocol fees are included in this value)"},"estimatedPriceImpact":{"type":"number","description":"Estimated price impact in percent. [-1;1]. > 0 = value loss. < 0 = value gain","minimum":-1,"maximum":1},"maxSlippage":{"type":"number","description":"Maximum allowed slippage used for the calculation of this trade. (0.01 = 1%)","minimum":0,"default":0.005,"maximum":1},"price":{"type":"number","description":"Price of the <code>to</code> token in <code>from</code> token. Does not included slippage."},"guaranteedPrice":{"type":"number","description":"Guaranteed price of the <code>to</code> token in <code>from</code> token including slippage."},"previouslyRequiredTrades":{"description":"List of IDs of the trades that have to be executed before this trade.","type":"array","items":{"type":"string"}},"allowanceTarget":{"type":"string","description":"Allowance target to set the allowance to if <code>allowanceNeeded</code> is <code>true</code>"},"estimatedGasUnits":{"format":"int64","type":"integer","description":"Estimated gas units for this trade. (in WEI)"},"suggestedGasPrice":{"format":"int64","type":"integer","description":"Suggested gas price [LOW/MARKET/AGGRESSIVE] fetched from a block explorer (e.g. Etherscan). (in WEI)"},"estimatedGasFees":{"format":"int64","type":"integer","description":"Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"estimatedFees":{"format":"int64","type":"integer","deprecated":true,"description":"[USE estimatedGasFees INSTEAD] Estimated gas fees for this trade [estimatedGasUnits * suggestedGasPrice]. (in WEI)"},"expirationTimestamp":{"format":"date-time","type":"string","description":"Shows an approximate expiration estimation for this trade. When a trade is expired, <code>/rebalancing/refresh-expired-quotes</code> can be used to refresh the quote for this trade. Alternatively, a new rebalancing can be calculated."},"transactions":{"type":"array","items":{"type":"string"}},"fill":{"$ref":"#/components/schemas/FillDto"}},"required":["from","to","fromAmount","toAmount","minToReceiveBeforeFees","minToReceive","fromValueInUsd","toValueInUsd","minToReceiveBeforeFeesInUsd","minToReceiveInUsd","estimatedPriceImpact","maxSlippage","price","guaranteedPrice","previouslyRequiredTrades","allowanceTarget","estimatedGasUnits","suggestedGasPrice","estimatedGasFees","estimatedFees","expirationTimestamp","transactions","fill"]},"FillDto":{"type":"object","properties":{"liquiditySource":{"$ref":"#/components/schemas/SimpleLiquiditySourceDto"},"proportionInBps":{"type":"number"},"from":{"$ref":"#/components/schemas/SimpleTokenDto"},"to":{"$ref":"#/components/schemas/SimpleTokenDto"},"subFills":{"type":"array","items":{"type":"string"}}},"required":["liquiditySource","proportionInBps","from","to","subFills"]},"SimpleLiquiditySourceDto":{"type":"object","properties":{"identifier":{"type":"string"},"readableName":{"type":"string"},"iconUrl":{"type":"string"},"enabled":{"type":"boolean"}},"required":["identifier","readableName","iconUrl","enabled"]},"TenderlySimulationDto":{"type":"object","properties":{"status":{"type":"boolean","description":"Simulation status. True if tx simulation succeeded, false otherwise."},"errorMessage":{"type":"string","description":"Error message. Just present if <code>status</code> is <code>false</code>."},"blockNumber":{"type":"number","description":"Block number used for the simulation."},"gas":{"format":"int64","type":"integer","description":"Amount of gas provided for the simulation."},"gasUsed":{"format":"int64","type":"integer","description":"Amount of gas used for the simulation."}},"required":["status","errorMessage","blockNumber","gas","gasUsed"]}}}}
```


# Healthcheck

Check if 31Third is up and running

## GET /1.3/healthcheck

> Returns 'Hello 31Third Trading' if this service is up and running

```json
{"openapi":"3.0.0","info":{"title":"31Third Trading API","version":"1.3"},"tags":[{"name":"healthcheck","description":"Perform healthchecks on this API and underlying services"}],"paths":{"/1.3/healthcheck":{"get":{"operationId":"HealthcheckController_getHealthcheck","summary":"Returns 'Hello 31Third Trading' if this service is up and running","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"string"}}}}},"tags":["healthcheck"]}}}}
```


# What does RFQ mean?

## Introduction

RFQ stands for Request for Quote, which is a trading mechanism which allows traders to request a price quote for a specific trade from liquidity providers, rather than relying on the traditional order book system.&#x20;

## Benefits

RFQ gives traders more control over the execution of their trades, while also providing full transparency into the prices quoted by liquidity providers. RFQ can be more efficient, cost-effective, and less impactful on the market than other trading mechanisms, making it an attractive option for many traders in the DeFi space.

#### Customization

RFQ allows traders to request a price quote for a specific trade, giving them greater control over the execution of their trades. This can be particularly useful in situations where market conditions are volatile or liquidity is limited.

#### Transparency

RFQ provides traders with full transparency into the prices quoted by liquidity providers. This allows traders to compare prices and select the best option for their needs.

#### Efficiency

RFQ can be more efficient than other trading mechanisms, such as order books, as it eliminates the need for traders to wait for orders to be filled. Instead, traders can quickly obtain a price quote and execute their trade.

#### Reduced Market Impact

RFQ can help reduce market impact by enabling traders to trade without revealing their full intentions to the market. This can be especially important for large trades, where revealing the full size of the order could lead to unfavorable price movements.

#### Lower Costs

RFQ can be more cost-effective than other trading mechanisms, such as market orders or limit orders, as traders can negotiate the price directly with liquidity providers. This can result in lower transaction costs and better pricing for the trader.


# Overview

The 31Third batch trade smart contracts enable the execution of multiple transactions together as one bundle and collect a configurable fee in basis points of the receiving currency of the trade. The current implementation supports the following:

* Trades through 0xExchangeProxy ([`0xDef1C0ded9bec7F1a1670819833240f027b25EfF`](https://etherscan.io/address/0xDef1C0ded9bec7F1a1670819833240f027b25EfF))
* Wrapping/Unwrapping (W)ETH ([`0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`](https://etherscan.io/address/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))

## Architecture

For easily integrating with other liquidity sources, such as Aave, Curve, Balancer, and more in the future, the contracts utilize the adapter pattern and register the concrete implementations in a registry. The architecture can be seen in the following diagram:

<figure><img src="/files/1hF164HD7NTynmhemJsK" alt=""><figcaption><p>Contract architecture</p></figcaption></figure>


# Contracts

The heart of the 31Third protocol is the [BatchTrade](/protocol/contracts/batchtrade) contract. Addresses of all contracts are listed in the following section:

## Ethereum

<table><thead><tr><th width="285">Contract</th><th>Address</th></tr></thead><tbody><tr><td>BatchTrade</td><td><a href="https://etherscan.io/address/0xd20c024560cca40288c05bab650ac087ae9b0f6e">0xD20c024560ccA40288C05BAB650ac087ae9b0f6e</a></td></tr><tr><td>ExchangeAdapterRegistry</td><td><a href="https://etherscan.io/address/0xCb253Fa948135Ab7dd220aaD42ae38590650CD82">0xCb253Fa948135Ab7dd220aaD42ae38590650CD82</a></td></tr><tr><td><p>ThreeOneThirdAdapter </p><p>(for <a href="https://enzyme.finance/">Enzyme</a>)</p></td><td><a href="https://etherscan.io/address/0x5a1c0e89133c4cd844a8b345370565f1368a79a8">0x5a1c0E89133C4Cd844A8B345370565f1368A79A8</a></td></tr></tbody></table>

Adapters for every integration (0x, ParaSwap, Lido, Aave, Compound) are registered on the ExchangeAdapterRegistry.

## Polygon

<table><thead><tr><th width="286">Contract</th><th>Address</th></tr></thead><tbody><tr><td>BatchTrade</td><td><a href="https://polygonscan.com/address/0xd20c024560cca40288c05bab650ac087ae9b0f6e">0xD20c024560ccA40288C05BAB650ac087ae9b0f6e</a></td></tr><tr><td>ExchangeAdapterRegistry</td><td><a href="https://polygonscan.com/address/0xCb253Fa948135Ab7dd220aaD42ae38590650CD82">0xCb253Fa948135Ab7dd220aaD42ae38590650CD82</a></td></tr><tr><td><p>ThreeOneThirdAdapter </p><p>(for <a href="https://enzyme.finance/">Enzyme</a>)</p></td><td><a href="https://polygonscan.com/address/0x5a1c0E89133C4Cd844A8B345370565f1368A79A8">0x5a1c0E89133C4Cd844A8B345370565f1368A79A8</a></td></tr><tr><td>ThreeOneThirdAdapter (for Enzyme testnet)</td><td><a href="https://polygonscan.com/address/0x0c4dc97e6c0d94327f3ca1873ae5868f5d0a6f05">0x0c4dc97e6c0D94327F3ca1873aE5868F5D0A6f05</a></td></tr></tbody></table>

Adapters for every integration (0x, ParaSwap, Aave, Compound) are registered on the ExchangeAdapterRegistry.

## Arbitrum

<table><thead><tr><th width="285">Contract</th><th>Address</th></tr></thead><tbody><tr><td>BatchTrade</td><td><a href="https://arbiscan.io/address/0xD20c024560ccA40288C05BAB650ac087ae9b0f6e">0xD20c024560ccA40288C05BAB650ac087ae9b0f6e</a></td></tr><tr><td>ExchangeAdapterRegistry</td><td><a href="https://arbiscan.io/address/0xCb253Fa948135Ab7dd220aaD42ae38590650CD82">0xCb253Fa948135Ab7dd220aaD42ae38590650CD82</a></td></tr><tr><td><p>ThreeOneThirdAdapter </p><p>(for <a href="https://enzyme.finance/">Enzyme</a>)</p></td><td><a href="https://arbiscan.io/address/0x5a1c0E89133C4Cd844A8B345370565f1368A79A8">0x5a1c0E89133C4Cd844A8B345370565f1368A79A8</a></td></tr></tbody></table>

Adapters for every integration (0x, ParaSwap, Aave, Compound) are registered on the ExchangeAdapterRegistry.

## Base

<table><thead><tr><th width="285">Contract</th><th>Address</th></tr></thead><tbody><tr><td>BatchTrade</td><td><a href="https://basescan.org/address/0xD20c024560ccA40288C05BAB650ac087ae9b0f6e">0xD20c024560ccA40288C05BAB650ac087ae9b0f6e</a></td></tr><tr><td>ExchangeAdapterRegistry</td><td><a href="https://basescan.org/address/0xCb253Fa948135Ab7dd220aaD42ae38590650CD82">0xCb253Fa948135Ab7dd220aaD42ae38590650CD82</a></td></tr><tr><td><p>ThreeOneThirdAdapter </p><p>(for <a href="https://enzyme.finance/">Enzyme</a>)</p></td><td><a href="https://basescan.org/address/0x5a1c0E89133C4Cd844A8B345370565f1368A79A8">0x5a1c0E89133C4Cd844A8B345370565f1368A79A8</a></td></tr></tbody></table>

Adapters for every integration (0x, ParaSwap, Aave, Compound) are registered on the ExchangeAdapterRegistry.

## BNB Smart Chain

<table><thead><tr><th width="291">Contract</th><th>Address</th></tr></thead><tbody><tr><td>BatchTrade</td><td><a href="https://bscscan.com/address/0xd20c024560cca40288c05bab650ac087ae9b0f6e#code">0xD20c024560ccA40288C05BAB650ac087ae9b0f6e</a></td></tr><tr><td>ExchangeAdapterRegistry</td><td><a href="https://bscscan.com/address/0xcb253fa948135ab7dd220aad42ae38590650cd82#code">0xCb253Fa948135Ab7dd220aaD42ae38590650CD82</a></td></tr></tbody></table>

Adapters for every integration (0x, ParaSwap, Aave) are registered on the ExchangeAdapterRegistry.


# BatchTrade

The BatchTrade contract is the heart of 31Third's protocol and enables executing multiple token interactions (trades, wrapping, staking, ...) within one transaction. This page describes how the contract is setup and how batch trades can be executed by fetching rebalancings from the [31Third API](/31third-api/overview) and executing them via the `batchTrade()`-function on-chain.

## Configuration

With the deployment of our protocol a few configurations have been made and will be explained here for transperancy.

### ExchangeAdapterRegistry

This is a registry contract storing all supported integrations handling how to call external protocols like the [0x ExchangeProxy](https://etherscan.io/address/0xdef1c0ded9bec7f1a1670819833240f027b25eff) or contracts like [Wrapped Ether](https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2). It is set on BatchTrade deployment and is immutable.

### Fees

31Third charges fees on batch trades. On deployment a fee recipient wallet, active fees in basis points and max fees in basis points are configured. More on how the owner of the contract can adapt these values can be found under [Owner Privilege](/protocol/contracts/owner-privilege).

Details on fees can be found on the [FAQ](/resources/faq) page.

### Trade Signer

Trades returned by the 31Third API include a signature which will be verified on chain to prevent sending malicious `calldata` to external contracts. The public key of the signer pair is set on deployment but can also be adapted by the owner for security purposes.

## batchTrade(...)

This section explains how a batch trade can be executed. For the usage you have to request rebalancings from our API. If you're not familiar with the usage yet check out [31Third API](/31third-api/overview).

A batch trade receives an array of `Trade` structs and a `BatchTradeConfig` struct. All passed trades are executed based on the data passed within the `Trade` struct array. The structs will be explained below.

The following flow diagram shows the execution flow of a batch trade. For each entry in the trades array the following flow is executed:

* Get concrete adapter for trade
* Get `address` of external contract, `calldata` and `value` for execution of the trade
* Transfer sell token from the `sender` wallet to the `BatchTrade` contract (has to be approved)
  * (Check if we got expected sell amount)
* Execute trade on external contract
  * (Check if we got at least min expected receive amount)
* Deduct fees and store in `BatchTrade` contract
* Return received token to `sender` wallet.

<figure><img src="/files/BK4H79MRiKhz45Y6Gd9H" alt=""><figcaption><p>Batch trade flow</p></figcaption></figure>

<mark style="color:red;">**In case of error:**</mark> If the execution of an external trade fails the smart contract recognizes this either by getting an error or if the `minToReceive` amount is not reached. If a trade failed and `batchTradeConfig.revertOnError` is `false` already executed trades will stay executed and the transaction will stop here. If the `minToReceive` amount is not reached or `batchTradeConfig.revertOnError` is `true`, the whole execution is reverted.

### Trade struct

```solidity
struct Trade {
  string exchangeName;            // Name of the exchange the trade should be executed
  address from;                   // Address of the token to sell
  uint256 fromAmount;             // Amount of the token to sell
  address to;                     // Address of the token that will be received
  uint256 minToReceiveBeforeFees; // Minimal amount to receive
  bytes data;                     // Arbitrary call data which is sent to the exchange
  bytes signature;                // Signature to verify received trade data
}
```

### BatchTradeConfig struct

```solidity
struct BatchTradeConfig {
  bool checkFeelessWallets; // Determines if a check for feeless trading should be performed
  bool revertOnError;       // If true, batch trade reverts on error, otherwise execution just stops
}
```

### Usage example with ethers.js

The 31Third API returns a DTO containing the following properties:

```typescript
export interface RebalancingResponseDto extends BaseEntityModel {
  ...
  txHandler: Address;    // address of deployed BatchTrade
  txData: string;        // calldata containing encoded Trades and BatchTradeConfig
  txValue: BigNumberDto; // value native currency sent for trading
  ...
}
```

which can be passed into [ethers signer.sendTransaction](https://docs.ethers.org/v5/api/signer/#Signer-sendTransaction) as follows:

```typescript
signer.sendTransaction({
  to: rebalancing.txHandler,
  data: rebalancing.txData,
  value: rebalancing.txValue,
});
```


# Owner Privilege

This page elaborates owner privileges.

## BatchTrade

### activate()/deactivate()

Owner can pause and unpause batchTrading. This is intended to be used when a new version of 31Third protocol will be deployed.

### updateFeeRecipient()

Owner can update the fee recipient wallet.

### updateBasisPoints()

Owner can update fee basis points in a range of:$$0 <= feeBasisPoints <= maxFeeBasisPoints$$

### reduceMaxFeeBasisPoints()

Owner can reduce max fee basis points.

(Max fee basis points are currently set to twenty basis points.)

### addFeelessWallet()/removeFeelessWallet()

Owner can add and remove wallets which are eligable for feeless trading.

### updateTradeSigner()

Owner can adapt the public key used for validating the sent `Trade` struct data sent into `batchTrade(...)`.

## ExchangeAdapterRegistry

### addAdapter()/removeAdapter()

Owner can add/remove adapters which are used the establish the connection to external exchange contracts like [0x ExchangeProxy](https://etherscan.io/address/0xDef1C0ded9bec7F1a1670819833240f027b25EfF).


# Prohibition

It is currently not possible to execute batch trades with tokens that have included fee systems in the transfer function. Handling such tokens might lead to unexpected behavior; therefore, transactions executed with a token with a transfer fee will be reverted.

{% hint style="info" %}
If we receive many requests asking to support such tokens we will implement specific handling for these tokens in future versions of 31Third protocol.
{% endhint %}


# Audit

## Protocol

31third-protocol has been audited by Quantstamp. You can check out the PDF or [view it on their website](https://certificate.quantstamp.com/full/31-third/d11ac960-91e8-49c2-9cb3-c44e11e442f9/index.html).

{% file src="/files/erFuhcXUepTXfdzmpSys" %}
31third-protocol audit report by Quantstamp
{% endfile %}

Additional adapters (GenericAdapter, GenericEqualSpenderAndHandlerAdapter) for 31third-protocol has been audited by Quantstamp. You can check out the PDF or [view it on their website](https://certificate.quantstamp.com/full/31-third-diff-update/c091a773-0a24-4658-940a-5c14a2e08498/index.html).

{% file src="/files/5xczaTuPd4XhPETvGVgD" %}
Generic adapters for 31third-protocol audit report by Quantstamp
{% endfile %}

Adaptions to be able to support tokens that have wei imprecisions on transfer due to rounding (e.g. Aave, Lido) has been audited by Quantstamp. You can check out the PDF or [view it on their website](https://certificate.quantstamp.com/full/31-third-batch-trade-diff/c8e66693-9915-40fe-8340-841aed02076f/index.html).

{% file src="/files/IBY45jUtDywJQJuS5P6Z" %}
Support for wei imprecision for 31third-protocol audit report by Quantstamp
{% endfile %}

## External Adapters

### Enzyme

Our adapter to interact with the [enzyme-protocol](https://github.com/enzymefinance/protocol) has been audited by ChainSecurity. You can check out the PDF or [view it on their website](https://chainsecurity.com/security-audit/enzyme-31third-adapter/).

{% file src="/files/MLduz5QDkEIs1IetTpWt" %}
31ThirdAdapter for Enzyme audit report by ChainSecurity
{% endfile %}

{% file src="/files/Rf8zf1dOTEhWkIH7SHjg" %}
31ThirdAdapter (1.0.1) for Enzyme audit report by ChainSecurity
{% endfile %}


# Statistics

{% content-ref url="/pages/N5CKEYXRto89ydnCAass" %}
[Gas cost analysis](/protocol/statistics/gas-cost-analysis)
{% endcontent-ref %}


# Gas cost analysis

The following table shows the approximate savings of gas units comparing block execution by **31Third** with executing single trades on either **0x Protocol** or **ParaSwap**.

<figure><img src="/files/HXLEfqjLl0QvNaiQr9jy" alt=""><figcaption><p>Gas cost analysis</p></figcaption></figure>


# Fees

31Third charges ten basis points on trading volume on executed trades. Ethereum network fees are not included in the price.


# FAQ

#### **What does 31Third mean?**

313 is the area code of Detroit, and three-one-third was also the name of Eminem's first group. We may come from Detroit.

#### **Which wallets do you support?**

We support MetaMask, WalletConnect, and all major custodians. Let us know if you want to add a wallet we have not yet integrated.

#### **Which chains do you support?**

We are supporting Ethereum, Polygon and Optimism and will expand to Base, Arbitrum, Blast and BNB soon.

#### **Do you have a token?**

No.

#### **What are network fees?**

Network, or gas fees, fluctuate based on supply and demand for the network's computational power. If there is a lot of congestion, you can expect higher gas fees and vice versa. Low gas fees are considered anywhere from 0 to 30 GWEI, whereas higher gas prices include base fees of 80+ GWEI.

#### **How is the protocol deployed?**

We are using Gnosis Safe.

#### **Are you open source?**

Our smart contract is open source and can be reviewed here. Our algorithmic smart order router and user interface are not open source.

#### **What tokens can I trade?**

We support a wide range of allowed tokens. Let us know if you want to add a token we have not yet cleared.


