diff --git a/docs/content/sidebars/standards.js b/docs/content/sidebars/standards.js index 43e8537fdbfa2..ad0727dd351f2 100644 --- a/docs/content/sidebars/standards.js +++ b/docs/content/sidebars/standards.js @@ -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', diff --git a/docs/content/snippets/deepbook.mdx b/docs/content/snippets/deepbook.mdx new file mode 100644 index 0000000000000..fd22210ec26c0 --- /dev/null +++ b/docs/content/snippets/deepbook.mdx @@ -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 DeepBook{isV3 ? "V2" : "V3"} docs + } + + return ( + <> + This documentation is for version {isV3 ? "3" : "2"} 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 . + + ) + +} + +:::info + + + +::: \ No newline at end of file diff --git a/docs/content/standards/deepbook.mdx b/docs/content/standards/deepbook.mdx index 6d4bed9fd7502..e2ae5555ce796 100644 --- a/docs/content/standards/deepbook.mdx +++ b/docs/content/standards/deepbook.mdx @@ -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 + -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. +- DeepBook framework docs: Autogenerated framework documentation for DeepBookV2. diff --git a/docs/content/standards/deepbookv2.mdx b/docs/content/standards/deepbookv2.mdx new file mode 100644 index 0000000000000..2a275562c73de --- /dev/null +++ b/docs/content/standards/deepbookv2.mdx @@ -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. + diff --git a/docs/content/standards/deepbook/design.mdx b/docs/content/standards/deepbookv2/design.mdx similarity index 99% rename from docs/content/standards/deepbook/design.mdx rename to docs/content/standards/deepbookv2/design.mdx index c60ba5986173a..88d656d11cc1c 100644 --- a/docs/content/standards/deepbook/design.mdx +++ b/docs/content/standards/deepbookv2/design.mdx @@ -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. diff --git a/docs/content/standards/deepbook/orders.mdx b/docs/content/standards/deepbookv2/orders.mdx similarity index 98% rename from docs/content/standards/deepbook/orders.mdx rename to docs/content/standards/deepbookv2/orders.mdx index c0cc7822dc642..cb14c01181797 100644 --- a/docs/content/standards/deepbook/orders.mdx +++ b/docs/content/standards/deepbookv2/orders.mdx @@ -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. diff --git a/docs/content/standards/deepbook/pools.mdx b/docs/content/standards/deepbookv2/pools.mdx similarity index 97% rename from docs/content/standards/deepbook/pools.mdx rename to docs/content/standards/deepbookv2/pools.mdx index bc833df61478a..dd98a44ce578b 100644 --- a/docs/content/standards/deepbook/pools.mdx +++ b/docs/content/standards/deepbookv2/pools.mdx @@ -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. diff --git a/docs/content/standards/deepbook/query-the-pool.mdx b/docs/content/standards/deepbookv2/query-the-pool.mdx similarity index 98% rename from docs/content/standards/deepbook/query-the-pool.mdx rename to docs/content/standards/deepbookv2/query-the-pool.mdx index 960d66c0d3f93..728f08c7ec20b 100644 --- a/docs/content/standards/deepbook/query-the-pool.mdx +++ b/docs/content/standards/deepbookv2/query-the-pool.mdx @@ -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} diff --git a/docs/content/standards/deepbook/routing-a-swap.mdx b/docs/content/standards/deepbookv2/routing-a-swap.mdx similarity index 99% rename from docs/content/standards/deepbook/routing-a-swap.mdx rename to docs/content/standards/deepbookv2/routing-a-swap.mdx index 8f52e66705188..776efbb740157 100644 --- a/docs/content/standards/deepbook/routing-a-swap.mdx +++ b/docs/content/standards/deepbookv2/routing-a-swap.mdx @@ -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} diff --git a/docs/content/standards/deepbook/trade-and-swap.mdx b/docs/content/standards/deepbookv2/trade-and-swap.mdx similarity index 99% rename from docs/content/standards/deepbook/trade-and-swap.mdx rename to docs/content/standards/deepbookv2/trade-and-swap.mdx index 6db8575d1acf1..6daf98a943b65 100644 --- a/docs/content/standards/deepbook/trade-and-swap.mdx +++ b/docs/content/standards/deepbookv2/trade-and-swap.mdx @@ -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} diff --git a/docs/content/standards/deepbookv3.mdx b/docs/content/standards/deepbookv3.mdx new file mode 100644 index 0000000000000..deb8250ff2312 --- /dev/null +++ b/docs/content/standards/deepbookv3.mdx @@ -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). diff --git a/docs/content/standards/deepbookv3/balance-manager.mdx b/docs/content/standards/deepbookv3/balance-manager.mdx new file mode 100644 index 0000000000000..c3fc786e66e85 --- /dev/null +++ b/docs/content/standards/deepbookv3/balance-manager.mdx @@ -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( + balance_manager: &mut BalanceManager, + coin: Coin, + 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( + balance_manager: &mut BalanceManager, + withdraw_amount: u64, + ctx: &mut TxContext, +): Coin + +public fun withdraw_all( + balance_manager: &mut BalanceManager, + ctx: &mut TxContext, +): Coin +``` + +### 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(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 +``` \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/design.mdx b/docs/content/standards/deepbookv3/design.mdx new file mode 100644 index 0000000000000..8b9f02e6e2cff --- /dev/null +++ b/docs/content/standards/deepbookv3/design.mdx @@ -0,0 +1,146 @@ +--- +title: DeepBook Design +sidebar_label: Design +--- + +{@include: ../../snippets/deepbook.mdx} + +At a high level, the DeepBook design follows the following flow, which revolves around three shared objects: + - `Pool`: A shared object that represents one market and is responsible for managing its order book, users, stakes, and so on. See the [Pool shared object](#pool) section to learn more. + - `PoolRegistry`: Used only during pool creation, it makes sure that duplicate pools are not created and maintains package versioning. + - `BalanceManager`: Used to source a user's funds when placing orders. A single `BalanceManager` can be used between all pools. See [BalanceManager](./balance-manager.mdx) to learn more. + +

