---
description: >-
  dex 合约是指打算利用 Sei 的 dex 模块中的功能的 CosmWasm 合约 A dex contract refers to a CosmWasm
  contract that intends to make use of functionalities from Sei's dex module
---

# 部署交易合约 (Deploy an exchange contract)

### 合约开发 (Contract Development)

To leverage the highly efficient `dex` module of Sei, a **dex-registered** (see later section of this page) CosmWasm contract **has to** implement the following four `SudoMsg` interfaces:

为了利用 Sei 的高效 dex 模块，dex 注册（参见本页后面部分）的 CosmWasm 合约必须实现以下四个 SudoMsg 接口：

#### SudoMsg::BulkOrderPlacements

This endpoint receives orders placed in the current block on Sei dex and needs to respond with any order id that is not intended to go through by the contract.

该端点接收放在 Sei dex 上当前区块中的订单，并且需要使用任何不经由合约的订单 ID 进行响应。

```
// request
BulkOrderPlacements {
    orders: Vec<OrderPlacement>,
    deposits: Vec<DepositInfo>,
}
```

```
// response
pub struct BulkOrderPlacementsResponse {
    pub unsuccessful_orders: Vec<UnsuccessfulOrder>,
}
```

#### SudoMsg::BulkOrderCancellation

This endpoint receives orders cancelled in the current block on Sei dex.

该端点接收在 Sei dex 上当前区块中取消的订单。

```
// request
BulkOrderCancellations {
    ids: Vec<u64>,
}
```

#### SudoMsg::Settlement

This endpoint receives orders settled in the current block on Sei dex and dex doesn't need response from this endpoint.

该端点接收在 Sei dex 上当前区块结算的订单，而 dex 不需要来自该端点的响应。

```
// request
Settlement {
    epoch: i64,
    entries: Vec<SettlementEntry>,
}
```

#### SudoMsg::NewBlock

This endpoint receives the latest epoch at the beginning of each block.

该端点在每个块的开头接收最新的纪元(数据)。

```
// request
Settlement {
    epoch: i64,
    entries: Vec<SettlementEntry>,
}
```

#### SudoMsg::FinalizeBlock

This endpoint receives the order placement results for orders sent by **this contract** only. Also note that this endpoint is not needed if the contract is not registered as **NeedHook** in the dex module.

该端点仅接收**此合约**发送的订单之下单结果。另请注意，如果合约未在 dex 模块中注册为 **NeedHook** ，则不需要此端点。

```
// request
FinalizeBlock {
    contract_order_results: Vec<ContractOrderResult>,
}
```

Data type definitions (official Sei libraries for these types coming soon):

数据类型定义（这些类型的官方库即将推出）：

```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SudoMsg {
    Settlement {
        epoch: i64,
        entries: Vec<SettlementEntry>,
    },

    SetFundingPaymentRate {
        epoch: i64,
        asset_denom: String,
        price_diff: Decimal,
        negative: bool,
    },

    BulkOrderPlacements {
        orders: Vec<OrderPlacement>,
        deposits: Vec<DepositInfo>,
    },

    BulkOrderCancellations {
        cancellations: Vec<OrderCancellation>,
    },

    Liquidation {
        requests: Vec<LiquidationRequest>,
    },
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]
pub struct BulkOrderPlacementsResponse {
    pub unsuccessful_order_ids: Vec<u64>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct SettlementEntry {
    pub account: String,
    pub price_denom: String,
    pub asset_denom: String,
    pub quantity: Decimal,
    pub execution_cost_or_proceed: Decimal,
    pub expected_cost_or_proceed: Decimal,
    pub position_direction: PositionDirection,
    pub order_type: OrderType,
    pub order_id: u64,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct OrderPlacement {
    pub id: u64,
    pub status: i32,
    pub account: String,
    pub contract_address: String,
    pub price_denom: String,
    pub asset_denom: String,
    pub price: Decimal,
    pub quantity: Decimal,
    pub order_type: i32,
    pub position_direction: i32,
    pub data: String,
    pub status_description: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct DepositInfo {
    pub account: String,
    pub denom: String,
    pub amount: Decimal,
}
```

Response objects like `BulkOrderPlacementsResponse` need to be first serialized as JSON strings, and then encoded with base64:

类似 `BulkOrderPlacementsResponse` 这样的响应对象，需要先序列化为 JSON 字符串，然后用 base64 编码：

```
let response = BulkOrderPlacementsResponse{...};
let serialized_json = serde_json::to_string(&response).unwrap();
let base64_json_str = base64::encode(serialized_json);
let binary = Binary::from_base64(base64_json_str.as_ref()).unwrap();

let mut response: Response = Response::new();
response = response.set_data(binary);
```

There is no requirement on `execute` and `query` endpoints. That being said, it's encouraged to minimize the usage of `execute` and build the bulk of your exchange logic into the aforementioned `sudo` endpoints, for performance reasons.

对执行和查询端点没有要求。话虽如此，出于性能原因，鼓励尽量减少执行并将大部分交换/交易所逻辑构建到上述 sudo 端点中。

### 构建/上传/实例化合约 (Build/Upload/Instantiate Contract)

The same as deploying [a generic CosmWasm contract](https://app.gitbook.com/o/YiBih4jOIh8lif9Z44jw/s/vVOoEaSQGRIbgTgSvoEo/~/changes/o8t1moYwsbabrANIlgnx/smart-contracts-and-local-development/deploy-a-generic-contract#build-cosmwasm-contract).

与部署 [通用 CosmWasm 合约](https://zenofchain.gitbook.io/sei-zhong-wen-wen-dang-sei-docs-chnby-chainguys/zhi-neng-he-yue-he-ben-di-kai-fa-smart-contracts-local-development/bu-shu-tong-yong-he-yue-deployageneric-contract) 相同。

### 向 DEX 模块注册合约 (Register Contract with DEX Module)

In order to leverage `dex` module's functionalities, you need to register your contract with `dex`. To do so, send a `register-contract` transaction to the `dex` module. Template of the command is:

为了利用 dex 模块的功能，您需要使用 dex 注册您的合约。为此，向 dex 模块发送一个 `register-contract` 交易。该命令的模板是：

```
register-contract [contract address] [code id] [need hook] [need order matching] [dependency1,dependency2,…]
```

Example: 举例：

```
seid tx dex register-contract sei14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr 1 true true -y --from=bob --chain-id=sei-chain --fees=10000000ust --gas=500000 --broadcast-mode=block
```

Note the two boolean variables represents:

请注意，两个布尔变量表示：

* NeedHook
* NeedOrderMatching

### Sei Cosmwasm

[Sei cosmwasm](https://crates.io/crates/sei-cosmwasm) crate provides Sei specific bindings for cosmwasm contract to be able to interact with the Sei blockchain by exposing custom messages, queries, and structs that correspond to custom module functionality in the Sei chain. Contracts can import the latest version of the crate and directly interact with a vary of sei modules.

[Sei cosmwasm](https://crates.io/crates/sei-cosmwasm) 库为 cosmwasm 合约提供 Sei 的特定绑定，以使其可以通过以下方式与Sei区块链交互：公开在Sei区块链上与自定义模块、查询和结构对应的自定义消息。合约可以导入最新版本的库并直接与各种 sei 模块交互。
