Skip to content

Commit

Permalink
[docs] Deepbook v3 (MystenLabs#18530)
Browse files Browse the repository at this point in the history
## Description 

Updates the deepbook documentation

## Test plan 

How did you test the new or updated feature?

---

## Release notes

Check each box that your changes affect. If none of the boxes relate to
your changes, release notes aren't required.

For each box you select, include information after the relevant heading
that describes the impact of your changes that a user might notice and
any actions they must take to implement updates.

- [ ] Protocol: 
- [ ] Nodes (Validators and Full nodes): 
- [ ] Indexer: 
- [ ] JSON-RPC: 
- [ ] GraphQL: 
- [ ] CLI: 
- [ ] Rust SDK:
  • Loading branch information
ronny-mysten authored and tx-tomcat committed Jul 29, 2024
1 parent b7ea0bb commit e02a1c9
Show file tree
Hide file tree
Showing 24 changed files with 1,047 additions and 22 deletions.
39 changes: 33 additions & 6 deletions docs/content/sidebars/standards.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,39 @@ const standards = [
id: 'standards/deepbook',
},
items: [
'standards/deepbook/design',
'standards/deepbook/orders',
'standards/deepbook/pools',
'standards/deepbook/query-the-pool',
'standards/deepbook/routing-a-swap',
'standards/deepbook/trade-and-swap',
{
type: 'category',
label: 'DeepBook V3',
link: {
type: 'doc',
id: 'standards/deepbookv3',
},
items: [
'standards/deepbookv3/design',
'standards/deepbookv3/balance-manager',
'standards/deepbookv3/query-the-pool',
'standards/deepbookv3/orders',
'standards/deepbookv3/swaps',
'standards/deepbookv3/flash-loans',
'standards/deepbookv3/staking-governance',
],
},
{
type: 'category',
label: 'DeepBook V2',
link: {
type: 'doc',
id: 'standards/deepbookv2',
},
items: [
'standards/deepbookv2/design',
'standards/deepbookv2/orders',
'standards/deepbookv2/pools',
'standards/deepbookv2/query-the-pool',
'standards/deepbookv2/routing-a-swap',
'standards/deepbookv2/trade-and-swap',
],
},
],
},
'standards/display',
Expand Down
25 changes: 25 additions & 0 deletions docs/content/snippets/deepbook.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useLocation } from "@docusaurus/router";
import useGlobalData from '@docusaurus/useGlobalData';
import Link from '@docusaurus/Link';

export function DBV() {
const location = useLocation();
const isV3 = location.pathname.includes("v3");

function DBLink() {
return <Link href={isV3 ? "/standards/deepbookv2" : "/standards/deepbookv3"}>DeepBook{isV3 ? "V2" : "V3"} docs</Link>
}

return (
<>
This documentation is for <b>version {isV3 ? "3" : "2"}</b> of DeepBook. DeepBook{isV3 ? "V3" : "V2"} is currently available in {isV3 ? "Devnet and Testnet" : "Mainnet"}. For documentation on version {isV3 ? "2" : "3"} of DeepBook, see <DBLink />.
</>
)

}

:::info

<DBV />

:::
24 changes: 15 additions & 9 deletions docs/content/standards/deepbook.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,26 @@ title: DeepBook
description: A central limit order book that offers features and functionality for marketplaces on Sui. Token exchanges leveraging the layer can feature transparency, a full range of trading options, and customer privacy.
---

As Sui's first native liquidity layer, DeepBook provides token trading activity. Token exchanges leveraging the layer can feature transparency, a full range of trading options, and customer privacy. DeepBook operates as a decentralized and permissionless environment to support token trades.
import DocCardList from '@theme/DocCardList';