![1](./images/DBv3Architecture.png)

+ +## Pool shared object {#pool} + +All public facing functions take in the `Pool` shared object as a mutable or immutable reference. `Pool` is made up of three distinct components: + - [`Book`](#book) + - [`State`](#state) + - [`Vault`](#vault) + +Logic is isolated between components and each component builds on top of the previous one. By maintaining a book, then state, then vault relationship, DeepBook can provide data availability guarantees, improve code readability, and help make maintaining and upgrading the protocol easier. + +

![Pool Modules](./images/pool.png)

+ +### Book + +This component is made up of the main `Book` module along with `Fill`, `OrderInfo`, and `Order` modules. The `Book` struct maintains two `BigVector` objects for bids and asks, as well as some metadata. It is responsible for storing, matching, modifying, and removing `Orders`. + +When placing an order, an `OrderInfo` is first created. If applicable, it is first matched against existing maker orders, accumulating `Fill`s in the process. Any remaining quantity will be used to create an `Order` object and injected into the book. By the end of book processing, the `OrderInfo` object has enough information to update all relevant users and the overall state. + +### State + +`State` stores `Governance`, `History`, and `Account`. It processes all requests, updating at least one of these stored structs. + +#### Governance + +The `Governance` module stores data related to the pool's trading params. These parameters are the taker fee, maker fee, and the stake required. Stake required represents the amount of DEEP tokens that a user must have staked in this specific pool to be eligible for taker and maker incentives. + +Every epoch, users with non zero stake can submit a proposal to change these parameters. The proposed fees are bounded. + +| min_value (bps) | max_value (bps) | Pool type | Taker or maker | +| --- | --- | --- | --- | +| 5 | 10 | Volatile | Taker | +| 2 | 5 | Volatile | Maker | +| 0.5 | 1 | Stable | Taker | +| 0.2 | 0.5 | Stable | Maker | +| 0 | 0 | Whitelisted | Taker and maker | + +Users can also vote on live proposals. When a proposal exceeds the quorum, the new trade parameters are queued to go live from the following epoch and onwards. Proposals and votes are reset every epoch. Users can start submitting and voting on proposals the epoch following their stake. Quorum is equivalent to half of the total voting power. A user's voting power is calculated with the following formula where ${V}$ is the voting power, ${S}$ is the amount staked, and ${V_c}$ is the voting power cutoff. ${V_c}$ is currently set to 100,000 DEEP. + +

$\LARGE V=\min\lparen S,V_c \rparen + \max\lparen \sqrt{S} - \sqrt{V_c} ,0 \rparen$

+ +The following diagram helps visualize the governance lifecycle. + +

![DeepBook Governance Timeline](./images/governance.png)

+ +#### History + +The `History` module stores aggregated volumes, trading params, fees collected and fees to burn for the current epoch and previous epochs. During order processing, fills are used to calculate and update the total volume. Additionally, if the maker of the trade has enough stake, the total staked volume is also updated. + +The first operation of every epoch will trigger an update, moving the current epoch data into historic data, and resetting the current epoch data. + +User rebate calculations are done in this module. During every epoch, a maker is eligible for rebates as long as their DEEP staked is over the stake required and have contributed in maker volume. The following formula is used to calculate maker fees, quoted from the [Whitepaper: DeepBook Token](/doc/deepbook.pdf) document. Details on maker incentives can be found in section 2.2 of the whitepaper. + +
+ +The computation of incentives – which happens after an epoch ends and is only given to makers +who have staked the required number of DEEP tokens in advance – is calculated in Equation (3) for +a given maker ${i}$. Equation (3) introduces several new variables. First, ${M}$ refers to the set of makers +who stake a sufficient number of DEEP tokens, and $\bar{M}$ refers to the set of makers who do not fulfill +this condition. Second, ${F}$ refers to total fees (collected both from takers and the maker) that a +maker’s volume has generated in a given epoch. Third, ${L}$ refers to the total liquidity provided by +a maker – and specifically the liquidity traded, not just the liquidity quoted. Finally, the critical +point ${p}$ is the “phaseout” point, at which – if total liquidity provided by other makers’ crosses this +point – incentives are zero for the maker in that epoch. This point ${p}$ is constant for all makers in +a pool and epoch. + +

