### Complete Margin Pool Setup Workflow Source: https://docs.sui.io/standards/deepbook/-margin-sdk/maintainer Orchestrates the complete setup process for a new margin pool, including creating protocol configurations, instantiating the pool, and enabling it for borrowing against specific DeepBook pools. This function streamlines the deployment of new margin pools. ```typescript setupNewMarginPool = (tx: Transaction) => { const coinKey = 'SUI'; // Step 1: Create protocol config const poolConfig = tx.add( this.maintainerContract.newProtocolConfig( coinKey, { supplyCap: 1_000_000, // 1M SUI maxUtilizationRate: 0.75, referralSpread: 0.1, minBorrow: 10, }, { baseRate: 0.01, baseSlope: 0.08, optimalUtilization: 0.8, excessSlope: 0.8, }, ), ); // Step 2: Create the margin pool tx.add(this.maintainerContract.createMarginPool(coinKey, poolConfig)); // Step 3: Enable specific DeepBook pools for borrowing const marginPoolCapId = '0x...'; // Get from pool creation event tx.add(this.maintainerContract.enableDeepbookPoolForLoan('SUI_DBUSDC', coinKey, marginPoolCapId)); tx.add(this.maintainerContract.enableDeepbookPoolForLoan('SUI_USDT', coinKey, marginPoolCapId)); }; ``` -------------------------------- ### Example Asset Response Source: https://docs.sui.io/standards/deepbook/v3-indexer An example of a successful response from the /assets endpoint, showcasing the structure and data for specific assets like Sui Name Service (NS) and AUSD. ```json { "NS": { "unified_cryptoasset_id": "32942", "name": "Sui Name Service", "contractAddress": "0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178", "contractAddressUrl": "https://suiscan.xyz/mainnet/object/0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178", "can_deposit": "true", "can_withdraw": "true" }, "AUSD": { "unified_cryptoasset_id": "32864", "name": "AUSD", "contractAddress": "0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2", "contractAddressUrl": "https://suiscan.xyz/mainnet/object/0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2", "can_deposit": "true", "can_withdraw": "true" } } ``` -------------------------------- ### Get Points API Request (HTTP) Source: https://docs.sui.io/standards/deepbook/v3-indexer An example HTTP GET request to the '/get_points' endpoint. It demonstrates how to pass a comma-separated list of addresses as a query parameter to retrieve their points. ```http /get_points?addresses=0x344c2734b1d211bd15212bfb7847c66a3b18803f3f5ab00f5ff6f87b6fe6d27d,0x47dcbbc8561fe3d52198336855f0983878152a12524749e054357ac2e3573d58 ``` -------------------------------- ### Install DeepBook Margin SDK Source: https://docs.sui.io/standards/deepbook/-margin-sdk Installs the `@mysten/deepbook-v3` package, which contains the margin trading functionality, using npm or yarn. ```sh npm install @mysten/deepbook-v3 ``` -------------------------------- ### Install DeepBookV3 SDK using npm or yarn Source: https://docs.sui.io/standards/deepbook/v3-sdk Instructions on how to install the DeepBookV3 SDK package using either npm or yarn. This is the first step to integrating the SDK into your project. ```shell npm install @mysten/deepbook-v3 # or yarn add @mysten/deepbook-v3 ``` -------------------------------- ### Demonstrate DeepBook Margin Trading Operations (TypeScript) Source: https://docs.sui.io/standards/deepbook/-margin-sdk An example demonstrating margin trading operations using the DeepBookMarginTrader client. It shows how to deposit funds, borrow assets, place leveraged limit orders, and supply assets to a margin pool. This example assumes default pools and coins are used. ```typescript (async () => { const privateKey = ''; // Can encapsulate this in a .env file // Initialize with margin managers if created const marginManagers = { MARGIN_MANAGER_1: { address: '', poolKey: 'SUI_DBUSDC', }, }; const traderClient = new DeepBookMarginTrader(privateKey, 'testnet', marginManagers); const tx = new Transaction(); // Margin manager contract calls traderClient.client.deepbook.marginManager.deposit('MARGIN_MANAGER_1', 'DBUSDC', 10000)(tx); traderClient.client.deepbook.marginManager.borrowBase('MARGIN_MANAGER_1', 'SUI_DBUSDC', 100)(tx); // Place leveraged orders traderClient.client.deepbook.poolProxy.placeLimitOrder({ poolKey: 'SUI_DBUSDC', marginManagerKey: 'MARGIN_MANAGER_1', clientOrderId: '12345', price: 2.5, quantity: 100, isBid: true, payWithDeep: true, })(tx); // Margin pool operations const supplierCap = tx.add(traderClient.client.deepbook.marginPool.mintSupplierCap()); traderClient.client.deepbook.marginPool.supplyToMarginPool('DBUSDC', supplierCap, 5000)(tx); let res = await traderClient.signAndExecute(tx); console.dir(res, { depth: null }); })(); ``` -------------------------------- ### Get Points API Response Example (JSON) Source: https://docs.sui.io/standards/deepbook/v3-indexer This JSON structure shows a successful response from the '/get_points' API, detailing the total points for specified addresses. It's a common format for returning user-specific data. ```json [ { "address": "0x344c2734b1d211bd15212bfb7847c66a3b18803f3f5ab00f5ff6f87b6fe6d27d", "total_points": 1250000 }, { "address": "0x47dcbbc8561fe3d52198336855f0983878152a12524749e054357ac2e3573d58", "total_points": 750000 } ] ``` -------------------------------- ### Example OHLCV Candlestick Data Request Source: https://docs.sui.io/standards/deepbook/v3-indexer An example HTTP request to the /ohclv endpoint to fetch hourly candlestick data for the SUI_USDC pool, limited to the last 10 candles. ```http /ohclv/SUI_USDC?interval=1h&limit=10 ``` -------------------------------- ### DeepBookMarketMaker Flash Loan Example Source: https://docs.sui.io/standards/deepbook/v3-sdk/flash-loans This TypeScript example demonstrates a complete flash loan transaction within a `DeepBookMarketMaker` class. It includes borrowing base assets, executing trades using borrowed assets, and returning the borrowed assets to settle the loan. ```typescript // Example of a flash loan transaction // Borrow 1 DEEP from DEEP_SUI pool // Swap 0.5 DBUSDC for SUI in SUI_DBUSDC pool, pay with deep borrowed // Swap SUI back to DEEP // Return 1 DEEP to DEEP_SUI pool flashLoanExample = async (tx: Transaction) => { const borrowAmount = 1; const [deepCoin, flashLoan] = tx.add(this.flashLoans.borrowBaseAsset('DEEP_SUI', borrowAmount)); // Execute trade using borrowed DEEP const [baseOut, quoteOut, deepOut] = tx.add( this.deepBook.swapExactQuoteForBase({ poolKey: 'SUI_DBUSDC', amount: 0.5, deepAmount: 1, minOut: 0, deepCoin: deepCoin, }), ); tx.transferObjects([baseOut, quoteOut, deepOut], this.getActiveAddress()); // Execute second trade to get back DEEP for repayment const [baseOut2, quoteOut2, deepOut2] = tx.add( this.deepBook.swapExactQuoteForBase({ poolKey: 'DEEP_SUI', amount: 10, deepAmount: 0, minOut: 0, }), ); tx.transferObjects([quoteOut2, deepOut2], this.getActiveAddress()); // Return borrowed DEEP const loanRemain = tx.add( this.flashLoans.returnBaseAsset('DEEP_SUI', borrowAmount, baseOut2, flashLoan), ); // Send the remaining coin to user's address tx.transferObjects([loanRemain], this.getActiveAddress()); }; ``` -------------------------------- ### Get Pools Source: https://docs.sui.io/standards/deepbook/v3-indexer Retrieves a list of all available trading pools and their details. ```APIDOC ## GET /get_pools ### Description Retrieves a list of all available trading pools and their details. ### Method GET ### Endpoint /get_pools ### Parameters None ### Request Example None ### Response #### Success Response (200) - **pool_id** (string) - Unique identifier for the trading pool. - **pool_name** (string) - Name of the trading pool. - **base_asset_id** (string) - Identifier for the base asset in the pool. - **base_asset_decimals** (integer) - Number of decimal places for the base asset. - **base_asset_symbol** (string) - Symbol of the base asset. - **base_asset_name** (string) - Name of the base asset. - **quote_asset_id** (string) - Identifier for the quote asset in the pool. - **quote_asset_decimals** (integer) - Number of decimal places for the quote asset. - **quote_asset_symbol** (string) - Symbol of the quote asset. - **quote_asset_name** (string) - Name of the quote asset. - **min_size** (integer) - Minimum trade size for the pool. - **lot_size** (integer) - Lot size for trading in the pool. - **tick_size** (integer) - Tick size for price fluctuations in the pool. #### Response Example ```json [ { "pool_id": "0xb663828d6217467c8a1838a03793da896cbe745b150ebd57d82f814ca579fc22", "pool_name": "DEEP_SUI", "base_asset_id": "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP", "base_asset_decimals": 6, "base_asset_symbol": "DEEP", "base_asset_name": "DeepBook Token", "quote_asset_id": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI", "quote_asset_decimals": 9, "quote_asset_symbol": "SUI", "quote_asset_name": "Sui", "min_size": 100000000, "lot_size": 10000000, "tick_size": 10000000 } ] ``` ``` -------------------------------- ### GET /assets Source: https://docs.sui.io/standards/deepbook/v3-indexer Retrieves asset information for all coins currently being traded on DeepBookV3. ```APIDOC ## GET /assets ### Description Retrieves asset information for all coins currently being traded on DeepBookV3. ### Method GET ### Endpoint /assets ### Parameters None ### Response #### Success Response (200) *The response structure for this endpoint is not detailed in the provided text. It is expected to return information about available assets.* #### Response Example *Example response not provided in the source text.* ``` -------------------------------- ### GET /assets Source: https://docs.sui.io/standards/deepbook/v3-indexer Retrieves information about available assets, including their contract addresses and deposit/withdrawal status. ```APIDOC ## GET /assets ### Description Retrieves information about available assets, including their contract addresses and deposit/withdrawal status. ### Method GET ### Endpoint /assets ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **ASSET_NAME** (object) - An object where keys are asset symbols and values are asset details. - **unified_cryptoasset_id** (string) - The unique identifier for the crypto asset. - **name** (string) - The name of the crypto asset. - **contractAddress** (string) - The contract address of the asset. - **contractAddressUrl** (string) - A URL to view the contract address on a block explorer. - **can_deposit** (string) - Indicates if deposits are enabled ('true' or 'false'). - **can_withdraw** (string) - Indicates if withdrawals are enabled ('true' or 'false'). #### Response Example ```json { "NS": { "unified_cryptoasset_id": "32942", "name": "Sui Name Service", "contractAddress": "0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178", "contractAddressUrl": "https://suiscan.xyz/mainnet/object/0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178", "can_deposit": "true", "can_withdraw": "true" }, "AUSD": { "unified_cryptoasset_id": "32864", "name": "AUSD", "contractAddress": "0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2", "contractAddressUrl": "https://suiscan.xyz/mainnet/object/0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2", "can_deposit": "true", "can_withdraw": "true" } } ``` ``` -------------------------------- ### Complete Balance Manager Setup Workflow Source: https://docs.sui.io/standards/deepbook/v3-sdk/balance-manager Executes a comprehensive workflow for setting up a balance manager, including creation with a custom owner, sharing, minting essential capabilities (TradeCap, DepositCap, WithdrawCap), and transferring these capabilities to the owner's address. ```typescript completeSetup = async (tx: Transaction) => { const ownerAddress = '0x123...'; // Step 1: Create manager with custom owner const manager = tx.add(this.balanceManager.createBalanceManagerWithOwner(ownerAddress)); // Step 2: Share the manager tx.add(this.balanceManager.shareBalanceManager(manager)); // Step 3: Mint capabilities const tradeCap = tx.add(this.balanceManager.mintTradeCap('MANAGER_1')); const depositCap = tx.add(this.balanceManager.mintDepositCap('MANAGER_1')); const withdrawCap = tx.add(this.balanceManager.mintWithdrawalCap('MANAGER_1')); // Step 4: Transfer capabilities to owner tx.transferObjects([depositCap, withdrawCap, tradeCap], ownerAddress); }; ``` -------------------------------- ### Get Trade Count API Endpoint Source: https://docs.sui.io/standards/deepbook/v3-indexer Fetches the total number of trades executed across all pools within a specified time range. Requires start and end times in Unix timestamp format. ```http /trade_count?start_time=&end_time= ``` -------------------------------- ### Example DeepBook Market Maker Usage Source: https://docs.sui.io/standards/deepbook/v3-sdk Demonstrates how to set up and use the DeepBookMarketMaker client. It includes initializing the client, performing read-only calls to check balances and order book ranges, and executing transactions for depositing and withdrawing funds via a balance manager. ```typescript (async () => { const privateKey = ''; // Can encapsulate this in a .env file // Initialize with balance managers if created const balanceManagers = { MANAGER_1: { address: '', tradeCap: '', }, }; const mmClient = new DeepBookMarketMaker(privateKey, 'testnet', balanceManagers); const tx = new Transaction(); // Read only call console.log(await mmClient.client.deepbook.checkManagerBalance('MANAGER_1', 'SUI')); console.log(await mmClient.client.deepbook.getLevel2Range('SUI_DBUSDC', 0.1, 100, true)); // Balance manager contract call mmClient.client.deepbook.balanceManager.depositIntoManager('MANAGER_1', 'DBUSDT', 10000)(tx); mmClient.client.deepbook.balanceManager.withdrawAllFromManager( 'MANAGER_1', 'DBUSDT', mmClient.getActiveAddress(), )(tx); let res = await mmClient.signAndExecute(tx); dir(res, { depth: null }); })(); ``` -------------------------------- ### Place Limit Order on Sui IO Deepbook Source: https://docs.sui.io/standards/deepbook/-margin-sdk/orders Demonstrates how to place a limit order using the `placeLimitOrder` function. It requires pool and margin manager keys, client order ID, price, quantity, and order direction (bid/ask). Optional parameters include expiration, order type, self-matching options, and whether to pay with DEEP. ```tsx // Params for limit order interface PlaceMarginLimitOrderParams { poolKey: string; marginManagerKey: string; clientOrderId: string; price: number; quantity: number; isBid: boolean; expiration?: number | bigint; orderType?: OrderType; selfMatchingOption?: SelfMatchingOptions; payWithDeep?: boolean; } // Example: Place a buy limit order for 10 SUI at $2.50 placeLimitOrder = (tx: Transaction) => { const poolKey = 'SUI_DBUSDC'; const managerKey = 'MARGIN_MANAGER_1'; tx.add( this.poolProxyContract.placeLimitOrder({ poolKey, marginManagerKey: managerKey, clientOrderId: '12345', price: 2.5, quantity: 10, isBid: true, payWithDeep: true, }), ); }; ``` -------------------------------- ### Get referral multiplier Source: https://docs.sui.io/standards/deepbook/v3/contract-information/referral Get the current multiplier for a pool referral. ```APIDOC ## Get referral multiplier ### Description Get the current multiplier for a pool referral. ### Method GET ### Endpoint /referrals/{referral_id}/multiplier ### Parameters #### Path Parameters - **referral_id** (ID) - Required - The ID of the referral to query. ### Response #### Success Response (200) - **multiplier** (f64) - The current referral multiplier. #### Response Example ```json { "multiplier": 0.5 } ``` ``` -------------------------------- ### Initialize DeepBookClient with Sui gRPC Client Source: https://docs.sui.io/standards/deepbook/v3-sdk Demonstrates how to initialize the DeepBookClient by extending a Sui gRPC client. This setup is necessary for interacting with DeepBook V3 functionalities, requiring a private key and environment selection (mainnet or testnet). ```typescript import { SuiGrpcClient } from '@mysten/sui.js/client'; import { deepbook, DeepBookClient } from '@mysten/deepbook-v3'; import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519'; import { decodeSuiPrivateKey } from '@mysten/sui.js/cryptography'; // Define ClientWithExtensions type for clarity type ClientWithExtensions = SuiGrpcClient & T; class DeepBookMarketMaker { client: ClientWithExtensions<{ deepbook: DeepBookClient }>; keypair: Ed25519Keypair; constructor(privateKey: string, env: 'testnet' | 'mainnet') { this.keypair = this.getSignerFromPK(privateKey); this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), }), ); } getSignerFromPK = (privateKey: string): Ed25519Keypair => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; getActiveAddress() { return this.keypair.toSuiAddress(); } } ``` -------------------------------- ### Get referral owner Source: https://docs.sui.io/standards/deepbook/v3/contract-information/referral Get the owner address of a pool referral object. ```APIDOC ## Get referral owner ### Description Get the owner address of a pool referral object. ### Method GET ### Endpoint /referrals/{referral_id}/owner ### Parameters #### Path Parameters - **referral_id** (ID) - Required - The ID of the referral. ### Response #### Success Response (200) - **owner_address** (Address) - The address of the referral owner. #### Response Example ```json { "owner_address": "0x1234567890abcdef1234567890abcdef1234567890" } ``` ``` -------------------------------- ### Get referral pool ID Source: https://docs.sui.io/standards/deepbook/v3/contract-information/referral Get the pool ID associated with a pool referral object. ```APIDOC ## Get referral pool ID ### Description Get the pool ID associated with a pool referral object. ### Method GET ### Endpoint /referrals/{referral_id}/pool ### Parameters #### Path Parameters - **referral_id** (ID) - Required - The ID of the referral. ### Response #### Success Response (200) - **pool_id** (ID) - The ID of the pool associated with the referral. #### Response Example ```json { "pool_id": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" } ``` ``` -------------------------------- ### Get Owner Address of a Pool Referral Source: https://docs.sui.io/standards/deepbook/v3-sdk/balance-manager Use `balanceManagerReferralOwner` to get the owner address of a pool referral (DeepBookPoolReferral). This read-only function requires the referral ID and returns a transaction object. ```typescript balanceManagerReferralOwner = (tx: Transaction, referralId: string) => { tx.add(this.balanceManager.balanceManagerReferralOwner(referralId)); }; ``` -------------------------------- ### Create Protocol Configuration Source: https://docs.sui.io/standards/deepbook/-margin-sdk/maintainer Creates a new protocol configuration object, combining margin pool settings and interest rate parameters. Returns a transaction object for further processing. ```APIDOC ## POST /maintainer/newProtocolConfig ### Description Use `newProtocolConfig` to create a new protocol configuration object combining margin pool settings and interest parameters. The call returns a function that takes a `Transaction` object. ### Method POST ### Endpoint /maintainer/newProtocolConfig ### Parameters #### Query Parameters - **coinKey** (String) - Required - Identifies the asset type. - **marginPoolConfig** (MarginPoolConfigParams) - Required - Object with margin pool settings. - **interestConfig** (InterestConfigParams) - Required - Object with interest rate parameters. ### Request Example ```json { "coinKey": "USDC", "marginPoolConfig": { "supplyCap": 1000000, "maxUtilizationRate": 0.8, "referralSpread": 0.01, "minBorrow": 10 }, "interestConfig": { "baseRate": 0.02, "baseSlope": 0.05, "optimalUtilization": 0.8, "excessSlope": 0.2 } } ``` ### Response #### Success Response (200) - **transaction** (Function) - A function that takes a `Transaction` object to finalize the configuration. #### Response Example ```json { "transaction": "" } ``` ``` -------------------------------- ### Example OHLCV Candlestick Data Response Source: https://docs.sui.io/standards/deepbook/v3-indexer An example JSON response for the OHLCV candlestick data endpoint, showing the format of the 'candles' array with sample data. ```json { "candles": [ [1738000000, 3.5, 3.6, 3.4, 3.55, 1000000], [1738003600, 3.55, 3.7, 3.5, 3.65, 1500000] ] } ``` -------------------------------- ### Initialize DeepBook Market Maker Client Source: https://docs.sui.io/standards/deepbook/v3-sdk Initializes the DeepBookMarketMaker client with a keypair and network environment. It allows for overriding default pools with a custom PoolMap and supports optional balance managers and admin capabilities. The client is extended with DeepBookClient functionalities. ```typescript export class DeepBookMarketMaker { keypair: Keypair; client: ClientWithExtensions<{ deepbook: DeepBookClient }>; constructor( keypair: string | Keypair, env: 'testnet' | 'mainnet', balanceManagers?: { [key: string]: BalanceManager }, adminCap?: string, ) { if (typeof keypair === 'string') { this.keypair = DeepBookMarketMaker.#getSignerFromPK(keypair); } else { this.keypair = keypair; } this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), balanceManagers, adminCap, }), ); } static #getSignerFromPK = (privateKey: string) => { const { schema, secretKey } = decodeSuiPrivateKey(privateKey); if (schema === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported schema: ${schema}`); }; signAndExecute = async (tx: Transaction) => { const result = await this.client.core.signAndExecuteTransaction({ ransaction: tx, signer: this.keypair, include: { effects: true }, }); if (result.$kind === 'FailedTransaction') { throw new Error('Transaction failed'); } return result.Transaction; }; getActiveAddress() { return this.keypair.getPublicKey().toSuiAddress(); } } ``` -------------------------------- ### DeepBookClient Initialization with Sui Source: https://docs.sui.io/standards/deepbook/-margin-sdk Initializes the DeepBook client by extending a Sui gRPC client with DeepBook functionality. It requires a private key for signing and the network environment (testnet or mainnet). The client is configured with the appropriate network endpoint and DeepBook address. ```tsx class DeepBookMarginTrader { client: ClientWithExtensions<{ deepbook: DeepBookClient }>; keypair: Ed25519Keypair; constructor(privateKey: string, env: 'testnet' | 'mainnet') { this.keypair = this.getSignerFromPK(privateKey); this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), }), ); } getSignerFromPK = (privateKey: string): Ed25519Keypair => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; getActiveAddress() { return this.keypair.toSuiAddress(); } } ``` -------------------------------- ### Get Pool ID Associated with a Pool Referral Source: https://docs.sui.io/standards/deepbook/v3-sdk/balance-manager Use `balanceManagerReferralPoolId` to get the pool ID associated with a pool referral (DeepBookPoolReferral). This read-only function requires the referral ID and returns a transaction object. ```typescript balanceManagerReferralPoolId = (tx: Transaction, referralId: string) => { tx.add(this.balanceManager.balanceManagerReferralPoolId(referralId)); }; ``` -------------------------------- ### Create and Share a New Balance Manager Source: https://docs.sui.io/standards/deepbook/v3-sdk/balance-manager Example demonstrating how to create and share a new balance manager using the `createAndShareBalanceManager` function. This function adds the operation to a transaction object. ```typescript createBalanceManager = (tx: Transaction) => { tx.add(this.balanceManager.createAndShareBalanceManager()); }; ``` -------------------------------- ### Get Referral Fee Events API Request (HTTP) Source: https://docs.sui.io/standards/deepbook/v3-indexer This HTTP GET request format is used to retrieve referral fee events. It requires 'pool_id' and 'referral_id' as parameters to filter the events. ```http /referral_fee_events?pool_id=&referral_id= ``` -------------------------------- ### Place Market Order on Sui IO Deepbook Source: https://docs.sui.io/standards/deepbook/-margin-sdk/orders Shows how to place a market order using `placeMarketOrder`. This function requires pool and margin manager keys, a client order ID, quantity, and order direction. It also supports the `payWithDeep` option. ```tsx // Example: Place a market sell order for 5 SUI placeMarketOrder = (tx: Transaction) => { const poolKey = 'SUI_DBUSDC'; const managerKey = 'MARGIN_MANAGER_1'; tx.add( this.poolProxyContract.placeMarketOrder({ poolKey, marginManagerKey: managerKey, clientOrderId: '12346', quantity: 5, isBid: false, payWithDeep: true, }), ); }; ``` -------------------------------- ### Initialize DeepBook Margin Trader Client (TypeScript) Source: https://docs.sui.io/standards/deepbook/-margin-sdk Initializes the DeepBookMarginTrader client with a private key, network environment, and optional margin managers. It sets up the necessary client connections for interacting with DeepBook services on the Sui network. Dependencies include the Sui gRPC client and DeepBook extensions. ```typescript export class DeepBookMarginTrader { keypair: Keypair; client: ClientWithExtensions<{ deepbook: DeepBookClient }>; constructor( keypair: string | Keypair, env: 'testnet' | 'mainnet', marginManagers?: { [key: string]: MarginManager }, maintainerCap?: string, ) { if (typeof keypair === 'string') { this.keypair = DeepBookMarginTrader.#getSignerFromPK(keypair); } this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), marginManagers, marginMaintainerCap: maintainerCap, }), ); } static #getSignerFromPK = (privateKey: string) => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; signAndExecute = async (tx: Transaction) => { const result = await this.client.core.signAndExecuteTransaction({ transaction: tx, signer: this.keypair, include: { effects: true }, }); if (result.$kind === 'FailedTransaction') { throw new Error('Transaction failed'); } return result.Transaction; }; getActiveAddress() { return this.keypair.getPublicKey().toSuiAddress(); } } ``` -------------------------------- ### Place Reduce-Only Order on Sui IO Deepbook Source: https://docs.sui.io/standards/deepbook/-margin-sdk/orders Illustrates placing a reduce-only limit order with `placeReduceOnlyLimitOrder`. This is useful for closing existing positions without opening new ones. It requires similar parameters to a limit order, including `isBid` to specify if it's reducing a short or long position. ```tsx // Example: Place a reduce-only limit order to close a position placeReduceOnly = (tx: Transaction) => { const poolKey = 'SUI_DBUSDC'; const managerKey = 'MARGIN_MANAGER_1'; tx.add( this.poolProxyContract.placeReduceOnlyLimitOrder({ poolKey, marginManagerKey: managerKey, clientOrderId: '12347', price: 2.6, quantity: 10, isBid: true, // Buying back to reduce short position payWithDeep: true, }), ); }; ``` -------------------------------- ### Get Historical Volume for Specific Pools (HTTP) Source: https://docs.sui.io/standards/deepbook/v3-indexer Fetches historical trading volume for specified pools within a given time range. Users can choose to get volume in the base or quote asset. Pool names are comma-delimited, and time is specified using Unix timestamps. ```http GET /historical_volume/:pool_names?start_time=&end_time=&volume_in_base= ``` -------------------------------- ### Initialize DeepBook Client with Existing Margin Manager (TypeScript) Source: https://docs.sui.io/standards/deepbook/-margin-sdk This snippet demonstrates how to initialize the DeepBook client with a pre-existing margin manager. It requires the client to be configured with the margin manager's address and pool key, typically loaded from environment variables. ```typescript config(); const MARGIN_MANAGER_KEY = 'MARGIN_MANAGER_1'; class DeepBookMarginTrader { client: ClientWithExtensions<{ deepbook: DeepBookClient }>; keypair: Ed25519Keypair; constructor(privateKey: string, env: 'testnet' | 'mainnet') { this.keypair = this.getSignerFromPK(privateKey); this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), marginManagers: this.getMarginManagers(), }), ); } getSignerFromPK = (privateKey: string): Ed25519Keypair => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; getActiveAddress() { return this.keypair.toSuiAddress(); } getMarginManagers(): { [key: string]: MarginManager } { const marginManagerAddress = process.env.MARGIN_MANAGER_ADDRESS; const poolKey = process.env.POOL_KEY || 'SUI_DBUSDC'; if (!marginManagerAddress) { throw new Error('No margin manager address found'); } return { [MARGIN_MANAGER_KEY]: { address: marginManagerAddress, poolKey: poolKey, }, }; } } ``` -------------------------------- ### GET /deep_supply Source: https://docs.sui.io/standards/deepbook/v3-indexer Retrieves the total supply of DEEP tokens. ```APIDOC ## GET /deep_supply ### Description Returns the total supply of DEEP tokens. ### Method GET ### Endpoint /deep_supply ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **total_supply** (string) - The total supply of DEEP tokens. #### Response Example ```json { "total_supply": "1000000000" } ``` ``` -------------------------------- ### Initialize Deepbook Client with Existing Balance Manager (TypeScript) Source: https://docs.sui.io/standards/deepbook/v3-sdk This snippet demonstrates how to initialize the Deepbook client with an existing balance manager. It requires the balance manager address and trade capability to be set in the environment variables. The client is extended with DeepBookClient functionality. ```typescript config(); const BALANCE_MANAGER_KEY = 'MANAGER_1'; class DeepBookMarketMaker { client: ClientWithExtensions<{ deepbook: DeepBookClient }>; keypair: Ed25519Keypair; constructor(privateKey: string, env: 'testnet' | 'mainnet') { this.keypair = this.getSignerFromPK(privateKey); this.client = new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), balanceManagers: this.getBalanceManagers(), }), ); } getSignerFromPK = (privateKey: string): Ed25519Keypair => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; getActiveAddress() { return this.keypair.toSuiAddress(); } getBalanceManagers(): { [key: string]: BalanceManager } { const balanceManagerAddress = process.env.BALANCE_MANAGER_ADDRESS; const balanceManagerTradeCap = process.env.BALANCE_MANAGER_TRADE_CAP; if (!balanceManagerAddress) { throw new Error('No balance manager address found'); } return { [BALANCE_MANAGER_KEY]: { address: balanceManagerAddress, tradeCap: balanceManagerTradeCap, }, }; } } ``` -------------------------------- ### Create and Reinitialize DeepBook Client with New Margin Manager (TypeScript) Source: https://docs.sui.io/standards/deepbook/-margin-sdk This example shows how to create a new margin manager on the blockchain and then reinitialize the DeepBook client with this newly created manager. This involves submitting a transaction to create the manager and then updating the client configuration. ```typescript const MARGIN_MANAGER_KEY = 'MARGIN_MANAGER_1'; class DeepBookMarginTrader { client: ClientWithExtensions<{ deepbook: DeepBookClient }>; keypair: Ed25519Keypair; env: 'testnet' | 'mainnet'; constructor(privateKey: string, env: 'testnet' | 'mainnet') { this.env = env; this.keypair = this.getSignerFromPK(privateKey); this.client = this.#createClient(env); } #createClient(env: 'testnet' | 'mainnet', marginManagers?: { [key: string]: MarginManager }) { return new SuiGrpcClient({ network: env, baseUrl: env === 'mainnet' ? 'https://fullnode.mainnet.sui.io:443' : 'https://fullnode.testnet.sui.io:443', }).$extend( deepbook({ address: this.getActiveAddress(), marginManagers, }), ); } getSignerFromPK = (privateKey: string): Ed25519Keypair => { const { scheme, secretKey } = decodeSuiPrivateKey(privateKey); if (scheme === 'ED25519') return Ed25519Keypair.fromSecretKey(secretKey); throw new Error(`Unsupported scheme: ${scheme}`); }; getActiveAddress() { return this.keypair.toSuiAddress(); } auto createMarginManagerAndReinitialize() { let tx = new Transaction(); const poolKey = 'SUI_DBUSDC'; tx.add(this.client.deepbook.marginManager.newMarginManager(poolKey)); const result = await this.client.core.signAndExecuteTransaction({ ransaction: tx, signer: this.keypair, include: { effects: true, objectTypes: true }, }); if (result.$kind === 'FailedTransaction') { throw new Error('Transaction failed'); } const objectTypes = result.Transaction?.objectTypes ?? {}; const marginManagerAddress = result.Transaction?.effects?.changedObjects?.find( (obj) => obj.idOperation === 'Created' && objectTypes[obj.objectId]?.includes('MarginManager'), )?.objectId; if (!marginManagerAddress) { throw new Error('Failed to create margin manager'); } const marginManagers: { [key: string]: MarginManager } = { [MARGIN_MANAGER_KEY]: { address: marginManagerAddress, poolKey: poolKey, }, }; this.client = this.#createClient(this.env, marginManagers); } } ``` -------------------------------- ### Create Interest Configuration Source: https://docs.sui.io/standards/deepbook/-margin-sdk/maintainer Creates an interest configuration object. Returns a transaction object for further processing. ```APIDOC ## POST /maintainer/newInterestConfig ### Description Use `newInterestConfig` to create an interest configuration object. The call returns a function that takes a `Transaction` object. ### Method POST ### Endpoint /maintainer/newInterestConfig ### Parameters #### Query Parameters - **interestConfig** (InterestConfigParams) - Required - Object containing interest rate parameters: - **baseRate** (Number) - Base interest rate. - **baseSlope** (Number) - Interest rate slope before kink. - **optimalUtilization** (Number) - The kink point (e.g., 0.8). - **excessSlope** (Number) - Interest rate slope after kink. ### Request Example ```json { "interestConfig": { "baseRate": 0.02, "baseSlope": 0.05, "optimalUtilization": 0.8, "excessSlope": 0.2 } } ``` ### Response #### Success Response (200) - **transaction** (Function) - A function that takes a `Transaction` object to finalize the configuration. #### Response Example ```json { "transaction": "" } ``` ``` -------------------------------- ### GET /summary Source: https://docs.sui.io/standards/deepbook/v3-indexer Returns a summary of all trading pairs in DeepBook V3, including details like last price, 24h price change, and volume. ```APIDOC ## GET /summary ### Description Returns a summary of all trading pairs in DeepBook V3, including details like last price, 24h price change, and volume. ### Method GET ### Endpoint `/summary` ### Parameters None ### Response #### Success Response (200) - **trading_pairs** (string) - The name of the trading pair. - **quote_currency** (string) - The quote currency of the trading pair. - **last_price** (float) - The last traded price. - **lowest_price_24h** (float) - The lowest price in the last 24 hours. - **highest_bid** (float) - The highest bid price. - **base_volume** (float) - The trading volume in the base currency for the last 24 hours. - **price_change_percent_24h** (float) - The percentage change in price over the last 24 hours. - **quote_volume** (float) - The trading volume in the quote currency for the last 24 hours. - **lowest_ask** (float) - The lowest ask price. - **highest_price_24h** (float) - The highest price in the last 24 hours. - **base_currency** (string) - The base currency of the trading pair. #### Response Example ```json [ { "trading_pairs": "AUSD_USDC", "quote_currency": "USDC", "last_price": 1.0006, "lowest_price_24h": 0.99905, "highest_bid": 1.0006, "base_volume": 1169.2, "price_change_percent_24h": 0.07501125168773992, "quote_volume": 1168.961637, "lowest_ask": 1.0007, "highest_price_24h": 1.00145, "base_currency": "AUSD" }, { "quote_volume": 4063809.55231, "lowest_price_24h": 0.9999, "highest_price_24h": 1.009, "base_volume": 4063883.6, "quote_currency": "USDC", "price_change_percent_24h": 0.0, "base_currency": "WUSDC", "trading_pairs": "WUSDC_USDC", "last_price": 1.0, "highest_bid": 1.0, "lowest_ask": 1.0001 }, { "price_change_percent_24h": 0.0, "quote_currency": "USDC", "lowest_price_24h": 0.0, "quote_volume": 0.0, "base_volume": 0.0, "highest_price_24h": 0.0, "lowest_ask": 1.04, "last_price": 1.04, "base_currency": "WUSDT", "highest_bid": 0.90002, "trading_pairs": "WUSDT_USDC" }, ... ] ``` ```