# 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.md) 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.md).

Details on fees can be found on the [FAQ](/resources/faq.md) 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.md).

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,
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.31third.com/protocol/contracts/batchtrade.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