$\LARGE \textsf {Incentives } \textsf {for } \textsf {Maker } i = \max\Bigg\lbrack F_i\Bigg\lparen 1 + \large\cfrac{\sum_{j \in \bar{M}} F_j} {\sum_{j \in M} F_j} \Bigg\rparen\Bigg\lparen \LARGE 1 - \large\cfrac{\sum_{j \in M \cup \bar{M}} L_j - L_i}{p}\Bigg\rparen \LARGE ,0 \Bigg\rbrack$ (3)

+ +
+ +In essence, if the total volume during an epoch is greater than the median volume from the last 28 days, then there are no rebates. The lower the volume compared to the median, the more rebates are available. The maximum amount of rebates for an epoch is equivalent to the total amount of DEEP collected during that epoch. Remaining DEEP is burned. + +#### Account + +`Account` represents a single user and their relevant data. Everything related to volumes, stake, voted proposal, unclaimed rebates, and balances to be transferred. There is a one to one relationship between a `BalanceManager` and an `Account`. + +Every epoch, the first action that a user performs will update their account, triggering a calculation of any potential rebates from the previous epoch, as well as resetting their volumes for the current epoch. Any new stakes from the previous epoch become active. + +Each account has settled and owed balances. Settled balances are what the pool owes to the user, and owed balances are what the user owes to the pool. For example, when placing an order, the user's owed balances increase, representing the funds that the user has to pay to place that order. Then, if a maker order is taken by another user, the maker's settled balances increase, representing the funds that the maker is owed. + +### Vault + +Every transaction that a user performs on DeepBook resets their settled and owed balances. The vault then processes these balances for the user, deducting or adding to funds to their `BalanceManager`. + +The vault also stores the `DeepPrice` struct. This object holds up to 100 data points representing the conversion rate between the pool's base or quote asset and DEEP. These data points are sourced from a whitelisted pool, DEEP/USDC or DEEP/SUI. This conversion rate is used to determine the quantity of DEEP tokens required to pay for trading fees. + +### `BigVector` + +`BigVector` is an arbitrary sized vector-like data structure, implemented using an on-chain B+ Tree to support almost constant time (log base max_fan_out) random access, insertion and removal. + +Iteration is supported by exposing access to leaf nodes (slices). Finding the initial slice can be done in almost constant time, and subsequently finding the previous or next slice can also be done in constant time. + +Nodes in the B+ Tree are stored as individual dynamic fields hanging off the `BigVector`. + +## Place limit order flow + +The following diagram of the lifecycle of an order placement action helps visualize the book, then state, then vault flow. + +

![Place limit order flow](./images/placeorder.png)