DeepBook is open for community development. You can use the [Sui Improvement Proposals](https://github.com/sui-foundation/sips?ref=blog.sui.io) (SIPs) process to suggest changes to make DeepBook better.
DeepBook is a next-generation decentralized central limit order book (CLOB) built on Sui. DeepBook leverages Sui's parallel execution and low transaction fees to bring a highly performant, low-latency exchange on chain.

## Versioning

The latest development iteration of DeepBook is version 3 (DeepBookV3). [DeebBookV3](./deepbookv3.mdx) is currently available in both Devnet and Testnet. [DeepBookV2](./deepbookv2.mdx) is the current Mainnet iteration of DeepBook.

DeepBook does not include an end-user interface for token trading. Rather, it offers built-in trading functionality that can support token trades from decentralized exchanges, wallets, or other apps. You can leverage its SDK to build functionality for token trades and price queries.
DeepBookV3 is scheduled to replace DeepBookV2 on Mainnet in the second half of 2024.

## Liquidity support
<DocCardList/>

Similar to order books for other market places, DeepBook's central limit order book (CLOB) architecture enables you to enter market and limit orders. You can sell SUI tokens, referred to as an "ask," can set your price, referred to as a limit order, or sell at the market's going rate. If you are seeking to buy SUI, referred to as a "bid," you can pay the current market price or set a limit amount you're willing to pay. Limit orders only get fulfilled if the CLOB finds a match between a buyer and seller.
## Open source

DeepBook is open for community development. You can use the [Sui Improvement Proposals](https://github.com/sui-foundation/sips?ref=blog.sui.io) (SIPs) process to suggest changes to make DeepBook better.

If you put in a limit order for 1,000 SUI, and no single seller is currently offering that quantity of tokens, DeepBook automatically pools the current asks to meet the quantity of your bid.
- [DeepBookV2 packages](https://github.com/MystenLabs/sui/tree/main/crates/sui-framework/packages/deepbook) (part of Sui framework)
- [DeepBookV3 repository on GitHub](https://github.com/MystenLabs/deepbookv3)

## Transparency and privacy

As a CLOB, DeepBook works like a digital ledger, logging bids and asks in chronological order and automatically finding matches between the two sides. It takes into account user parameters on trades such as prices.
## Related links

The digital ledger is open so people can view the trades and prices, giving clear proof of fairness. You can use this transparency to create metrics and dashboards to monitor trading activity.
- <a href="/references/framework/deepbook" data-no-link-check>DeepBook framework docs</a>: Autogenerated framework documentation for DeepBookV2.
25 changes: 25 additions & 0 deletions docs/content/standards/deepbookv2.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: DeepBookV2
description: A central limit order book that offers features and functionality for marketplaces on Sui. Token exchanges leveraging the layer can feature transparency, a full range of trading options, and customer privacy.
---

{@include: ../snippets/deepbook.mdx}

As Sui's first native liquidity layer, DeepBook provides token trading activity. Token exchanges leveraging the layer can feature transparency, a full range of trading options, and customer privacy. DeepBook operates as a decentralized and permissionless environment to support token trades.

DeepBook is open for community development. You can use the [Sui Improvement Proposals](https://github.com/sui-foundation/sips?ref=blog.sui.io) (SIPs) process to suggest changes to make DeepBook better.

DeepBook does not include an end-user interface for token trading. Rather, it offers built-in trading functionality that can support token trades from decentralized exchanges, wallets, or other apps. You can leverage its SDK to build functionality for token trades and price queries.

## Liquidity support

Similar to order books for other market places, DeepBook's central limit order book (CLOB) architecture enables you to enter market and limit orders. You can sell SUI tokens, referred to as an "ask," can set your price, referred to as a limit order, or sell at the market's going rate. If you are seeking to buy SUI, referred to as a "bid," you can pay the current market price or set a limit amount you're willing to pay. Limit orders only get fulfilled if the CLOB finds a match between a buyer and seller.

If you put in a limit order for 1,000 SUI, and no single seller is currently offering that quantity of tokens, DeepBook automatically pools the current asks to meet the quantity of your bid.

## Transparency and privacy

As a CLOB, DeepBook works like a digital ledger, logging bids and asks in chronological order and automatically finding matches between the two sides. It takes into account user parameters on trades such as prices.

The digital ledger is open so people can view the trades and prices, giving clear proof of fairness. You can use this transparency to create metrics and dashboards to monitor trading activity.

Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
---
title: DeepBook Design
sidebar_label: Design
slug: /deepbook-design
---

{@include: ../../snippets/deepbook.mdx}

## Pools {#pools}

At the center of DeepBook is a hyper-efficient per-current pair shared-object pool structure. This architecture maximally utilizes Sui's Narwhal and Bullshark engine to minimize contention and achieve high throughput.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
---
title: DeepBook Orders
slug: /deepbook-orders
sidebar_label: Orders
---

{@include: ../../snippets/deepbook.mdx}

## Order book structure {#order-book-structure}

DeepBook adopts a hyper-efficient approach to store orders. Each pool stores the unfilled maker orders. Taker orders are filled instantaneously within the same transaction the order is submitted. Bid and ask orders are stored separately, each with a two-level nested crit-bit tree. The first level crit-bit tree is ordered using the price of the maker order, and the second level crit-bit tree is ordered using the order id of the maker order.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
---
title: DeepBook Pools
slug: /deepbook-pools
---

{@include: ../../snippets/deepbook.mdx}

At the center of DeepBook is a hyper-efficient per-current pair shared-object `Pool` structure. This architecture maximally utilizes Sui's Narwhal and Bullshark engine to minimize contention and achieve high throughput.

For each base and quote asset trading pair, a globally shared `Pool` is created to bookkeep open orders on the order book and handle placement, cancellation, and settlement of orders. Under this architecture, transactions involving different trading pairs can be easily parallelized to maximize throughput.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
---
title: Query the Pool
slug: /query-the-pool
---

{@include: ../../snippets/deepbook.mdx}

This section shows how to query the pool and order status.

## Order status {#order-status}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
---
title: Routing a Swap
slug: /routing-a-swap
---

{@include: ../../snippets/deepbook.mdx}

Follow these instructions to construct and execute a trade using a smart-routing swap.

## Find the best route to swap {#swap-route}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
---
title: Trade and Swap
slug: /trade-and-swap
---

{@include: ../../snippets/deepbook.mdx}

This section shows how to construct and execute a trade on the DeepBook protocol.

## Create a pool {#create-pool}
Expand Down
40 changes: 40 additions & 0 deletions docs/content/standards/deepbookv3.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: DeepBookV3
description: A central limit order book that offers features and functionality for marketplaces on Sui. Token exchanges leveraging the layer can feature transparency, a full range of trading options, and customer privacy.
---

{@include: ../snippets/deepbook.mdx}

DeepBook is a next-generation decentralized central limit order book (CLOB) built on Sui. DeepBook leverages Sui's parallel execution and low transaction fees to bring a highly performant, low-latency exchange on chain.

The latest version delivers new features including flash loans, governance, improved account abstraction, and enhancements to the existing matching engine. This version also introduces its own tokenomics with the [DEEP token](https://suiscan.xyz/mainnet/coin/0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP/txs), which you can stake for additional benefits.

DeepBook does not include an end-user interface for token trading. Rather, it offers built-in trading functionality that can support token trades from decentralized exchanges, wallets, or other apps. The available SDK abstracts away a lot of the complexities of interacting with the chain and building programmable transaction blocks, lowering the barrier of entry for active market making.

## DeepBook tokenomics

The DEEP token is used to pay for trading fees on the exchange. Future upgrades will allow users to pay trading fees using the input token, but owning, using, and staking DEEP will continue to provide benefits to active DeepBook traders on the Sui network.

Users that stake DEEP can enjoy taker and maker incentives. Taker incentives can reduce trading fees by half, dropping them to as low as 0.25 basis points (bps) on stable pairs and 2.5 bps on volatile pairs. Maker incentives are rebates earned based on maker volume generated.

## Liquidity support

Similar to order books for other market places, DeepBook's CLOB architecture enables you to enter market and limit orders. You can sell SUI tokens, referred to as an "ask," can set your price, referred to as a limit order, or sell at the market's going rate. If you are seeking to buy SUI, referred to as a "bid," you can pay the current market price or set a limit price. Limit orders only get fulfilled if the CLOB finds a match between a buyer and seller.

If you put in a limit order for 1,000 SUI, and no single seller is currently offering that quantity of tokens, DeepBook automatically pools the current asks to meet the quantity of your bid.

## Transparency and privacy

As a CLOB, DeepBook works like a digital ledger, logging bids and asks in chronological order and automatically finding matches between the two sides. It takes into account user parameters on trades such as prices.

The digital ledger is open so people can view the trades and prices, giving clear proof of fairness. You can use this transparency to create metrics and dashboards to monitor trading activity.

## Documentation

This documentation outlines the design of DeepBook, its public endpoints, and provides guidance for integrations. The SDK abstracts away a lot of the complexities of interacting with the chain and building programmable transaction blocks, lowering the barrier of entry for active market making.

## Open source

DeepBook is open for community development. You can use the [Sui Improvement Proposals](https://github.com/sui-foundation/sips?ref=blog.sui.io) (SIPs) process to suggest changes to make DeepBook better.

[DeepBook repository on GitHub](https://github.com/MystenLabs/deepbookv3).
115 changes: 115 additions & 0 deletions docs/content/standards/deepbookv3/balance-manager.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
---
title: BalanceManager
description: Learn about the balance manager and how it works
---

{@include: ../../snippets/deepbook.mdx}

The `BalanceManager` shared object holds all balances for different assets. To perform trades, pass a combination of `BalanceManager` and `TradeProof` into a [pool](./design.mdx#pool). `TradeProof`s are generated in one of two ways, either by the `BalanceManager` owner directly, or by any `TradeCap` owner. The owner can generate a `TradeProof` without the risk of equivocation. The `TradeCap` owner, because it's an owned object, risks equivocation when generating a `TradeProof`. Generally, a high frequency trading engine trades as the default owner.

With exception to swaps, all interactions with DeepBook require a `BalanceManager` as one of its inputs. When orders are matched, funds are transferred to or from the `BalanceManager`. You can use a single `BalanceManager` between all pools.

## API

Following are the different public functions that the `BalanceManager` exposes.

### Create a `BalanceManager`

The `new()` function creates a `BalanceManager` hot potato (a struct with no abilities). Combine it with `share`, or else the transaction fails. You can combine the transaction with deposit calls, allowing you to create, deposit, then share the balance manager in one transaction.

```move
/// Create a new Balance Manager.
public fun new(ctx: &mut TxContext): BalanceManager;
/// Share the balance manager.
public fun share(balance_manager: BalanceManager);
```

### Mint a `TradeCap`

The owner of a `BalanceManager` can mint a `TradeCap` and send it to another address. Upon receipt, that address will have the capability to place orders with this `BalanceManager`. The address owner cannot deposit or withdraw funds, however. The maximum number of `TradeCap` that can be assigned for a `BalanceManager` is `1000`. If this limit is reached, one or more existing `TradeCap` must be revoked before minting new ones.

```move
/// Mint a `TradeCap`, only owner can mint a `TradeCap`.
public fun mint_trade_cap(
balance_manager: &mut BalanceManager,
ctx: &mut TxContext
): TradeCap
/// Revoke a `TradeCap`. Only the owner can revoke a `TradeCap`.
public fun revoke_trade_cap(
balance_manager: &mut BalanceManager,
trade_cap_id: &ID,
ctx: &TxContext
)
```

### Generate a `TradeProof`

To call any function that requires a balance check or transfer, the user must provide their `BalanceManager` as well as a `TradeProof`. There are two ways to generate a trade proof, one used by the owner and another used by a `TradeCap` owner.

```move
/// Generate a `TradeProof` by the owner. The owner does not require a capability
/// and can generate TradeProofs without the risk of equivocation.
public fun generate_proof_as_owner(
balance_manager: &mut BalanceManager,
ctx: &TxContext
): TradeProof
/// Generate a `TradeProof` with a `TradeCap`.
/// Risk of equivocation since `TradeCap` is an owned object.
public fun generate_proof_as_trader(
balance_manager: &mut BalanceManager,
trade_cap: &TradeCap,
ctx: &TxContext
): TradeProof
```

### Deposit funds

Only the owner can deposit funds into the `BalanceManager`.

```move
/// Deposit funds to a balance_manager. Only owner can call this directly.
public fun deposit<T>(
balance_manager: &mut BalanceManager,
coin: Coin<T>,
ctx: &mut TxContext,
)
```

### Withdraw funds

Only the owner can withdraw funds from the `BalanceManager`.

```move
/// Withdraw funds from a balance_manager. Only owner can call this directly.
/// If withdraw_all is true, amount is ignored and full balance withdrawn.
/// If withdraw_all is false, withdraw_amount is withdrawn.
public fun withdraw<T>(
balance_manager: &mut BalanceManager,
withdraw_amount: u64,
ctx: &mut TxContext,
): Coin<T>
public fun withdraw_all<T>(
balance_manager: &mut BalanceManager,
ctx: &mut TxContext,
): Coin<T>
```

### Read endpoints

```move
/// Validate that this `TradeProof` can access the balance manager's funds.
public fun validate_proof(balance_manager: &BalanceManager, proof: &TradeProof)
/// Returns the balance of a Coin in an balance_manager.
public fun balance<T>(balance_manager: &BalanceManager): u64
/// Returns the owner of the balance_manager.
public fun owner(balance_manager: &BalanceManager): address
/// Returns the owner of the balance_manager.
public fun id(balance_manager: &BalanceManager): ID
```
Loading

0 comments on commit e02a1c9

Please sign in to comment.