Skip to main content

darklake_sdk_on_chain/
lib.rs

1//! # Darklake DEX on-chain SDK
2//!
3//! A standalone SDK for interacting with Darklake AMM pools on Solana. This SDK provides two main usage flows:
4//!
5//! 1. **Transaction Functions (`_tx`)**: Return fully formatted transaction that can be signed and sent
6//! 2. **Instruction Functions (`_ix`)**: Return core instruction, allowing users to manage additional calls as needed
7//!
8//! > **⚠️ All public SDK methods are async** - require `.await` when called.
9//!
10//! > **📚 Detailed Examples**: For comprehensive examples and advanced usage patterns, see the [SDK Examples Repository](https://github.com/darklakefi/sdk-on-chain-examples).
11//!
12//! ## Internal State Management
13//!
14//! The functions are only necessary if `_ix` functions are used. As the SDK user is expected to call `load_poo` and `updated_accounts` before calling any `_ix`.
15//!
16//! The SDK includes internal chain state tracking functions:
17//! - **`load_pool`**: Loads pool data for internal state tracking
18//! - **`update_accounts`**: Updates internal state with latest chain data
19//! - **`get_order`**: Exception helper that bypasses internal cache and fetches the latest order state directly from the chain. This is used to help reduce on-chain calls when only the order is needed. Also exports `Order` struct.
20//!
21//! ## 🚀 Quick Start
22//!
23//! ### Installation
24//!
25//! Add this to your `Cargo.toml`:
26//!
27//! ```toml
28//! [dependencies]
29//! darklake-sdk-on-chain = "0.1.7"
30//! ```
31//!
32//! ### Basic Setup
33//!
34//! ```rust
35//! use darklake_sdk_on_chain::DarklakeSDK;
36//! use solana_sdk::commitment_config::CommitmentLevel;
37//!
38//! // Initialize the SDK
39//! let mut sdk = DarklakeSDK::new(
40//!     "https://api.devnet.solana.com",
41//!     CommitmentLevel::Confirmed,
42//!     true, // is_devnet
43//!     None, // label (optional, up to 10 characters)
44//!     None, // ref_code (optional, up to 20 characters)
45//! )?;
46//! ```
47//!
48//! #### Optional Parameters
49//!
50//! - **`label`**: Optional string up to 10 characters for identifying your application (Supply `None` if not needed)
51//! - **`ref_code`**: Optional string up to 20 characters for referral tracking (Supply `None` if not needed)
52//!
53//! ## 📝 Important Notes
54//!
55//! ### Versioned Transactions
56//! The SDK uses **Versioned Transactions** by default, which is the preferred approach for better performance and reduced transaction size. All transaction functions (`_tx`) return `VersionedTransaction` objects.
57//!
58//! ### Address Lookup Table
59//! For devnet usage, you can import the pre-configured address lookup table (DEVNET_LOOKUP/MAINNET_LOOKUP):
60//! ```rust
61//! use darklake_sdk_on_chain::DEVNET_LOOKUP;
62//! ```
63//!
64//! ## ⚠️ Important: SOL/WSOL Handling
65//!
66//! **The Darklake DEX does not support direct SOL pairs - only WSOL (Wrapped SOL) pairs are supported.**
67//!
68//! ### Automatic Handling (Transaction Functions)
69//! The transaction functions (`swap_tx`) automatically handle SOL/WSOL conversion by:
70//! - Adding wrap instructions when SOL is provided as input
71//! - Adding unwrap instructions when WSOL is received as output
72//!
73//! ### Manual Handling (Instruction Functions)
74//! The instruction functions (`swap_ix`, `finalize_ix`) **do not** automatically handle SOL/WSOL wrapping. When using these methods:
75//! - You must manually add wrap instructions if needed
76//! - Supply the `unwrap_wsol` parameter in `FinalizeParamsIx` if necessary or add a WSOL token account closing.
77//!
78//! ## 📖 Usage Patterns
79//!
80//! ### 1. Transaction Functions (`_tx`) - Fully Formatted Transactions
81//!
82//! These functions return complete transactions ready to be signed and sent:
83//!
84//! #### Trading (Swap)
85//!
86//! ```rust
87//! // Swap tx
88//! let (swap_tx, order_key, min_out, salt) = sdk
89//!     .swap_tx(&token_mint_x, &token_mint_y, 1_000, 1, &user_keypair.pubkey())
90//!     .await?;
91//!
92//! let tx = VersionedTransaction::try_new(swap_tx.message, &[&user_keypair])?;
93//! let res = rpc_client.send_and_confirm_transaction_with_spinner(&tx)?;
94//! ```
95//!
96//! #### Finalizing Swap
97//!
98//! ```rust
99//! let finalize_tx: solana_sdk::transaction::VersionedTransaction = sdk
100//!     .finalize_tx(&order_key, unwrap_wsol, min_out, salt, None)
101//!     .await?;
102//!
103//! let tx = VersionedTransaction::try_new(finalize_tx.message, &[&user_keypair])?;
104//! ```
105//!
106//! ### 2. Instruction Functions (`_ix`) - Core Instructions
107//!
108//! These functions return core instructions, allowing you to manage additional calls as needed:
109//!
110//! #### Trading with Manual Control
111//!
112//! ```rust
113//! sdk.load_pool(&token_mint_x, &token_mint_y).await?;
114//!
115//! sdk.update_accounts().await?;
116//!
117//! let salt = [1, 2, 3, 4, 5, 6, 7, 8];
118//! let min_out = 1;
119//!
120//! let swap_params = SwapParamsIx {
121//!     source_mint: token_mint_x,
122//!     destination_mint: token_mint_y,
123//!     token_transfer_authority: user_keypair.pubkey(),
124//!     in_amount: 1_000,
125//!     swap_mode: SwapMode::ExactIn,
126//!     min_out,
127//!     salt,
128//! };
129//!
130//! let swap_ix = sdk.swap_ix(&swap_params).await?;
131//!
132//! let recent_blockhash = rpc_client
133//!     .get_latest_blockhash()
134//!     .context("Failed to get recent blockhash")?;
135//!
136//! let address_lookup_table = get_address_lookup_table(&rpc_client, DEVNET_LOOKUP).await?;
137//!
138//! let message_v0 = v0::Message::try_compile(
139//!     &user_keypair.pubkey(),
140//!     &[swap_ix],
141//!     &[address_lookup_table.clone()],
142//!     recent_blockhash,
143//! )?;
144//!
145//! let mut transaction = VersionedTransaction {
146//!     signatures: vec![],
147//!     message: VersionedMessage::V0(message_v0),
148//! };
149//!
150//! transaction.signatures = vec![user_keypair.sign_message(&transaction.message.serialize())];
151//! ```
152//!
153//! #### Finalizing with Manual Control
154//!
155//! ```rust
156//! let finalize_params = FinalizeParamsIx {
157//!     settle_signer: user_keypair.pubkey(),
158//!     order_owner: user_keypair.pubkey(),
159//!     unwrap_wsol: false,      // Set to true if output is wrapped SOL
160//!     min_out,                 // Same min_out as swap
161//!     salt,                    // Same salt as swap
162//!     output: order.d_out,     // Fetched from on chain order
163//!     commitment: order.c_min, // Fetched from on chain order
164//!     deadline: order.deadline, // Fetched from on chain order
165//!     current_slot: rpc_client.get_slot()?,
166//! };
167//!
168//! let compute_budget_ix: Instruction = ComputeBudgetInstruction::set_compute_unit_limit(500_000);
169//!
170//! let finalize_ix = sdk.finalize_ix(&finalize_params).await?;
171//!
172//! let recent_blockhash = rpc_client
173//!     .get_latest_blockhash()
174//!     .context("Failed to get recent blockhash")?;
175//!
176//! let message_v0 = v0::Message::try_compile(
177//!     &user_keypair.pubkey(),
178//!     &[compute_budget_ix, finalize_ix],
179//!     &[address_lookup_table],
180//!     recent_blockhash,
181//! )?;
182//!
183//! let mut transaction = VersionedTransaction {
184//!     signatures: vec![],
185//!     message: VersionedMessage::V0(message_v0),
186//! };
187//!
188//! transaction.signatures = vec![user_keypair.sign_message(&transaction.message.serialize())];
189//! ```
190//!
191//! ## 🔧 API Reference
192//!
193//! ### DarklakeSDK Constructor
194//!
195//! #### `DarklakeSDK::new(rpc_endpoint, commitment_level, is_devnet, label, ref_code)`
196//!
197//! Creates a new Darklake SDK instance.
198//!
199//! **Parameters:**
200//! - `rpc_endpoint: &str` - Solana RPC endpoint URL
201//! - `commitment_level: CommitmentLevel` - Commitment level for RPC calls
202//! - `is_devnet: bool` - Whether using devnet. Currently only devnet/mainnet supported.
203//! - `label: Option<&str>` - Optional application/user label (max 10 characters). For example `Some("duck-ag")`.
204//! - `ref_code: Option<&str>` - Optional referral code (max 20 characters)
205//!
206//! **Returns:** `Result<DarklakeSDK>`
207//!
208//! **Example:**
209//! ```rust
210//! let sdk = DarklakeSDK::new(
211//!     "https://api.devnet.solana.com",
212//!     CommitmentLevel::Confirmed,
213//!     true, // is_devnet
214//!     None, // label
215//!     None, // ref_code
216//! )?;
217//! ```
218//!
219//! ### DarklakeSDK Methods
220//!
221//! #### Transaction Functions (`_tx`) - Fully Formatted Transactions
222//!
223//! - **`quote(&token_in, &token_out, amount_in)`** - Get a quote for a swap
224//! - **`swap_tx(&token_in, &token_out, amount_in, min_amount_out, &token_owner)`** - Generate swap transaction, returns `(VersionedTransaction, order_key, min_amount_out, salt)`
225//! - **`finalize_tx(&order_key, unwrap_wsol, min_out, salt, settle_signer)`** - Generate finalize transaction using parameters from swap_tx
226//!
227//! #### Instruction Functions (`_ix`) - Core Instructions
228//!
229//! - **`swap_ix(&swap_params)`** - Generate swap instruction
230//! - **`finalize_ix(&finalize_params)`** - Generate finalize instruction
231//!
232//! #### Internal State Management
233//!
234//! - **`load_pool(&token_x, &token_y)`** - Load pool data for internal state tracking
235//! - **`update_accounts()`** - Update internal state with latest chain data
236//! - **`get_order(&user, commitment_level)`** - Get order data (bypasses internal cache, fetches latest state directly from chain)
237//!
238//! ### Parameter Types
239//!
240//! #### SwapParamsIx
241//! ```rust
242//! pub struct SwapParamsIx {
243//!     pub source_mint: Pubkey,
244//!     pub destination_mint: Pubkey,
245//!     pub token_transfer_authority: Pubkey,
246//!     pub in_amount: u64,
247//!     pub swap_mode: SwapMode,
248//!     pub min_out: u64,
249//!     pub salt: [u8; 8],
250//! }
251//! ```
252//!
253//! #### FinalizeParamsIx
254//! ```rust
255//! pub struct FinalizeParamsIx {
256//!     pub settle_signer: Pubkey,
257//!     pub order_owner: Pubkey,
258//!     pub unwrap_wsol: bool, // Set to true if output is WSOL and you want to unwrap it to SOL
259//!     pub min_out: u64,
260//!     pub salt: [u8; 8],
261//!     pub output: u64,
262//!     pub commitment: [u8; 32],
263//!     pub deadline: u64,
264//!     pub current_slot: u64,
265//! }
266//! ```
267//!
268//! ## 🌐 Network Configuration
269//!
270//! SDK needs an rpc url which is used for on chain data fetching.
271//!
272//! ### Address Lookup Tables
273//! The SDK provides pre-configured address lookup tables for use with versioned transaction:
274//! - **`DEVNET_LOOKUP`**: Pre-configured address lookup table for devnet usage
275//! - **`MAINNET_LOOKUP`**: Pre-configured address lookup table for mainnet usage
276//!
277//! ```rust
278//! use darklake_sdk_on_chain::DEVNET_LOOKUP;
279//! ```
280//!
281//! ## 📈 Performance Considerations
282//!
283//! - **Proof generation**: currently non-async and blocking
284//!
285//! ## 📄 License
286//!
287//! MIT License - see LICENSE file for details.
288//!
289//! ## 🆘 Support
290//!
291//! For issues and questions:
292//! - Check the examples in the repository
293//! - Review the SDK source code
294//! - Open an issue on the repository
295//!
296//! ---
297//! **Note**: Make sure you are using the same commitment level both for your own rpc and the sdk, unless you know what you are doing.
298//!
299//! **Note**: This SDK is for interacting with the Darklake DEX on Solana. Always test thoroughly on devnet before using on mainnet.
300
301mod account_metas;
302mod amm;
303mod constants;
304mod darklake_amm;
305mod proof;
306mod reduced_amm_params;
307mod sdk;
308mod utils;
309
310pub use sdk::DarklakeSDK;
311
312pub use reduced_amm_params::{
313    AddLiquidityParamsIx, FinalizeParamsIx, InitializePoolParamsIx, RemoveLiquidityParamsIx,
314    SwapParamsIx,
315};
316
317pub use darklake_amm::Order;
318
319pub use amm::SwapMode;
320
321pub use constants::{DEVNET_LOOKUP, MAINNET_LOOKUP};