+ +### Pool + +In the `Pool` module, `place_order_int` is called with the user's input parameters. In this function, four things happen in order: + 1. An `OrderInfo` is created. + 1. The `Book` function `create_order` is called. + 1. The `State` function `process_create` is called. + 1. The `Vault` function `settle_balance_manager` is called. + +### Book + +The order creation within the book involves three primary tasks: + - Validate inputs. + - Match against existing orders. + - Inject any remaining quantity into the order book as a limit order. + +Validation of inputs ensures that quantity, price, timestamp, and order type are within expected ranges. + +To match an `OrderInfo` against the book, the list of `Order`s is iterated in the opposite side of the book. If there is an overlap in price and the existing maker order has not expired, then DeepBook matches their quantities and generates a `Fill`. DeepBook appends that fill to the `OrderInfo` fills, to use later in state. DeepBook updates the existing maker order quantities and status during each match, and removes them from the book if they are completely filled or expired. + +Finally, if the `OrderInfo` object has any remaining quantity, DeepBook converts it into a compact `Order` object and injects it into the order book. `Order` has the minimum amount of data necessary for matching, while `OrderInfo` has the maximum amount of data for general processing. + +Regardless of direction or order type, all DeepBook matching is processed in a single function. + +### State + +The `process_create` function in `State` handles the processing of an order creation event within the pool's state: calculating the transaction amounts and fees for the order, and updating the account volumes accordingly. + +First, the function processes the list of fills from the `OrderInfo` object, updating volumes tracked and settling funds for the makers involved. Next, the function retrieves the account's total trading volume and active stake. It calculates the taker's fee based on the user's account stake and volume in DEEP tokens, while the maker fee is retrieved from the governance trade parameters. To receive discounted taker fees, the account must have more than the minimum stake for the pool, and the trading volume in DEEP tokens must exceed the same threshold. If any quantity remains in the `OrderInfo` object, it is added to the account's list of orders as an `Order` and is already created in `Book`. + +Finally, the function calculates the partial taker fills and maker order quantities, if there are any, with consideration for the taker and maker fees. It adds these to the previously settled and owed balances from the account. Trade history is updated with the total fees collected from the order and two tuples are returned to `Pool`, settled and owed balances, in (base, quote, DEEP) format, ensuring the correct assets are transferred in `Vault`. + +### Vault + +The `settle_balance_manager` function in `Vault` is responsible for managing the transfer of any settled and owed amounts for the `BalanceManager`. It starts by validating that the trader is authorized to use the `BalanceManager`. For each asset type, if the `balances_out` exceeds the `balances_in`, the difference is split from the vault's balance and deposited into the `BalanceManager`. Conversely, if the `balances_in` exceeds the `balances_out`, the difference is withdrawn from the `BalanceManager` and joined to the vault's balance. This process is repeated for base, quote, and DEEP asset balances, ensuring all asset balances are accurately reflected and settled between the vault and the `BalanceManager`. \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/flash-loans.mdx b/docs/content/standards/deepbookv3/flash-loans.mdx new file mode 100644 index 0000000000000..561785f0a6259 --- /dev/null +++ b/docs/content/standards/deepbookv3/flash-loans.mdx @@ -0,0 +1,63 @@ +--- +title: Flash Loans +description: Use DeepBook to perform flash loans, uncollaterized loans that are borrowed and repaid within the same programmable transaction block. +--- + +{@include: ../../snippets/deepbook.mdx} + +Flash loans by definition are uncollaterized loans that are borrowed and repaid within the same programmable transaction block. Users can borrow flash loans in the base or quote asset from any DeepBook pool. Flash loans return a `FlashLoan` hot potato (struct with no abilities), which must be returned back to the pool by the end of the call. The transaction is atomic, so the entire transaction fails if the loan is not returned. + +The quantity borrowed can be the maximum amount that the pool owns. Borrowing from a pool and trading in the same pool can result in failures because trading requires the movement of funds. If the funds are borrowed, then there are no funds to move. + +## API + +Following are the endpoints that the `Pool` exposes for flash loans. + +### Borrow flash loan base + +Borrow base assets from the `Pool`. The function returns a hot potato, forcing the borrower to return the assets within the same transaction. + +```move +public fun borrow_flashloan_base( + self: &mut Pool, + base_amount: u64, + ctx: &mut TxContext, +): (Coin, FlashLoan) +``` +​ +### Borrow flash loan quote + +Borrow quote assets from the `Pool`. The function returns a hot potato, forcing the borrower to return the assets within the same transaction. + +```move +public fun borrow_flashloan_quote( + self: &mut Pool, + quote_amount: u64, + ctx: &mut TxContext, +): (Coin, FlashLoan) +``` +​ +### Retrieve flash loan base + +Return the flash loaned base assets to the `Pool`. `FlashLoan` object is unwrapped only if the assets are returned, otherwise the transaction fails. + +```move +public fun return_flashloan_base( + self: &mut Pool, + coin: Coin, + flash_loan: FlashLoan, +) +``` +​ +### Retrieve flash loan quote + +Return the flash loaned quote assets to the `Pool`. `FlashLoan` object is unwrapped only if the assets are returned, +otherwise the transaction fails. + +```move +public fun return_flashloan_quote( + self: &mut Pool, + coin: Coin, + flash_loan: FlashLoan, +) +``` \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/images/DBv3Architecture.png b/docs/content/standards/deepbookv3/images/DBv3Architecture.png new file mode 100644 index 0000000000000..17acf888e21a2 Binary files /dev/null and b/docs/content/standards/deepbookv3/images/DBv3Architecture.png differ diff --git a/docs/content/standards/deepbookv3/images/governance.png b/docs/content/standards/deepbookv3/images/governance.png new file mode 100644 index 0000000000000..0d412b8155156 Binary files /dev/null and b/docs/content/standards/deepbookv3/images/governance.png differ diff --git a/docs/content/standards/deepbookv3/images/placeorder.png b/docs/content/standards/deepbookv3/images/placeorder.png new file mode 100644 index 0000000000000..527fdb210a88f Binary files /dev/null and b/docs/content/standards/deepbookv3/images/placeorder.png differ diff --git a/docs/content/standards/deepbookv3/images/pool.png b/docs/content/standards/deepbookv3/images/pool.png new file mode 100644 index 0000000000000..29de96feb701e Binary files /dev/null and b/docs/content/standards/deepbookv3/images/pool.png differ diff --git a/docs/content/standards/deepbookv3/orders.mdx b/docs/content/standards/deepbookv3/orders.mdx new file mode 100644 index 0000000000000..2ba69d840e75a --- /dev/null +++ b/docs/content/standards/deepbookv3/orders.mdx @@ -0,0 +1,289 @@ +--- +title: DeepBook Orders +sidebar_label: Orders +--- + +{@include: ../../snippets/deepbook.mdx} + +Users can create limit or market orders, modify orders, and cancel orders. The `BalanceManager` must have the necessary funds to process orders. DeepBook has four order options and three self matching options. Initially, all trading fees are paid with the DEEP token. Consequently, if you set the `pay_with_deep` flag to `false`, orders automatically fail until the following upgrade. + +Users can modify their existing order, reducing the size, lowering the expiration time, or both. Users cannot modify their order to increase their size or increase their expiration time. To do that, they must cancel the original order and place a new order. + +Users can cancel a single order or cancel all of their orders. + +## API + +Following are the order related endpoints that `Pool` exposes. + +### Order options + +The following constants define the options available for orders. + +```move +// Restrictions on limit orders. +// No restriction on the order. +const NO_RESTRICTION: u8 = 0; +// Mandates that whatever amount of an order that can be executed in the +// current transaction, be filled and then the rest of the order canceled. +const IMMEDIATE_OR_CANCEL: u8 = 1; +// Mandates that the entire order size be filled in the current transaction. +// Otherwise, the order is canceled. +const FILL_OR_KILL: u8 = 2; +// Mandates that the entire order be passive. Otherwise, cancel the order. +const POST_ONLY: u8 = 3; +``` + +### Self-matching options + +The following constants define the options available for self-matching orders. + +```move +// Self matching types. +// Self matching is allowed. +const SELF_MATCHING_ALLOWED: u8 = 0; +// Cancel the taker order. +const CANCEL_TAKER: u8 = 1; +// Cancel the maker order. +const CANCEL_MAKER: u8 = 2; +``` + +### OrderInfo struct + +Placing a limit order or a market order creates and returns an `OrderInfo` object. DeepBook automatically drops this object after the order completes or is placed in the book. Use `OrderInfo` to inspect the execution details of the request as it represents all order information. DeepBook does not catch any errors, so if there’s a failure of any kind, then the entire transaction fails. + +```move +public struct OrderInfo has store, drop { + // ID of the pool + pool_id: ID, + // ID of the order within the pool + order_id: u128, + // ID of the account the order uses + balance_manager_id: ID, + // ID of the order defined by client + client_order_id: u64, + // Trader of the order + trader: address, + // Order type, NO_RESTRICTION, IMMEDIATE_OR_CANCEL, FILL_OR_KILL, POST_ONLY + order_type: u8, + // Self matching option, + self_matching_option: u8, + // Price, only used for limit orders + price: u64, + // Whether the order is a buy or a sell + is_bid: bool, + // Quantity (in base asset terms) when the order is placed + original_quantity: u64, + // Deep conversion used by the order + order_deep_price: OrderDeepPrice, + // Expiration timestamp in ms + expire_timestamp: u64, + // Quantity executed so far + executed_quantity: u64, + // Cumulative quote quantity executed so far + cumulative_quote_quantity: u64, + // Any partial fills + fills: vector, + // Whether the fee is in DEEP terms + fee_is_deep: bool, + // Fees paid so far in base/quote/DEEP terms + paid_fees: u64, + epoch: u64, + // Status of the order + status: u8, + // Is a market_order + market_order: bool, +} +``` + +### OrderDeepPrice struct + +The `OrderDeepPrice` struct represents the conversion rate of DEEP at the time the order was placed. +```move +public struct OrderDeepPrice has copy, store, drop { + asset_is_base: bool, + deep_per_asset: u64, +} +``` + +### Fill struct + +The `Fill` struct represents the results of a match between two orders. Use this struct to update the state. + +```move +public struct Fill has store, drop, copy { + // ID of the maker order + maker_order_id: u128, + // account_id of the maker order + balance_manager_id: ID, + // Whether the maker order is expired + expired: bool, + // Whether the maker order is fully filled + completed: bool, + // Quantity filled + base_quantity: u64, + // Quantity of quote currency filled + quote_quantity: u64, + // Whether the taker is bid + taker_is_bid: bool, + // Maker epoch + maker_epoch: u64, + // Maker deep price + maker_deep_price: OrderDeepPrice, +} +``` + +### Events + +DeepBook emits `OrderFilled` when a maker order is filled. + +```move +public struct OrderFilled has copy, store, drop { + pool_id: ID, + maker_order_id: u128, + taker_order_id: u128, + maker_client_order_id: u64, + taker_client_order_id: u64, + price: u64, + taker_is_bid: bool, + base_quantity: u64, + quote_quantity: u64, + maker_balance_manager_id: ID, + taker_balance_manager_id: ID, + timestamp: u64, +} +``` + +DeepBook emits `OrderCanceled` when a maker order is canceled. + +```move +public struct OrderCanceled has copy, store, drop { + pool_id: ID, + order_id: u128, + client_order_id: u64, + price: u64, + is_bid: bool, + base_asset_quantity_canceled: u64, + timestamp: u64, +} +``` + +DeepBook emits `OrderModified` on modification of a maker order. + +```move +public struct OrderModified has copy, store, drop { + pool_id: ID, + order_id: u128, + client_order_id: u64, + price: u64, + is_bid: bool, + new_quantity: u64, + timestamp: u64, +} +``` + +DeepBook emits `OrderPlaced` when it injects a maker order into the order book. + +```move +public struct OrderPlaced has copy, store, drop { + balance_manager_id: ID, + pool_id: ID, + order_id: u128, + client_order_id: u64, + trader: address, + price: u64, + is_bid: bool, + placed_quantity: u64, + expire_timestamp: u64, +} +``` + +### Place limit order + +Place a limit order. Quantity is in base asset terms. For current version `pay_with_deep` must be true, so the +fee is paid with DEEP tokens. + +You must combine a `BalanceManager` call of generating a `TradeProof` before placing orders. + +```move +public fun place_limit_order( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + client_order_id: u64, + order_type: u8, + self_matching_option: u8, + price: u64, + quantity: u64, + is_bid: bool, + pay_with_deep: bool, + expire_timestamp: u64, + clock: &Clock, + ctx: &TxContext, +): OrderInfo +``` + +### Place market order + +Place a market order. Quantity is in base asset terms. Calls `place_limit_order` with a price of `MAX_PRICE` for bids and `MIN_PRICE` for asks. DeepBook cancels the order for any quantity not filled. + +```move +public fun place_market_order( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + client_order_id: u64, + self_matching_option: u8, + quantity: u64, + is_bid: bool, + pay_with_deep: bool, + clock: &Clock, + ctx: &TxContext, +): OrderInfo +``` + +### Modify order + +Modifies an order given `order_id` and `new_quantity`. New quantity must be less than the original quantity and more than the filled quantity. Order must not have already expired. + +The `modify_order` function does not return anything. If the transaction is successful, then assume the modification was successful. + +```move +public fun modify_order( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + order_id: u128, + new_quantity: u64, + clock: &Clock, + ctx: &TxContext, +) +``` + +### Cancel order + +Cancel an order. The order must be owned by the `balance_manager`. The order is removed from the book and the `balance_manager` open orders. The `balance_manager` balance is updated with the order's remaining quantity. + +Similar to modify, `cancel_order` does not return anything. DeepBook emits `OrderCanceled` event. + +```move +public fun cancel_order( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + order_id: u128, + clock: &Clock, + ctx: &TxContext, +) +``` + +### Withdraw settled amounts + +Withdraw settled amounts to the `balance_manager`. All orders automatically withdraw settled amounts. This can be called explicitly to withdraw all settled funds from the pool. + +```move +public fun withdraw_settled_amounts( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, +) +``` \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/query-the-pool.mdx b/docs/content/standards/deepbookv3/query-the-pool.mdx new file mode 100644 index 0000000000000..e8b80f796cadf --- /dev/null +++ b/docs/content/standards/deepbookv3/query-the-pool.mdx @@ -0,0 +1,120 @@ +--- +title: Query the Pool +--- + +{@include: ../../snippets/deepbook.mdx} + +The `Pool` shared object represents a market, such as a SUI/USDC market. That `Pool` is the only one representing that unique pairing (SUI/USDC) and the pairing is the only member of that particular `Pool`. See [DeepBook Design](./design.mdx#pool) to learn more about the structure of pools. + +To perform trades, you pass a `BalanceManager` and `TradeProof` into the relvant `Pool`. Unlike `Pool`s, `BalanceManager` shared objects can contain any type of token, such that the same `BalanceManager` can access multiple `Pool`s to interact with many different trade pairings. See [BalanceManager](./balance-manager.mdx) to learn more. + +## API + +DeepBook exposes a set of endpoints that can be used to query any pool. + +### Check whitelist status + +Accessor to check whether the pool is whitelisted. + +```move +public fun whitelisted(self: &Pool): bool +``` + +### Check quote quantity against base + +Dry run to determine the quote quantity out for a given base quantity. + +```move +public fun get_quote_quantity_out( + self: &Pool, + base_quantity: u64, + clock: &Clock, +): (u64, u64, u64) +``` + +### Check quote quantity against quote + +Dry run to determine the base quantity out for a given quote quantity. + +```move +public fun get_base_quantity_out( + self: &Pool, + quote_quantity: u64, + clock: &Clock, +): (u64, u64, u64) +``` + +### Check quote quantity against quote or base + +Dry run to determine the quantity out for a given base or quote quantity. Only one out of base or quote quantity should be non-zero. Returns the (`base_quantity_out`, `quote_quantity_out`, `deep_quantity_required`). + +```move +public fun get_quantity_out( + self: &Pool, + base_quantity: u64, + quote_quantity: u64, + clock: &Clock, +): (u64, u64, u64) +``` + +### Retrieve mid price for a pool + +Returns the mid price of the pool. + +```move +public fun mid_price( + self: &Pool, + clock: &Clock, +): u64 +``` + +### Retrieve order IDs + +Returns the `order_id` for all open orders for the `balance_manager` in the pool. + +```move +public fun account_open_orders( + self: &Pool, + balance_manager: ID, +): VecSet +``` + +### Retrieve prices and quantities for an order book + +Returns vectors holding the prices (`price_vec`) and quantities (`quantity_vec`) for the level2 order book. The `price_low` and `price_high` are inclusive, all orders within the range are returned. `is_bid` is `true` for bids and `false` for asks. + +```move +public fun get_level2_range( + self: &Pool, + price_low: u64, + price_high: u64, + is_bid: bool, +): (vector, vector) +``` + +Returns vectors holding the prices (`price_vec`) and quantities (`quantity_vec`) for the level2 order book. `ticks` are the maximum number of ticks to return starting from best bid and best ask. (`bid_price`, `bid_quantity`, `ask_price`, `ask_quantity`) are returned as four vectors. The price vectors are sorted in descending order for bids and ascending order for asks. + +```move +public fun get_level2_ticks_from_mid( + self: &Pool, + ticks: u64, +): (vector, vector, vector, vector) +``` + +### Retrieve balances + +Get all balances held in this pool. + +```move +public fun vault_balances( + self: &Pool, +): (u64, u64, u64) +``` + +### Retrieve Pool ID + +Get the ID of the pool given the asset types. + +```move +public fun get_pool_id_by_asset(registry: &Registry): ID +``` \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/staking-governance.mdx b/docs/content/standards/deepbookv3/staking-governance.mdx new file mode 100644 index 0000000000000..29d3dc6a52e2a --- /dev/null +++ b/docs/content/standards/deepbookv3/staking-governance.mdx @@ -0,0 +1,92 @@ +--- +title: Staking and Governance +--- + +{@include: ../../snippets/deepbook.mdx} + +DeepBook’s novel approach to governance allows users to update a single pool’s three parameters: + - taker fee rate + - maker fee rate + - stake required + +Stake required is the amount of DEEP tokens a user must have staked in the pool to take advantage of taker and maker incentives. Each individual DeepBook pool has independent governance, and governance can be conducted every epoch. See [Design](./design.mdx#governance) to learn more about governance. + +![DeepBook Governance Timeline.png](./images/governance.png) + +## API + +`Pool` exposes the following endpoints for staking and governance. + +### Stake + +DEEP tokens must be available in the `balance_manager` for staking. A user’s stake becomes active in the following epoch. If the user’s active stake is greater than the stake required, the user can get reduced taker fees and can accumulate trading fee rebates during that epoch. + +```move +public fun stake( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + amount: u64, + ctx: &TxContext, +) +``` + +### Unstake + +All of the user’s active and inactive stake are removed and added back into the `BalanceManager`. Any casted votes are removed. Maker rebates for the epoch are forfeited, and any reduced taker fees for the remaining epoch are disabled. + +The `balance_manager` must have enough staked DEEP tokens. The `balance_manager` data is updated with the unstaked amount. Balance is transferred to the `balance_manager` immediately. + +```move +public fun unstake( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + ctx: &TxContext, +) +``` + +### Submit proposal + +Users with a non zero active stake can submit proposals. One proposal per user. The user automatically votes for the proposal they submit. + +Submit a proposal to change the taker fee, maker fee, and stake required. The `balance_manager` must have enough staked DEEP tokens to participate. Each `balance_manager` can only submit one proposal per epoch. If the maximum proposal is reached, the proposal with the lowest vote is removed. If the `balance_manager` has less voting power than the lowest voted proposal, the proposal is not added. + +```move +public fun submit_proposal( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + taker_fee: u64, + maker_fee: u64, + stake_required: u64, + ctx: &TxContext, +) +``` + +### Vote + +Users with non-zero voting power can vote on a proposal. All voting power is used on a single proposal. If the user has voted on a different proposal during this epoch, then that vote is removed and recasted into the new proposal. The `balance_manager` must have enough staked DEEP tokens to participate. + +```move +public fun vote( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + proposal_id: ID, + ctx: &TxContext, +) +``` + +### Claim rebates + +Use `claim_rebates` to claim the rewards for the `balance_manager`. The `balance_manager` must have rewards to claim. The `balance_manager` data is updated with the claimed rewards. + +```move +public fun claim_rebates( + self: &mut Pool, + balance_manager: &mut BalanceManager, + trade_proof: &TradeProof, + ctx: &TxContext, +) +``` \ No newline at end of file diff --git a/docs/content/standards/deepbookv3/swaps.mdx b/docs/content/standards/deepbookv3/swaps.mdx new file mode 100644 index 0000000000000..ccd82e6bd66c2 --- /dev/null +++ b/docs/content/standards/deepbookv3/swaps.mdx @@ -0,0 +1,64 @@ +--- +title: Swaps +--- + +{@include: ../../snippets/deepbook.mdx} + +DeepBook provides a swap-like interface commonly seen in automatic market makers (AMMs). Unlike the order functions, you can call `swap_exact_amount` without a `BalanceManager`. You call it directly with `Coin` objects instead. When swapping from base to quote, `base_in` must have a positive value while `quote_in` must be zero. When swapping from quote to base, `quote_in` must be positive and `base_in` zero. Some `deep_in` amount is required to pay for trading fees. You can overestimate this amount, as the unused DEEP tokens are returned at the end of the call. + +You can use the `get_amount_out` endpoint to simulate a swap. The function returns the exact amount of DEEP tokens that the swap requires. + +## API + +Following are the endpoints that the `Pool` exposes for swaps. + +### Swap exact base for quote + +Swap exact base quantity without needing a `balance_manager`. DEEP quantity can be overestimated. Returns three `Coin` objects: base, quote, and deep. Some base quantity may be left over, if the input quantity is not divisible by lot size. + +You can overestimate the amount of DEEP required. The remaining balance is returned. + +```move +public fun swap_exact_base_for_quote( + self: &mut Pool, + base_in: Coin, + deep_in: Coin, + clock: &Clock, + ctx: &mut TxContext, +): (Coin, Coin, Coin) +``` + +### Swap exact quote for base + +Swap exact quote quantity without needing a `balance_manager`. You can overestimate DEEP quantity. Returns three `Coin` objects: + - `BaseAsset` + - `QuoteAsset` + - `DEEP` + +Some quote quantity might be left over if the input quantity is not divisible by lot size. + +```move +public fun swap_exact_quote_for_base( + self: &mut Pool, + quote_in: Coin, + deep_in: Coin, + clock: &Clock, + ctx: &mut TxContext, +): (Coin, Coin, Coin) +``` + +### Swap exact quantity + +This function is what the previous two functions call with `coin::zer()` set for the third coin. Users can call this directly for base → quote or quote → base as long as base or quote have a zero value. + +```move +/// Swap exact quantity without needing an balance_manager. +public fun swap_exact_quantity( + self: &mut Pool, + base_in: Coin, + quote_in: Coin, + deep_in: Coin, + clock: &Clock, + ctx: &mut TxContext, +): (Coin, Coin, Coin) +``` \ No newline at end of file diff --git a/docs/site/static/doc/deepbook.pdf b/docs/site/static/doc/deepbook.pdf new file mode 100644 index 0000000000000..29369d26149f8 Binary files /dev/null and b/docs/site/static/doc/deepbook.pdf differ diff --git a/docs/site/vercel.json b/docs/site/vercel.json index 5cddd73361c08..5b7660d18f693 100644 --- a/docs/site/vercel.json +++ b/docs/site/vercel.json @@ -100,6 +100,12 @@ { "source": "/concepts/sui-move-concepts/patterns/id-pointer", "destination": "https://move-book.com/storage/uid-and-id.html", "permanent": true }, { "source": "/concepts/sui-move-concepts/patterns/transferrable-witness", "destination": "https://move-book.com/programmability/witness-pattern.html", "permanent": true }, { "source": "/guides/developer/advanced/asset-tokenization", "destination": "/guides/developer/nft/asset-tokenization", "permanent": true }, - { "source": "/references/move/move-toml", "destination": "https://move-book.com/concepts/manifest.html", "permanent": true } + { "source": "/references/move/move-toml", "destination": "https://move-book.com/concepts/manifest.html", "permanent": true }, + { "source": "/standards/deepbook-pools", "destination": "/standards/deepbookv2/pools", "permanent": true }, + { "source": "/standards/routing-a-swap", "destination": "/standards/deepbookv2/routing-a-swap", "permanent": true }, + { "source": "/standards/trade-and-swap", "destination": "/standards/deepbookv2/trade-and-swap", "permanent": true }, + { "source": "/standards/query-the-pool", "destination": "/standards/deepbookv2/query-the-pool", "permanent": true }, + { "source": "/standards/deepbook-design", "destination": "/standards/deepbookv2/design", "permanent": true }, + { "source": "/standards/deepbook-orders", "destination": "/standards/deepbookv2/orders", "permanent": true } ] }