repo_id
stringclasses
279 values
file_path
stringlengths
43
179
content
stringlengths
1
4.18M
__index_level_0__
int64
0
0
solana_public_repos/orca-so/whirlpools/rust-sdk/macros
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/src/wasm_enum.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{parse::Nothing, parse_quote, Fields, ItemEnum, Result, Type}; pub fn wasm_enum_impl(item: ItemEnum, _attr: Nothing) -> Result<TokenStream> { let mut item = item; // Add attributes to u64 fields for variant in &mut item.variants { if let Fields::Named(fields) = &mut variant.fields { for field in &mut fields.named { if let Type::Path(type_path) = &field.ty { if type_path.path.is_ident("u64") { field .attrs .push(parse_quote!(#[serde(serialize_with = "crate::u64_serialize")])); field.attrs.push(parse_quote!(#[tsify(type = "bigint")])); } } } } } let expanded = quote! { #[derive(::serde::Serialize, ::serde::Deserialize, ::tsify::Tsify)] #[serde(rename_all = "camelCase")] #[tsify(from_wasm_abi, into_wasm_abi)] #item }; Ok(expanded) } #[cfg(test)] mod tests { use super::*; use syn::parse_quote; #[test] fn test_enum() { let item: ItemEnum = parse_quote! { #[existing_attr] pub enum TestEnum { A(u64, u128), B { a: u64, #[existing_attr] b: u128 }, C } }; let attr = Nothing {}; let result = wasm_enum_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [derive (:: serde :: Serialize , :: serde :: Deserialize , :: tsify :: Tsify)] # [serde (rename_all = \"camelCase\")] # [tsify (from_wasm_abi , into_wasm_abi)] # [existing_attr] pub enum TestEnum { A (u64 , u128) , B { # [serde (serialize_with = \"crate::u64_serialize\")] # [tsify (type = \"bigint\")] a : u64 , # [existing_attr] b : u128 } , C }"); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/macros
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/src/lib.rs
mod wasm_const; mod wasm_enum; mod wasm_fn; mod wasm_struct; use proc_macro::TokenStream; use syn::{parse::Nothing, parse2, Item, Result}; #[proc_macro_attribute] pub fn wasm_expose(attr: TokenStream, item: TokenStream) -> TokenStream { match wasm_expose_impl(attr, item) { Ok(expanded) => expanded, Err(err) => err.to_compile_error().into(), } } fn wasm_expose_impl(attr: TokenStream, item: TokenStream) -> Result<TokenStream> { let attr: Nothing = parse2(attr.into())?; let item: Item = parse2(item.into())?; let result = match item { Item::Struct(s) => crate::wasm_struct::wasm_struct_impl(s, attr), Item::Enum(e) => crate::wasm_enum::wasm_enum_impl(e, attr), Item::Const(c) => crate::wasm_const::wasm_const_impl(c, attr), Item::Fn(f) => crate::wasm_fn::wasm_fn_impl(f, attr), _ => Err(syn::Error::new_spanned(item, "Unexpected item")), }; result.map(|ts| ts.into()) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/macros
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/src/wasm_const.rs
use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse::Nothing, Expr, ExprUnary, ItemConst, Lit, Result, UnOp}; // FIXME: also add the rustdoc comment to the generated ts constant pub fn wasm_const_impl(item: ItemConst, _attr: Nothing) -> Result<TokenStream> { let const_name = format_ident!("_{}", item.ident); let const_type = &item.ty; let const_value = match &*item.expr { Expr::Lit(syn::ExprLit { lit, .. }) => match lit { Lit::Int(value) => Ok(quote! { #value }), Lit::Float(value) => Ok(quote! { #value }), Lit::Bool(value) => Ok(quote! { #value }), Lit::Str(value) => Ok(quote! { #value }), _ => { return Err(syn::Error::new_spanned( &item.expr, "Unsupported literal type", )) } }, Expr::Array(array) => { let elements: Result<Vec<_>> = array .elems .iter() .map(|elem| match elem { Expr::Lit(syn::ExprLit { lit, .. }) => match lit { Lit::Int(value) => Ok(quote! { #value }), Lit::Float(value) => Ok(quote! { #value }), Lit::Bool(value) => Ok(quote! { #value }), Lit::Str(value) => Ok(quote! { #value }), _ => Err(syn::Error::new_spanned( elem, "Unsupported array element type", )), }, _ => Err(syn::Error::new_spanned( elem, "Expected a literal type in array", )), }) .collect(); elements.map(|elems| quote! { [#(#elems),*] }) } Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => match &**expr { Expr::Lit(syn::ExprLit { lit, .. }) => match lit { Lit::Int(value) => Ok(quote! { -#value }), Lit::Float(value) => Ok(quote! { -#value }), _ => { return Err(syn::Error::new_spanned( &item.expr, "Unsupported literal type", )) } }, _ => { return Err(syn::Error::new_spanned( &item.expr, "Expected a literal after unary operator", )) } }, _ => { return Err(syn::Error::new_spanned( &item.expr, "Expected a literal or array", )) } }?; let expanded = quote! { #[::wasm_bindgen::prelude::wasm_bindgen(skip_jsdoc)] pub fn #const_name() -> #const_type { #const_value } #item }; Ok(expanded) } #[cfg(test)] pub mod tests { use super::*; use syn::parse_quote; #[test] fn test_usize() { let item: ItemConst = parse_quote! { #[existing_attr] pub const TICK_ARRAY_SIZE_TS: usize = 88; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _TICK_ARRAY_SIZE_TS () -> usize { 88 } # [existing_attr] pub const TICK_ARRAY_SIZE_TS : usize = 88 ;"); } #[test] fn test_float() { let item: ItemConst = parse_quote! { #[existing_attr] pub const PI_TS: f64 = 3.14; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _PI_TS () -> f64 { 3.14 } # [existing_attr] pub const PI_TS : f64 = 3.14 ;"); } #[test] fn test_negative_int() { let item: ItemConst = parse_quote! { #[existing_attr] pub const NEG_INT_TS: i32 = -42; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _NEG_INT_TS () -> i32 { - 42 } # [existing_attr] pub const NEG_INT_TS : i32 = - 42 ;"); } #[test] fn test_negative_float() { let item: ItemConst = parse_quote! { #[existing_attr] pub const NEG_FLOAT_TS: f64 = -3.14; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _NEG_FLOAT_TS () -> f64 { - 3.14 } # [existing_attr] pub const NEG_FLOAT_TS : f64 = - 3.14 ;"); } #[test] fn test_bool() { let item: ItemConst = parse_quote! { #[existing_attr] pub const IS_ENABLED_TS: bool = true; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _IS_ENABLED_TS () -> bool { true } # [existing_attr] pub const IS_ENABLED_TS : bool = true ;"); } #[test] fn test_string() { let item: ItemConst = parse_quote! { #[existing_attr] pub const NAME_TS: &str = "example"; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _NAME_TS () -> & str { \"example\" } # [existing_attr] pub const NAME_TS : & str = \"example\" ;"); } #[test] fn test_int_array() { let item: ItemConst = parse_quote! { #[existing_attr] pub const NUMBERS: [i32; 3] = [1, 2, 3]; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _NUMBERS () -> [i32 ; 3] { [1 , 2 , 3] } # [existing_attr] pub const NUMBERS : [i32 ; 3] = [1 , 2 , 3] ;"); } #[test] fn test_bool_array() { let item: ItemConst = parse_quote! { #[existing_attr] pub const BOOLS: [bool; 2] = [true, false]; }; let attr = Nothing {}; let result = wasm_const_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (skip_jsdoc)] pub fn _BOOLS () -> [bool ; 2] { [true , false] } # [existing_attr] pub const BOOLS : [bool ; 2] = [true , false] ;"); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/macros
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/src/wasm_fn.rs
use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse::Nothing, Ident, ItemFn, Result}; pub fn wasm_fn_impl(item: ItemFn, _attr: Nothing) -> Result<TokenStream> { let js_name = to_js_name(item.clone().sig.ident); let expanded = quote! { #[::wasm_bindgen::prelude::wasm_bindgen(js_name = #js_name, skip_jsdoc)] #item }; Ok(expanded) } fn to_js_name(ident: Ident) -> Ident { let mut js_name = String::new(); let mut capitalize_next = false; for (i, c) in ident.to_string().chars().enumerate() { if i == 0 { js_name.push(c.to_lowercase().next().unwrap()); } else if c == '_' { capitalize_next = true; } else if capitalize_next { js_name.push(c.to_uppercase().next().unwrap()); capitalize_next = false; } else { js_name.push(c); } } format_ident!("{}", js_name) } #[cfg(test)] mod tests { use super::*; use syn::parse_quote; #[test] fn test_fn() { let item = parse_quote! { #[existing_attr] pub fn foo_foo_bar(a: u64, b: u128) -> u64 { 42 } }; let attr = Nothing {}; let result = wasm_fn_impl(item, attr); let output = result.unwrap().to_string(); assert_eq!(output, "# [:: wasm_bindgen :: prelude :: wasm_bindgen (js_name = fooFooBar , skip_jsdoc)] # [existing_attr] pub fn foo_foo_bar (a : u64 , b : u128) -> u64 { 42 }"); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/Cargo.toml
[package] name = "orca_whirlpools" version = "0.1.0" description = "Orca's high-level rust sdk to interact with Orca's on-chain Whirlpool program." include = ["src/*"] documentation = "https://orca-so.github.io/whirlpools/" homepage = "https://orca.so" repository = "https://github.com/orca-so/whirlpools" license = "Apache-2.0" keywords = ["solana", "crypto", "defi", "dex", "amm"] authors = ["team@orca.so"] edition = "2021" [features] default = [] [dependencies] solana-program = { version = "^1.18" } solana-client = { version = "^1.18" } solana-sdk = { version = "^1.18" } solana-account-decoder = { version = "^1.18" } spl-token = { version = "^4.0" } spl-token-2022 = { version = "^3.0" } spl-memo = { version = "^4.0" } spl-associated-token-account = { version = "^3.0" } orca_whirlpools_core = { path = "../core", features = ["floats"] } orca_whirlpools_client = { path = "../client", features = ["core-types"] } bincode = { version = "^1.3" } serde = { version = "^1.0" } serde_json = { version = "^1.0" } [dev-dependencies] serial_test = { version = "^3.1" } solana-program-test = { version = "^1.18" } solana-version = { version = "^1.18" } async-trait = { version = "^0.1" } base64 = { version = "^0.20" } toml = { version = "^0.7" } tokio = { version = "1.0", features = ["sync"] } spl-pod = "0.1.0"
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/README.md
# Orca Whirlpools Rust SDK For on-chain uses, see the [client](../client) crate.
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/package.json
{ "name": "@orca-so/whirlpools-rust", "version": "0.0.1", "scripts": { "build": "cargo build", "test": "cargo test --lib", "format": "cargo clippy --fix --allow-dirty --allow-staged && cargo fmt", "lint": "cargo clippy && cargo fmt --check", "clean": "cargo clean" }, "devDependencies": { "@orca-so/whirlpools-rust-client": "*", "@orca-so/whirlpools-rust-core": "*" } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/swap.rs
use std::{error::Error, iter::zip}; use orca_whirlpools_client::{ get_oracle_address, get_tick_array_address, AccountsType, RemainingAccountsInfo, RemainingAccountsSlice, SwapV2, SwapV2InstructionArgs, TickArray, Whirlpool, }; use orca_whirlpools_core::{ get_tick_array_start_tick_index, swap_quote_by_input_token, swap_quote_by_output_token, ExactInSwapQuote, ExactOutSwapQuote, TickArrayFacade, TickFacade, TICK_ARRAY_SIZE, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{ instruction::AccountMeta, instruction::Instruction, pubkey::Pubkey, signature::Keypair, }; use crate::{ token::{get_current_transfer_fee, prepare_token_accounts_instructions, TokenAccountStrategy}, FUNDER, SLIPPAGE_TOLERANCE_BPS, }; // TODO: transfer hooks /// Represents the type of a swap operation. /// /// This enum is used to specify whether the swap is an exact input or exact output type. #[derive(Debug, Clone, PartialEq)] pub enum SwapType { /// Indicates a swap where the input token amount is specified. ExactIn, /// Indicates a swap where the output token amount is specified. ExactOut, } /// Represents the quote for a swap operation. /// /// This enum contains the details of the swap quote based on the type of swap. #[derive(Debug, Clone)] pub enum SwapQuote { /// The quote for a swap with a specified input token amount. ExactIn(ExactInSwapQuote), /// The quote for a swap with a specified output token amount. ExactOut(ExactOutSwapQuote), } /// Represents the instructions and quote for executing a token swap. /// /// This struct contains the instructions required to perform the swap, along with the computed /// quote and any additional signers required. #[derive(Debug)] pub struct SwapInstructions { /// A vector of Solana `Instruction` objects required to execute the swap. pub instructions: Vec<Instruction>, /// A `SwapQuote` representing the details of the swap. pub quote: SwapQuote, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, } fn uninitialized_tick_array(start_tick_index: i32) -> TickArrayFacade { TickArrayFacade { start_tick_index, ticks: [TickFacade::default(); TICK_ARRAY_SIZE], } } async fn fetch_tick_arrays_or_default( rpc: &RpcClient, whirlpool_address: Pubkey, whirlpool: &Whirlpool, ) -> Result<[(Pubkey, TickArrayFacade); 5], Box<dyn Error>> { let tick_array_start_index = get_tick_array_start_tick_index(whirlpool.tick_current_index, whirlpool.tick_spacing); let offset = whirlpool.tick_spacing as i32 * TICK_ARRAY_SIZE as i32; let tick_array_indexes = [ tick_array_start_index, tick_array_start_index + offset, tick_array_start_index + offset * 2, tick_array_start_index - offset, tick_array_start_index - offset * 2, ]; let tick_array_addresses: Vec<Pubkey> = tick_array_indexes .iter() .map(|&x| get_tick_array_address(&whirlpool_address, x).map(|y| y.0)) .collect::<Result<Vec<Pubkey>, _>>()?; let tick_array_infos = rpc.get_multiple_accounts(&tick_array_addresses).await?; let maybe_tick_arrays: Vec<Option<TickArrayFacade>> = tick_array_infos .iter() .map(|x| x.as_ref().and_then(|y| TickArray::from_bytes(&y.data).ok())) .map(|x| x.map(|y| y.into())) .collect(); let tick_arrays: Vec<TickArrayFacade> = maybe_tick_arrays .iter() .enumerate() .map(|(i, x)| x.unwrap_or(uninitialized_tick_array(tick_array_indexes[i]))) .collect::<Vec<TickArrayFacade>>(); let result: [(Pubkey, TickArrayFacade); 5] = zip(tick_array_addresses, tick_arrays) .collect::<Vec<(Pubkey, TickArrayFacade)>>() .try_into() .map_err(|_| "Failed to convert tick arrays to array".to_string())?; Ok(result) } /// Generates the instructions necessary to execute a token swap. /// /// This function generates instructions for executing swaps, supporting both exact input and exact output scenarios. /// It calculates the necessary accounts, tick arrays, and swap quote using the provided parameters. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client for fetching accounts and interacting with the blockchain. /// * `whirlpool_address` - The public key of the Whirlpool against which the swap will be executed. /// * `amount` - The token amount specified for the swap. For `SwapType::ExactIn`, this is the input token amount. /// For `SwapType::ExactOut`, this is the output token amount. /// * `specified_mint` - The public key of the token mint being swapped. /// * `swap_type` - The type of swap (`SwapType::ExactIn` or `SwapType::ExactOut`). /// * `slippage_tolerance_bps` - An optional slippage tolerance, in basis points (BPS). Defaults to the global setting if not provided. /// * `signer` - An optional public key of the wallet or account executing the swap. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `SwapInstructions` on success: /// * `instructions` - A vector of `Instruction` objects required to execute the swap. /// * `quote` - A `SwapQuote` providing the computed details of the swap. /// * `additional_signers` - A vector of `Keypair` objects representing any additional signers required for the instructions. /// /// # Errors /// /// Returns an error if: /// - The signer is invalid or missing. /// - The Whirlpool or token mint accounts are not found or have invalid data. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use crate::utils::load_wallet; /// use orca_whirlpools::{ /// set_whirlpools_config_address, swap_instructions, SwapType, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let wallet = load_wallet(); /// let whirlpool_address = /// Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); /// let mint_address = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); /// let input_amount = 1_000_000; /// /// let result = swap_instructions( /// &rpc, /// whirlpool_address, /// input_amount, /// mint_address, /// SwapType::ExactIn, /// Some(100), /// Some(wallet.pubkey()), /// ) /// .await /// .unwrap(); /// /// println!("Quote estimated token out: {:?}", result.quote); /// println!("Number of Instructions: {}", result.instructions.len()); /// } /// ``` pub async fn swap_instructions( rpc: &RpcClient, whirlpool_address: Pubkey, amount: u64, specified_mint: Pubkey, swap_type: SwapType, slippage_tolerance_bps: Option<u16>, signer: Option<Pubkey>, ) -> Result<SwapInstructions, Box<dyn Error>> { let slippage_tolerance_bps = slippage_tolerance_bps.unwrap_or(*SLIPPAGE_TOLERANCE_BPS.try_lock()?); let signer = signer.unwrap_or(*FUNDER.try_lock()?); if signer == Pubkey::default() { return Err("Signer must be provided".into()); } let whirlpool_info = rpc.get_account(&whirlpool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_info.data)?; let specified_input = swap_type == SwapType::ExactIn; let specified_token_a = specified_mint == whirlpool.token_mint_a; let a_to_b = specified_token_a == specified_input; let tick_arrays = fetch_tick_arrays_or_default(rpc, whirlpool_address, &whirlpool).await?; let mint_infos = rpc .get_multiple_accounts(&[whirlpool.token_mint_a, whirlpool.token_mint_b]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or(format!("Mint a not found: {}", whirlpool.token_mint_a))?; let mint_b_info = mint_infos[1] .as_ref() .ok_or(format!("Mint b not found: {}", whirlpool.token_mint_b))?; let oracle_address = get_oracle_address(&whirlpool_address)?.0; let current_epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), current_epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), current_epoch); let quote = match swap_type { SwapType::ExactIn => SwapQuote::ExactIn(swap_quote_by_input_token( amount, specified_token_a, slippage_tolerance_bps, whirlpool.clone().into(), tick_arrays.map(|x| x.1).into(), transfer_fee_a, transfer_fee_b, )?), SwapType::ExactOut => SwapQuote::ExactOut(swap_quote_by_output_token( amount, specified_token_a, slippage_tolerance_bps, whirlpool.clone().into(), tick_arrays.map(|x| x.1).into(), transfer_fee_a, transfer_fee_b, )?), }; let max_in_amount = match quote { SwapQuote::ExactIn(quote) => quote.token_in, SwapQuote::ExactOut(quote) => quote.token_max_in, }; let token_a_spec = if a_to_b { TokenAccountStrategy::WithBalance(whirlpool.token_mint_a, max_in_amount) } else { TokenAccountStrategy::WithoutBalance(whirlpool.token_mint_a) }; let token_b_spec = if a_to_b { TokenAccountStrategy::WithoutBalance(whirlpool.token_mint_b) } else { TokenAccountStrategy::WithBalance(whirlpool.token_mint_b, max_in_amount) }; let mut instructions: Vec<Instruction> = Vec::new(); let token_accounts = prepare_token_accounts_instructions(rpc, signer, vec![token_a_spec, token_b_spec]).await?; instructions.extend(token_accounts.create_instructions); let other_amount_threshold = match quote { SwapQuote::ExactIn(quote) => quote.token_min_out, SwapQuote::ExactOut(quote) => quote.token_max_in, }; let token_owner_account_a = token_accounts .token_account_addresses .get(&whirlpool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&whirlpool.token_mint_b) .ok_or("Token B owner account not found")?; let swap_instruction = SwapV2 { token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, token_authority: signer, whirlpool: whirlpool_address, token_mint_a: whirlpool.token_mint_a, token_mint_b: whirlpool.token_mint_b, token_owner_account_a: *token_owner_account_a, token_vault_a: whirlpool.token_vault_a, token_owner_account_b: *token_owner_account_b, token_vault_b: whirlpool.token_vault_b, tick_array0: tick_arrays[0].0, tick_array1: tick_arrays[1].0, tick_array2: tick_arrays[2].0, oracle: oracle_address, } .instruction_with_remaining_accounts( SwapV2InstructionArgs { amount, other_amount_threshold, sqrt_price_limit: 0, amount_specified_is_input: specified_input, a_to_b, remaining_accounts_info: Some(RemainingAccountsInfo { slices: vec![RemainingAccountsSlice { accounts_type: AccountsType::SupplementalTickArrays, length: 2, }], }), }, &[ AccountMeta::new(tick_arrays[3].0, false), AccountMeta::new(tick_arrays[4].0, false), ], ); instructions.push(swap_instruction); instructions.extend(token_accounts.cleanup_instructions); Ok(SwapInstructions { instructions, quote, additional_signers: token_accounts.additional_signers, }) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/decrease_liquidity.rs
use std::{ collections::HashSet, error::Error, time::{SystemTime, UNIX_EPOCH}, }; use orca_whirlpools_client::{ get_position_address, get_tick_array_address, Position, TickArray, Whirlpool, }; use orca_whirlpools_client::{ ClosePosition, ClosePositionWithTokenExtensions, CollectFeesV2, CollectFeesV2InstructionArgs, CollectRewardV2, CollectRewardV2InstructionArgs, DecreaseLiquidityV2, DecreaseLiquidityV2InstructionArgs, }; use orca_whirlpools_core::{ collect_fees_quote, collect_rewards_quote, decrease_liquidity_quote, decrease_liquidity_quote_a, decrease_liquidity_quote_b, get_tick_array_start_tick_index, get_tick_index_in_array, CollectFeesQuote, CollectRewardsQuote, DecreaseLiquidityQuote, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{account::Account, instruction::Instruction, pubkey::Pubkey, signature::Keypair}; use spl_associated_token_account::get_associated_token_address_with_program_id; use crate::{ token::{get_current_transfer_fee, prepare_token_accounts_instructions, TokenAccountStrategy}, FUNDER, SLIPPAGE_TOLERANCE_BPS, }; // TODO: support transfer hooks /// Represents the parameters for decreasing liquidity in a pool. /// /// You must specify only one of the parameters (`TokenA`, `TokenB`, or `Liquidity`). /// Based on the provided value, the SDK computes the other two parameters. #[derive(Debug, Clone)] pub enum DecreaseLiquidityParam { /// Specifies the amount of Token A to withdraw. TokenA(u64), /// Specifies the amount of Token B to withdraw. TokenB(u64), /// Specifies the amount of liquidity to decrease. Liquidity(u128), } /// Represents the instructions and quote for decreasing liquidity in a position. #[derive(Debug)] pub struct DecreaseLiquidityInstruction { /// The quote details for decreasing liquidity, including: /// - The liquidity delta. /// - Estimated amounts of Token A and Token B to withdraw. /// - Minimum token amounts based on the specified slippage tolerance. pub quote: DecreaseLiquidityQuote, /// A vector of Solana instructions required to execute the decrease liquidity operation. pub instructions: Vec<Instruction>, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, } /// Generates instructions to decrease liquidity from an existing position. /// /// This function computes the necessary quote and creates Solana instructions to reduce liquidity /// from an existing pool position, specified by the position's mint address. /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for fetching necessary accounts and pool data. /// * `position_mint_address` - The public key of the NFT mint address representing the pool position. /// * `param` - A variant of `DecreaseLiquidityParam` specifying the liquidity reduction method (by Token A, Token B, or liquidity amount). /// * `slippage_tolerance_bps` - An optional slippage tolerance in basis points. Defaults to the global slippage tolerance if not provided. /// * `authority` - An optional public key of the account authorizing the liquidity removal. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `DecreaseLiquidityInstruction` on success: /// /// * `quote` - The computed quote for decreasing liquidity, including liquidity delta, token estimates, and minimum tokens. /// * `instructions` - A vector of `Instruction` objects required to execute the decrease liquidity operation. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// /// # Errors /// /// This function will return an error if: /// - The `authority` account is invalid or missing. /// - The position or token mint accounts are not found or have invalid data. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// decrease_liquidity_instructions, set_whirlpools_config_address, DecreaseLiquidityParam, WhirlpoolsConfigInput /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// use crate::utils::load_wallet; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let wallet = load_wallet(); /// let position_mint_address = Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); /// let param = DecreaseLiquidityParam::TokenA(1_000_000); /// let result = decrease_liquidity_instructions( /// &rpc, /// position_mint_address, /// param, /// Some(100), /// Some(wallet.pubkey()), /// ) /// .await.unwrap(); /// println!("Liquidity Increase Quote: {:?}", result.quote); /// println!("Number of Instructions: {}", result.instructions.len()); /// } /// ``` pub async fn decrease_liquidity_instructions( rpc: &RpcClient, position_mint_address: Pubkey, param: DecreaseLiquidityParam, slippage_tolerance_bps: Option<u16>, authority: Option<Pubkey>, ) -> Result<DecreaseLiquidityInstruction, Box<dyn Error>> { let slippage_tolerance_bps = slippage_tolerance_bps.unwrap_or(*SLIPPAGE_TOLERANCE_BPS.try_lock()?); let authority = authority.unwrap_or(*FUNDER.try_lock()?); if authority == Pubkey::default() { return Err("Authority must be provided".into()); } let position_address = get_position_address(&position_mint_address)?.0; let position_info = rpc.get_account(&position_address).await?; let position = Position::from_bytes(&position_info.data)?; let pool_info = rpc.get_account(&position.whirlpool).await?; let pool = Whirlpool::from_bytes(&pool_info.data)?; let mint_infos = rpc .get_multiple_accounts(&[pool.token_mint_a, pool.token_mint_b, position_mint_address]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; let position_mint_info = mint_infos[2] .as_ref() .ok_or("Position mint info not found")?; let current_epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), current_epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), current_epoch); let quote = match param { DecreaseLiquidityParam::TokenA(amount) => decrease_liquidity_quote_a( amount, slippage_tolerance_bps, pool.sqrt_price, position.tick_lower_index, position.tick_upper_index, transfer_fee_a, transfer_fee_b, ), DecreaseLiquidityParam::TokenB(amount) => decrease_liquidity_quote_b( amount, slippage_tolerance_bps, pool.sqrt_price, position.tick_lower_index, position.tick_upper_index, transfer_fee_a, transfer_fee_b, ), DecreaseLiquidityParam::Liquidity(amount) => decrease_liquidity_quote( amount, slippage_tolerance_bps, pool.sqrt_price, position.tick_lower_index, position.tick_upper_index, transfer_fee_a, transfer_fee_b, ), }?; let mut instructions: Vec<Instruction> = Vec::new(); let lower_tick_array_start_index = get_tick_array_start_tick_index(position.tick_lower_index, pool.tick_spacing); let upper_tick_array_start_index = get_tick_array_start_tick_index(position.tick_upper_index, pool.tick_spacing); let position_token_account_address = get_associated_token_address_with_program_id( &authority, &position_mint_address, &position_mint_info.owner, ); let lower_tick_array_address = get_tick_array_address(&position.whirlpool, lower_tick_array_start_index)?.0; let upper_tick_array_address = get_tick_array_address(&position.whirlpool, upper_tick_array_start_index)?.0; let token_accounts = prepare_token_accounts_instructions( rpc, authority, vec![ TokenAccountStrategy::WithoutBalance(pool.token_mint_a), TokenAccountStrategy::WithoutBalance(pool.token_mint_b), ], ) .await?; instructions.extend(token_accounts.create_instructions); let token_owner_account_a = token_accounts .token_account_addresses .get(&pool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&pool.token_mint_b) .ok_or("Token B owner account not found")?; instructions.push( DecreaseLiquidityV2 { whirlpool: position.whirlpool, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, position_authority: authority, position: position_address, position_token_account: position_token_account_address, token_mint_a: pool.token_mint_a, token_mint_b: pool.token_mint_b, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: pool.token_vault_a, token_vault_b: pool.token_vault_b, tick_array_lower: lower_tick_array_address, tick_array_upper: upper_tick_array_address, } .instruction(DecreaseLiquidityV2InstructionArgs { liquidity_amount: quote.liquidity_delta, token_min_a: quote.token_min_a, token_min_b: quote.token_min_b, remaining_accounts_info: None, }), ); instructions.extend(token_accounts.cleanup_instructions); Ok(DecreaseLiquidityInstruction { quote, instructions, additional_signers: token_accounts.additional_signers, }) } /// Represents the instructions and quotes for closing a liquidity position. /// /// This struct contains the instructions required to close a position, along with detailed /// information about the liquidity decrease, available fees to collect, and available rewards to collect. #[derive(Debug)] pub struct ClosePositionInstruction { /// A vector of `Instruction` objects required to execute the position closure. pub instructions: Vec<Instruction>, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, /// The computed quote for decreasing liquidity, including liquidity delta, token estimates, and minimum tokens. pub quote: DecreaseLiquidityQuote, /// Details of the fees available to collect from the position: /// - `fee_owed_a` - The amount of fees available to collect in token A. /// - `fee_owed_b` - The amount of fees available to collect in token B. pub fees_quote: CollectFeesQuote, /// Details of the rewards available to collect from the position: /// - `rewards` - An array containing up to three `CollectRewardQuote` entries, one for each reward token. /// - Each entry includes `rewards_owed`, the amount of the respective reward token available to collect. pub rewards_quote: CollectRewardsQuote, } /// Generates instructions to close a liquidity position. /// /// This function collects all fees and rewards, removes any remaining liquidity, and closes /// the position. It returns the necessary instructions, quotes for fees and rewards, and the /// liquidity quote for the closed position. /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for fetching accounts and pool data. /// * `position_mint_address` - The public key of the NFT mint address representing the position to be closed. /// * `slippage_tolerance_bps` - An optional slippage tolerance in basis points. Defaults to the global slippage tolerance if not provided. /// * `authority` - An optional public key of the account authorizing the transaction. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `ClosePositionInstruction` on success: /// /// * `instructions` - A vector of `Instruction` objects required to execute the position closure. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// * `quote` - The computed quote for decreasing liquidity, including liquidity delta, token estimates, and minimum tokens. /// * `fees_quote` - Details of the fees available to collect from the position: /// - `fee_owed_a` - The amount of fees available to collect in token A. /// - `fee_owed_b` - The amount of fees available to collect in token B. /// * `rewards_quote` - Details of the rewards available to collect from the position: /// - `rewards` - An array containing up to three `CollectRewardQuote` entries, one for each reward token. /// - Each entry includes `rewards_owed`, the amount of the respective reward token available to collect. /// /// # Errors /// /// This function will return an error if: /// - The `authority` account is invalid or missing. /// - The position, token mint, or reward accounts are not found or have invalid data. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use crate::utils::load_wallet; /// use orca_whirlpools::{ /// close_position_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let wallet = load_wallet(); /// /// let position_mint_address = /// Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); /// /// let result = close_position_instructions( /// &rpc, /// position_mint_address, /// Some(100), /// Some(wallet.pubkey()), /// ) /// .await /// .unwrap(); /// /// println!("Quote token max B: {:?}", result.quote.token_est_b); /// println!("Fees Quote: {:?}", result.fees_quote); /// println!("Rewards Quote: {:?}", result.rewards_quote); /// println!("Number of Instructions: {}", result.instructions.len()); /// } /// ``` pub async fn close_position_instructions( rpc: &RpcClient, position_mint_address: Pubkey, slippage_tolerance_bps: Option<u16>, authority: Option<Pubkey>, ) -> Result<ClosePositionInstruction, Box<dyn Error>> { let slippage_tolerance_bps = slippage_tolerance_bps.unwrap_or(*SLIPPAGE_TOLERANCE_BPS.try_lock()?); let authority = authority.unwrap_or(*FUNDER.try_lock()?); if authority == Pubkey::default() { return Err("Authority must be provided".into()); } let position_address = get_position_address(&position_mint_address)?.0; let position_info = rpc.get_account(&position_address).await?; let position = Position::from_bytes(&position_info.data)?; let pool_info = rpc.get_account(&position.whirlpool).await?; let pool = Whirlpool::from_bytes(&pool_info.data)?; let mint_infos = rpc .get_multiple_accounts(&[ pool.token_mint_a, pool.token_mint_b, position_mint_address, pool.reward_infos[0].mint, pool.reward_infos[1].mint, pool.reward_infos[2].mint, ]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; let position_mint_info = mint_infos[2] .as_ref() .ok_or("Position mint info not found")?; let reward_infos: Vec<Option<Account>> = pool .reward_infos .iter() .enumerate() .map(|(i, x)| { if x.mint == Pubkey::default() { None } else { mint_infos[i + 3].clone() } }) .collect(); let current_epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), current_epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), current_epoch); let quote = decrease_liquidity_quote( position.liquidity, slippage_tolerance_bps, pool.sqrt_price, position.tick_lower_index, position.tick_upper_index, transfer_fee_a, transfer_fee_b, )?; let lower_tick_array_start_index = get_tick_array_start_tick_index(position.tick_lower_index, pool.tick_spacing); let upper_tick_array_start_index = get_tick_array_start_tick_index(position.tick_upper_index, pool.tick_spacing); let position_token_account_address = get_associated_token_address_with_program_id( &authority, &position_mint_address, &position_mint_info.owner, ); let lower_tick_array_address = get_tick_array_address(&position.whirlpool, lower_tick_array_start_index)?.0; let upper_tick_array_address = get_tick_array_address(&position.whirlpool, upper_tick_array_start_index)?.0; let tick_array_infos = rpc .get_multiple_accounts(&[lower_tick_array_address, upper_tick_array_address]) .await?; let lower_tick_array_info = tick_array_infos[0] .as_ref() .ok_or("Lower tick array info not found")?; let lower_tick_array = TickArray::from_bytes(&lower_tick_array_info.data)?; let lower_tick = &lower_tick_array.ticks[get_tick_index_in_array( position.tick_lower_index, lower_tick_array_start_index, pool.tick_spacing, )? as usize]; let upper_tick_array_info = tick_array_infos[1] .as_ref() .ok_or("Upper tick array info not found")?; let upper_tick_array = TickArray::from_bytes(&upper_tick_array_info.data)?; let upper_tick = &upper_tick_array.ticks[get_tick_index_in_array( position.tick_upper_index, upper_tick_array_start_index, pool.tick_spacing, )? as usize]; let fees_quote = collect_fees_quote( pool.clone().into(), position.clone().into(), lower_tick.clone().into(), upper_tick.clone().into(), transfer_fee_a, transfer_fee_b, )?; let unix_timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(); let rewards_quote = collect_rewards_quote( pool.clone().into(), position.clone().into(), lower_tick.clone().into(), upper_tick.clone().into(), unix_timestamp, get_current_transfer_fee(reward_infos[0].as_ref(), current_epoch), get_current_transfer_fee(reward_infos[1].as_ref(), current_epoch), get_current_transfer_fee(reward_infos[2].as_ref(), current_epoch), )?; let mut required_mints: HashSet<TokenAccountStrategy> = HashSet::new(); if quote.liquidity_delta > 0 || fees_quote.fee_owed_a > 0 || fees_quote.fee_owed_b > 0 { required_mints.insert(TokenAccountStrategy::WithoutBalance(pool.token_mint_a)); required_mints.insert(TokenAccountStrategy::WithoutBalance(pool.token_mint_b)); } for i in 0..3 { if rewards_quote.rewards[i].rewards_owed > 0 { required_mints.insert(TokenAccountStrategy::WithoutBalance( pool.reward_infos[i].mint, )); } } let token_accounts = prepare_token_accounts_instructions(rpc, authority, required_mints.into_iter().collect()) .await?; let mut instructions: Vec<Instruction> = Vec::new(); instructions.extend(token_accounts.create_instructions); let token_owner_account_a = token_accounts .token_account_addresses .get(&pool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&pool.token_mint_b) .ok_or("Token B owner account not found")?; if quote.liquidity_delta > 0 { instructions.push( DecreaseLiquidityV2 { whirlpool: position.whirlpool, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, position_authority: authority, position: position_address, position_token_account: position_token_account_address, token_mint_a: pool.token_mint_a, token_mint_b: pool.token_mint_b, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: pool.token_vault_a, token_vault_b: pool.token_vault_b, tick_array_lower: lower_tick_array_address, tick_array_upper: upper_tick_array_address, } .instruction(DecreaseLiquidityV2InstructionArgs { liquidity_amount: quote.liquidity_delta, token_min_a: quote.token_min_a, token_min_b: quote.token_min_b, remaining_accounts_info: None, }), ); } if fees_quote.fee_owed_a > 0 || fees_quote.fee_owed_b > 0 { instructions.push( CollectFeesV2 { whirlpool: position.whirlpool, position_authority: authority, position: position_address, position_token_account: position_token_account_address, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: pool.token_vault_a, token_vault_b: pool.token_vault_b, token_mint_a: pool.token_mint_a, token_mint_b: pool.token_mint_b, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, } .instruction(CollectFeesV2InstructionArgs { remaining_accounts_info: None, }), ); } for i in 0..3 { if rewards_quote.rewards[i].rewards_owed == 0 { continue; } let reward_info = reward_infos[i] .as_ref() .ok_or("Reward mint info not found")?; let reward_owner = token_accounts .token_account_addresses .get(&pool.reward_infos[i].mint) .ok_or("Reward owner account not found")?; instructions.push( CollectRewardV2 { whirlpool: position.whirlpool, position_authority: authority, position: position_address, position_token_account: position_token_account_address, reward_owner_account: *reward_owner, reward_vault: pool.reward_infos[i].vault, reward_mint: pool.reward_infos[i].mint, reward_token_program: reward_info.owner, memo_program: spl_memo::ID, } .instruction(CollectRewardV2InstructionArgs { reward_index: i as u8, remaining_accounts_info: None, }), ); } match position_mint_info.owner { spl_token::ID => { instructions.push( ClosePosition { position_authority: authority, position: position_address, position_token_account: position_token_account_address, position_mint: position_mint_address, receiver: authority, token_program: spl_token::ID, } .instruction(), ); } spl_token_2022::ID => { instructions.push( ClosePositionWithTokenExtensions { position_authority: authority, position: position_address, position_token_account: position_token_account_address, position_mint: position_mint_address, receiver: authority, token2022_program: spl_token_2022::ID, } .instruction(), ); } _ => { return Err("Unsupported token program".into()); } } instructions.extend(token_accounts.cleanup_instructions); Ok(ClosePositionInstruction { instructions, additional_signers: token_accounts.additional_signers, quote, fees_quote, rewards_quote, }) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/config.rs
use std::{error::Error, sync::Mutex}; use orca_whirlpools_client::get_whirlpools_config_extension_address; use solana_program::pubkey::Pubkey; /// The Whirlpools program's config account address for Solana Mainnet. const SOLANA_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS: Pubkey = Pubkey::new_from_array([ 19, 228, 65, 248, 57, 19, 202, 104, 176, 99, 79, 176, 37, 253, 234, 168, 135, 55, 232, 65, 16, 209, 37, 94, 53, 123, 51, 119, 221, 238, 28, 205, ]); /// The Whirlpools program's config account address for Solana Devnet. const SOLANA_DEVNET_WHIRLPOOLS_CONFIG_ADDRESS: Pubkey = Pubkey::new_from_array([ 217, 51, 106, 61, 244, 143, 54, 30, 87, 6, 230, 156, 60, 182, 182, 217, 23, 116, 228, 121, 53, 200, 82, 109, 229, 160, 245, 159, 33, 90, 35, 106, ]); /// The Whirlpools program's config account address for Eclipse Mainnet. const ECLIPSE_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS: Pubkey = Pubkey::new_from_array([ 215, 64, 234, 8, 195, 52, 100, 209, 19, 230, 37, 101, 156, 135, 37, 41, 139, 254, 65, 104, 208, 137, 96, 39, 84, 13, 60, 221, 36, 203, 151, 49, ]); /// The Whirlpools program's config account address for Eclipse Testnet. const ECLIPSE_TESTNET_WHIRLPOOLS_CONFIG_ADDRESS: Pubkey = Pubkey::new_from_array([ 213, 230, 107, 150, 137, 123, 254, 203, 164, 137, 81, 181, 70, 54, 172, 140, 176, 39, 16, 72, 150, 84, 130, 137, 232, 108, 97, 236, 197, 119, 201, 83, ]); /// The default address for the Whirlpools program's config extension account. const SOLANA_MAINNET_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS: Pubkey = Pubkey::new_from_array([ 90, 182, 180, 56, 174, 38, 113, 211, 112, 187, 90, 174, 90, 115, 121, 167, 83, 122, 96, 10, 152, 57, 209, 52, 207, 240, 174, 74, 201, 7, 87, 54, ]); /// The currently selected address for the Whirlpools program's config account. pub static WHIRLPOOLS_CONFIG_ADDRESS: Mutex<Pubkey> = Mutex::new(SOLANA_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS); /// The currently selected address for the Whirlpools program's config extension account. pub static WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS: Mutex<Pubkey> = Mutex::new(SOLANA_MAINNET_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS); /// Input type for setting the Whirlpools configuration. pub enum WhirlpoolsConfigInput { Address(Pubkey), SolanaMainnet, SolanaDevnet, EclipseMainnet, EclipseTestnet, } impl From<Pubkey> for WhirlpoolsConfigInput { fn from(val: Pubkey) -> Self { WhirlpoolsConfigInput::Address(val) } } impl From<WhirlpoolsConfigInput> for Pubkey { fn from(val: WhirlpoolsConfigInput) -> Self { match val { WhirlpoolsConfigInput::Address(pubkey) => pubkey, WhirlpoolsConfigInput::SolanaMainnet => SOLANA_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS, WhirlpoolsConfigInput::SolanaDevnet => SOLANA_DEVNET_WHIRLPOOLS_CONFIG_ADDRESS, WhirlpoolsConfigInput::EclipseMainnet => ECLIPSE_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS, WhirlpoolsConfigInput::EclipseTestnet => ECLIPSE_TESTNET_WHIRLPOOLS_CONFIG_ADDRESS, } } } /// Sets the currently selected address for the Whirlpools program's config account. pub fn set_whirlpools_config_address(input: WhirlpoolsConfigInput) -> Result<(), Box<dyn Error>> { let address: Pubkey = input.into(); *WHIRLPOOLS_CONFIG_ADDRESS.try_lock()? = address; *WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS.try_lock()? = get_whirlpools_config_extension_address(&address)?.0; Ok(()) } /// The tick spacing for the SPLASH pool. pub const SPLASH_POOL_TICK_SPACING: u16 = 32896; /// The default funder for the Whirlpools program. pub const DEFAULT_FUNDER: Pubkey = Pubkey::new_from_array([0; 32]); /// The currently selected funder for the Whirlpools program. pub static FUNDER: Mutex<Pubkey> = Mutex::new(DEFAULT_FUNDER); /// Sets the currently selected funder for the Whirlpools program. pub fn set_funder(funder: Pubkey) -> Result<(), Box<dyn Error>> { *FUNDER.try_lock()? = funder; Ok(()) } /// The default slippage tolerance, expressed in basis points. Value of 100 is equivalent to 1%. pub const DEFAULT_SLIPPAGE_TOLERANCE_BPS: u16 = 100; /// The currently selected slippage tolerance, expressed in basis points. pub static SLIPPAGE_TOLERANCE_BPS: Mutex<u16> = Mutex::new(DEFAULT_SLIPPAGE_TOLERANCE_BPS); /// Sets the currently selected slippage tolerance, expressed in basis points. pub fn set_slippage_tolerance_bps(tolerance: u16) -> Result<(), Box<dyn Error>> { *SLIPPAGE_TOLERANCE_BPS.try_lock()? = tolerance; Ok(()) } /// Defines the strategy for handling SOL wrapping in a transaction. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NativeMintWrappingStrategy { /// Creates an auxiliary token account using a keypair. /// Optionally adds funds to the account. /// Closes it at the end of the transaction. Keypair, /// Functions similarly to Keypair, but uses a seed account instead. Seed, /// Treats the native balance and associated token account (ATA) for `NATIVE_MINT` as one. /// Will create the ATA if it doesn't exist. /// Optionally adds funds to the account. /// Closes it at the end of the transaction if it did not exist before. Ata, /// Uses or creates the ATA without performing any SOL wrapping or unwrapping. None, } /// The default SOL wrapping strategy. pub const DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY: NativeMintWrappingStrategy = NativeMintWrappingStrategy::Keypair; /// The currently selected SOL wrapping strategy. pub static NATIVE_MINT_WRAPPING_STRATEGY: Mutex<NativeMintWrappingStrategy> = Mutex::new(DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY); /// Sets the currently selected SOL wrapping strategy. pub fn set_native_mint_wrapping_strategy( strategy: NativeMintWrappingStrategy, ) -> Result<(), Box<dyn Error>> { *NATIVE_MINT_WRAPPING_STRATEGY.try_lock()? = strategy; Ok(()) } /// Resets the configuration to its default values. pub fn reset_configuration() -> Result<(), Box<dyn Error>> { *WHIRLPOOLS_CONFIG_ADDRESS.try_lock()? = SOLANA_MAINNET_WHIRLPOOLS_CONFIG_ADDRESS; *WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS.try_lock()? = SOLANA_MAINNET_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS; *FUNDER.try_lock()? = DEFAULT_FUNDER; *NATIVE_MINT_WRAPPING_STRATEGY.try_lock()? = DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY; *SLIPPAGE_TOLERANCE_BPS.try_lock()? = DEFAULT_SLIPPAGE_TOLERANCE_BPS; Ok(()) } #[cfg(test)] mod tests { use super::*; use serial_test::serial; use std::str::FromStr; #[test] #[serial] fn test_set_whirlpools_config_address() { let new_config = Pubkey::from_str("GdDMspJi2oQaKDtABKE24wAQgXhGBoxq8sC21st7GJ3E").unwrap(); let new_extension = Pubkey::from_str("Ez4MMUVb7VrKFcTSbi9Yz2ivXwdwCqJicnDaRHbe96Yk").unwrap(); set_whirlpools_config_address(new_config.into()).unwrap(); assert_eq!(*WHIRLPOOLS_CONFIG_ADDRESS.lock().unwrap(), new_config); assert_eq!( *WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS.lock().unwrap(), new_extension ); reset_configuration().unwrap(); } #[test] #[serial] fn test_set_whirlpools_config_address_by_network() { use std::str::FromStr; let expected_config = Pubkey::from_str("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR").unwrap(); // Replace with actual base58 value for the array let expected_extension = Pubkey::from_str("475EJ7JqnRpVLoFVzp2ruEYvWWMCf6Z8KMWRujtXXNSU").unwrap(); // Replace with the expected extension set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); assert_eq!(*WHIRLPOOLS_CONFIG_ADDRESS.lock().unwrap(), expected_config); assert_eq!( *WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS.lock().unwrap(), expected_extension ); reset_configuration().unwrap(); } #[test] #[serial] fn test_set_funder() { let new_funder = Pubkey::from_str("GdDMspJi2oQaKDtABKE24wAQgXhGBoxq8sC21st7GJ3E").unwrap(); set_funder(new_funder).unwrap(); assert_eq!(*FUNDER.lock().unwrap(), new_funder); reset_configuration().unwrap(); } #[test] #[serial] fn test_set_sol_wrapping_strategy() { let new_strategy = NativeMintWrappingStrategy::Ata; set_native_mint_wrapping_strategy(new_strategy).unwrap(); assert_eq!(*NATIVE_MINT_WRAPPING_STRATEGY.lock().unwrap(), new_strategy); reset_configuration().unwrap(); } #[test] #[serial] fn test_set_slippage_tolerance_bps() { let new_tolerance = 200; set_slippage_tolerance_bps(new_tolerance).unwrap(); assert_eq!(*SLIPPAGE_TOLERANCE_BPS.lock().unwrap(), new_tolerance); reset_configuration().unwrap(); } #[test] #[serial] fn test_reset_configuration() { let config = Pubkey::from_str("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ").unwrap(); let extension = Pubkey::from_str("777H5H3Tp9U11uRVRzFwM8BinfiakbaLT8vQpeuhvEiH").unwrap(); reset_configuration().unwrap(); assert_eq!(*WHIRLPOOLS_CONFIG_ADDRESS.lock().unwrap(), config); assert_eq!( *WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS.lock().unwrap(), extension ); assert_eq!(*FUNDER.lock().unwrap(), Pubkey::default()); assert_eq!( *NATIVE_MINT_WRAPPING_STRATEGY.lock().unwrap(), NativeMintWrappingStrategy::Keypair ); assert_eq!(*SLIPPAGE_TOLERANCE_BPS.lock().unwrap(), 100); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/token.rs
use orca_whirlpools_core::TransferFee; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::account::Account as SolanaAccount; use solana_sdk::hash::hashv; use solana_sdk::program_error::ProgramError; use solana_sdk::signature::Keypair; use solana_sdk::signer::Signer; use solana_sdk::system_instruction::{create_account, create_account_with_seed, transfer}; use solana_sdk::{instruction::Instruction, pubkey::Pubkey, system_instruction}; use spl_associated_token_account::{ get_associated_token_address_with_program_id, instruction::{create_associated_token_account, create_associated_token_account_idempotent}, }; use spl_token::instruction::{close_account, initialize_account3, sync_native}; use spl_token::solana_program::program_pack::Pack; use spl_token::{native_mint, ID as TOKEN_PROGRAM_ID}; use spl_token_2022::extension::transfer_fee::TransferFeeConfig; use spl_token_2022::extension::ExtensionType; use spl_token_2022::extension::{BaseStateWithExtensions, StateWithExtensions}; use spl_token_2022::state::{Account, Mint}; use spl_token_2022::ID as TOKEN_2022_PROGRAM_ID; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::{collections::HashMap, error::Error}; use crate::{NativeMintWrappingStrategy, NATIVE_MINT_WRAPPING_STRATEGY}; #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) enum TokenAccountStrategy { WithoutBalance(Pubkey), WithBalance(Pubkey, u64), } #[derive(Debug)] pub(crate) struct TokenAccountInstructions { pub create_instructions: Vec<Instruction>, pub cleanup_instructions: Vec<Instruction>, pub token_account_addresses: HashMap<Pubkey, Pubkey>, pub additional_signers: Vec<Keypair>, } pub(crate) async fn prepare_token_accounts_instructions( rpc: &RpcClient, owner: Pubkey, spec: Vec<TokenAccountStrategy>, ) -> Result<TokenAccountInstructions, Box<dyn Error>> { let mint_addresses: Vec<Pubkey> = spec .iter() .map(|x| match x { TokenAccountStrategy::WithoutBalance(mint) => *mint, TokenAccountStrategy::WithBalance(mint, _) => *mint, }) .collect(); let native_mint_wrapping_strategy = *NATIVE_MINT_WRAPPING_STRATEGY.try_lock()?; let native_mint_index = mint_addresses .iter() .position(|&x| x == spl_token::native_mint::ID); let has_native_mint = native_mint_index.is_some(); let maybe_mint_account_infos = rpc.get_multiple_accounts(&mint_addresses).await?; let mint_account_infos: Vec<&SolanaAccount> = maybe_mint_account_infos .iter() .map(|x| x.as_ref().ok_or(ProgramError::UninitializedAccount)) .collect::<Result<Vec<&SolanaAccount>, ProgramError>>()?; let ata_addresses: Vec<Pubkey> = mint_account_infos .iter() .enumerate() .map(|(i, x)| { get_associated_token_address_with_program_id(&owner, &mint_addresses[i], &x.owner) }) .collect(); let ata_account_infos = rpc.get_multiple_accounts(&ata_addresses).await?; let mut token_account_addresses: HashMap<Pubkey, Pubkey> = HashMap::new(); let mut create_instructions: Vec<Instruction> = Vec::new(); let mut cleanup_instructions: Vec<Instruction> = Vec::new(); let mut additional_signers: Vec<Keypair> = Vec::new(); let use_native_mint_ata = native_mint_wrapping_strategy == NativeMintWrappingStrategy::Ata || native_mint_wrapping_strategy == NativeMintWrappingStrategy::None; for i in 0..mint_addresses.len() { let mint_address = mint_addresses[i]; let ata_address = ata_addresses[i]; token_account_addresses.insert(mint_address, ata_address); if native_mint_index == Some(i) && !use_native_mint_ata { continue; } if ata_account_infos[i].is_some() { continue; } create_instructions.push(create_associated_token_account( &owner, &ata_address, &mint_address, &mint_account_infos[i].owner, )); } for i in 0..mint_addresses.len() { if native_mint_index == Some(i) && native_mint_wrapping_strategy != NativeMintWrappingStrategy::None { continue; } let existing_balance = if let Some(account_info) = &ata_account_infos[i] { if mint_account_infos[i].owner == TOKEN_2022_PROGRAM_ID { // For Token-2022 accounts, use StateWithExtensions let account_state = StateWithExtensions::<Account>::unpack(&account_info.data)?; account_state.base.amount } else { // For regular token accounts, use Account::unpack Account::unpack(&account_info.data)?.amount } } else { 0 }; let required_balance = if let TokenAccountStrategy::WithBalance(_, balance) = spec[i] { balance } else { 0 }; if existing_balance < required_balance { return Err(format!("Insufficient balance for mint {}", mint_addresses[i]).into()); } } if has_native_mint && native_mint_wrapping_strategy == NativeMintWrappingStrategy::Keypair { let keypair = Keypair::new(); let mut lamports = rpc .get_minimum_balance_for_rent_exemption(Account::LEN) .await?; if let TokenAccountStrategy::WithBalance(_, balance) = spec[native_mint_index.unwrap_or(0)] { lamports += balance; } create_instructions.push(create_account( &owner, &keypair.pubkey(), lamports, Account::LEN as u64, &TOKEN_PROGRAM_ID, )); create_instructions.push(initialize_account3( &TOKEN_PROGRAM_ID, &keypair.pubkey(), &native_mint::ID, &owner, )?); cleanup_instructions.push(close_account( &TOKEN_PROGRAM_ID, &keypair.pubkey(), &owner, &owner, &[], )?); token_account_addresses.insert(native_mint::ID, keypair.pubkey()); additional_signers.push(keypair); } if has_native_mint && native_mint_wrapping_strategy == NativeMintWrappingStrategy::Seed { let mut lamports = rpc .get_minimum_balance_for_rent_exemption(Account::LEN) .await?; if let TokenAccountStrategy::WithBalance(_, balance) = spec[native_mint_index.unwrap_or(0)] { lamports += balance; } // Generating secure seed takes longer and is not really needed here. // With date, it should only create collisions if the same owner // creates multiple accounts at exactly the same time (in ms) let seed = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or(Duration::from_secs(0)) .as_millis() .to_string(); let pubkey = Pubkey::new_from_array( hashv(&[ owner.to_bytes().as_ref(), seed.as_bytes(), TOKEN_PROGRAM_ID.to_bytes().as_ref(), ]) .to_bytes(), ); create_instructions.push(create_account_with_seed( &owner, &pubkey, &owner, &seed, lamports, Account::LEN as u64, &TOKEN_PROGRAM_ID, )); create_instructions.push(initialize_account3( &TOKEN_PROGRAM_ID, &pubkey, &native_mint::ID, &owner, )?); cleanup_instructions.push(close_account( &TOKEN_PROGRAM_ID, &pubkey, &owner, &owner, &[], )?); token_account_addresses.insert(native_mint::ID, pubkey); } if has_native_mint && native_mint_wrapping_strategy == NativeMintWrappingStrategy::Ata { let account_info = &ata_account_infos[native_mint_index.unwrap_or(0)]; let existing_balance: u64 = if let Some(account_info) = account_info { Account::unpack(&account_info.data)?.amount } else { 0 }; let required_balance = if let TokenAccountStrategy::WithBalance(_, balance) = spec[native_mint_index.unwrap_or(0)] { balance } else { 0 }; if existing_balance < required_balance { create_instructions.push(transfer( &owner, &token_account_addresses[&native_mint::ID], required_balance - existing_balance, )); create_instructions.push(sync_native( &TOKEN_PROGRAM_ID, &token_account_addresses[&native_mint::ID], )?); } // If the ATA did not exist before, we close it at the end of the transaction. if account_info.is_none() { cleanup_instructions.push(close_account( &TOKEN_PROGRAM_ID, &token_account_addresses[&native_mint::ID], &owner, &owner, &[], )?); } } Ok(TokenAccountInstructions { create_instructions, cleanup_instructions, token_account_addresses, additional_signers, }) } pub(crate) fn get_current_transfer_fee( mint_account_info: Option<&SolanaAccount>, current_epoch: u64, ) -> Option<TransferFee> { let token_mint_data = &mint_account_info?.data; let token_mint_unpacked = StateWithExtensions::<Mint>::unpack(token_mint_data).ok()?; if let Ok(transfer_fee_config) = token_mint_unpacked.get_extension::<TransferFeeConfig>() { let fee = transfer_fee_config.get_epoch_fee(current_epoch); return Some(TransferFee { fee_bps: fee.transfer_fee_basis_points.into(), max_fee: fee.maximum_fee.into(), }); } None } /// Orders two mint addresses by their canonical byte order. /// /// This function compares two Solana `Pubkey` values and returns an array where the first element /// is the smaller key in canonical byte order, and the second element is the larger key. /// /// # Arguments /// /// * `mint1` - The first mint address to compare. /// * `mint2` - The second mint address to compare. /// /// # Returns /// /// An array `[Pubkey, Pubkey]` where the first element is the smaller mint address and the second is the larger. /// /// # Example /// /// ```rust /// use solana_program::pubkey::Pubkey; /// use orca_whirlpools_sdk::order_mints; /// use std::str::FromStr; /// /// let mint1 = Pubkey::from_str("MintAddress1").unwrap(); /// let mint2 = Pubkey::from_str("MintAddress2").unwrap(); /// /// let ordered_mints = order_mints(mint1, mint2); /// println!("Ordered mints: {:?}", ordered_mints); /// ``` pub fn order_mints(mint1: Pubkey, mint2: Pubkey) -> [Pubkey; 2] { if mint1.lt(&mint2) { [mint1, mint2] } else { [mint2, mint1] } } #[cfg(test)] mod tests { use super::*; use crate::tests::{ setup_ata, setup_ata_te, setup_ata_with_amount, setup_mint, setup_mint_te, setup_mint_te_fee, setup_mint_with_decimals, RpcContext, }; use serial_test::serial; use solana_program::program_option::COption; use spl_token_2022::extension::ExtensionType; use std::str::FromStr; // 1. Basic Utility Tests #[test] fn test_order_mints() { let mint1 = Pubkey::from_str("Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa").unwrap(); let mint2 = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); let [mint_a, mint_b] = order_mints(mint1, mint2); assert_eq!(mint_a, mint1); assert_eq!(mint_b, mint2); let [mint_c, mint_d] = order_mints(mint2, mint1); assert_eq!(mint_c, mint1); assert_eq!(mint_d, mint2); } // 2. Regular Token Tests #[tokio::test] #[serial] async fn test_no_tokens() { let ctx = RpcContext::new().await; let result = prepare_token_accounts_instructions(&ctx.rpc, ctx.signer.pubkey(), vec![]) .await .unwrap(); // Verify empty result assert_eq!(result.token_account_addresses.len(), 0); } #[tokio::test] #[serial] async fn test_token_without_balance() { let ctx = RpcContext::new().await; let mint = setup_mint(&ctx).await.unwrap(); let ata = get_associated_token_address_with_program_id( &ctx.signer.pubkey(), &mint, &TOKEN_PROGRAM_ID, ); let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithoutBalance(mint)], ) .await .unwrap(); assert_eq!(result.token_account_addresses[&mint], ata); // Use idempotent version of create ATA let mut instructions = vec![create_associated_token_account_idempotent( &ctx.signer.pubkey(), &ctx.signer.pubkey(), &mint, &TOKEN_PROGRAM_ID, )]; instructions.extend(result.create_instructions); ctx.send_transaction(instructions).await.unwrap(); let account = ctx.rpc.get_account(&ata).await.unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, 0); assert_eq!(token_account.mint, mint); assert_eq!(token_account.owner, ctx.signer.pubkey()); } #[tokio::test] #[serial] async fn test_token_account_with_balance() { let ctx = RpcContext::new().await; let amount = 1_000_000u64; // Create a mint let mint = setup_mint(&ctx).await.unwrap(); // Create ATA with initial balance let ata = setup_ata_with_amount(&ctx, mint, amount).await.unwrap(); // Now prepare instructions - should not create new instructions since account exists with sufficient balance let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithBalance(mint, amount)], ) .await .unwrap(); // Verify account state let account = ctx.rpc.get_account(&ata).await.unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, amount); assert_eq!(token_account.mint, mint); assert_eq!(token_account.owner, ctx.signer.pubkey()); } #[tokio::test] #[serial] async fn test_insufficient_balance() { let ctx = RpcContext::new().await; // Create a mint and token account with small balance using token.rs helpers let mint = setup_mint(&ctx).await.unwrap(); let initial_amount = 1_000u64; let _ata = setup_ata_with_amount(&ctx, mint, initial_amount) .await .unwrap(); // Try to prepare instructions requiring more balance let required_amount = 2_000u64; let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithBalance(mint, required_amount)], ) .await; // Should fail due to insufficient balance assert!(result.is_err()); assert!(result .unwrap_err() .to_string() .contains("Insufficient balance")); } #[tokio::test] #[serial] async fn test_existing_token_account() { let ctx = RpcContext::new().await; // Create a mint and token account using token.rs helpers let mint = setup_mint(&ctx).await.unwrap(); let ata = setup_ata(&ctx, mint).await.unwrap(); // Verify initial state let initial_account = ctx.rpc.get_account(&ata).await.unwrap(); assert!(Account::unpack(&initial_account.data).is_ok()); // Try to prepare instructions for existing account let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithoutBalance(mint)], ) .await .unwrap(); // Verify account wasn't modified let final_account = ctx.rpc.get_account(&ata).await.unwrap(); assert_eq!(initial_account.data, final_account.data); } // 3. Native Token Tests #[tokio::test] #[serial] async fn test_native_mint_wrapping_none() { let ctx = RpcContext::new().await; crate::set_native_mint_wrapping_strategy(NativeMintWrappingStrategy::None).unwrap(); let ata = get_associated_token_address_with_program_id( &ctx.signer.pubkey(), &native_mint::ID, &TOKEN_PROGRAM_ID, ); let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithoutBalance(native_mint::ID)], ) .await .unwrap(); assert_eq!(result.token_account_addresses[&native_mint::ID], ata); // Use idempotent version of create ATA let mut instructions = vec![create_associated_token_account_idempotent( &ctx.signer.pubkey(), &ctx.signer.pubkey(), &native_mint::ID, &TOKEN_PROGRAM_ID, )]; instructions.extend(result.create_instructions); ctx.send_transaction(instructions).await.unwrap(); let account = ctx.rpc.get_account(&ata).await.unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, 0); } #[tokio::test] #[serial] async fn test_native_mint_wrapping_ata() { let ctx = RpcContext::new().await; crate::set_native_mint_wrapping_strategy(NativeMintWrappingStrategy::Ata).unwrap(); let ata = get_associated_token_address_with_program_id( &ctx.signer.pubkey(), &native_mint::ID, &TOKEN_PROGRAM_ID, ); let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithoutBalance(native_mint::ID)], ) .await .unwrap(); assert_eq!(result.token_account_addresses[&native_mint::ID], ata); // Use idempotent version of create ATA let mut instructions = vec![create_associated_token_account_idempotent( &ctx.signer.pubkey(), &ctx.signer.pubkey(), &native_mint::ID, &TOKEN_PROGRAM_ID, )]; instructions.extend(result.create_instructions); ctx.send_transaction(instructions).await.unwrap(); let account = ctx.rpc.get_account(&ata).await.unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, 0); assert_eq!(token_account.mint, native_mint::ID); assert_eq!(token_account.owner, ctx.signer.pubkey()); } #[tokio::test] #[serial] async fn test_native_mint_wrapping_keypair() { let ctx = RpcContext::new().await; crate::set_native_mint_wrapping_strategy(NativeMintWrappingStrategy::Keypair).unwrap(); let amount = 1_000_000u64; let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithBalance(native_mint::ID, amount)], ) .await .unwrap(); // Verify token account address is mapped correctly assert!(result .token_account_addresses .contains_key(&native_mint::ID)); let token_address = result.token_account_addresses[&native_mint::ID]; // Execute create instructions ctx.send_transaction_with_signers( result.create_instructions.clone(), result.additional_signers.iter().collect(), ) .await .unwrap(); // Verify account was created with correct state let accounts = ctx .rpc .get_multiple_accounts(&[token_address]) .await .unwrap(); let account = accounts[0].as_ref().unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, amount); assert_eq!(token_account.mint, native_mint::ID); assert_eq!(token_account.owner, ctx.signer.pubkey()); // Execute cleanup instructions ctx.send_transaction(result.cleanup_instructions) .await .unwrap(); // Verify account was cleaned up let accounts = ctx .rpc .get_multiple_accounts(&[token_address]) .await .unwrap(); assert!(accounts[0].is_none() || accounts[0].as_ref().unwrap().data.is_empty()); } #[tokio::test] #[serial] async fn test_native_mint_wrapping_seed() { let ctx = RpcContext::new().await; crate::set_native_mint_wrapping_strategy(NativeMintWrappingStrategy::Seed).unwrap(); let amount = 1_000_000u64; let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![TokenAccountStrategy::WithBalance(native_mint::ID, amount)], ) .await .unwrap(); // Verify token account address is mapped correctly assert!(result .token_account_addresses .contains_key(&native_mint::ID)); let token_address = result.token_account_addresses[&native_mint::ID]; // Execute and verify using get_multiple_accounts ctx.send_transaction_with_signers( result.create_instructions, result.additional_signers.iter().collect(), ) .await .unwrap(); let accounts = ctx .rpc .get_multiple_accounts(&[token_address]) .await .unwrap(); let account = accounts[0].as_ref().unwrap(); let token_account = Account::unpack(&account.data).unwrap(); assert_eq!(token_account.amount, amount); } #[tokio::test] #[serial] async fn test_native_token_balance() -> Result<(), Box<dyn Error>> { let ctx = RpcContext::new().await; let amount = 1_000_000_000; // 1 SOL // Setup native token (wSOL) account with balance using helper function let wsol_ata = setup_ata_with_amount(&ctx, native_mint::ID, amount).await?; // Verify the account was created and funded let account = ctx.rpc.get_account(&wsol_ata).await?; let token_account = Account::unpack(&account.data)?; assert_eq!(token_account.amount, amount); assert_eq!(token_account.mint, native_mint::ID); assert_eq!(token_account.owner, ctx.signer.pubkey()); Ok(()) } // 4. Token-2022 Tests #[tokio::test] #[serial] async fn test_token_2022_extensions() -> Result<(), Box<dyn Error>> { let ctx = RpcContext::new().await; // Create Token-2022 mint with transfer fee let mint_te = setup_mint_te_fee(&ctx).await?; let mint_account = ctx.rpc.get_account(&mint_te).await?; // Test transfer fee at epoch 0 let older = get_current_transfer_fee(Some(&mint_account), 0).unwrap(); assert_eq!(older.fee_bps, 100); // 1% assert_eq!(older.max_fee, 1_000_000_000); // 1 token // Test transfer fee at epoch 2 let newer = get_current_transfer_fee(Some(&mint_account), 2).unwrap(); assert_eq!(newer.fee_bps, 150); // 1.5% assert_eq!(newer.max_fee, 1_000_000_000); // 1 token // Test with no fee let no_fee_result = get_current_transfer_fee(None, 0); assert!(no_fee_result.is_none()); Ok(()) } // 5. Mixed Token Types Test #[tokio::test] #[serial] async fn test_multiple_token_types() { let ctx = RpcContext::new().await; // Set native mint wrapping strategy to ATA crate::set_native_mint_wrapping_strategy(NativeMintWrappingStrategy::Ata).unwrap(); // Create different types of mints let regular_mint = setup_mint(&ctx).await.unwrap(); let token_2022_mint = setup_mint_te(&ctx, &[]).await.unwrap(); // Create ATAs for each mint type let native_ata = setup_ata_with_amount(&ctx, native_mint::ID, 1_000_000) .await .unwrap(); let regular_ata = setup_ata(&ctx, regular_mint).await.unwrap(); let token_2022_ata = setup_ata_te(&ctx, token_2022_mint, None).await.unwrap(); // Verify all accounts exist let addresses = vec![native_ata, regular_ata, token_2022_ata]; let accounts = ctx.rpc.get_multiple_accounts(&addresses).await.unwrap(); assert!(accounts.iter().all(|acc| acc.is_some())); // Prepare instructions for all token types let result = prepare_token_accounts_instructions( &ctx.rpc, ctx.signer.pubkey(), vec![ TokenAccountStrategy::WithoutBalance(native_mint::ID), TokenAccountStrategy::WithoutBalance(regular_mint), TokenAccountStrategy::WithoutBalance(token_2022_mint), ], ) .await .unwrap(); // Verify token account addresses are mapped correctly assert_eq!(result.token_account_addresses[&native_mint::ID], native_ata); assert_eq!(result.token_account_addresses[&regular_mint], regular_ata); assert_eq!( result.token_account_addresses[&token_2022_mint], token_2022_ata ); // Verify correct program ID for each account type let accounts = ctx.rpc.get_multiple_accounts(&addresses).await.unwrap(); assert_eq!(accounts[0].as_ref().unwrap().owner, TOKEN_PROGRAM_ID); // Native assert_eq!(accounts[1].as_ref().unwrap().owner, TOKEN_PROGRAM_ID); // Regular assert_eq!(accounts[2].as_ref().unwrap().owner, TOKEN_2022_PROGRAM_ID); // Token-2022 } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/increase_liquidity.rs
use std::error::Error; use std::str::FromStr; use orca_whirlpools_client::{ get_position_address, get_tick_array_address, InitializeTickArray, InitializeTickArrayInstructionArgs, OpenPositionWithTokenExtensions, OpenPositionWithTokenExtensionsInstructionArgs, Position, TickArray, Whirlpool, }; use orca_whirlpools_client::{IncreaseLiquidityV2, IncreaseLiquidityV2InstructionArgs}; use orca_whirlpools_core::{ get_full_range_tick_indexes, get_initializable_tick_index, get_tick_array_start_tick_index, increase_liquidity_quote, increase_liquidity_quote_a, increase_liquidity_quote_b, order_tick_indexes, price_to_tick_index, IncreaseLiquidityQuote, TransferFee, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::account::Account; use solana_sdk::program_pack::Pack; use solana_sdk::signer::Signer; use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signature::Keypair}; use spl_associated_token_account::get_associated_token_address_with_program_id; use spl_token_2022::state::Mint; use crate::{get_rent, SPLASH_POOL_TICK_SPACING}; use crate::{ token::{get_current_transfer_fee, prepare_token_accounts_instructions, TokenAccountStrategy}, FUNDER, SLIPPAGE_TOLERANCE_BPS, }; // TODO: support transfer hooks fn get_increase_liquidity_quote( param: IncreaseLiquidityParam, slippage_tolerance_bps: u16, pool: &Whirlpool, tick_lower_index: i32, tick_upper_index: i32, transfer_fee_a: Option<TransferFee>, transfer_fee_b: Option<TransferFee>, ) -> Result<IncreaseLiquidityQuote, Box<dyn Error>> { let result = match param { IncreaseLiquidityParam::TokenA(amount) => increase_liquidity_quote_a( amount, slippage_tolerance_bps, pool.sqrt_price, tick_lower_index, tick_upper_index, transfer_fee_a, transfer_fee_b, ), IncreaseLiquidityParam::TokenB(amount) => increase_liquidity_quote_b( amount, slippage_tolerance_bps, pool.sqrt_price, tick_lower_index, tick_upper_index, transfer_fee_a, transfer_fee_b, ), IncreaseLiquidityParam::Liquidity(amount) => increase_liquidity_quote( amount, slippage_tolerance_bps, pool.sqrt_price, tick_lower_index, tick_upper_index, transfer_fee_a, transfer_fee_b, ), }?; Ok(result) } /// Represents the parameters for increasing liquidity in a position. /// /// You must choose one of the variants (`TokenA`, `TokenB`, or `Liquidity`). /// The SDK will calculate the remaining values based on the provided input. #[derive(Debug, Clone)] pub enum IncreaseLiquidityParam { /// Specifies the amount of token A to add to the position. TokenA(u64), /// Specifies the amount of token B to add to the position. TokenB(u64), /// Specifies the amount of liquidity to add to the position. Liquidity(u128), } /// Represents the instructions and quote for increasing liquidity in a position. /// /// This struct includes the necessary transaction instructions, as well as a detailed /// quote describing the liquidity increase. #[derive(Debug)] pub struct IncreaseLiquidityInstruction { /// The computed quote for increasing liquidity, including: /// - `liquidity_delta` - The change in liquidity. /// - `token_est_a` - The estimated amount of token A required. /// - `token_est_b` - The estimated amount of token B required. /// - `token_max_a` - The maximum allowable amount of token A based on slippage tolerance. /// - `token_max_b` - The maximum allowable amount of token B based on slippage tolerance. pub quote: IncreaseLiquidityQuote, /// A vector of `Instruction` objects required to execute the liquidity increase. pub instructions: Vec<Instruction>, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, } /// Generates instructions to increase liquidity for an existing position. /// /// This function computes the necessary quote and creates instructions to add liquidity /// to an existing pool position, specified by the position's mint address. /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for fetching necessary accounts and pool data. /// * `position_mint_address` - The public key of the NFT mint address representing the pool position. /// * `param` - A variant of `IncreaseLiquidityParam` specifying the liquidity addition method (by Token A, Token B, or liquidity amount). /// * `slippage_tolerance_bps` - An optional slippage tolerance in basis points. Defaults to the global slippage tolerance if not provided. /// * `authority` - An optional public key of the account authorizing the liquidity addition. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `IncreaseLiquidityInstruction` on success: /// /// * `quote` - The computed quote for increasing liquidity, including liquidity delta, token estimates, and maximum tokens based on slippage tolerance. /// * `instructions` - A vector of `Instruction` objects required to execute the liquidity addition. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// /// # Errors /// /// This function will return an error if: /// - The `authority` account is invalid or missing. /// - The position or token mint accounts are not found or have invalid data. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// increase_liquidity_instructions, set_whirlpools_config_address, IncreaseLiquidityParam, /// WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// use crate::utils::load_wallet; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let wallet = load_wallet(); /// let position_mint_address = Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); /// let param = IncreaseLiquidityParam::TokenA(1_000_000); /// /// let result = increase_liquidity_instructions( /// &rpc, /// position_mint_address, /// param, /// Some(100), /// Some(wallet.pubkey()), /// ) /// .await.unwrap(); /// /// println!("Liquidity Increase Quote: {:?}", result.quote); /// println!("Number of Instructions: {}", result.instructions.len()); /// } /// ``` pub async fn increase_liquidity_instructions( rpc: &RpcClient, position_mint_address: Pubkey, param: IncreaseLiquidityParam, slippage_tolerance_bps: Option<u16>, authority: Option<Pubkey>, ) -> Result<IncreaseLiquidityInstruction, Box<dyn Error>> { let slippage_tolerance_bps = slippage_tolerance_bps.unwrap_or(*SLIPPAGE_TOLERANCE_BPS.try_lock()?); let authority = authority.unwrap_or(*FUNDER.try_lock()?); if authority == Pubkey::default() { return Err("Authority must be provided".into()); } let position_address = get_position_address(&position_mint_address)?.0; let position_info = rpc.get_account(&position_address).await?; let position = Position::from_bytes(&position_info.data)?; let pool_info = rpc.get_account(&position.whirlpool).await?; let pool = Whirlpool::from_bytes(&pool_info.data)?; let mint_infos = rpc .get_multiple_accounts(&[pool.token_mint_a, pool.token_mint_b, position_mint_address]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; let position_mint_info = mint_infos[2] .as_ref() .ok_or("Position mint info not found")?; let current_epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), current_epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), current_epoch); let quote = get_increase_liquidity_quote( param, slippage_tolerance_bps, &pool, position.tick_lower_index, position.tick_upper_index, transfer_fee_a, transfer_fee_b, )?; let mut instructions: Vec<Instruction> = Vec::new(); let lower_tick_array_start_index = get_tick_array_start_tick_index(position.tick_lower_index, pool.tick_spacing); let upper_tick_array_start_index = get_tick_array_start_tick_index(position.tick_upper_index, pool.tick_spacing); let position_token_account_address = get_associated_token_address_with_program_id( &authority, &position_mint_address, &position_mint_info.owner, ); let lower_tick_array_address = get_tick_array_address(&position.whirlpool, lower_tick_array_start_index)?.0; let upper_tick_array_address = get_tick_array_address(&position.whirlpool, upper_tick_array_start_index)?.0; let token_accounts = prepare_token_accounts_instructions( rpc, authority, vec![ TokenAccountStrategy::WithBalance(pool.token_mint_a, quote.token_max_a), TokenAccountStrategy::WithBalance(pool.token_mint_b, quote.token_max_b), ], ) .await?; instructions.extend(token_accounts.create_instructions); let token_owner_account_a = token_accounts .token_account_addresses .get(&pool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&pool.token_mint_b) .ok_or("Token B owner account not found")?; instructions.push( IncreaseLiquidityV2 { whirlpool: position.whirlpool, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, position_authority: authority, position: position_address, position_token_account: position_token_account_address, token_mint_a: pool.token_mint_a, token_mint_b: pool.token_mint_b, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: pool.token_vault_a, token_vault_b: pool.token_vault_b, tick_array_lower: lower_tick_array_address, tick_array_upper: upper_tick_array_address, } .instruction(IncreaseLiquidityV2InstructionArgs { liquidity_amount: quote.liquidity_delta, token_max_a: quote.token_max_a, token_max_b: quote.token_max_b, remaining_accounts_info: None, }), ); instructions.extend(token_accounts.cleanup_instructions); Ok(IncreaseLiquidityInstruction { quote, instructions, additional_signers: token_accounts.additional_signers, }) } /// Represents the instructions and quote for opening a liquidity position. /// /// This struct contains the instructions required to open a new position, along with detailed /// information about the liquidity increase, the cost of initialization, and the mint address /// of the position NFT. #[derive(Debug)] pub struct OpenPositionInstruction { /// The public key of the position NFT that represents ownership of the newly opened position. pub position_mint: Pubkey, /// The computed quote for increasing liquidity, including liquidity delta, token estimates, /// and maximum tokens based on slippage tolerance. pub quote: IncreaseLiquidityQuote, /// A vector of `Instruction` objects required to execute the position opening. pub instructions: Vec<Instruction>, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, /// The cost of initializing the position, measured in lamports. pub initialization_cost: u64, } async fn internal_open_position( rpc: &RpcClient, pool_address: Pubkey, whirlpool: Whirlpool, param: IncreaseLiquidityParam, lower_tick_index: i32, upper_tick_index: i32, mint_a_info: &Account, mint_b_info: &Account, slippage_tolerance_bps: Option<u16>, funder: Option<Pubkey>, ) -> Result<OpenPositionInstruction, Box<dyn Error>> { let funder = funder.unwrap_or(*FUNDER.try_lock()?); let slippage_tolerance_bps = slippage_tolerance_bps.unwrap_or(*SLIPPAGE_TOLERANCE_BPS.try_lock()?); let rent = get_rent(rpc).await?; if funder == Pubkey::default() { return Err("Funder must be provided".into()); } let tick_range = order_tick_indexes(lower_tick_index, upper_tick_index); let lower_initializable_tick_index = get_initializable_tick_index( tick_range.tick_lower_index, whirlpool.tick_spacing, Some(false), ); let upper_initializable_tick_index = get_initializable_tick_index( tick_range.tick_upper_index, whirlpool.tick_spacing, Some(true), ); let mut instructions: Vec<Instruction> = Vec::new(); let mut non_refundable_rent: u64 = 0; let mut additional_signers: Vec<Keypair> = Vec::new(); let epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), epoch); let quote = get_increase_liquidity_quote( param, slippage_tolerance_bps, &whirlpool, lower_initializable_tick_index, upper_initializable_tick_index, transfer_fee_a, transfer_fee_b, )?; additional_signers.push(Keypair::new()); let position_mint = additional_signers[0].pubkey(); let lower_tick_start_index = get_tick_array_start_tick_index(lower_initializable_tick_index, whirlpool.tick_spacing); let upper_tick_start_index = get_tick_array_start_tick_index(upper_initializable_tick_index, whirlpool.tick_spacing); let position_address = get_position_address(&position_mint)?.0; let position_token_account_address = get_associated_token_address_with_program_id(&funder, &position_mint, &spl_token_2022::ID); let lower_tick_array_address = get_tick_array_address(&pool_address, lower_tick_start_index)?.0; let upper_tick_array_address = get_tick_array_address(&pool_address, upper_tick_start_index)?.0; let token_accounts = prepare_token_accounts_instructions( rpc, funder, vec![ TokenAccountStrategy::WithBalance(whirlpool.token_mint_a, quote.token_max_a), TokenAccountStrategy::WithBalance(whirlpool.token_mint_b, quote.token_max_b), ], ) .await?; instructions.extend(token_accounts.create_instructions); additional_signers.extend(token_accounts.additional_signers); let tick_array_infos = rpc .get_multiple_accounts(&[lower_tick_array_address, upper_tick_array_address]) .await?; if tick_array_infos[0].is_none() { instructions.push( InitializeTickArray { whirlpool: pool_address, funder, tick_array: lower_tick_array_address, system_program: solana_sdk::system_program::id(), } .instruction(InitializeTickArrayInstructionArgs { start_tick_index: lower_tick_start_index, }), ); non_refundable_rent += rent.minimum_balance(TickArray::LEN); } if tick_array_infos[1].is_none() && lower_tick_start_index != upper_tick_start_index { instructions.push( InitializeTickArray { whirlpool: pool_address, funder, tick_array: upper_tick_array_address, system_program: solana_sdk::system_program::id(), } .instruction(InitializeTickArrayInstructionArgs { start_tick_index: upper_tick_start_index, }), ); non_refundable_rent += rent.minimum_balance(TickArray::LEN); } let token_owner_account_a = token_accounts .token_account_addresses .get(&whirlpool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&whirlpool.token_mint_b) .ok_or("Token B owner account not found")?; instructions.push( OpenPositionWithTokenExtensions { funder, owner: funder, position: position_address, position_mint, position_token_account: position_token_account_address, whirlpool: pool_address, token2022_program: spl_token_2022::ID, system_program: solana_sdk::system_program::id(), associated_token_program: spl_associated_token_account::ID, metadata_update_auth: Pubkey::from_str("3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr")?, } .instruction(OpenPositionWithTokenExtensionsInstructionArgs { tick_lower_index: lower_initializable_tick_index, tick_upper_index: upper_initializable_tick_index, with_token_metadata_extension: true, }), ); instructions.push( IncreaseLiquidityV2 { whirlpool: pool_address, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, position_authority: funder, position: position_address, position_token_account: position_token_account_address, token_mint_a: whirlpool.token_mint_a, token_mint_b: whirlpool.token_mint_b, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: whirlpool.token_vault_a, token_vault_b: whirlpool.token_vault_b, tick_array_lower: lower_tick_array_address, tick_array_upper: upper_tick_array_address, } .instruction(IncreaseLiquidityV2InstructionArgs { liquidity_amount: quote.liquidity_delta, token_max_a: quote.token_max_a, token_max_b: quote.token_max_b, remaining_accounts_info: None, }), ); instructions.extend(token_accounts.cleanup_instructions); Ok(OpenPositionInstruction { position_mint, quote, instructions, additional_signers, initialization_cost: non_refundable_rent, }) } /// Opens a full-range position in a liquidity pool. /// /// This function creates a new position within the full price range for the specified pool, /// which is ideal for full-range liquidity provisioning, such as in Splash Pools. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `pool_address` - The public key of the liquidity pool. /// * `param` - Parameters for increasing liquidity, specified as `IncreaseLiquidityParam`. /// * `slippage_tolerance_bps` - An optional slippage tolerance in basis points. Defaults to the global slippage tolerance if not provided. /// * `funder` - An optional public key of the funder account. Defaults to the global funder if not provided. /// /// # Returns /// /// Returns a `Result` containing an `OpenPositionInstruction` on success, which includes: /// * `position_mint` - The mint address of the position NFT. /// * `quote` - The computed liquidity quote, including liquidity delta, token estimates, and maximum tokens. /// * `instructions` - A vector of `Instruction` objects required for creating the position. /// * `additional_signers` - A vector of `Keypair` objects for additional transaction signers. /// * `initialization_cost` - The cost of initializing the position, in lamports. /// /// # Errors /// /// Returns an error if: /// - The funder account is invalid. /// - The pool or token mint accounts are not found or invalid. /// - Any RPC request fails. /// /// # Example /// /// ```rust /// use solana_client::rpc_client::RpcClient; /// use solana_sdk::{pubkey::Pubkey, signer::Keypair}; /// use orca_whirlpools::{open_full_range_position_instructions, IncreaseLiquidityParam}; /// use std::str::FromStr; /// /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com"); /// /// let whirlpool_pubkey = Pubkey::from_str("WHIRLPOOL_ADDRESS").unwrap();; /// let param = IncreaseLiquidityParam::TokenA(1_000_000); /// let slippage_tolerance_bps = Some(100); /// /// let wallet = Keypair::new(); /// let funder = Some(wallet.pubkey()); /// /// let result = open_full_range_position_instructions( /// &rpc, /// whirlpool_pubkey, /// param, /// slippage_tolerance_bps, /// funder, /// ).unwrap(); /// /// println!("Position Mint: {:?}", result.position_mint); /// println!("Initialization Cost: {} lamports", result.initialization_cost); /// ``` pub async fn open_full_range_position_instructions( rpc: &RpcClient, pool_address: Pubkey, param: IncreaseLiquidityParam, slippage_tolerance_bps: Option<u16>, funder: Option<Pubkey>, ) -> Result<OpenPositionInstruction, Box<dyn Error>> { let whirlpool_info = rpc.get_account(&pool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_info.data)?; let tick_range = get_full_range_tick_indexes(whirlpool.tick_spacing); let mint_infos = rpc .get_multiple_accounts(&[whirlpool.token_mint_a, whirlpool.token_mint_b]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; internal_open_position( rpc, pool_address, whirlpool, param, tick_range.tick_lower_index, tick_range.tick_upper_index, mint_a_info, mint_b_info, slippage_tolerance_bps, funder, ) .await } /// Opens a position in a liquidity pool within a specific price range. /// /// This function creates a new position in the specified price range for a given pool. /// It allows for providing liquidity in a targeted range, optimizing capital efficiency. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `pool_address` - The public key of the liquidity pool. /// * `lower_price` - The lower bound of the price range for the position. /// * `upper_price` - The upper bound of the price range for the position. /// * `param` - Parameters for increasing liquidity, specified as `IncreaseLiquidityParam`. /// * `slippage_tolerance_bps` - An optional slippage tolerance in basis points. Defaults to the global slippage tolerance if not provided. /// * `funder` - An optional public key of the funder account. Defaults to the global funder if not provided. /// /// # Returns /// /// Returns a `Result` containing an `OpenPositionInstruction` on success, which includes: /// * `position_mint` - The mint address of the position NFT. /// * `quote` - The computed liquidity quote, including liquidity delta, token estimates, and maximum tokens. /// * `instructions` - A vector of `Instruction` objects required for creating the position. /// * `additional_signers` - A vector of `Keypair` objects for additional transaction signers. /// * `initialization_cost` - The cost of initializing the position, in lamports. /// /// # Errors /// /// Returns an error if: /// - The funder account is invalid. /// - The pool or token mint accounts are not found or invalid. /// - Any RPC request fails. /// - The pool is a Splash Pool, as they only support full-range positions. /// /// # Example /// /// ```rust /// use solana_client::rpc_client::RpcClient; /// use solana_sdk::{pubkey::Pubkey, signer::Keypair}; /// use orca_whirlpools::{open_position_instructions, IncreaseLiquidityParam}; /// use std::str::FromStr; /// /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com"); /// /// let whirlpool_pubkey = Pubkey::from_str("WHIRLPOOL_ADDRESS").unwrap(); /// let lower_price = 0.00005; /// let upper_price = 0.00015; /// let param = IncreaseLiquidityParam::TokenA(1_000_000); /// let slippage_tolerance_bps = Some(100); /// /// let wallet = Keypair::new(); /// let funder = Some(wallet.pubkey()); /// /// let result = open_position_instructions( /// &rpc, /// whirlpool_pubkey, /// lower_price, /// upper_price, /// param, /// slippage_tolerance_bps, /// funder, /// ).unwrap(); /// /// println!("Position Mint: {:?}", result.position_mint); /// println!("Initialization Cost: {} lamports", result.initialization_cost); /// ``` pub async fn open_position_instructions( rpc: &RpcClient, pool_address: Pubkey, lower_price: f64, upper_price: f64, param: IncreaseLiquidityParam, slippage_tolerance_bps: Option<u16>, funder: Option<Pubkey>, ) -> Result<OpenPositionInstruction, Box<dyn Error>> { let whirlpool_info = rpc.get_account(&pool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_info.data)?; if whirlpool.tick_spacing == SPLASH_POOL_TICK_SPACING { return Err("Splash pools only support full range positions".into()); } let mint_infos = rpc .get_multiple_accounts(&[whirlpool.token_mint_a, whirlpool.token_mint_b]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_a = Mint::unpack(&mint_a_info.data)?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; let mint_b = Mint::unpack(&mint_b_info.data)?; let decimals_a = mint_a.decimals; let decimals_b = mint_b.decimals; let lower_tick_index = price_to_tick_index(lower_price, decimals_a, decimals_b); let upper_tick_index = price_to_tick_index(upper_price, decimals_a, decimals_b); internal_open_position( rpc, pool_address, whirlpool, param, lower_tick_index, upper_tick_index, mint_a_info, mint_b_info, slippage_tolerance_bps, funder, ) .await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/lib.rs
mod account; mod config; mod create_pool; mod decrease_liquidity; mod harvest; mod increase_liquidity; mod pool; mod position; mod swap; mod token; #[cfg(test)] mod e2e; #[cfg(test)] mod tests; pub use account::*; pub use config::*; pub use create_pool::*; pub use decrease_liquidity::*; pub use harvest::*; pub use increase_liquidity::*; pub use pool::*; pub use position::*; pub use swap::*; pub use token::*;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/account.rs
use serde::Deserialize; use serde_json::from_value; use solana_account_decoder::UiAccountData; use solana_client::{nonblocking::rpc_client::RpcClient, rpc_request::TokenAccountsFilter}; use solana_program::pubkey::Pubkey; use solana_sdk::rent::Rent; use solana_sdk::sysvar::SysvarId; use std::{error::Error, str::FromStr}; #[derive(Debug, Clone)] pub struct ParsedTokenAccount { pub pubkey: Pubkey, pub token_program: Pubkey, pub mint: Pubkey, pub amount: u64, } #[derive(Deserialize, Clone, Debug)] struct Parsed { info: SplToken, } #[derive(Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] struct SplToken { mint: String, token_amount: Amount, } #[derive(Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] struct Amount { amount: String, ui_amount_string: String, ui_amount: f64, decimals: u8, } pub(crate) async fn get_token_accounts_for_owner( rpc: &RpcClient, owner: Pubkey, program_id: Pubkey, ) -> Result<Vec<ParsedTokenAccount>, Box<dyn Error>> { let accounts = rpc .get_token_accounts_by_owner(&owner, TokenAccountsFilter::ProgramId(program_id)) .await?; let mut token_accounts: Vec<ParsedTokenAccount> = Vec::new(); for account in accounts { if let UiAccountData::Json(data) = account.account.data { let token: Parsed = from_value(data.parsed)?; token_accounts.push(ParsedTokenAccount { pubkey: Pubkey::from_str(&account.pubkey)?, token_program: program_id, mint: Pubkey::from_str(&token.info.mint)?, amount: token.info.token_amount.amount.parse::<u64>()?, }); } } Ok(token_accounts) } pub(crate) async fn get_rent(rpc: &RpcClient) -> Result<Rent, Box<dyn Error>> { let rent = rpc.get_account(&Rent::id()).await?; let rent: Rent = bincode::deserialize(&rent.data)?; Ok(rent) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/create_pool.rs
use std::collections::HashSet; use std::error::Error; use orca_whirlpools_client::{ get_fee_tier_address, get_tick_array_address, get_token_badge_address, get_whirlpool_address, }; use orca_whirlpools_client::{ InitializePoolV2, InitializePoolV2InstructionArgs, InitializeTickArray, InitializeTickArrayInstructionArgs, }; use orca_whirlpools_client::{TickArray, Whirlpool}; use orca_whirlpools_core::{ get_full_range_tick_indexes, get_tick_array_start_tick_index, price_to_sqrt_price, sqrt_price_to_tick_index, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_program::rent::Rent; use solana_program::system_program; use solana_program::sysvar::SysvarId; use solana_program::{instruction::Instruction, pubkey::Pubkey}; use solana_sdk::signature::Keypair; use solana_sdk::signer::Signer; use spl_token::solana_program::program_pack::Pack; use spl_token_2022::state::{Account, Mint}; use crate::token::order_mints; use crate::{get_rent, FUNDER, SPLASH_POOL_TICK_SPACING, WHIRLPOOLS_CONFIG_ADDRESS}; /// Represents the instructions and metadata for creating a pool. pub struct CreatePoolInstructions { /// The list of instructions needed to create the pool. pub instructions: Vec<Instruction>, /// The estimated rent exemption cost for initializing the pool, in lamports. pub initialization_cost: u64, /// The address of the newly created pool. pub pool_address: Pubkey, /// The list of signers for the instructions. pub additional_signers: Vec<Keypair>, } /// Creates the necessary instructions to initialize a Splash Pool. /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for communicating with the blockchain. /// * `token_a` - The public key of the first token mint address to include in the pool. /// * `token_b` - The public key of the second token mint address to include in the pool. /// * `initial_price` - An optional initial price of token A in terms of token B. Defaults to 1.0 if not provided. /// * `funder` - An optional public key of the account funding the initialization process. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `CreatePoolInstructions` on success: /// * `instructions` - A vector of Solana instructions needed to initialize the pool. /// * `initialization_cost` - The estimated rent exemption cost for initializing the pool, in lamports. /// * `pool_address` - The public key of the newly created pool. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// /// # Errors /// /// This function will return an error if: /// - The funder account is invalid. /// - Token mints are not found or have invalid data. /// - The token mint order does not match the canonical byte order. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// create_splash_pool_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::{pubkey::Pubkey, signature::Signer, signer::keypair::Keypair}; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); /// let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC /// let initial_price = Some(0.01); /// let wallet = Keypair::new(); // CAUTION: This wallet is not persistent. /// let funder = Some(wallet.pubkey()); /// /// let create_pool_instructions = /// create_splash_pool_instructions(&rpc, token_a, token_b, initial_price, funder) /// .await /// .unwrap(); /// /// println!("Pool Address: {:?}", create_pool_instructions.pool_address); /// println!( /// "Initialization Cost: {} lamports", /// create_pool_instructions.initialization_cost /// ); /// } /// ``` pub async fn create_splash_pool_instructions( rpc: &RpcClient, token_a: Pubkey, token_b: Pubkey, initial_price: Option<f64>, funder: Option<Pubkey>, ) -> Result<CreatePoolInstructions, Box<dyn Error>> { create_concentrated_liquidity_pool_instructions( rpc, token_a, token_b, SPLASH_POOL_TICK_SPACING, initial_price, funder, ) .await } /// Creates the necessary instructions to initialize a Concentrated Liquidity Pool (CLMM). /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for communicating with the blockchain. /// * `token_a` - The public key of the first token mint address to include in the pool. /// * `token_b` - The public key of the second token mint address to include in the pool. /// * `tick_spacing` - The spacing between price ticks for the pool. /// * `initial_price` - An optional initial price of token A in terms of token B. Defaults to 1.0 if not provided. /// * `funder` - An optional public key of the account funding the initialization process. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `CreatePoolInstructions` on success: /// * `instructions` - A vector of Solana instructions needed to initialize the pool. /// * `initialization_cost` - The estimated rent exemption cost for initializing the pool, in lamports. /// * `pool_address` - The public key of the newly created pool. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// /// # Errors /// /// This function will return an error if: /// - The funder account is invalid. /// - Token mints are not found or have invalid data. /// - The token mint order does not match the canonical byte order. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ``` /// use orca_whirlpools::{ /// create_concentrated_liquidity_pool_instructions, set_whirlpools_config_address, /// WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::{pubkey::Pubkey, signature::Signer, signer::keypair::Keypair}; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); /// let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC /// let tick_spacing = 64; /// let initial_price = Some(0.01); /// let wallet = Keypair::new(); // CAUTION: This wallet is not persistent. /// let funder = Some(wallet.pubkey()); /// /// let create_pool_instructions = create_concentrated_liquidity_pool_instructions( /// &rpc, /// token_a, /// token_b, /// tick_spacing, /// initial_price, /// funder, /// ) /// .await /// .unwrap(); /// /// println!("Pool Address: {:?}", create_pool_instructions.pool_address); /// println!( /// "Initialization Cost: {} lamports", /// create_pool_instructions.initialization_cost /// ); /// } /// ``` pub async fn create_concentrated_liquidity_pool_instructions( rpc: &RpcClient, token_a: Pubkey, token_b: Pubkey, tick_spacing: u16, initial_price: Option<f64>, funder: Option<Pubkey>, ) -> Result<CreatePoolInstructions, Box<dyn Error>> { let initial_price = initial_price.unwrap_or(1.0); let funder = funder.unwrap_or(*FUNDER.try_lock()?); if funder == Pubkey::default() { return Err("Funder must be provided".into()); } if order_mints(token_a, token_b)[0] != token_a { return Err("Token order needs to be flipped to match the canonical ordering (i.e. sorted on the byte repr. of the mint pubkeys)".into()); } let rent = get_rent(rpc).await?; let account_infos = rpc.get_multiple_accounts(&[token_a, token_b]).await?; let mint_a_info = account_infos[0] .as_ref() .ok_or(format!("Mint {} not found", token_a))?; let mint_a = Mint::unpack(&mint_a_info.data)?; let decimals_a = mint_a.decimals; let token_program_a = mint_a_info.owner; let mint_b_info = account_infos[1] .as_ref() .ok_or(format!("Mint {} not found", token_b))?; let mint_b = Mint::unpack(&mint_b_info.data)?; let decimals_b = mint_b.decimals; let token_program_b = mint_b_info.owner; let initial_sqrt_price: u128 = price_to_sqrt_price(initial_price, decimals_a, decimals_b); let pool_address = get_whirlpool_address( &*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?, &token_a, &token_b, tick_spacing, )? .0; let fee_tier = get_fee_tier_address(&*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?, tick_spacing)?.0; let token_badge_a = get_token_badge_address(&*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?, &token_a)?.0; let token_badge_b = get_token_badge_address(&*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?, &token_b)?.0; let token_vault_a = Keypair::new(); let token_vault_b = Keypair::new(); let mut initialization_cost: u64 = 0; let mut instructions = vec![]; instructions.push( InitializePoolV2 { whirlpools_config: *WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?, token_mint_a: token_a, token_mint_b: token_b, token_badge_a, token_badge_b, funder, whirlpool: pool_address, token_vault_a: token_vault_a.pubkey(), token_vault_b: token_vault_b.pubkey(), fee_tier, token_program_a, token_program_b, system_program: system_program::id(), rent: Rent::id(), } .instruction(InitializePoolV2InstructionArgs { initial_sqrt_price, tick_spacing, }), ); initialization_cost += rent.minimum_balance(Whirlpool::LEN); initialization_cost += rent.minimum_balance(Account::LEN); // TODO: token 22 size initialization_cost += rent.minimum_balance(Account::LEN); // TODO: token 22 size let full_range = get_full_range_tick_indexes(tick_spacing); let lower_tick_index = get_tick_array_start_tick_index(full_range.tick_lower_index, tick_spacing); let upper_tick_index = get_tick_array_start_tick_index(full_range.tick_upper_index, tick_spacing); let initial_tick_index = sqrt_price_to_tick_index(initial_sqrt_price); let current_tick_index = get_tick_array_start_tick_index(initial_tick_index, tick_spacing); let tick_array_indexes = HashSet::from([lower_tick_index, upper_tick_index, current_tick_index]); for start_tick_index in tick_array_indexes { let tick_array_address = get_tick_array_address(&pool_address, start_tick_index)?; instructions.push( InitializeTickArray { whirlpool: pool_address, tick_array: tick_array_address.0, funder, system_program: system_program::id(), } .instruction(InitializeTickArrayInstructionArgs { start_tick_index }), ); initialization_cost += rent.minimum_balance(TickArray::LEN); } Ok(CreatePoolInstructions { instructions, initialization_cost, pool_address, additional_signers: vec![token_vault_a, token_vault_b], }) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/pool.rs
use std::error::Error; use orca_whirlpools_client::{ fetch_all_fee_tier_with_filter, get_fee_tier_address, get_whirlpool_address, FeeTier, FeeTierFilter, Whirlpool, WhirlpoolsConfig, }; use orca_whirlpools_core::sqrt_price_to_price; use solana_client::nonblocking::rpc_client::RpcClient; use solana_program::pubkey::Pubkey; use solana_sdk::{program_error::ProgramError, program_pack::Pack}; use spl_token::state::Mint; use crate::{token::order_mints, SPLASH_POOL_TICK_SPACING, WHIRLPOOLS_CONFIG_ADDRESS}; /// Represents an uninitialized pool. /// /// This struct contains the configuration and token details necessary to initialize a pool. #[derive(Debug, Clone)] pub struct UninitializedPool { /// The address of the pool. pub address: Pubkey, /// The whirlpools_config address for the pool. pub whirlpools_config: Pubkey, /// The spacing between ticks in the pool. pub tick_spacing: u16, /// The fee rate applied to swaps in the pool. pub fee_rate: u16, /// The protocol's share of fees. pub protocol_fee_rate: u16, /// The mint address for token A in the pool. pub token_mint_a: Pubkey, /// The mint address for token B in the pool. pub token_mint_b: Pubkey, } /// Represents an initialized pool. /// /// This struct contains the pool's address, data, and current price. #[derive(Debug, Clone)] pub struct InitializedPool { /// The address of the pool. pub address: Pubkey, /// The `Whirlpool` struct containing the pool's state and configuration. pub data: Whirlpool, /// The current price in the pool. pub price: f64, } impl InitializedPool { fn from_bytes( bytes: &[u8], whirlpool_address: Pubkey, mint_a: Mint, mint_b: Mint, ) -> Result<Self, Box<dyn Error>> { let whirlpool = Whirlpool::from_bytes(bytes)?; let price = sqrt_price_to_price(whirlpool.sqrt_price, mint_a.decimals, mint_b.decimals); Ok(InitializedPool { address: whirlpool_address, data: whirlpool, price, }) } } /// Represents information about a pool, either initialized or uninitialized. /// /// This enum provides a unified way to describe both initialized and uninitialized pools, /// encapsulating their specific data structures. #[derive(Debug, Clone)] pub enum PoolInfo { /// Represents a pool that has been initialized and contains its current state and price. /// - `InitializedPool` - The struct holding the initialized pool's data and price. Initialized(InitializedPool), /// Represents a pool that has not been initialized yet but contains its configuration and token details. /// - `UninitializedPool` - The struct holding the uninitialized pool's configuration details. Uninitialized(UninitializedPool), } /// Fetches the details of a specific Splash Pool. /// /// This function retrieves information about a pool with the predefined tick spacing for Splash Pools. /// It determines whether the pool is initialized or not and returns the corresponding details. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `token_1` - The public key of the first token mint in the pool. /// * `token_2` - The public key of the second token mint in the pool. /// /// # Returns /// /// A `Result` containing `PoolInfo`: /// * `PoolInfo::Initialized` if the pool is initialized, including the pool's state and price. /// * `PoolInfo::Uninitialized` if the pool is not yet initialized, including configuration details. /// /// # Errors /// /// This function will return an error if: /// - Any required account or mint information cannot be fetched. /// - The pool or its configuration details are invalid. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// fetch_splash_pool, set_whirlpools_config_address, PoolInfo, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); /// let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC /// /// let pool_info = fetch_splash_pool(&rpc, token_a, token_b).await.unwrap(); /// /// match pool_info { /// PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), /// PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), /// } /// } /// ``` pub async fn fetch_splash_pool( rpc: &RpcClient, token_1: Pubkey, token_2: Pubkey, ) -> Result<PoolInfo, Box<dyn Error>> { fetch_concentrated_liquidity_pool(rpc, token_1, token_2, SPLASH_POOL_TICK_SPACING).await } /// Fetches the details of a specific Concentrated Liquidity Pool. /// /// This function retrieves information about a pool for the specified tick spacing. /// It determines whether the pool is initialized or not and returns the corresponding details. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `token_1` - The public key of the first token mint in the pool. /// * `token_2` - The public key of the second token mint in the pool. /// * `tick_spacing` - The tick spacing of the pool. /// /// # Returns /// /// A `Result` containing `PoolInfo`: /// * `PoolInfo::Initialized` if the pool is initialized, including the pool's state and price. /// * `PoolInfo::Uninitialized` if the pool is not yet initialized, including configuration details. /// /// # Errors /// /// This function will return an error if: /// - Any required account or mint information cannot be fetched. /// - The pool or its configuration details are invalid. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// fetch_concentrated_liquidity_pool, set_whirlpools_config_address, PoolInfo, /// WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); /// let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC /// let tick_spacing = 64; /// /// let pool_info = fetch_concentrated_liquidity_pool(&rpc, token_a, token_b, tick_spacing) /// .await /// .unwrap(); /// /// match pool_info { /// PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), /// PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), /// } /// } /// ``` pub async fn fetch_concentrated_liquidity_pool( rpc: &RpcClient, token_1: Pubkey, token_2: Pubkey, tick_spacing: u16, ) -> Result<PoolInfo, Box<dyn Error>> { let whirlpools_config_address = &*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?; let [token_a, token_b] = order_mints(token_1, token_2); let whirlpool_address = get_whirlpool_address(whirlpools_config_address, &token_a, &token_b, tick_spacing)?.0; let fee_tier_address = get_fee_tier_address(whirlpools_config_address, tick_spacing)?; let account_infos = rpc .get_multiple_accounts(&[ whirlpool_address, *whirlpools_config_address, fee_tier_address.0, token_a, token_b, ]) .await?; let whirlpools_config_info = account_infos[1].as_ref().ok_or(format!( "Whirlpools config {} not found", whirlpools_config_address ))?; let whirlpools_config = WhirlpoolsConfig::from_bytes(&whirlpools_config_info.data)?; let fee_tier_info = account_infos[2] .as_ref() .ok_or(format!("Fee tier {} not found", fee_tier_address.0))?; let fee_tier = FeeTier::from_bytes(&fee_tier_info.data)?; let mint_a_info = account_infos[3] .as_ref() .ok_or(format!("Mint {} not found", token_a))?; let mint_a = Mint::unpack(&mint_a_info.data)?; let mint_b_info = account_infos[4] .as_ref() .ok_or(format!("Mint {} not found", token_b))?; let mint_b = Mint::unpack(&mint_b_info.data)?; if let Some(whirlpool_info) = &account_infos[0] { let initialized_pool = InitializedPool::from_bytes(&whirlpool_info.data, whirlpool_address, mint_a, mint_b)?; Ok(PoolInfo::Initialized(initialized_pool)) } else { Ok(PoolInfo::Uninitialized(UninitializedPool { address: whirlpool_address, whirlpools_config: *whirlpools_config_address, tick_spacing, fee_rate: fee_tier.default_fee_rate, protocol_fee_rate: whirlpools_config.default_protocol_fee_rate, token_mint_a: token_a, token_mint_b: token_b, })) } } /// Fetches all possible liquidity pools between two token mints in Orca Whirlpools. /// /// This function retrieves information about all pools between the specified token mints, /// including both initialized and uninitialized pools. If a pool does not exist, it creates /// a placeholder account for the uninitialized pool with default configuration details. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `token_1` - The public key of the first token mint in the pool. /// * `token_2` - The public key of the second token mint in the pool. /// /// # Returns /// /// A `Result` containing a `Vec<PoolInfo>`: /// * `PoolInfo::Initialized` for initialized pools, including pool state and price. /// * `PoolInfo::Uninitialized` for uninitialized pools, including configuration details. /// /// # Errors /// /// This function will return an error if: /// - Any required account or mint information cannot be fetched. /// - The pool or its configuration details are invalid. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// fetch_whirlpools_by_token_pair, set_whirlpools_config_address, PoolInfo, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); /// let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC /// /// let pool_infos = fetch_whirlpools_by_token_pair(&rpc, token_a, token_b) /// .await /// .unwrap(); /// /// for pool_info in pool_infos { /// match pool_info { /// PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), /// PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), /// } /// } /// } /// ``` pub async fn fetch_whirlpools_by_token_pair( rpc: &RpcClient, token_1: Pubkey, token_2: Pubkey, ) -> Result<Vec<PoolInfo>, Box<dyn Error>> { let whirlpools_config_address = &*WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?; let [token_a, token_b] = order_mints(token_1, token_2); let fee_tiers = fetch_all_fee_tier_with_filter( rpc, vec![FeeTierFilter::WhirlpoolsConfig(*whirlpools_config_address)], ) .await?; let account_infos = rpc .get_multiple_accounts(&[*whirlpools_config_address, token_a, token_b]) .await?; let whirlpools_config_info = account_infos[0].as_ref().ok_or(format!( "Whirlpools config {} not found", whirlpools_config_address ))?; let whirlpools_config = WhirlpoolsConfig::from_bytes(&whirlpools_config_info.data)?; let mint_a_info = account_infos[1] .as_ref() .ok_or(format!("Mint {} not found", token_a))?; let mint_a = Mint::unpack(&mint_a_info.data)?; let mint_b_info = account_infos[2] .as_ref() .ok_or(format!("Mint {} not found", token_b))?; let mint_b = Mint::unpack(&mint_b_info.data)?; let whirlpool_addresses: Vec<Pubkey> = fee_tiers .iter() .map(|fee_tier| fee_tier.data.tick_spacing) .map(|tick_spacing| { get_whirlpool_address(whirlpools_config_address, &token_a, &token_b, tick_spacing) }) .map(|x| x.map(|y| y.0)) .collect::<Result<Vec<Pubkey>, ProgramError>>()?; let whirlpool_infos = rpc.get_multiple_accounts(&whirlpool_addresses).await?; let mut whirlpools: Vec<PoolInfo> = Vec::new(); for i in 0..whirlpool_addresses.len() { let pool_address = whirlpool_addresses[i]; let pool_info = whirlpool_infos.get(i).and_then(|x| x.as_ref()); let fee_tier = &fee_tiers[i]; if let Some(pool_info) = pool_info { let initialized_pool = InitializedPool::from_bytes(&pool_info.data, pool_address, mint_a, mint_b)?; whirlpools.push(PoolInfo::Initialized(initialized_pool)); } else { whirlpools.push(PoolInfo::Uninitialized(UninitializedPool { address: pool_address, whirlpools_config: *whirlpools_config_address, tick_spacing: fee_tier.data.tick_spacing, fee_rate: fee_tier.data.default_fee_rate, protocol_fee_rate: whirlpools_config.default_protocol_fee_rate, token_mint_a: token_a, token_mint_b: token_b, })); } } Ok(whirlpools) } #[cfg(test)] mod tests { use super::*; use crate::tests::{ setup_ata_with_amount, setup_mint_with_decimals, setup_whirlpool, RpcContext, }; use serial_test::serial; use solana_program_test::tokio; use solana_sdk::signer::Signer; struct TestContext { ctx: RpcContext, mint_a: Pubkey, mint_b: Pubkey, splash_pool: Pubkey, concentrated_pool: Pubkey, } impl TestContext { async fn new() -> Result<Self, Box<dyn Error>> { let ctx = RpcContext::new().await; let mint_a = setup_mint_with_decimals(&ctx, 9).await?; let mint_b = setup_mint_with_decimals(&ctx, 9).await?; setup_ata_with_amount(&ctx, mint_a, 500_000_000_000).await?; setup_ata_with_amount(&ctx, mint_b, 500_000_000_000).await?; // Setup all pools let concentrated_pool = setup_whirlpool(&ctx, mint_a, mint_b, 64).await?; let splash_pool = setup_whirlpool(&ctx, mint_a, mint_b, SPLASH_POOL_TICK_SPACING).await?; Ok(Self { ctx, mint_a, mint_b, splash_pool, concentrated_pool, }) } } #[tokio::test] #[serial] async fn test_fetch_splash_pool() { let test_ctx = TestContext::new().await.unwrap(); if let PoolInfo::Initialized(pool) = fetch_splash_pool(&test_ctx.ctx.rpc, test_ctx.mint_a, test_ctx.mint_b) .await .unwrap() { assert_eq!(pool.data.liquidity, 0); assert_eq!(pool.data.tick_spacing, SPLASH_POOL_TICK_SPACING); assert_eq!(pool.address, test_ctx.splash_pool); assert_eq!(pool.data.token_mint_a, test_ctx.mint_a); assert_eq!(pool.data.token_mint_b, test_ctx.mint_b); assert_eq!(pool.data.fee_rate, 1000); assert_eq!(pool.data.protocol_fee_rate, 0); } else { panic!("Expected initialized pool"); } } #[tokio::test] #[serial] async fn test_fetch_concentrated_liquidity_pool() { let test_ctx = TestContext::new().await.unwrap(); if let PoolInfo::Initialized(pool) = fetch_concentrated_liquidity_pool( &test_ctx.ctx.rpc, test_ctx.mint_a, test_ctx.mint_b, 64, ) .await .unwrap() { assert_eq!(pool.data.liquidity, 0); assert_eq!(pool.data.tick_spacing, 64); assert_eq!(pool.address, test_ctx.concentrated_pool); assert_eq!(pool.data.token_mint_a, test_ctx.mint_a); assert_eq!(pool.data.token_mint_b, test_ctx.mint_b); assert_eq!(pool.data.fee_rate, 300); assert_eq!(pool.data.protocol_fee_rate, 0); } else { panic!("Expected initialized pool"); } } #[tokio::test] #[serial] async fn test_fetch_non_existent_pool() { let test_ctx = TestContext::new().await.unwrap(); if let PoolInfo::Uninitialized(pool) = fetch_concentrated_liquidity_pool( &test_ctx.ctx.rpc, test_ctx.mint_a, test_ctx.mint_b, 128, ) .await .unwrap() { assert_eq!(pool.tick_spacing, 128); assert_eq!(pool.token_mint_a, test_ctx.mint_a); assert_eq!(pool.token_mint_b, test_ctx.mint_b); assert_eq!(pool.fee_rate, 1000); assert_eq!(pool.protocol_fee_rate, 0); } else { panic!("Expected uninitialized pool"); } } #[tokio::test] #[serial] #[ignore = "Skipped until solana-bankrun supports getProgramAccounts"] async fn test_fetch_all_pools_for_pair() { let test_ctx = TestContext::new().await.unwrap(); let pools = fetch_whirlpools_by_token_pair(&test_ctx.ctx.rpc, test_ctx.mint_a, test_ctx.mint_b) .await .unwrap(); assert_eq!(pools.len(), 3); // 2 initialized + 1 uninitialized (128 tick spacing) // Verify concentrated liquidity pool let concentrated = pools .iter() .find(|p| match p { PoolInfo::Initialized(p) => p.data.tick_spacing == 64, _ => false, }) .unwrap(); if let PoolInfo::Initialized(pool) = concentrated { assert_eq!(pool.address, test_ctx.concentrated_pool); assert_eq!(pool.data.fee_rate, 300); } // Verify splash pool let splash = pools .iter() .find(|p| match p { PoolInfo::Initialized(p) => p.data.tick_spacing == SPLASH_POOL_TICK_SPACING, _ => false, }) .unwrap(); if let PoolInfo::Initialized(pool) = splash { assert_eq!(pool.address, test_ctx.splash_pool); assert_eq!(pool.data.fee_rate, 1000); } // Verify uninitialized pool let uninitialized = pools .iter() .find(|p| match p { PoolInfo::Uninitialized(p) => p.tick_spacing == 128, _ => false, }) .unwrap(); if let PoolInfo::Uninitialized(pool) = uninitialized { assert_eq!(pool.fee_rate, 1000); } } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/harvest.rs
use std::{ collections::HashSet, error::Error, time::{SystemTime, UNIX_EPOCH}, }; use orca_whirlpools_client::{ get_position_address, get_tick_array_address, Position, TickArray, Whirlpool, }; use orca_whirlpools_client::{ CollectFeesV2, CollectFeesV2InstructionArgs, CollectRewardV2, CollectRewardV2InstructionArgs, UpdateFeesAndRewards, }; use orca_whirlpools_core::{ collect_fees_quote, collect_rewards_quote, get_tick_array_start_tick_index, get_tick_index_in_array, CollectFeesQuote, CollectRewardsQuote, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{account::Account, instruction::Instruction, pubkey::Pubkey, signature::Keypair}; use spl_associated_token_account::get_associated_token_address_with_program_id; use crate::{ token::{get_current_transfer_fee, prepare_token_accounts_instructions, TokenAccountStrategy}, FUNDER, }; // TODO: support transfer hooks /// Represents the instructions and quotes for harvesting a position. /// /// This struct contains the instructions required to harvest a position, along with detailed /// information about the available fees and rewards to collect. #[derive(Debug)] pub struct HarvestPositionInstruction { /// A vector of `Instruction` objects required to execute the harvesting process. pub instructions: Vec<Instruction>, /// A vector of `Keypair` objects representing additional signers required for the instructions. pub additional_signers: Vec<Keypair>, /// Details of the fees available to collect from the position: /// - `fee_owed_a` - The amount of fees available to collect in token A. /// - `fee_owed_b` - The amount of fees available to collect in token B. pub fees_quote: CollectFeesQuote, /// Details of the rewards available to collect from the position: /// - `rewards` - An array containing up to three `CollectRewardQuote` entries, one for each reward token. /// - Each entry includes `rewards_owed`, the amount of the respective reward token available to collect. pub rewards_quote: CollectRewardsQuote, } /// Generates instructions to harvest a position. /// /// Harvesting a position involves collecting any accumulated fees and rewards /// from the position. The position remains open, and liquidity is not removed. /// /// # Arguments /// /// * `rpc` - A reference to a Solana RPC client for fetching accounts and pool data. /// * `position_mint_address` - The public key of the NFT mint address representing the pool position. /// * `authority` - An optional public key of the account authorizing the harvesting process. Defaults to the global funder if not provided. /// /// # Returns /// /// A `Result` containing `HarvestPositionInstruction` on success: /// /// * `fees_quote` - A breakdown of the fees owed to the position owner, including the amounts for Token A and Token B. /// * `rewards_quote` - A breakdown of the rewards owed, including up to three reward tokens. /// * `instructions` - A vector of `Instruction` objects required to execute the harvesting process. /// * `additional_signers` - A vector of `Keypair` objects representing additional signers required for the instructions. /// /// # Errors /// /// This function will return an error if: /// - The `authority` account is invalid or missing. /// - The position or token mint accounts are not found or have invalid data. /// - Any RPC request to the blockchain fails. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// harvest_position_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// use crate::utils::load_wallet; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let wallet = load_wallet(); /// /// let position_mint_address = /// Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); /// /// let result = harvest_position_instructions(&rpc, position_mint_address, Some(wallet.pubkey())) /// .await /// .unwrap(); /// /// println!("Fees Quote: {:?}", result.fees_quote); /// println!("Rewards Quote: {:?}", result.rewards_quote); /// println!("Number of Instructions: {}", result.instructions.len()); /// } /// ``` pub async fn harvest_position_instructions( rpc: &RpcClient, position_mint_address: Pubkey, authority: Option<Pubkey>, ) -> Result<HarvestPositionInstruction, Box<dyn Error>> { let authority = authority.unwrap_or(*FUNDER.try_lock()?); if authority == Pubkey::default() { return Err("Authority must be provided".into()); } let position_address = get_position_address(&position_mint_address)?.0; let position_info = rpc.get_account(&position_address).await?; let position = Position::from_bytes(&position_info.data)?; let pool_info = rpc.get_account(&position.whirlpool).await?; let pool = Whirlpool::from_bytes(&pool_info.data)?; let mint_infos = rpc .get_multiple_accounts(&[ pool.token_mint_a, pool.token_mint_b, position_mint_address, pool.reward_infos[0].mint, pool.reward_infos[1].mint, pool.reward_infos[2].mint, ]) .await?; let mint_a_info = mint_infos[0] .as_ref() .ok_or("Token A mint info not found")?; let mint_b_info = mint_infos[1] .as_ref() .ok_or("Token B mint info not found")?; let position_mint_info = mint_infos[2] .as_ref() .ok_or("Position mint info not found")?; let reward_infos: Vec<Option<Account>> = pool .reward_infos .iter() .enumerate() .map(|(i, x)| { if x.mint == Pubkey::default() { None } else { mint_infos[i + 3].clone() } }) .collect(); let current_epoch = rpc.get_epoch_info().await?.epoch; let transfer_fee_a = get_current_transfer_fee(Some(mint_a_info), current_epoch); let transfer_fee_b = get_current_transfer_fee(Some(mint_b_info), current_epoch); let lower_tick_array_start_index = get_tick_array_start_tick_index(position.tick_lower_index, pool.tick_spacing); let upper_tick_array_start_index = get_tick_array_start_tick_index(position.tick_upper_index, pool.tick_spacing); let position_token_account_address = get_associated_token_address_with_program_id( &authority, &position_mint_address, &position_mint_info.owner, ); let lower_tick_array_address = get_tick_array_address(&position.whirlpool, lower_tick_array_start_index)?.0; let upper_tick_array_address = get_tick_array_address(&position.whirlpool, upper_tick_array_start_index)?.0; let tick_array_infos = rpc .get_multiple_accounts(&[lower_tick_array_address, upper_tick_array_address]) .await?; let lower_tick_array_info = tick_array_infos[0] .as_ref() .ok_or("Lower tick array info not found")?; let lower_tick_array = TickArray::from_bytes(&lower_tick_array_info.data)?; let lower_tick = &lower_tick_array.ticks[get_tick_index_in_array( position.tick_lower_index, lower_tick_array_start_index, pool.tick_spacing, )? as usize]; let upper_tick_array_info = tick_array_infos[1] .as_ref() .ok_or("Upper tick array info not found")?; let upper_tick_array = TickArray::from_bytes(&upper_tick_array_info.data)?; let upper_tick = &upper_tick_array.ticks[get_tick_index_in_array( position.tick_upper_index, upper_tick_array_start_index, pool.tick_spacing, )? as usize]; let fees_quote = collect_fees_quote( pool.clone().into(), position.clone().into(), lower_tick.clone().into(), upper_tick.clone().into(), transfer_fee_a, transfer_fee_b, )?; let unix_timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(); let rewards_quote = collect_rewards_quote( pool.clone().into(), position.clone().into(), lower_tick.clone().into(), upper_tick.clone().into(), unix_timestamp, get_current_transfer_fee(reward_infos[0].as_ref(), current_epoch), get_current_transfer_fee(reward_infos[1].as_ref(), current_epoch), get_current_transfer_fee(reward_infos[2].as_ref(), current_epoch), )?; let mut required_mints: HashSet<TokenAccountStrategy> = HashSet::new(); if fees_quote.fee_owed_a > 0 || fees_quote.fee_owed_b > 0 { required_mints.insert(TokenAccountStrategy::WithoutBalance(pool.token_mint_a)); required_mints.insert(TokenAccountStrategy::WithoutBalance(pool.token_mint_b)); } for i in 0..3 { if rewards_quote.rewards[i].rewards_owed > 0 { required_mints.insert(TokenAccountStrategy::WithoutBalance( pool.reward_infos[i].mint, )); } } let token_accounts = prepare_token_accounts_instructions(rpc, authority, required_mints.into_iter().collect()) .await?; let mut instructions: Vec<Instruction> = Vec::new(); instructions.extend(token_accounts.create_instructions); if position.liquidity > 0 { instructions.push( UpdateFeesAndRewards { whirlpool: position.whirlpool, position: position_address, tick_array_lower: lower_tick_array_address, tick_array_upper: upper_tick_array_address, } .instruction(), ); } if fees_quote.fee_owed_a > 0 || fees_quote.fee_owed_b > 0 { let token_owner_account_a = token_accounts .token_account_addresses .get(&pool.token_mint_a) .ok_or("Token A owner account not found")?; let token_owner_account_b = token_accounts .token_account_addresses .get(&pool.token_mint_b) .ok_or("Token B owner account not found")?; instructions.push( CollectFeesV2 { whirlpool: position.whirlpool, position_authority: authority, position: position_address, position_token_account: position_token_account_address, token_owner_account_a: *token_owner_account_a, token_owner_account_b: *token_owner_account_b, token_vault_a: pool.token_vault_a, token_vault_b: pool.token_vault_b, token_mint_a: pool.token_mint_a, token_mint_b: pool.token_mint_b, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, memo_program: spl_memo::ID, } .instruction(CollectFeesV2InstructionArgs { remaining_accounts_info: None, }), ); } for i in 0..3 { if rewards_quote.rewards[i].rewards_owed == 0 { continue; } let reward_info = reward_infos[i] .as_ref() .ok_or("Reward mint info not found")?; let reward_owner = token_accounts .token_account_addresses .get(&pool.reward_infos[i].mint) .ok_or("Reward owner account not found")?; instructions.push( CollectRewardV2 { whirlpool: position.whirlpool, position_authority: authority, position: position_address, position_token_account: position_token_account_address, reward_owner_account: *reward_owner, reward_vault: pool.reward_infos[i].vault, reward_mint: pool.reward_infos[i].mint, reward_token_program: reward_info.owner, memo_program: spl_memo::ID, } .instruction(CollectRewardV2InstructionArgs { reward_index: i as u8, remaining_accounts_info: None, }), ); } instructions.extend(token_accounts.cleanup_instructions); Ok(HarvestPositionInstruction { instructions, additional_signers: token_accounts.additional_signers, fees_quote, rewards_quote, }) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/position.rs
use std::{collections::HashMap, error::Error}; use orca_whirlpools_client::{ fetch_all_position_with_filter, get_bundled_position_address, get_position_address, get_position_bundle_address, DecodedAccount, Position, PositionBundle, PositionFilter, }; use orca_whirlpools_core::POSITION_BUNDLE_SIZE; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::account::Account; use solana_sdk::pubkey::Pubkey; use crate::{get_token_accounts_for_owner, ParsedTokenAccount}; /// Represents a single Position account. /// /// This struct contains the address of the position NFT, its decoded data, and the token program /// associated with the position NFT, which can be either the standard SPL Token Program or /// the Token 2022 Program. #[derive(Debug)] pub struct HydratedPosition { /// The public key of the Position account. pub address: Pubkey, /// The decoded `Position` account data. pub data: Position, /// The public key of the token program associated with the position NFT (either SPL Token or Token 2022). pub token_program: Pubkey, } /// Represents a single bundled position within a `PositionBundle` account. /// /// A bundled position is part of a larger `PositionBundle` and contains its own /// address and decoded position data. #[derive(Debug)] pub struct HydratedBundledPosition { /// The public key of the bundled position. pub address: Pubkey, /// The decoded `Position` account data for the bundled position. pub data: Position, } /// Represents a Position Bundle account, which includes multiple bundled positions. /// /// This struct contains the address and decoded data of the `PositionBundle` account, /// along with the individual bundled positions and the associated token program. #[derive(Debug)] pub struct HydratedPositionBundle { /// The public key of the Position Bundle account. pub address: Pubkey, /// The decoded `PositionBundle` account data. pub data: PositionBundle, /// A vector of `HydratedBundledPosition` objects representing the bundled positions represented by the position NFT. pub positions: Vec<HydratedBundledPosition>, /// The public key of the token program associated with the position bundle NFT (either SPL Token or Token 2022). pub token_program: Pubkey, } /// Represents either a standalone Position account or a Position Bundle account. /// /// This enum distinguishes between a single `HydratedPosition` and a `HydratedPositionBundle`, /// providing a unified type for handling both cases. #[derive(Debug)] pub enum PositionOrBundle { /// A standalone `HydratedPosition`. Position(HydratedPosition), /// A `HydratedPositionBundle` containing multiple bundled positions. PositionBundle(HydratedPositionBundle), } fn get_position_in_bundle_addresses(position_bundle: &PositionBundle) -> Vec<Pubkey> { let mut positions: Vec<Pubkey> = Vec::new(); for i in 0..POSITION_BUNDLE_SIZE { let byte_index = i / 8; let bit_index = i % 8; if position_bundle.position_bitmap[byte_index] & (1 << bit_index) != 0 { let result = get_bundled_position_address(&position_bundle.position_bundle_mint, i as u8); if let Ok(result) = result { positions.push(result.0); } } } positions } /// Fetches all positions owned by a given wallet in the Orca Whirlpools. /// /// This function retrieves token accounts owned by the wallet, using both the SPL Token Program /// and Token 2022 Program. It identifies accounts holding exactly one token, which represent /// either a position or a position bundle. For each of these accounts, it fetches the corresponding /// position or bundle data, including any bundled positions, and returns them. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `owner` - The public key of the wallet whose positions should be fetched. /// /// # Returns /// /// A `Result` containing a vector of `PositionOrBundle` objects, representing the decoded /// positions or position bundles owned by the given wallet. /// /// # Errors /// /// This function will return an error if: /// - Token accounts cannot be fetched. /// - Position or position bundle addresses cannot be derived. /// - RPC calls fail when fetching account data. /// /// # Example /// ```rust /// use orca_whirlpools::{ /// fetch_positions_for_owner, set_whirlpools_config_address, WhirlpoolsConfigInput /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let whirlpool_address = /// Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); /// /// let positions = fetch_positions_for_owner(&rpc, whirlpool_address) /// .await /// .unwrap(); /// /// println!("Positions: {:?}", positions); /// } /// ``` pub async fn fetch_positions_for_owner( rpc: &RpcClient, owner: Pubkey, ) -> Result<Vec<PositionOrBundle>, Box<dyn Error>> { let token_accounts = get_token_accounts_for_owner(rpc, owner, spl_token::ID).await?; let token_extension_accounts = get_token_accounts_for_owner(rpc, owner, spl_token_2022::ID).await?; let potiential_tokens: Vec<ParsedTokenAccount> = [token_accounts, token_extension_accounts] .into_iter() .flatten() .filter(|x| x.amount == 1) .collect(); let position_addresses: Vec<Pubkey> = potiential_tokens .iter() .map(|x| get_position_address(&x.mint).map(|x| x.0)) .collect::<Result<Vec<Pubkey>, _>>()?; let position_bundle_addresses: Vec<Pubkey> = potiential_tokens .iter() .map(|x| get_position_bundle_address(&x.mint).map(|x| x.0)) .collect::<Result<Vec<Pubkey>, _>>()?; let position_infos = rpc.get_multiple_accounts(&position_addresses).await?; let positions: Vec<Option<Position>> = position_infos .iter() .map(|x| x.as_ref().and_then(|x| Position::from_bytes(&x.data).ok())) .collect(); let position_bundle_infos = rpc .get_multiple_accounts(&position_bundle_addresses) .await?; let position_bundles: Vec<Option<PositionBundle>> = position_bundle_infos .iter() .map(|x| { x.as_ref() .and_then(|x| PositionBundle::from_bytes(&x.data).ok()) }) .collect(); let bundled_positions_addresses: Vec<Pubkey> = position_bundles .iter() .flatten() .flat_map(get_position_in_bundle_addresses) .collect(); let bundled_positions_infos: Vec<Account> = rpc .get_multiple_accounts(&bundled_positions_addresses) .await? .into_iter() .flatten() .collect(); let mut bundled_positions_map: HashMap<Pubkey, Vec<(Pubkey, Position)>> = HashMap::new(); for i in 0..bundled_positions_addresses.len() { let bundled_position_address = bundled_positions_addresses[i]; let bundled_position_info = &bundled_positions_infos[i]; let position = Position::from_bytes(&bundled_position_info.data)?; let key = position.position_mint; bundled_positions_map.entry(key).or_default(); if let Some(x) = bundled_positions_map.get_mut(&key) { x.push((bundled_position_address, position)) } } let mut position_or_bundles: Vec<PositionOrBundle> = Vec::new(); for i in 0..potiential_tokens.len() { let position = &positions[i]; let position_bundle = &position_bundles[i]; let token_account = &potiential_tokens[i]; if let Some(position) = position { let position_address = position_addresses[i]; position_or_bundles.push(PositionOrBundle::Position(HydratedPosition { address: position_address, data: position.clone(), token_program: token_account.token_program, })); } if let Some(position_bundle) = position_bundle { let position_bundle_address = position_bundle_addresses[i]; let positions = bundled_positions_map .get(&position_bundle.position_bundle_mint) .unwrap_or(&Vec::new()) .iter() .map(|x| HydratedBundledPosition { address: x.0, data: x.1.clone(), }) .collect(); position_or_bundles.push(PositionOrBundle::PositionBundle(HydratedPositionBundle { address: position_bundle_address, data: position_bundle.clone(), positions, token_program: token_account.token_program, })); } } Ok(position_or_bundles) } /// Fetches all positions associated with a specific Whirlpool. /// /// This function retrieves all positions linked to the given Whirlpool address using /// program filters. The positions are decoded and returned as a vector of hydrated position objects. /// /// # Arguments /// /// * `rpc` - A reference to the Solana RPC client. /// * `whirlpool` - The public key of the Whirlpool whose positions should be fetched. /// /// # Returns /// /// A `Result` containing a vector of `DecodedAccount<Position>` objects, representing the /// positions associated with the given Whirlpool. /// /// # Errors /// /// This function will return an error if: /// - RPC calls fail while fetching filtered accounts. /// - Decoding the position data fails. /// /// # Example /// /// ```rust /// use orca_whirlpools::{ /// fetch_positions_in_whirlpool, set_whirlpools_config_address, WhirlpoolsConfigInput, /// }; /// use solana_client::nonblocking::rpc_client::RpcClient; /// use solana_sdk::pubkey::Pubkey; /// use std::str::FromStr; /// /// #[tokio::main] /// async fn main() { /// set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); /// let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); /// let whirlpool_address = /// Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); /// /// let positions = fetch_positions_in_whirlpool(&rpc, whirlpool_address) /// .await /// .unwrap(); /// /// println!("Positions: {:?}", positions); /// } /// ``` pub async fn fetch_positions_in_whirlpool( rpc: &RpcClient, whirlpool: Pubkey, ) -> Result<Vec<DecodedAccount<Position>>, Box<dyn Error>> { let filters = vec![PositionFilter::Whirlpool(whirlpool)]; fetch_all_position_with_filter(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/e2e.rs
use std::error::Error; use orca_whirlpools_client::{get_position_address, Position, Whirlpool}; use serial_test::serial; use solana_program_test::tokio::{self}; use solana_sdk::{program_pack::Pack, pubkey::Pubkey, signer::Signer}; use spl_token_2022::state::Account; use crate::{ close_position_instructions, create_concentrated_liquidity_pool_instructions, create_splash_pool_instructions, decrease_liquidity_instructions, harvest_position_instructions, increase_liquidity_instructions, open_full_range_position_instructions, swap_instructions, tests::{setup_ata_with_amount, setup_mint_with_decimals, RpcContext}, DecreaseLiquidityParam, IncreaseLiquidityParam, SwapQuote, SwapType, SPLASH_POOL_TICK_SPACING, }; struct TestContext { ctx: RpcContext, mint_a: Pubkey, mint_b: Pubkey, ata_a: Pubkey, ata_b: Pubkey, } impl TestContext { pub async fn new() -> Result<Self, Box<dyn Error>> { let ctx = RpcContext::new().await; let mint_a = setup_mint_with_decimals(&ctx, 9).await?; let mint_b = setup_mint_with_decimals(&ctx, 9).await?; let ata_a = setup_ata_with_amount(&ctx, mint_a, 500_000_000_000).await?; let ata_b = setup_ata_with_amount(&ctx, mint_b, 500_000_000_000).await?; Ok(Self { ctx, mint_a, mint_b, ata_a, ata_b, }) } pub async fn init_splash_pool(&self) -> Result<Pubkey, Box<dyn Error>> { let splash_pool = create_splash_pool_instructions( &self.ctx.rpc, self.mint_a, self.mint_b, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( splash_pool.instructions, splash_pool.additional_signers.iter().collect(), ) .await?; let whirlpool_info = &self.ctx.rpc.get_account(&splash_pool.pool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_info.data)?; assert_eq!(whirlpool.token_mint_a, self.mint_a); assert_eq!(whirlpool.token_mint_b, self.mint_b); assert_eq!(whirlpool.tick_spacing, SPLASH_POOL_TICK_SPACING); Ok(splash_pool.pool_address) } pub async fn init_concentrated_liquidity_pool(&self) -> Result<Pubkey, Box<dyn Error>> { let cl_pool = create_concentrated_liquidity_pool_instructions( &self.ctx.rpc, self.mint_a, self.mint_b, 128, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( cl_pool.instructions, cl_pool.additional_signers.iter().collect(), ) .await?; let whirlpool_info = &self.ctx.rpc.get_account(&cl_pool.pool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_info.data)?; assert_eq!(whirlpool.token_mint_a, self.mint_a); assert_eq!(whirlpool.token_mint_b, self.mint_b); assert_eq!(whirlpool.tick_spacing, 128); Ok(cl_pool.pool_address) } pub async fn open_position(&self, pool: Pubkey) -> Result<Pubkey, Box<dyn Error>> { let infos_before = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&infos_before[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&infos_before[1].as_ref().unwrap().data)?; let position = open_full_range_position_instructions( &self.ctx.rpc, pool, IncreaseLiquidityParam::Liquidity(1000000000), None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( position.instructions, position.additional_signers.iter().collect(), ) .await?; let position_address = get_position_address(&position.position_mint)?.0; let infos_after = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_after = Account::unpack(&infos_after[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&infos_after[1].as_ref().unwrap().data)?; let position_after = Position::from_bytes(&infos_after[2].as_ref().unwrap().data)?; assert_eq!(position.quote.liquidity_delta, position_after.liquidity); assert_eq!( token_a_before.amount - token_a_after.amount, position.quote.token_est_a, ); assert_eq!( token_b_before.amount - token_b_after.amount, position.quote.token_est_b, ); Ok(position.position_mint) } pub async fn increase_liquidity(&self, position_mint: Pubkey) -> Result<(), Box<dyn Error>> { let position_address = get_position_address(&position_mint)?.0; let infos_before = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_before = Account::unpack(&infos_before[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&infos_before[1].as_ref().unwrap().data)?; let position_before = Position::from_bytes(&infos_before[2].as_ref().unwrap().data)?; let increase_liquidity = increase_liquidity_instructions( &self.ctx.rpc, position_mint, IncreaseLiquidityParam::Liquidity(1000000000), None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( increase_liquidity.instructions, increase_liquidity.additional_signers.iter().collect(), ) .await?; let infos_after = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_after = Account::unpack(&infos_after[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&infos_after[1].as_ref().unwrap().data)?; let position_after = Position::from_bytes(&infos_after[2].as_ref().unwrap().data)?; assert_eq!( position_after.liquidity - position_before.liquidity, increase_liquidity.quote.liquidity_delta ); assert_eq!( token_a_before.amount - token_a_after.amount, increase_liquidity.quote.token_est_a, ); assert_eq!( token_b_before.amount - token_b_after.amount, increase_liquidity.quote.token_est_b, ); Ok(()) } pub async fn decrease_liquidity(&self, position_mint: Pubkey) -> Result<(), Box<dyn Error>> { let position_address = get_position_address(&position_mint)?.0; let infos_before = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_before = Account::unpack(&infos_before[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&infos_before[1].as_ref().unwrap().data)?; let position_before = Position::from_bytes(&infos_before[2].as_ref().unwrap().data)?; let decrease_liquidity = decrease_liquidity_instructions( &self.ctx.rpc, position_mint, DecreaseLiquidityParam::Liquidity(10000), None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( decrease_liquidity.instructions, decrease_liquidity.additional_signers.iter().collect(), ) .await?; let infos_after = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_after = Account::unpack(&infos_after[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&infos_after[1].as_ref().unwrap().data)?; let position_after = Position::from_bytes(&infos_after[2].as_ref().unwrap().data)?; assert_eq!( position_before.liquidity - position_after.liquidity, decrease_liquidity.quote.liquidity_delta ); assert_eq!( token_a_after.amount - token_a_before.amount, decrease_liquidity.quote.token_est_a, ); assert_eq!( token_b_after.amount - token_b_before.amount, decrease_liquidity.quote.token_est_b, ); Ok(()) } pub async fn harvest_position(&self, position_mint: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let harvest_position = harvest_position_instructions( &self.ctx.rpc, position_mint, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( harvest_position.instructions, harvest_position.additional_signers.iter().collect(), ) .await?; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; assert_eq!( token_a_after.amount - token_a_before.amount, harvest_position.fees_quote.fee_owed_a, ); assert_eq!( token_b_after.amount - token_b_before.amount, harvest_position.fees_quote.fee_owed_b, ); Ok(()) } pub async fn close_position(&self, position_mint: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let close_position = close_position_instructions( &self.ctx.rpc, position_mint, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( close_position.instructions, close_position.additional_signers.iter().collect(), ) .await?; let position_address = get_position_address(&position_mint)?.0; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b, position_address]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; assert!(after_infos[2].is_none()); assert_eq!( token_a_after.amount - token_a_before.amount, close_position.quote.token_est_a + close_position.fees_quote.fee_owed_a, ); assert_eq!( token_b_after.amount - token_b_before.amount, close_position.quote.token_est_b + close_position.fees_quote.fee_owed_b, ); Ok(()) } pub async fn swap_a_exact_in(&self, pool: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let swap = swap_instructions( &self.ctx.rpc, pool, 100000, self.mint_a, SwapType::ExactIn, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( swap.instructions, swap.additional_signers.iter().collect(), ) .await?; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; if let SwapQuote::ExactIn(quote) = swap.quote { assert_eq!(token_a_before.amount - token_a_after.amount, quote.token_in,); assert_eq!( token_b_after.amount - token_b_before.amount, quote.token_est_out, ); } else { return Err("Swap quote is not ExactIn".into()); } Ok(()) } pub async fn swap_a_exact_out(&self, pool: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let swap = swap_instructions( &self.ctx.rpc, pool, 100000, self.mint_a, SwapType::ExactOut, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( swap.instructions, swap.additional_signers.iter().collect(), ) .await?; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; if let SwapQuote::ExactOut(quote) = swap.quote { assert_eq!( token_a_after.amount - token_a_before.amount, quote.token_out, ); assert_eq!( token_b_before.amount - token_b_after.amount, quote.token_est_in, ); } else { return Err("Swap quote is not ExactOut".into()); } Ok(()) } pub async fn swap_b_exact_in(&self, pool: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let swap = swap_instructions( &self.ctx.rpc, pool, 100, self.mint_b, SwapType::ExactIn, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( swap.instructions, swap.additional_signers.iter().collect(), ) .await?; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; if let SwapQuote::ExactIn(quote) = swap.quote { assert_eq!( token_a_after.amount - token_a_before.amount, quote.token_est_out, ); assert_eq!(token_b_before.amount - token_b_after.amount, quote.token_in,); } else { return Err("Swap quote is not ExactIn".into()); } Ok(()) } pub async fn swap_b_exact_out(&self, pool: Pubkey) -> Result<(), Box<dyn Error>> { let before_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_before = Account::unpack(&before_infos[0].as_ref().unwrap().data)?; let token_b_before = Account::unpack(&before_infos[1].as_ref().unwrap().data)?; let swap = swap_instructions( &self.ctx.rpc, pool, 100, self.mint_b, SwapType::ExactOut, None, Some(self.ctx.signer.pubkey()), ) .await?; self.ctx .send_transaction_with_signers( swap.instructions, swap.additional_signers.iter().collect(), ) .await?; let after_infos = &self .ctx .rpc .get_multiple_accounts(&[self.ata_a, self.ata_b]) .await?; let token_a_after = Account::unpack(&after_infos[0].as_ref().unwrap().data)?; let token_b_after = Account::unpack(&after_infos[1].as_ref().unwrap().data)?; if let SwapQuote::ExactOut(quote) = swap.quote { assert_eq!( token_a_before.amount - token_a_after.amount, quote.token_est_in, ); assert_eq!( token_b_after.amount - token_b_before.amount, quote.token_out, ); } else { return Err("Swap quote is not ExactOut".into()); } Ok(()) } } #[tokio::test] #[serial] async fn test_splash_pool() { let ctx = TestContext::new().await.unwrap(); let pool = ctx.init_splash_pool().await.unwrap(); let position_mint = ctx.open_position(pool).await.unwrap(); Box::pin(ctx.swap_a_exact_in(pool)).await.unwrap(); Box::pin(ctx.increase_liquidity(position_mint)) .await .unwrap(); Box::pin(ctx.swap_a_exact_out(pool)).await.unwrap(); Box::pin(ctx.harvest_position(position_mint)).await.unwrap(); Box::pin(ctx.swap_b_exact_in(pool)).await.unwrap(); Box::pin(ctx.decrease_liquidity(position_mint)) .await .unwrap(); Box::pin(ctx.swap_b_exact_out(pool)).await.unwrap(); Box::pin(ctx.close_position(position_mint)).await.unwrap(); } #[tokio::test] #[serial] async fn test_concentrated_liquidity_pool() { let ctx = TestContext::new().await.unwrap(); let pool = ctx.init_concentrated_liquidity_pool().await.unwrap(); let position_mint = ctx.open_position(pool).await.unwrap(); Box::pin(ctx.swap_a_exact_in(pool)).await.unwrap(); Box::pin(ctx.increase_liquidity(position_mint)) .await .unwrap(); Box::pin(ctx.swap_a_exact_out(pool)).await.unwrap(); Box::pin(ctx.harvest_position(position_mint)).await.unwrap(); Box::pin(ctx.swap_b_exact_in(pool)).await.unwrap(); Box::pin(ctx.decrease_liquidity(position_mint)) .await .unwrap(); Box::pin(ctx.swap_b_exact_out(pool)).await.unwrap(); Box::pin(ctx.close_position(position_mint)).await.unwrap(); }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/token_extensions.rs
use solana_sdk::{ pubkey::Pubkey, signer::{keypair::Keypair, Signer}, system_instruction, }; use spl_associated_token_account::{ get_associated_token_address_with_program_id, instruction::create_associated_token_account_idempotent, }; use spl_token_2022::{ extension::{ transfer_fee::instruction::{initialize_transfer_fee_config, set_transfer_fee}, ExtensionType, }, instruction::{initialize_mint2, mint_to}, state::Mint, ID as TOKEN_2022_PROGRAM_ID, }; use std::error::Error; use super::rpc::RpcContext; #[derive(Default)] pub struct SetupAtaConfig { pub amount: Option<u64>, } pub async fn setup_mint_te( ctx: &RpcContext, extensions: &[ExtensionType], ) -> Result<Pubkey, Box<dyn Error>> { let mint = Keypair::new(); let mut instructions = vec![]; // 1. Create account instruction let space = ExtensionType::try_calculate_account_len::<Mint>(extensions)?; let rent = ctx .rpc .get_minimum_balance_for_rent_exemption(space) .await?; instructions.push(system_instruction::create_account( &ctx.signer.pubkey(), &mint.pubkey(), rent, space as u64, &TOKEN_2022_PROGRAM_ID, )); // 2. Initialize extensions first for extension in extensions { match extension { ExtensionType::TransferFeeConfig => { instructions.push(initialize_transfer_fee_config( &TOKEN_2022_PROGRAM_ID, &mint.pubkey(), Some(&ctx.signer.pubkey()), Some(&ctx.signer.pubkey()), 100, // 1% (matching program) 1_000_000_000, // 1 token (matching program) )?); } _ => {} // Handle other extension types here if needed } } // 3. Initialize mint instructions.push(initialize_mint2( &TOKEN_2022_PROGRAM_ID, &mint.pubkey(), &ctx.signer.pubkey(), None, // freeze_authority 6, // decimals )?); // 4. Set extension configurations for extension in extensions { match extension { ExtensionType::TransferFeeConfig => { instructions.push(set_transfer_fee( &TOKEN_2022_PROGRAM_ID, &mint.pubkey(), &ctx.signer.pubkey(), &[], 150, // 1.5% (matching program) 1_000_000_000, // 1 token )?); } _ => {} // Handle other extension types here if needed } } ctx.send_transaction_with_signers(instructions, vec![&mint]) .await?; Ok(mint.pubkey()) } pub async fn setup_mint_te_fee(ctx: &RpcContext) -> Result<Pubkey, Box<dyn Error>> { setup_mint_te(ctx, &[ExtensionType::TransferFeeConfig]).await } pub async fn setup_ata_te( ctx: &RpcContext, mint: Pubkey, config: Option<SetupAtaConfig>, ) -> Result<Pubkey, Box<dyn Error>> { let config = config.unwrap_or_default(); let ata = get_associated_token_address_with_program_id( &ctx.signer.pubkey(), &mint, &TOKEN_2022_PROGRAM_ID, ); let mut instructions = vec![create_associated_token_account_idempotent( &ctx.signer.pubkey(), &ctx.signer.pubkey(), &mint, &TOKEN_2022_PROGRAM_ID, )]; if let Some(amount) = config.amount { instructions.push(mint_to( &TOKEN_2022_PROGRAM_ID, &mint, &ata, &ctx.signer.pubkey(), &[], amount, )?); } ctx.send_transaction(instructions).await?; Ok(ata) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/token.rs
use std::error::Error; use solana_sdk::{ program_pack::Pack, pubkey::Pubkey, signer::Signer, system_instruction::{create_account, transfer}, }; use spl_associated_token_account::{ get_associated_token_address_with_program_id, instruction::create_associated_token_account_idempotent, }; use spl_token::{ instruction::{initialize_mint2, mint_to, sync_native}, native_mint, state::Mint, ID as TOKEN_PROGRAM_ID, }; use super::RpcContext; pub async fn setup_ata(ctx: &RpcContext, mint: Pubkey) -> Result<Pubkey, Box<dyn Error>> { setup_ata_with_amount(ctx, mint, 0).await } pub async fn setup_ata_with_amount( ctx: &RpcContext, mint: Pubkey, amount: u64, ) -> Result<Pubkey, Box<dyn Error>> { let ata = get_associated_token_address_with_program_id( &ctx.signer.pubkey(), &mint, &TOKEN_PROGRAM_ID, ); let mut instructions = vec![create_associated_token_account_idempotent( &ctx.signer.pubkey(), &ctx.signer.pubkey(), &mint, &TOKEN_PROGRAM_ID, )]; if amount > 0 { if mint.eq(&native_mint::ID) { instructions.push(transfer(&ctx.signer.pubkey(), &ata, amount)); instructions.push(sync_native(&TOKEN_PROGRAM_ID, &ata)?); } else { instructions.push(mint_to( &TOKEN_PROGRAM_ID, &mint, &ata, &ctx.signer.pubkey(), &[], amount, )?); } } ctx.send_transaction(instructions).await?; Ok(ata) } pub async fn setup_mint(ctx: &RpcContext) -> Result<Pubkey, Box<dyn Error>> { setup_mint_with_decimals(ctx, 9).await } pub async fn setup_mint_with_decimals( ctx: &RpcContext, decimals: u8, ) -> Result<Pubkey, Box<dyn Error>> { let keypair = ctx.get_next_keypair(); let instructions = vec![ create_account( &ctx.signer.pubkey(), &keypair.pubkey(), 1_000_000_000, Mint::LEN as u64, &TOKEN_PROGRAM_ID, ), initialize_mint2( &TOKEN_PROGRAM_ID, &keypair.pubkey(), &ctx.signer.pubkey(), None, decimals, )?, ]; ctx.send_transaction_with_signers(instructions, vec![keypair]) .await?; Ok(keypair.pubkey()) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/anchor.rs
use std::{env::set_var, error::Error, fs::read_to_string, path::PathBuf, str::FromStr}; use solana_sdk::pubkey::Pubkey; use toml::Table; pub fn anchor_programs(path: String) -> Result<Vec<(String, Pubkey)>, Box<dyn Error>> { let mut programs: Vec<(String, Pubkey)> = Vec::new(); let mut sbf_out_dir: PathBuf = path.parse()?; let mut anchor_toml_path = sbf_out_dir.clone(); sbf_out_dir.push("target/deploy"); anchor_toml_path.push("Anchor.toml"); let toml_str = read_to_string(anchor_toml_path)?; let parsed_toml = Table::from_str(&toml_str)?; let toml_programs_raw = parsed_toml .get("programs") .and_then(|x| x.get("localnet")) .ok_or_else(|| "`programs.localnet` not found in Anchor.toml".to_string())?; let toml_programs_parsed = toml_programs_raw .as_table() .ok_or("Failed to parse `programs.localnet` table.")?; for (key, val) in toml_programs_parsed { let pubkey_with_quotes = val.to_string(); let pubkey_str = &pubkey_with_quotes[1..pubkey_with_quotes.len() - 1]; let pk = Pubkey::from_str(pubkey_str) .map_err(|_| format!("Invalid pubkey in `programs.localnet` table. {}", val))?; programs.push((key.to_string(), pk)); } set_var("SBF_OUT_DIR", sbf_out_dir); Ok(programs) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/mod.rs
mod anchor; mod program; mod rpc; mod token; mod token_extensions; pub use anchor::*; pub use program::*; pub use rpc::*; pub use token::*; pub use token_extensions::*;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/program.rs
use solana_sdk::{pubkey::Pubkey, signer::Signer, system_program}; use std::error::Error; use orca_whirlpools_client::{ get_fee_tier_address, get_token_badge_address, get_whirlpool_address, InitializePoolV2, InitializePoolV2InstructionArgs, }; use orca_whirlpools_core::{price_to_sqrt_price, tick_index_to_sqrt_price}; use solana_program::sysvar::rent::ID as RENT_PROGRAM_ID; use crate::WHIRLPOOLS_CONFIG_ADDRESS; use super::rpc::RpcContext; pub async fn setup_whirlpool( ctx: &RpcContext, token_a: Pubkey, token_b: Pubkey, tick_spacing: u16, ) -> Result<Pubkey, Box<dyn Error>> { let config = *WHIRLPOOLS_CONFIG_ADDRESS.try_lock()?; let fee_tier = get_fee_tier_address(&config, tick_spacing)?.0; let whirlpool = get_whirlpool_address(&config, &token_a, &token_b, tick_spacing)?.0; let token_badge_a = get_token_badge_address(&config, &token_a)?.0; let token_badge_b = get_token_badge_address(&config, &token_b)?.0; let vault_a = ctx.get_next_keypair(); let vault_b = ctx.get_next_keypair(); let mint_a_info = ctx.rpc.get_account(&token_a).await?; let mint_b_info = ctx.rpc.get_account(&token_b).await?; // Default initial price of 1.0 let sqrt_price = tick_index_to_sqrt_price(0); let instructions = vec![InitializePoolV2 { whirlpool, fee_tier, token_mint_a: token_a, token_mint_b: token_b, whirlpools_config: config, funder: ctx.signer.pubkey(), token_vault_a: vault_a.pubkey(), token_vault_b: vault_b.pubkey(), token_badge_a, token_badge_b, token_program_a: mint_a_info.owner, token_program_b: mint_b_info.owner, system_program: system_program::id(), rent: RENT_PROGRAM_ID, } .instruction(InitializePoolV2InstructionArgs { tick_spacing, initial_sqrt_price: sqrt_price, })]; ctx.send_transaction_with_signers(instructions, vec![&vault_a, &vault_b]) .await?; Ok(whirlpool) } pub async fn setup_position(_whirlpool: Pubkey) -> Result<Pubkey, Box<dyn Error>> { todo!() } pub async fn setup_te_position(_whirlpool: Pubkey) -> Result<Pubkey, Box<dyn Error>> { todo!() } pub async fn setup_position_bundle(_whirlpool: Pubkey) -> Result<Pubkey, Box<dyn Error>> { todo!() }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/rust-sdk/whirlpool/src/tests/rpc.rs
use std::sync::atomic::{AtomicUsize, Ordering}; use std::{error::Error, str::FromStr}; use async_trait::async_trait; use orca_whirlpools_client::{ get_fee_tier_address, FEE_TIER_DISCRIMINATOR, WHIRLPOOLS_CONFIG_DISCRIMINATOR, WHIRLPOOL_ID, }; use serde_json::{from_value, to_value, Value}; use solana_account_decoder::{UiAccount, UiAccountEncoding}; use solana_client::client_error::Result as ClientResult; use solana_client::{ client_error::{ClientError, ClientErrorKind}, nonblocking::rpc_client::RpcClient, rpc_client::{RpcClientConfig, SerializableTransaction}, rpc_request::RpcRequest, rpc_response::{Response, RpcBlockhash, RpcResponseContext, RpcVersionInfo}, rpc_sender::{RpcSender, RpcTransportStats}, }; use solana_program_test::tokio::sync::Mutex; use solana_program_test::{ProgramTest, ProgramTestContext}; use solana_sdk::bs58; use solana_sdk::epoch_info::EpochInfo; use solana_sdk::{ account::Account, commitment_config::CommitmentLevel, instruction::Instruction, message::{v0::Message, VersionedMessage}, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_program, transaction::VersionedTransaction, }; use solana_version::Version; use spl_memo::build_memo; use crate::tests::anchor_programs; use crate::{SPLASH_POOL_TICK_SPACING, WHIRLPOOLS_CONFIG_ADDRESS}; pub struct RpcContext { pub rpc: RpcClient, pub signer: Keypair, keypairs: Vec<Keypair>, keypair_index: AtomicUsize, } impl RpcContext { pub async fn new() -> Self { let signer = Keypair::new(); let mut test = ProgramTest::default(); test.prefer_bpf(true); test.add_account( signer.pubkey(), Account { lamports: 100_000_000_000, data: vec![], owner: system_program::ID, executable: false, rent_epoch: 0, }, ); let config = *WHIRLPOOLS_CONFIG_ADDRESS.lock().unwrap(); test.add_account( config, Account { lamports: 100_000_000_000, data: [ WHIRLPOOLS_CONFIG_DISCRIMINATOR, &signer.pubkey().to_bytes(), &signer.pubkey().to_bytes(), &signer.pubkey().to_bytes(), &[0; 2], ] .concat(), owner: WHIRLPOOL_ID, executable: false, rent_epoch: 0, }, ); let default_fee_tier = get_fee_tier_address(&config, 128).unwrap().0; test.add_account( default_fee_tier, Account { lamports: 100_000_000_000, data: [ FEE_TIER_DISCRIMINATOR, &config.to_bytes(), &128u16.to_le_bytes(), &1000u16.to_le_bytes(), ] .concat(), owner: WHIRLPOOL_ID, executable: false, rent_epoch: 0, }, ); let concentrated_fee_tier = get_fee_tier_address(&config, 64).unwrap().0; test.add_account( concentrated_fee_tier, Account { lamports: 100_000_000_000, data: [ FEE_TIER_DISCRIMINATOR, &config.to_bytes(), &64u16.to_le_bytes(), &300u16.to_le_bytes(), ] .concat(), owner: WHIRLPOOL_ID, executable: false, rent_epoch: 0, }, ); let splash_fee_tier = get_fee_tier_address(&config, SPLASH_POOL_TICK_SPACING) .unwrap() .0; test.add_account( splash_fee_tier, Account { lamports: 100_000_000_000, data: [ FEE_TIER_DISCRIMINATOR, &config.to_bytes(), &SPLASH_POOL_TICK_SPACING.to_le_bytes(), &1000u16.to_le_bytes(), ] .concat(), owner: WHIRLPOOL_ID, executable: false, rent_epoch: 0, }, ); let programs = anchor_programs("../..".to_string()).unwrap(); for (name, pubkey) in programs { test.add_program(&name, pubkey, None); } let context = Mutex::new(test.start_with_context().await); let rpc = RpcClient::new_sender(MockRpcSender { context }, RpcClientConfig::default()); let mut keypairs = (0..100).map(|_| Keypair::new()).collect::<Vec<_>>(); keypairs.sort_by_key(|x| x.pubkey()); Self { rpc, signer, keypairs, keypair_index: AtomicUsize::new(0), } } pub fn get_next_keypair(&self) -> &Keypair { let index = self.keypair_index.fetch_add(1, Ordering::Relaxed); &self.keypairs[index] } pub async fn send_transaction( &self, instructions: Vec<Instruction>, ) -> Result<Signature, Box<dyn Error>> { self.send_transaction_with_signers(instructions, vec![]) .await } pub async fn send_transaction_with_signers( &self, instructions: Vec<Instruction>, signers: Vec<&Keypair>, ) -> Result<Signature, Box<dyn Error>> { let blockhash = self.rpc.get_latest_blockhash().await?; // Sine blockhash is not guaranteed to be unique, we need to add a random memo to the tx // so that we can fire two seemingly identical transactions in a row. let memo = Keypair::new().to_base58_string(); let instructions = [instructions, vec![build_memo(memo.as_bytes(), &[])]].concat(); let message = VersionedMessage::V0(Message::try_compile( &self.signer.pubkey(), &instructions, &[], blockhash, )?); let transaction = VersionedTransaction::try_new(message, &[signers, vec![&self.signer]].concat())?; let signature = self.rpc.send_transaction(&transaction).await?; Ok(signature) } } fn get_encoding(config: &Value) -> UiAccountEncoding { config .as_object() .and_then(|x| x.get("encoding")) .and_then(|x| x.as_str()) .and_then(|x| from_value::<UiAccountEncoding>(x.into()).ok()) .unwrap_or(UiAccountEncoding::Base64) } fn to_wire_account( address: &Pubkey, account: Option<Account>, encoding: UiAccountEncoding, ) -> Result<Value, Box<dyn Error>> { if let Some(account) = account { let value = to_value(UiAccount::encode(address, &account, encoding, None, None))?; Ok(value) } else { Ok(Value::Null) } } async fn send( context: &mut ProgramTestContext, method: &str, params: &Vec<Value>, ) -> Result<Value, Box<dyn Error>> { let slot = context.banks_client.get_root_slot().await?; let response = match method { "getAccountInfo" => { let address_str = params[0].as_str().unwrap_or_default(); let address = Pubkey::from_str(address_str)?; let account = context .banks_client .get_account_with_commitment(address, CommitmentLevel::Confirmed) .await?; let encoding = get_encoding(&params[1]); to_value(Response { context: RpcResponseContext { slot, api_version: None, }, value: to_wire_account(&address, account, encoding)?, })? } "getMultipleAccounts" => { let default_addresses = Vec::new(); let addresses = params[0].as_array().unwrap_or(&default_addresses); let encoding = get_encoding(&params[1]); let mut accounts: Vec<Value> = Vec::new(); for address_str in addresses { let address_str = address_str.as_str().unwrap_or_default(); let address = Pubkey::from_str(address_str)?; let account = context .banks_client .get_account_with_commitment(address, CommitmentLevel::Confirmed) .await?; accounts.push(to_wire_account(&address, account, encoding)?); } to_value(Response { context: RpcResponseContext { slot, api_version: None, }, value: accounts, })? } "getMinimumBalanceForRentExemption" => { let data_len = params[0].as_u64().unwrap_or(0) as usize; let rent = context.banks_client.get_rent().await?; to_value(rent.minimum_balance(data_len))? } "getLatestBlockhash" => { let blockhash = context.banks_client.get_latest_blockhash().await?; to_value(Response { context: RpcResponseContext { slot, api_version: None, }, value: RpcBlockhash { blockhash: blockhash.to_string(), last_valid_block_height: slot + 150, }, })? } "sendTransaction" => { let transaction_base64 = params[0].as_str().unwrap_or_default(); let transaction_bytes = base64::decode(transaction_base64)?; let transaction = bincode::deserialize::<VersionedTransaction>(&transaction_bytes)?; let meta = context .banks_client .process_transaction_with_metadata(transaction.clone()) .await?; if let Err(e) = meta.result { return Err(e.to_string().into()); } let signature = transaction.get_signature(); let signature_base58 = bs58::encode(signature).into_string(); to_value(signature_base58)? } "getEpochInfo" => to_value(EpochInfo { epoch: slot / 32, slot_index: slot % 32, slots_in_epoch: 32, absolute_slot: slot, block_height: slot, transaction_count: Some(0), })?, "getVersion" => { let version = Version::default(); to_value(RpcVersionInfo { solana_core: version.to_string(), feature_set: Some(version.feature_set), })? } _ => return Err(format!("Method not implemented: {}", method).into()), }; Ok(response) } struct MockRpcSender { context: Mutex<ProgramTestContext>, } #[async_trait] impl RpcSender for MockRpcSender { async fn send(&self, request: RpcRequest, params: Value) -> ClientResult<Value> { let request_json = request.build_request_json(42, params.clone()); let method = request_json["method"].as_str().unwrap_or_default(); let default_params = Vec::new(); let params = request_json["params"].as_array().unwrap_or(&default_params); let mut context = self.context.lock().await; let response = send(&mut context, method, params).await.map_err(|e| { ClientError::new_with_request(ClientErrorKind::Custom(e.to_string()), request) })?; Ok(response) } fn get_transport_stats(&self) -> RpcTransportStats { RpcTransportStats::default() } fn url(&self) -> String { "MockRpcSender".to_string() } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/client/Cargo.toml
[package] name = "orca_whirlpools_client" version = "0.1.0" description = "Rust client to interact with Orca's on-chain Whirlpool program." include = ["src/*"] documentation = "https://orca-so.github.io/whirlpools/" homepage = "https://orca.so" repository = "https://github.com/orca-so/whirlpools" license = "Apache-2.0" keywords = ["solana", "crypto", "defi", "dex", "amm"] authors = ["team@orca.so"] edition = "2021" [features] default = ["core-types", "fetch"] anchor = ["dep:anchor-lang"] anchor-idl-build = [] core-types = ["dep:orca_whirlpools_core"] serde = ["dep:serde", "dep:serde_with"] fetch = ["dep:solana-client", "dep:solana-sdk", "dep:solana-account-decoder"] [dependencies] anchor-lang = { version = "^0.29", optional = true } borsh = { version = "^0.10" } num-derive = { version = "^0.4" } num-traits = { version = "^0.2" } orca_whirlpools_core = { path = "../core", optional = true } serde = { version = "^1.0", features = ["derive"], optional = true } serde_with = { version = "^3.10", optional = true } solana-program = { version = "^1.17" } solana-sdk = { version = "^1.17", optional = true } solana-client = { version = "^1.17", optional = true } solana-account-decoder = { version = "^1.17", optional = true } thiserror = { version = "^2.0" }
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/client/codama.js
import { createFromRoot } from "codama"; import { renderVisitor } from "@codama/renderers-rust"; import { rootNodeFromAnchor } from "@codama/nodes-from-anchor"; import { readFileSync } from "fs"; const idl = JSON.parse(readFileSync("../../target/idl/whirlpool.json", "utf8")); const node = rootNodeFromAnchor(idl); const visitor = renderVisitor("./src/generated"); // IDL generated with anchor 0.29 does not have the address field so we have to add it manually const codama = createFromRoot({ ...node, program: { ...node.program, publicKey: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc", }, }); codama.accept(visitor);
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/client/README.md
# Orca Whirlpools Client SDK ## Overview This package provides developers with low-level functionalities for interacting with the Whirlpool Program on Solana. It serves as a foundational tool that allows developers to manage and integrate detailed operations into their Rust projects, particularly those related to Orca's Whirlpool Program. This package offers granular control for advanced use cases. > NOTE: To ensure compatibility, use version 1.18 of the `solana-sdk` crate, which matches the version used to build the Whirlpool program. ## Key Features - **Codama Client**: The package includes a set of generated client code based on the Whirlpool Program IDL. This ensures all the necessary program information is easily accessible in a structured format. It handles all decoding and encoding of instructions and account data, making it much easier to interact with the program. - **PDA (Program Derived Addresses) Utilities**: This feature contains utility functions that help derive Program Derived Addresses (PDAs) for accounts within the Whirlpool Program, simplifying address derivation for developers. ## Installation ```bash cargo add orca_whirlpools_client ``` ## Usage Here are some basic examples of how to use the package: ### Deriving a PDA To derive a PDA for a Whirlpool account, you can use the `get_whirlpool_address` PDA utility. ```rust use orca_whirlpools_client::get_whirlpool_address; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; fn main() { let whirlpool_config_address = Pubkey::from_str("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR").unwrap(); let token_mint_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); // wSOL let token_mint_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // DevUSDC let tick_spacing = 64; let (whirlpool_pda, _bump) = get_whirlpool_address(&whirlpool_config_address, &token_mint_a, &token_mint_b, tick_spacing).unwrap(); println!("{:?}", whirlpool_pda); } ``` ### Example: Initialize Pool Instruction The following example demonstrates how to create an `InitializePool` instruction: ```rust use orca_whirlpools_client::{ instructions::InitializePoolV2Builder, get_fee_tier_address, get_token_badge_address, get_whirlpool_address, }; use solana_sdk::{ pubkey::Pubkey, signer::{keypair::Keypair, Signer}, }; use std::str::FromStr; fn main() { let whirlpool_config_address = Pubkey::from_str("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR").unwrap(); let token_mint_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); // wSOL let token_mint_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // DevUSDC let (token_badge_a, _bump) = get_token_badge_address(&whirlpool_config_address, &token_mint_a).unwrap(); let (token_badge_b, _bump) = get_token_badge_address(&whirlpool_config_address, &token_mint_b).unwrap(); let wallet = Keypair::new(); // CAUTION: this wallet is not persistent let tick_spacing = 8; let (whirlpool_pda, _bump) = get_whirlpool_address(&whirlpool_config_address, &token_mint_a, &token_mint_b, tick_spacing).unwrap(); let token_vault_a = Keypair::new(); let token_vault_b = Keypair::new(); let (fee_tier, _bump) = get_fee_tier_address(&whirlpool_config_address, tick_spacing).unwrap(); let token_program_a = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap(); let token_program_b = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap(); let initial_sqrt_price = 7459106261056563200u128; let initialize_pool_v2_instruction = InitializePoolV2Builder::new() .whirlpools_config(whirlpool_config_address) .token_mint_a(token_mint_a) .token_mint_b(token_mint_b) .token_badge_a(token_badge_a) .token_badge_b(token_badge_b) .funder(wallet.pubkey()) .whirlpool(whirlpool_pda) .token_vault_a(token_vault_a.pubkey()) .token_vault_b(token_vault_b.pubkey()) .fee_tier(fee_tier) .token_program_a(token_program_a) .token_program_b(token_program_b) .tick_spacing(tick_spacing) .initial_sqrt_price(initial_sqrt_price) .instruction(); println!("{:?}", initialize_pool_v2_instruction); } ```
0
solana_public_repos/orca-so/whirlpools/rust-sdk
solana_public_repos/orca-so/whirlpools/rust-sdk/client/package.json
{ "name": "@orca-so/whirlpools-rust-client", "version": "0.0.1", "type": "module", "scripts": { "build": "node ./codama.js && cargo build", "test": "cargo test --lib", "format": "cargo clippy --fix --allow-dirty --allow-staged && cargo fmt", "lint": "cargo clippy && cargo fmt --check", "clean": "cargo clean" }, "devDependencies": { "@codama/nodes-from-anchor": "^1.0.0", "@codama/renderers-rust": "^1.0.3", "@orca-so/whirlpools-program": "*", "@orca-so/whirlpools-rust-core": "*", "codama": "^1.0.0" } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/lib.rs
#[rustfmt::skip] mod generated; mod pda; #[cfg(feature = "fetch")] mod gpa; #[cfg(feature = "core-types")] mod core_types; pub use generated::accounts::*; pub use generated::errors::*; pub use generated::instructions::*; pub use generated::programs::WHIRLPOOL_ID as ID; pub use generated::programs::*; pub use generated::types::*; pub use pda::*; #[cfg(feature = "fetch")] pub use gpa::*;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/token_badge.rs
use std::error::Error; use solana_client::nonblocking::rpc_client::RpcClient; use solana_client::rpc_filter::{Memcmp, RpcFilterType}; use solana_program::pubkey::Pubkey; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; use crate::TokenBadge; pub const TOKEN_BADGE_DISCRIMINATOR: &[u8] = &[116, 219, 204, 229, 249, 116, 255, 150]; #[derive(Debug, Clone)] pub enum TokenBadgeFilter { WhirlpoolsConfig(Pubkey), TokenMint(Pubkey), } impl From<TokenBadgeFilter> for RpcFilterType { fn from(val: TokenBadgeFilter) -> Self { match val { TokenBadgeFilter::WhirlpoolsConfig(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } TokenBadgeFilter::TokenMint(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(40, address.to_bytes().to_vec())) } } } } pub async fn fetch_all_token_badge_with_filter( rpc: &RpcClient, filters: Vec<TokenBadgeFilter>, ) -> Result<Vec<DecodedAccount<TokenBadge>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, TOKEN_BADGE_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/tick_array.rs
use std::error::Error; use solana_client::nonblocking::rpc_client::RpcClient; use solana_client::rpc_filter::{Memcmp, RpcFilterType}; use solana_program::pubkey::Pubkey; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; use crate::TickArray; pub const TICK_ARRAY_DISCRIMINATOR: &[u8] = &[69, 97, 189, 190, 110, 7, 66, 187]; #[derive(Debug, Clone)] pub enum TickArrayFilter { Whirlpool(Pubkey), StartTickIndex(i32), } impl From<TickArrayFilter> for RpcFilterType { fn from(val: TickArrayFilter) -> Self { match val { TickArrayFilter::Whirlpool(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(9956, address.to_bytes().to_vec())) } TickArrayFilter::StartTickIndex(tick_index) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, tick_index.to_le_bytes().to_vec())) } } } } pub async fn fetch_all_tick_array_with_filter( rpc: &RpcClient, filters: Vec<TickArrayFilter>, ) -> Result<Vec<DecodedAccount<TickArray>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, TICK_ARRAY_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/whirlpools_config.rs
use std::error::Error; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_filter::{Memcmp, RpcFilterType}, }; use solana_sdk::pubkey::Pubkey; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; use crate::WhirlpoolsConfig; pub const WHIRLPOOLS_CONFIG_DISCRIMINATOR: &[u8] = &[157, 20, 49, 224, 217, 87, 193, 254]; #[derive(Debug, Clone)] pub enum WhirlpoolsConfigFilter { FeeAuthority(Pubkey), CollectProtocolFeesAuthority(Pubkey), RewardEmissionsSuperAuthority(Pubkey), DefaultProtocolFeeRate(u16), } impl From<WhirlpoolsConfigFilter> for RpcFilterType { fn from(val: WhirlpoolsConfigFilter) -> Self { match val { WhirlpoolsConfigFilter::FeeAuthority(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } WhirlpoolsConfigFilter::CollectProtocolFeesAuthority(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(40, address.to_bytes().to_vec())) } WhirlpoolsConfigFilter::RewardEmissionsSuperAuthority(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(72, address.to_bytes().to_vec())) } WhirlpoolsConfigFilter::DefaultProtocolFeeRate(fee_rate) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(104, fee_rate.to_le_bytes().to_vec())) } } } } pub async fn fetch_all_whirlpools_config_with_filter( rpc: &RpcClient, filters: Vec<WhirlpoolsConfigFilter>, ) -> Result<Vec<DecodedAccount<WhirlpoolsConfig>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, WHIRLPOOLS_CONFIG_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/whirlpool.rs
use std::error::Error; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_filter::{Memcmp, RpcFilterType}, }; use solana_sdk::pubkey::Pubkey; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; use crate::Whirlpool; pub const WHIRLPOOL_DISCRIMINATOR: &[u8] = &[63, 149, 209, 12, 225, 128, 99, 9]; #[derive(Debug, Clone)] pub enum WhirlpoolFilter { WhirlpoolConfig(Pubkey), TickSpacing(u16), FeeRate(u16), ProtocolFeeRate(u16), TokenMintA(Pubkey), TokenVaultA(Pubkey), TokenMintB(Pubkey), TokenVaultB(Pubkey), RewardMint0(Pubkey), RewardVault0(Pubkey), RewardMint1(Pubkey), RewardVault1(Pubkey), RewardMint2(Pubkey), RewardVault2(Pubkey), } impl From<WhirlpoolFilter> for RpcFilterType { fn from(val: WhirlpoolFilter) -> Self { match val { WhirlpoolFilter::WhirlpoolConfig(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } WhirlpoolFilter::TickSpacing(tick_spacing) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(41, tick_spacing.to_le_bytes().to_vec()), ), WhirlpoolFilter::FeeRate(fee_rate) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(45, fee_rate.to_le_bytes().to_vec())) } WhirlpoolFilter::ProtocolFeeRate(protocol_fee_rate) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(47, protocol_fee_rate.to_le_bytes().to_vec()), ), WhirlpoolFilter::TokenMintA(token_mint_a) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(101, token_mint_a.to_bytes().to_vec())) } WhirlpoolFilter::TokenVaultA(token_vault_a) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(133, token_vault_a.to_bytes().to_vec()), ), WhirlpoolFilter::TokenMintB(token_mint_b) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(181, token_mint_b.to_bytes().to_vec())) } WhirlpoolFilter::TokenVaultB(token_vault_b) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(213, token_vault_b.to_bytes().to_vec()), ), WhirlpoolFilter::RewardMint0(reward_mint_0) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(269, reward_mint_0.to_bytes().to_vec()), ), WhirlpoolFilter::RewardVault0(reward_vault_0) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(301, reward_vault_0.to_bytes().to_vec()), ), WhirlpoolFilter::RewardMint1(reward_mint_1) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(397, reward_mint_1.to_bytes().to_vec()), ), WhirlpoolFilter::RewardVault1(reward_vault_1) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(429, reward_vault_1.to_bytes().to_vec()), ), WhirlpoolFilter::RewardMint2(reward_mint_2) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(525, reward_mint_2.to_bytes().to_vec()), ), WhirlpoolFilter::RewardVault2(reward_vault_2) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(557, reward_vault_2.to_bytes().to_vec()), ), } } } pub async fn fetch_all_whirlpool_with_filter( rpc: &RpcClient, filters: Vec<WhirlpoolFilter>, ) -> Result<Vec<DecodedAccount<Whirlpool>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, WHIRLPOOL_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/mod.rs
mod fee_tier; mod position; mod position_bundle; mod tick_array; mod token_badge; mod utils; mod whirlpool; mod whirlpools_config; mod whirlpools_config_extension; // FIXME: Discriminators for accounts are not yet added to codama-rust, // here they are added in such a way that if they are added to codama-rust, // we can remove them from here. pub use fee_tier::*; pub use position::*; pub use position_bundle::*; pub use tick_array::*; pub use token_badge::*; pub use utils::*; pub use whirlpool::*; pub use whirlpools_config::*; pub use whirlpools_config_extension::*;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/whirlpools_config_extension.rs
use std::error::Error; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_filter::{Memcmp, RpcFilterType}, }; use solana_sdk::pubkey::Pubkey; use crate::WhirlpoolsConfigExtension; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; pub const WHIRLPOOLS_CONFIG_EXTENSION_DISCRIMINATOR: &[u8] = &[2, 99, 215, 163, 240, 26, 153, 58]; #[derive(Debug, Clone)] pub enum WhirlpoolsConfigExtensionFilter { WhirlpoolsConfig(Pubkey), ConfigExtensionAuthority(Pubkey), ConfigTokenBadgeAuthority(Pubkey), } impl From<WhirlpoolsConfigExtensionFilter> for RpcFilterType { fn from(val: WhirlpoolsConfigExtensionFilter) -> Self { match val { WhirlpoolsConfigExtensionFilter::WhirlpoolsConfig(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } WhirlpoolsConfigExtensionFilter::ConfigExtensionAuthority(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(40, address.to_bytes().to_vec())) } WhirlpoolsConfigExtensionFilter::ConfigTokenBadgeAuthority(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(72, address.to_bytes().to_vec())) } } } } pub async fn fetch_all_whirlpools_config_extension_with_filter( rpc: &RpcClient, filters: Vec<WhirlpoolsConfigExtensionFilter>, ) -> Result<Vec<DecodedAccount<WhirlpoolsConfigExtension>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, WHIRLPOOLS_CONFIG_EXTENSION_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/fee_tier.rs
use solana_client::nonblocking::rpc_client::RpcClient; use solana_client::rpc_filter::Memcmp; use solana_client::rpc_filter::RpcFilterType; use solana_program::pubkey::Pubkey; use std::error::Error; use crate::FeeTier; use super::utils::fetch_decoded_program_accounts; use super::utils::DecodedAccount; pub const FEE_TIER_DISCRIMINATOR: &[u8] = &[56, 75, 159, 76, 142, 68, 190, 105]; #[derive(Debug, Clone)] pub enum FeeTierFilter { WhirlpoolsConfig(Pubkey), TickSpacing(u16), FeeRate(u16), } impl From<FeeTierFilter> for RpcFilterType { fn from(val: FeeTierFilter) -> Self { match val { FeeTierFilter::WhirlpoolsConfig(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } FeeTierFilter::TickSpacing(tick_spacing) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(40, tick_spacing.to_le_bytes().to_vec()), ), FeeTierFilter::FeeRate(fee_rate) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(42, fee_rate.to_le_bytes().to_vec())) } } } } pub async fn fetch_all_fee_tier_with_filter( rpc: &RpcClient, filters: Vec<FeeTierFilter>, ) -> Result<Vec<DecodedAccount<FeeTier>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, FEE_TIER_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/position_bundle.rs
use std::error::Error; use solana_client::nonblocking::rpc_client::RpcClient; use solana_client::rpc_filter::Memcmp; use solana_client::rpc_filter::RpcFilterType; use solana_program::pubkey::Pubkey; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; use crate::PositionBundle; pub const POSITION_BUNDLE_DISCRIMINATOR: &[u8] = &[129, 169, 175, 65, 185, 95, 32, 100]; #[derive(Debug, Clone)] pub enum PositionBundleFilter { Mint(Pubkey), } impl From<PositionBundleFilter> for RpcFilterType { fn from(val: PositionBundleFilter) -> Self { match val { PositionBundleFilter::Mint(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } } } } pub async fn fetch_all_position_bundle_with_filter( rpc: &RpcClient, filters: Vec<PositionBundleFilter>, ) -> Result<Vec<DecodedAccount<PositionBundle>>, Box<dyn Error>> { let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, POSITION_BUNDLE_DISCRIMINATOR.to_vec(), ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/position.rs
use std::error::Error; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_filter::{Memcmp, RpcFilterType}, }; use solana_sdk::pubkey::Pubkey; use crate::Position; use super::utils::{fetch_decoded_program_accounts, DecodedAccount}; pub const POSITION_DISCRIMINATOR: &[u8] = &[170, 188, 143, 228, 122, 64, 247, 208]; #[derive(Debug, Clone)] pub enum PositionFilter { Whirlpool(Pubkey), Mint(Pubkey), TickLowerIndex(i32), TickUpperIndex(i32), } impl From<PositionFilter> for RpcFilterType { fn from(val: PositionFilter) -> Self { match val { PositionFilter::Whirlpool(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(8, address.to_bytes().to_vec())) } PositionFilter::Mint(address) => { RpcFilterType::Memcmp(Memcmp::new_raw_bytes(40, address.to_bytes().to_vec())) } PositionFilter::TickLowerIndex(tick_lower_index) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(88, tick_lower_index.to_le_bytes().to_vec()), ), PositionFilter::TickUpperIndex(tick_upper_index) => RpcFilterType::Memcmp( Memcmp::new_raw_bytes(92, tick_upper_index.to_le_bytes().to_vec()), ), } } } pub async fn fetch_all_position_with_filter( rpc: &RpcClient, filters: Vec<PositionFilter>, ) -> Result<Vec<DecodedAccount<Position>>, Box<dyn Error>> { let discriminator = POSITION_DISCRIMINATOR.to_vec(); let mut filters: Vec<RpcFilterType> = filters.into_iter().map(|filter| filter.into()).collect(); filters.push(RpcFilterType::Memcmp(Memcmp::new_raw_bytes( 0, discriminator, ))); fetch_decoded_program_accounts(rpc, filters).await }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/gpa/utils.rs
use std::error::Error; use borsh::BorshDeserialize; use solana_account_decoder::UiAccountEncoding; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, rpc_filter::RpcFilterType, }; use solana_program::pubkey::Pubkey; use solana_sdk::account::Account; use crate::WHIRLPOOL_ID; #[derive(Debug, Clone)] pub struct DecodedAccount<T> { pub address: Pubkey, pub account: Account, pub data: T, } pub(crate) async fn fetch_decoded_program_accounts<T: BorshDeserialize>( rpc: &RpcClient, filters: Vec<RpcFilterType>, ) -> Result<Vec<DecodedAccount<T>>, Box<dyn Error>> { let accounts = rpc .get_program_accounts_with_config( &WHIRLPOOL_ID, RpcProgramAccountsConfig { filters: Some(filters), account_config: RpcAccountInfoConfig { encoding: Some(UiAccountEncoding::Base64), data_slice: None, commitment: None, min_context_slot: None, }, with_context: None, }, ) .await?; let mut decoded_accounts: Vec<DecodedAccount<T>> = Vec::new(); for (address, account) in accounts { let mut data = account.data.as_slice(); let decoded = T::deserialize(&mut data)?; decoded_accounts.push(DecodedAccount { address, account: account.clone(), data: decoded, }); } Ok(decoded_accounts) }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/token_badge.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_token_badge_address( whirlpools_config: &Pubkey, token_mint: &Pubkey, ) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[ b"token_badge", whirlpools_config.as_ref(), token_mint.as_ref(), ]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_token_badge_address() { let whirlpools_config = Pubkey::from_str("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ").unwrap(); let token_mint = Pubkey::from_str("2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo").unwrap(); let token_badge = Pubkey::from_str("HX5iftnCxhtu11ys3ZuWbvUqo7cyPYaVNZBrLL67Hrbm").unwrap(); let (address, _) = get_token_badge_address(&whirlpools_config, &token_mint).unwrap(); assert_eq!(address, token_badge); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/tick_array.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_tick_array_address( whirlpool: &Pubkey, start_tick_index: i32, ) -> Result<(Pubkey, u8), ProgramError> { let start_tick_index_str = start_tick_index.to_string(); let seeds = &[ b"tick_array", whirlpool.as_ref(), start_tick_index_str.as_bytes(), ]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_tick_array_address() { let whirlpool = Pubkey::from_str("2kJmUjxWBwL2NGPBV2PiA5hWtmLCqcKY6reQgkrPtaeS").unwrap(); let tick_array = Pubkey::from_str("8PhPzk7n4wU98Z6XCbVtPai2LtXSxYnfjkmgWuoAU8Zy").unwrap(); let (address, _) = get_tick_array_address(&whirlpool, 0).unwrap(); assert_eq!(address, tick_array); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/whirlpool.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_whirlpool_address( whirlpools_config: &Pubkey, token_mint_a: &Pubkey, token_mint_b: &Pubkey, tick_spacing: u16, ) -> Result<(Pubkey, u8), ProgramError> { let tick_spacing_bytes = tick_spacing.to_le_bytes(); let seeds = &[ b"whirlpool", whirlpools_config.as_ref(), token_mint_a.as_ref(), token_mint_b.as_ref(), tick_spacing_bytes.as_ref(), ]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_whirlpool_address() { let whirlpools_config = Pubkey::from_str("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ").unwrap(); let token_mint_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_mint_b = Pubkey::from_str("2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo").unwrap(); let whirlpool = Pubkey::from_str("JDQ9GDphXV5ENDrAQtRFvT98m3JwsVJJk8BYHoX8uTAg").unwrap(); let (address, _) = get_whirlpool_address(&whirlpools_config, &token_mint_a, &token_mint_b, 2).unwrap(); assert_eq!(address, whirlpool); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/mod.rs
mod fee_tier; mod oracle; mod position; mod position_bundle; mod tick_array; mod token_badge; mod whirlpool; mod whirlpools_config_extension; pub use fee_tier::*; pub use oracle::*; pub use position::*; pub use position_bundle::*; pub use tick_array::*; pub use token_badge::*; pub use whirlpool::*; pub use whirlpools_config_extension::*;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/oracle.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_oracle_address(whirlpool: &Pubkey) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[b"oracle", whirlpool.as_ref()]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_oracle_address() { let whirlpool = Pubkey::from_str("2kJmUjxWBwL2NGPBV2PiA5hWtmLCqcKY6reQgkrPtaeS").unwrap(); let oracle = Pubkey::from_str("821SHenpVGYY7BCXUzNhs8Xi4grG557fqRw4wzgaPQcS").unwrap(); let (address, _) = get_oracle_address(&whirlpool).unwrap(); assert_eq!(address, oracle); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/whirlpools_config_extension.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_whirlpools_config_extension_address( whirlpools_config: &Pubkey, ) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[b"config_extension", whirlpools_config.as_ref()]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_whirlpools_config_extension_address() { let whirlpools_config = Pubkey::from_str("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ").unwrap(); let whirlpools_config_extension = Pubkey::from_str("777H5H3Tp9U11uRVRzFwM8BinfiakbaLT8vQpeuhvEiH").unwrap(); let (address, _) = get_whirlpools_config_extension_address(&whirlpools_config).unwrap(); assert_eq!(address, whirlpools_config_extension); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/fee_tier.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_fee_tier_address( whirlpools_config: &Pubkey, tick_spacing: u16, ) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[ b"fee_tier", whirlpools_config.as_ref(), &tick_spacing.to_le_bytes(), ]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_fee_tier_address() { let whirlpools_config = Pubkey::from_str("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ").unwrap(); let fee_tier = Pubkey::from_str("62dSkn5ktwY1PoKPNMArZA4bZsvyemuknWUnnQ2ATTuN").unwrap(); let (address, _) = get_fee_tier_address(&whirlpools_config, 1).unwrap(); assert_eq!(address, fee_tier); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/position_bundle.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_position_bundle_address(position_mint: &Pubkey) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[b"position_bundle", position_mint.as_ref()]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } pub fn get_bundled_position_address( position_bundle_address: &Pubkey, bundle_index: u8, ) -> Result<(Pubkey, u8), ProgramError> { let bundle_index_str = bundle_index.to_string(); let seeds = &[ b"bundled_position", position_bundle_address.as_ref(), bundle_index_str.as_bytes(), ]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_position_bundle_address() { let position_mint = Pubkey::from_str("6sf6fSK6tTubFA2LMCeTzt4c6DeNVyA6WpDDgtWs7a5p").unwrap(); let position_bundle = Pubkey::from_str("At1QvbnANV6imkdNkfB4h1XsY4jbTzPAmScgjLCnM7jy").unwrap(); let (address, _) = get_position_bundle_address(&position_mint).unwrap(); assert_eq!(address, position_bundle); } #[test] fn test_get_bundled_position_address() { let position_bundle_address = Pubkey::from_str("6sf6fSK6tTubFA2LMCeTzt4c6DeNVyA6WpDDgtWs7a5p").unwrap(); let bundled_position = Pubkey::from_str("9Zj8oWYVQdBCtqMn9Z3YyGo8o7hVXLEUZ5x5no5ykVm6").unwrap(); let (address, _) = get_bundled_position_address(&position_bundle_address, 0).unwrap(); assert_eq!(address, bundled_position); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/pda/position.rs
use crate::generated::programs::WHIRLPOOL_ID; use solana_program::program_error::ProgramError; use solana_program::pubkey::Pubkey; pub fn get_position_address(position_mint: &Pubkey) -> Result<(Pubkey, u8), ProgramError> { let seeds = &[b"position", position_mint.as_ref()]; Pubkey::try_find_program_address(seeds, &WHIRLPOOL_ID).ok_or(ProgramError::InvalidSeeds) } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_get_position_address() { let position_mint = Pubkey::from_str("6sf6fSK6tTubFA2LMCeTzt4c6DeNVyA6WpDDgtWs7a5p").unwrap(); let position = Pubkey::from_str("2EtH4ZZStW8Ffh2CbbW4baekdtWgPLcBXfYQ6FRmMVsq").unwrap(); let (address, _) = get_position_address(&position_mint).unwrap(); assert_eq!(address, position); } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/core_types/tick_array.rs
use orca_whirlpools_core::{TickArrayFacade, TickFacade}; use crate::{Tick, TickArray}; impl From<TickArray> for TickArrayFacade { fn from(val: TickArray) -> Self { TickArrayFacade { start_tick_index: val.start_tick_index, ticks: val.ticks.map(|tick| tick.into()), } } } impl From<Tick> for TickFacade { fn from(val: Tick) -> Self { TickFacade { liquidity_net: val.liquidity_net, liquidity_gross: val.liquidity_gross, initialized: val.initialized, fee_growth_outside_a: val.fee_growth_outside_a, fee_growth_outside_b: val.fee_growth_outside_b, reward_growths_outside: val.reward_growths_outside, } } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/core_types/whirlpool.rs
use orca_whirlpools_core::{WhirlpoolFacade, WhirlpoolRewardInfoFacade}; use crate::{Whirlpool, WhirlpoolRewardInfo}; impl From<Whirlpool> for WhirlpoolFacade { fn from(val: Whirlpool) -> Self { WhirlpoolFacade { tick_spacing: val.tick_spacing, fee_rate: val.fee_rate, protocol_fee_rate: val.protocol_fee_rate, liquidity: val.liquidity, sqrt_price: val.sqrt_price, tick_current_index: val.tick_current_index, fee_growth_global_a: val.fee_growth_global_a, fee_growth_global_b: val.fee_growth_global_b, reward_last_updated_timestamp: val.reward_last_updated_timestamp, reward_infos: val.reward_infos.map(|info| info.into()), } } } impl From<WhirlpoolRewardInfo> for WhirlpoolRewardInfoFacade { fn from(val: WhirlpoolRewardInfo) -> Self { WhirlpoolRewardInfoFacade { emissions_per_second_x64: val.emissions_per_second_x64, growth_global_x64: val.growth_global_x64, } } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/core_types/mod.rs
mod position; mod tick_array; mod tick_range; mod whirlpool;
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/core_types/position.rs
use orca_whirlpools_core::{PositionFacade, PositionRewardInfoFacade}; use crate::{Position, PositionRewardInfo}; impl From<Position> for PositionFacade { fn from(val: Position) -> Self { PositionFacade { liquidity: val.liquidity, tick_lower_index: val.tick_lower_index, tick_upper_index: val.tick_upper_index, fee_growth_checkpoint_a: val.fee_growth_checkpoint_a, fee_growth_checkpoint_b: val.fee_growth_checkpoint_b, fee_owed_a: val.fee_owed_a, fee_owed_b: val.fee_owed_b, reward_infos: val.reward_infos.map(|info| info.into()), } } } impl From<PositionRewardInfo> for PositionRewardInfoFacade { fn from(val: PositionRewardInfo) -> Self { PositionRewardInfoFacade { growth_inside_checkpoint: val.growth_inside_checkpoint, amount_owed: val.amount_owed, } } }
0
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src
solana_public_repos/orca-so/whirlpools/rust-sdk/client/src/core_types/tick_range.rs
use orca_whirlpools_core::TickRange; use crate::Position; impl From<Position> for TickRange { fn from(val: Position) -> Self { TickRange { tick_lower_index: val.tick_lower_index, tick_upper_index: val.tick_upper_index, } } }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/rust/Cargo.toml
[package] name = "orca_whirlpools_docs" version = "0.1.0" publish = false edition = "2021" [dependencies] orca_whirlpools_core = { path = "../../rust-sdk/core", features = ["floats"] } orca_whirlpools_client = { path = "../../rust-sdk/client", features = ["anchor", "core-types"] } orca_whirlpools = { path = "../../rust-sdk/whirlpool" }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/rust/README.md
# Orca Whirlpools SDKs ![Overview of Orca Whirlpools SDK suite](/../whirlpools/img/01-Welcome/orca-sdks-overview-rustdocs.png) The Whirlpools SDKs are Orca's primary set of SDKs designed to provide enhanced, modular interaction with the Whirlpool Program on Solana and Eclipse. Whether you are managing liquidity, building applications that require pool infrastructure, or building automation tools that interact with the program, our SDKs cover a spectrum of functionality from low-level granular control to high-level abstractions. This offering is divided into three main components: ### 1. High-Level SDK (in development, requires Solana SDK v1.18) The High-Level SDK is our top recommendation for anyone who wants to integrate with the Whirlpool Program. It builds upon the Low-Level and Core SDKs to provide an easy-to-use interface for interacting with the Whirlpool Program. This SDK abstracts many of the underlying complexities, such as tick array management, and makes managing pools and positions, and executing swaps much simpler. It is suitable for developers who need efficient, high-level functionalities and want to minimize manual configuration and management. ### 2. Core SDK The Core SDK provides essential utilities for math operations and quotes, required for working with liquidity pools. This library focuses on calculations such as determining position status, price conversions, and computing quotes on adjusting liquidity and swaps. It is written in Rust but has been compiled to WebAssembly (Wasm) for easy integration into TypeScript projects. ### 3. Low-Level SDK (requires Solana SDK \<v2) The Low-Level SDK is autogenerated from the Whirlpool Program's Interface Description Language (IDL). This SDK provides direct program interactions and is designed for developers who need complete, low-level control over Whirlpool operations. It covers direct access to Solana accounts, instructions, and transactions.
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/rust/package.json
{ "name": "@orca-so/whirlpools-docs-rust", "version": "0.0.0", "private": true, "scripts": { "build": "cargo doc --lib --no-deps && cp -rf target/doc/. dist", "start": "cargo doc --lib --no-deps --open", "clean": "rimraf dist" }, "devDependencies": { "@orca-so/whirlpools-rust": "*", "@orca-so/whirlpools-rust-client": "*", "@orca-so/whirlpools-rust-core": "*" } }
0
solana_public_repos/orca-so/whirlpools/docs/rust
solana_public_repos/orca-so/whirlpools/docs/rust/src/lib.rs
#![doc = include_str!("../README.md")] pub mod orca_whirlpools_core { #![doc = include_str!("../../../rust-sdk/core/README.md")] pub use orca_whirlpools_core::*; } pub mod orca_whirlpools_client { #![doc = include_str!("../../../rust-sdk/client/README.md")] pub use orca_whirlpools_client::*; } pub mod orca_whirlpools { #![doc = include_str!("../../../rust-sdk/whirlpool/README.md")] pub use orca_whirlpools::*; }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/legacy/package.json
{ "name": "@orca-so/whirlpools-docs-legacy", "version": "0.0.0", "private": true, "scripts": { "build": "typedoc", "start": "typedoc && open dist/legacy/index.html", "clean": "rimraf dist" }, "devDependencies": { "@orca-so/whirlpools-sdk": "*", "typedoc": "^0.27.4", "typescript": "^5.7.2" } }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/legacy/typedoc.json
{ "entryPoints": ["../../legacy-sdk/whirlpool/src/index.ts"], "entryPointStrategy": "resolve", "githubPages": false, "skipErrorChecking": true, "out": "dist/legacy" }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/package.json
{ "name": "@orca-so/whirlpools-docs", "version": "0.0.0", "private": true, "scripts": { "build": "docusaurus build --out-dir dist", "start": "docusaurus start", "clean": "rimraf dist .docusaurus" }, "dependencies": { "@docusaurus/core": "^3.6.3", "@docusaurus/preset-classic": "^3.6.3", "@mdx-js/react": "^3.1.0", "clsx": "^2.1.1", "next": "^15.1.0", "prism-react-renderer": "^2.4.1", "react": "^18.3.1", "react-dom": "^18.3.1", "rehype-katex": "^7.0.1", "remark-math": "^6.0.0" }, "devDependencies": { "@docusaurus/module-type-aliases": "^3.6.3", "@docusaurus/tsconfig": "^3.6.3", "@docusaurus/types": "^3.6.3", "@orca-so/whirlpools-docs-legacy": "*", "@orca-so/whirlpools-docs-rust": "*", "@orca-so/whirlpools-docs-ts": "*", "@types/react": "^18.3.13" }, "browserslist": { "production": [ ">0.5%", "not dead", "not op_mini all" ], "development": [ "last 3 chrome version", "last 3 firefox version", "last 5 safari version" ] } }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docusaurus.config.js
import { themes } from "prism-react-renderer"; import remarkMath from "remark-math"; import rehypeKatex from "rehype-katex"; export default { title: "Whirlpools", tagline: "Open source concentrated liquidity AMM contract on Solana", favicon: "https://orca.so/favicon.ico", url: "https://orca-so.github.io/", baseUrl: "/whirlpools", organizationName: "orca-so", projectName: "whirlpools", onBrokenLinks: "throw", onBrokenMarkdownLinks: "warn", i18n: { defaultLocale: "en", locales: ["en"], }, staticDirectories: ["static", "../ts/dist", "../legacy/dist", "../rust/dist"], presets: [ [ "@docusaurus/preset-classic", { docs: { routeBasePath: "/", sidebarPath: "./sidebars.js", editUrl: "https://github.com/orca-so/whirlpools/tree/main/docs/whirlpool", remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex], }, theme: { customCss: "./static/index.css", }, }, ], ], stylesheets: [ { href: "https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css", type: "text/css", integrity: "sha384-odtC+0UGzzFL/6PNoE8rX/SPcQDXBJ+uRepguP4QkPCm2LBxH3FA3y+fKSiJ+AmM", crossorigin: "anonymous", }, ], themeConfig: { image: "img/docusaurus-social-card.jpg", navbar: { title: "Whirlpools", logo: { alt: "Orca Logo", src: "https://orca.so/android-chrome-192x192.png", }, items: [ { to: "/", label: "Docs", position: "left" }, { label: "Whirlpools SDKs Reference", position: "left", items: [ { href: "/ts/", label: "TS SDK Reference", target: "_blank", }, { href: "/orca_whirlpools_docs/", label: "Rust SDK Reference", target: "_blank", }, ], }, { href: "/legacy/", label: "Legacy SDK Reference", position: "left", target: "_blank", }, { href: "https://github.com/orca-so/whirlpools", label: "GitHub", position: "right", }, ], }, prism: { theme: themes.github, darkTheme: themes.dracula, }, }, };
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/tsconfig.json
{ "extends": "@docusaurus/tsconfig", "compilerOptions": { "baseUrl": "." } }
0
solana_public_repos/orca-so/whirlpools/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/sidebars.js
export default { sidebar: [{ type: "autogenerated", dirName: "." }], };
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/01-Welcome.mdx
--- sidebar_position: 1 slug: / --- import DocCard from '@theme/DocCard'; # Welcome On both the Solana and Eclipse networks, the Whirlpool Program runs as an open-sourced concentrated liquidity automated market maker (CLAMM). The program enables advanced DeFi operations such as creating liquidity pools and swapping. <DocCard item={{ type: 'link', href: 'https://github.com/orca-so/whirlpools', label: 'Whirlpools Program', description: 'https://github.com/orca-so/whirlpools' }} /> ## Overview of Orca Whirlpools SDK suite ![Overview of Orca Whirlpools SDK suite](../static/img/01-Welcome/orca-sdks-overview.png) Orca provides a range of SDKs that cater to different levels of development needs for interacting with the Whirlpool Program on Solana and Eclipse. Whether you are managing liquidity, building applications that require pool infrastructure, or building automation tools that interact with the program, our SDKs cover a spectrum of functionality from low-level granular control to high-level abstractions. What follows is a brief overview of our SDK suite, distinguishing between the Whirlpools SDKs and the Legacy SDK, and explaining their intended purposes and relationships. ### Whirlpools SDKs The Whirlpools SDKs are our primary set of SDKs designed to provide enhanced, modular interaction with the Whirlpool Program. This offering is divided into three main components: #### 1. High-Level SDK - **TypeScript**: [@orca-so/whirlpools](https://www.npmjs.com/package/@orca-so/whirlpools) (Requires Solana Web3.js SDK ≥v2.0) - **Rust**: orca_whirlpools (requires Solana SDK v1.18) - **Description**: The High-Level SDK is our top recommendation for anyone who wants to integrate with the Whirlpool Program. It builds upon the Low-Level and Core SDKs to provide an easy-to-use interface for interacting with the Whirlpool Program. This SDK abstracts many of the underlying complexities, such as tick array management, and makes managing pools and positions, and executing swaps much simpler. It is suitable for developers who need efficient, high-level functionalities and want to minimize manual configuration and management. #### 2. Core SDK - **TypeScript**: [@orca-so/whirlpools-core](https://www.npmjs.com/package/@orca-so/whirlpools-core) - **Rust**: [orca_whirlpools_core](https://crates.io/crates/orca_whirlpools_core) - **Description**: The Core SDK provides essential utilities for math operations and quotes, required for working with liquidity pools. This library focuses on calculations such as determining position status, price conversions, and computing quotes on adjusting liquidity and swaps. It is written in Rust but has been compiled to WebAssembly (Wasm) for easy integration into TypeScript projects. #### 3. Low-Level SDK - **TypeScript**: [@orca-so/whirlpools-client](https://www.npmjs.com/package/@orca-so/whirlpools-client) (Requires Solana Web3.js SDK ≥v2.0) - **Rust**: [orca_whirlpools_client](https://crates.io/crates/orca_whirlpools_client) (Requires Solana SDK \<v2) - **Description**: The Low-Level SDK is autogenerated from the Whirlpool Program's Interface Description Language (IDL) using Codama. This SDK provides direct program interactions and is designed for developers who need complete, low-level control over Whirlpool operations. It covers direct access to Solana accounts, instructions, and transactions. ### Legacy SDK - **TypeScript**: [@orca-so/whirlpools-sdk](https://www.npmjs.com/package/@orca-so/whirlpools-sdk) (Requires Solana Web3.js SDK \<v2.0) - **Description**: Despite being called "Legacy", this SDK remains a reliable choice for integrating with projects that use Solana Web3.js versions older than v2.0. It offers foundational tools for interacting with Orca's Whirlpool Program and includes utilities from @orca-so/common-sdk. ## How to use this documentation In the next section you will find information about the Whirlpool Program and its architecture. In the following sections you will find documentation on the Whirlpools SDKs and the Legacy SDK and how to use it to interact with the program. If you have any questions or need help, feel free to reach out to us on the [Discord](https://discord.orca.so).
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/08-Errors.mdx
import DocCard from '@theme/DocCard'; # Errors Whirlpool errors are emitted as a hexadecimal number (ex. 0x1771). Convert this value back to decimal to determine where the error is coming from. ## Anchor Errors (error code < 6000) Anchor - \>= 100 Instruction error codes - \>= 1000 IDL error codes - \>= 2000 constraint error codes - \>= 3000 account error codes - = 4000 state error code - \>= 4100 misc error codes - = 5000 deprecated error code <DocCard item={{ type: 'link', href: 'https://docs.rs/anchor-lang/latest/anchor_lang/error/enum.ErrorCode.html', label: 'Anchor Errors', description: 'https://docs.rs/anchor-lang/latest/anchor_lang/error/enum.ErrorCode.html' }} /> ## Whirlpool Errors (error code >= 6000) Match your error hex code with this page to find your Whirlpool errors. <DocCard item={{ type: 'link', href: 'https://github.com/orca-so/whirlpools/blob/main/programs/whirlpool/src/errors.rs', label: 'Whirlpools Anchor Errors', description: 'https://github.com/orca-so/whirlpools/blob/main/programs/whirlpool/src/errors.rs' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/06-PubkeySollet.mdx
import DocCard from '@theme/DocCard'; # PubkeySollet When interacting with Whirlpool, it is very useful to observe the transactions generated by Orca's UI. The transaction dump function provided by PubkeySollet allows you to know the data and accounts without executing a transaction. ![PubkeSollet Screenshot](../../static/img/05-Developer%20Tools/pubkey-sollet.webp) PubkeySollet is available on Chrome Web Store. <DocCard item={{ type: 'link', href: 'https://chromewebstore.google.com/detail/pubkeysollet/pjligelplfpbmdlachdpefnfdokedfea', label: 'PubkeySollet', description: 'https://chromewebstore.google.com/detail/pubkeysollet/pjligelplfpbmdlachdpefnfdokedfea' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/03-IDL.mdx
import DocCard from '@theme/DocCard'; # IDL An Interface Description Language (IDL) file provides a standardized JSON file describing the program's instructions and accounts. This file simplifies the process of integrating your on-chain program with client applications. To interact with the program, we highly recommend using our SDKs. For low-level control, use [`@orca-so/whirlpools_client`](https://www.npmjs.com/package/@orca-so/whirlpools-client) for TypeScript or [`orca_whirlpools_client`](https://crates.io/crates/orca_whirlpools_client) for Rust. Both are generated using Codama based on the IDL of the Whirlpool Program. If you're using a different programming language, or simply want to inspect our IDL you can download it by clicking on the link below. <DocCard item={{ type: 'link', href: 'https://github.com/orca-so/whirlpools/actions/runs/11329909458/artifacts/2053731610', label: 'Anchor IDL', description: 'https://github.com/orca-so/whirlpools/actions/runs/11329909458/artifacts/2053731610' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/01-A Note for Python Devs.mdx
import DocCard from '@theme/DocCard'; # A Note for Python Devs Python developers are able to interact with Whirlpool through Whirlpool Essential library! <DocCard item={{ type: 'link', href: 'https://pypi.org/project/whirlpool-essentials/', label: 'Whirlpool Essentials', description: 'https://pypi.org/project/whirlpool-essentials/' }} /> <DocCard item={{ type: 'link', href: 'https://github.com/everlastingsong/whirlpool-essentials', label: 'Whirlpool Essentials - GitHub', description: 'https://github.com/everlastingsong/whirlpool-essentials' }} /> Whirlpool Essentials library contains almost functions provided by SDK for Typescript. From the following code, you will find many common codes. ```python import asyncio from solana.rpc.async_api import AsyncClient from solders.pubkey import Pubkey from solders.keypair import Keypair from orca_whirlpool.constants import ORCA_WHIRLPOOL_PROGRAM_ID from orca_whirlpool.context import WhirlpoolContext from orca_whirlpool.utils import PriceMath, DecimalUtil SOL_USDC_8_WHIRLPOOL_PUBKEY = Pubkey.from_string("7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm") async def main(): connection = AsyncClient(RPC_ENDPOINT_URL) ctx = WhirlpoolContext(ORCA_WHIRLPOOL_PROGRAM_ID, connection, Keypair()) # get SOL/USDC(ts=8) whirlpool whirlpool_pubkey = SOL_USDC_8_WHIRLPOOL_PUBKEY whirlpool = await ctx.fetcher.get_whirlpool(whirlpool_pubkey) decimals_a = (await ctx.fetcher.get_token_mint(whirlpool.token_mint_a)).decimals # SOL_DECIMAL decimals_b = (await ctx.fetcher.get_token_mint(whirlpool.token_mint_b)).decimals # USDC_DECIMAL print("whirlpool token_mint_a", whirlpool.token_mint_a) print("whirlpool token_mint_b", whirlpool.token_mint_b) print("whirlpool tick_spacing", whirlpool.tick_spacing) print("whirlpool tick_current_index", whirlpool.tick_current_index) print("whirlpool sqrt_price", whirlpool.sqrt_price) price = PriceMath.sqrt_price_x64_to_price(whirlpool.sqrt_price, decimals_a, decimals_b) print("whirlpool price", DecimalUtil.to_fixed(price, decimals_b)) asyncio.run(main()) ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/07-Whirlpool Replayer.mdx
import DocCard from '@theme/DocCard'; # Whirlpool Replayer Extracting Whirlpool related transactions, from Solana's vast transaction history, and recovering historical states from that data has been an insurmountable problem. However, developers using Whirlpool can use the whirlpool-replayer library to get the state of a Whirlpool on a given day and all the instructions that were executed in sequence through callbacks. Within the callback, developers can focus on extracting the data they need. Don't worry. There is no absolutely need to have a special machine; whirlpool-replayer replays only the Whirlpool Program. Therefore, it requires very few machine resources and will run reliably on a laptop computer. Many use cases for whirlpool-replayer come to mind. - Extracting OHLCV history - Extracting liquidity distribution history - Calculating profit over the life cycle of a position - Back-testing of trade strategies <DocCard item={{ type: 'link', href: 'https://github.com/orca-so/whirlpool-tx-replayer', label: 'Whirlpool TX Replayer', description: 'https://github.com/orca-so/whirlpool-tx-replayer' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/04-API.mdx
--- sidebar-label: API --- import DocCard from '@theme/DocCard'; # API Endpoints <DocCard item={{ type: 'link', href: 'https://api.mainnet.orca.so/v1/whirlpool/list', label: 'Whirlpool List', description: 'https://api.mainnet.orca.so/v1/whirlpool/list' }} /> <DocCard item={{ type: 'link', href: 'https://api.mainnet.orca.so/v1/token/list', label: 'Token List', description: 'https://api.mainnet.orca.so/v1/token/list' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/02-A Note for Unity Devs.mdx
--- sidebar_label: A Note for C#/Unity Devs --- import DocCard from '@theme/DocCard'; # A Note for Unity/C# Devs Today, Unity/C# developers will have smooth access to Solana applications, including Whirlpool! ## Solana.Unity-SDK Garbles Labs is developing Solana.Unity-Core and Solana.Unity-SDK. Solana.Unity-SDK is the interface to access Solana.Unity-Core, Solnet implementation in .NET Standard 2.0 (Unity compatible). The SDK allows Unity/C# developers to access all the methods implemented in Solana.Unity-Core, including Whirlpool operations! <DocCard item={{ type: 'link', href: 'https://solana.unity-sdk.gg/', label: 'Solana.Unity-SDK - Introduction', description: 'https://solana.unity-sdk.gg/' }} /> <DocCard item={{ type: 'link', href: 'https://solana.unity-sdk.gg/docs/orca', label: 'DEX Integration with Orca - Docs', description: 'https://solana.unity-sdk.gg/docs/orca' }} /> <DocCard item={{ type: 'link', href: 'https://github.com/garbles-labs', label: 'Garbles Labs GitHub repository', description: 'https://github.com/garbles-labs' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/05-More Resources/05-Account Microscope.mdx
import DocCard from '@theme/DocCard'; # Account microscope When developing with Whirlpool, it is often necessary to check the state of accounts and to obtain a list of whirlpools and positions. And sometimes we want to do hexdump and download accounts to clone Whirlpool. 🔬 Account microscope have been designed to do those tasks. Please enjoy with it! <DocCard item={{ type: 'link', href: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/list', label: 'Entrance: The list of the Orca supported whirlpools', description: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/list' }} /> <DocCard item={{ type: 'link', href: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/whirlpool/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ', label: 'SOL/USDC(tickSpacing=64) Whirlpool account details', description: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/whirlpool/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ' }} /> <DocCard item={{ type: 'link', href: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/listPositions/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ', label: 'All positions in SOL/USDC(tickSpacing=64) Whirlpool', description: 'https://everlastingsong.github.io/account-microscope/#/whirlpool/listPositions/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ' }} /> <DocCard item={{ type: 'link', href: 'https://everlastingsong.github.io/account-microscope/#/generic/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ', label: 'Hexdump of SOL/USDC(tickSpacing=64) Whirlpool', description: 'https://everlastingsong.github.io/account-microscope/#/generic/HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/00-Installation.md
# Installation The legacy Whirlpools Typescript SDK (`@orca-so/whirlpools-sdk`) allows for easy interaction with a deployed Whirlpools program and is a solid choice if you are working the Solana Web3.js \<v2. In your project, run: ```bash yarn add "@orca-so/whirlpools-sdk" yarn add "@orca-so/common-sdk" yarn add "@coral-xyz/anchor@0.29.0" yarn add "@solana/web3.js" yarn add "@solana/spl-token" yarn add "decimal.js" ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/04-Performing Swaps.md
# Performing Swaps Before we begin, you should have an understanding of what ticks are and how they are stored. If not, you can reference [Price & Ticks](../02-Architecture%20Overview/02-Price%20&%20Ticks.md). ## Trade with WhirlpoolClient You can use the swap quote and WhirlpoolClient to easily perform a trade. Learn more about `amountSpecifiedIsInput` , `aToB` in the section below. ### Generating a swap quote by input or output token Generate quote with one of the quote functions: - [`swapQuoteByInputToken`](https://orca-so.github.io/whirlpools/legacy/functions/swapQuoteByInputToken.html) if you want an estimate on the amount of outputToken received on an amount of inputToken. - [`swapQuoteByOutputToken`](https://orca-so.github.io/whirlpools/legacy/functions/swapQuoteByInputToken.html) if you want an estimate on the amount of inputToken needed to receive a set amount of outputToken. The resulting [`SwapQuote`](https://orca-so.github.io/whirlpools/legacy/types/SwapQuote.html) object contains the estimations on the expected amount of tokenIn, tokenOut, fees, projected ending sqrtPrice. When you are ready, plug the quote object directly into the swapIx to perform the trade. ```tsx const whirlpoolPda = PDAUtil.getWhirlpool(...); const whirlpoolClient = buildWhirlpoolClient(ctx); const whirlpool = await whirlpoolClient.getPool(whirlpoolPda.publicKey, true); // use getData or refreshData, depending on whether you think your data is stale. const whirlpoolData = await whirlpool.getData(); const inputTokenQuote = await swapQuoteByInputToken( whirlpool, whirlpoolData.tokenMintB, new u64(190000000), Percentage.fromFraction(1, 1000), // 0.1% ctx.program.programId, fetcher, true ); // Send out the transaction const txId = await (await whirlpool.swap(inputTokenQuote)).buildAndExecute(); ``` ### Adding a developer fee to the swap The SDK also provides [`swapQuoteByInputTokenWithDevFees`](https://orca-so.github.io/whirlpools/legacy/functions/swapQuoteByInputTokenWithDevFees.html) & [`swapWithDevFees`](https://orca-so.github.io/whirlpools/legacy/interfaces/Whirlpool.html#swapWithDevFees) function to let developers take a fee as a percentage of the input asset. This feature is a convenient way to calculate the percentage, build a transfer instruction for the fee, and use the remaining input asset in a swap instruction. ```tsx // Wallet used to collect developer fees const DEV_WALLET = new PublicKey(...) const whirlpoolPda = PDAUtil.getWhirlpool(...); const whirlpoolClient = buildWhirlpoolClient(ctx); const whirlpool = await whirlpoolClient.getPool(whirlpoolPda.publicKey, true); // use getData or refreshData, depending on whether you think your data is stale. const whirlpoolData = await whirlpool.getData(); const inputTokenQuote = await swapQuoteByInputTokenWithDevFees( whirlpool, whirlpoolData.tokenMintB, new u64(190000000), Percentage.fromFraction(1, 1000), // 0.1% ctx.program.programId, fetcher, Percentage.fromFraction(2, 1000), // 0.2% of the input asset will be sent to DEV_WALLET true ); // Send out the transaction const txId = await (await whirlpool.swapWithDevFees(inputTokenQuote, DEV_WALLET)).buildAndExecute(); ``` > ℹ️ The developer fee transfer is performed by the SPL Token program or System program, and not the Whirlpools program. Best practice is to [pre-create Associated Token Accounts (ATA)](https://solanacookbook.com/references/token.html#how-to-create-a-token-account) for each token type which will be sent to the developer wallet. Also, if the fee will be payed in SOL, make sure that the developer wallet has at least 0.001 SOL to ensure that the wallet account will meet rent exemption. ## The Manual Way Manually constructing your own parameters gives you more flexibility in defining the boundaries of your trade. ### Trade Parameters The [`swap`](https://orca-so.github.io/whirlpools/legacy/interfaces/Whirlpool.html#swap) instruction requires the following input (and other common accounts) to execute the trade. ```tsx export type SwapInput = { amount: u64; otherAmountThreshold: u64; sqrtPriceLimit: BN; amountSpecifiedIsInput: boolean; aToB: boolean; tickArray0: PublicKey; tickArray1: PublicKey; tickArray2: PublicKey; }; ``` - Decide the trade direction with `aToB` - If true, you are trading from token A to B - If false, you are trading from token B to A - Decide the token you would like to cap with `amountSpecifiedIsInput` - If true, `amount` is the value representing the token being traded from. This amount is subject to trade fees before the trade calculation. - If false, `amount` is the value representing the token being traded to. This amount is the required token out amount from a trade after fees. - Decide whether you want to cap the other token of the trade using `otherAmountThreshold` - If `amountSpecifiedIsInput` is true, this amount represents the minimum amount of output token expected from this trade. If you do not want to cap, use 0. - If `amountSpecifiedIsInput` is false, this amount represents the maximum amount of input token that can be used to trade to an expected amount of the output token. If you do not want to cap, use the maximum amount of tokens in your wallet. - Decide the price limit that you would like to cap this trade to with `sqrtPriceLimit`. - If `aToB` is true, the trade will push the price lower. This amount is minimum sqrt-price that the trade will trade to if input token amount is sufficient. - If `aToB` is false, the trade will push the price higher. This amount is the maximum sqrt-price that the trade will trade to if the the input token amount is sufficient. - If you don't have a cap and want to trade as much as you've defined with `amount` and `otherAmountThreshold`, use the minimum price of your tick-array range for `bToA` and maximum price of your tick-range for `aToB`. If you don't mind hitting tick-array errors or you know your swap won't move the price too much, you can use [`MIN_SQRT_PRICE`](https://orca-so.github.io/whirlpools/legacy/variables/MIN_SQRT_PRICE.html) or [`MAX_SQRT_PRICE`](https://orca-so.github.io/whirlpools/legacy/variables/MAX_SQRT_PRICE.html). - sqrt-price is a x64 number. So your number would need to multiplied by 2^64. Use [`PriceMath`](https://orca-so.github.io/whirlpools/legacy/classes/PriceMath.html) utils here to help you do the conversion. - `amount` and `otherAmountThreshold` are u64 numbers. So make sure you shift your expected token numbers by the token's decimal. ### Tick Arrays The tick-array parameters are a sequence of tick-arrays that your swap may traverse through. `tickArray0` will always be the PublicKey of the TickArray that houses the current tick-index. In almost all cases, you can use the [`SwapUtils.getTickArrays`](https://orca-so.github.io/whirlpools/legacy/classes/SwapUtils.html#getTickArrays) to generate the sequence of tick-arrays that you need. If you opt for building it yourself and you know that your swap is small enough that it's unlikely to traverse through an array, simply provide the same tickArray0 account for all 3 accounts. Once you have the sequence of tick-array public keys, you can use the AccountFetcher to check that the tick-arrays are initialized. To learn more about tick-arrays and how its traversal works, read [Understanding Tick Arrays](../02-Architecture%20Overview/03-Understanding%20Tick%20Arrays.md). ### Common Usage Examples Assume all tokens below have a decimal of 6 1. Trading 100 token A for some amount of token B. ```tsx aToB = true amount = 100 * Math.pow(10, 6) amountSpecifiedIsInput = true otherAmountThreshold = 0 sqrt_price_limit = MIN_SQRT_PRICE ``` 2. Trading a max amount of 50 token B for 100 token A ```tsx aToB = false amount = 100 * Math.pow(10, 6) amountSpecifiedIsInput = false otherAmountThreshold = 50 sqrt_price_limit = MAX_SQRT_PRICE ``` 3. Trade whatever amount needed to move the price from current sqrt-price 50_x64 to sqrt_price 250_x64 ```tsx aToB = true amount = maxAmmountWallet amountSpecifiedIsInput = true otherAmountThreshold = 0 sqrt_price_limit = 250_x64 ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/05-Tutorial: Tour de Whirlpool/01-Overview.mdx
import DocCard from '@theme/DocCard'; # Tutorial: Tour de Whirlpool ## Overview ### What is Tour de Whirlpool? Tour de Whirlpool explains how to create programs that interact with Orca Whirlpools. In this tutorial you will learn how to perform the following operations programmatically. - Check balances for SOL and tokens - Send SOL and tokens - Perform swaps with both SOL and tokens - Manage Whirlpools positions - Open a position - Obtain a list of open positions - Check position status - Increase a position's liquidity - Decrease a position's liquidity - Harvest fees and rewards from a position - Close a position ### Target Audience - Previous experience using Solana, Orca, and Whirlpools from the web UI - Previous experience with Typescript or a similar language ### Tools Used - Typescript, for example code - Node.js, for running examples - Phantom, for Wallet actions - Solana CLI is used in tandem with Phantom for some Wallet actions - Devnet, for network interactions (It's free!) - This tutorial explains how to obtain the tokens used in examples ### Source Code <DocCard item={{ type: 'link', href: 'https://github.com/everlastingsong/tour-de-whirlpool/', label: 'Tour de Whirlpool', description: 'https://github.com/everlastingsong/tour-de-whirlpool/' }} /> ### How to get help - Join [Orca's Discord](https://dicord.orca.so). - Frequently asked questions are listed in [#dev-resources](https://discord.com/channels/798712664590254081/1049775881008193716). - Ask your questions in [#dev-questions](https://discord.com/channels/798712664590254081/838660851178274866).
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/05-Tutorial: Tour de Whirlpool/03-Obtain Sol and Tokens.mdx
import DocCard from '@theme/DocCard'; # Obtain SOL and Tokens Let's obtain the SOL and tokens we will use in the tutorial. You can obtain SOL on Devnet through airdrops, and you can mint your own tokens if you have SOL. However, for this tutorial, all of the tokens you need can be obtained from the site below. <DocCard item={{ type: 'link', href: 'https://everlastingsong.github.io/nebula/', label: 'devToken Nebula', description: 'https://everlastingsong.github.io/nebula/' }} /> ## Visiting the site and connecting your wallet Access the site and click on, "Connect Phantom". The Phantom extension will open, and if this is the first time you have visited the site, you will need to click "Connect". ![nebula01](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula01.png) After clicking "Connect" the other buttons on the site will be enabled, and you will be able to see your wallet balance. ![nebula02](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula02.avif) ## Obtaining SOL Click on "Airdrop 1 SOL" to obtain SOL. Click the button multiple times with several seconds in between. This way you can obtain more than 2 SOL. ![nebula03](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula03.avif) ※ When you do not have enough SOL repeat this step as needed. ## Obtaining Tokens You can obtain 4 different types of tokens by exchanging 0.2 SOL for each type. Click on each button in order starting from "Swap 0.2 SOL fro devUSDC" and ending with "Swap 0.2 SOL for devTMAC". Verify that the balances for the four token types are no longer 0. You will be asked to approve a transaction for each swap of 0.2 SOL for tokens. Approve transactions as needed. It is possible you will see a message saying that the transaction may fail, but go ahead and try it. ![nebula04](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula04.png) Make sure the balances for SOL and each token are higher than indicated in the list below. As long as the balances are higher than listed, the exact numbers do not matter. If any balance is too low, please continue with the SOL airdrops and swaps. - 1.0 SOL - 10.0 devUSDC - 10.0 devUSDT - 1000.0 devSAMO - 100.0 devTMAC ![nebula05](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula05.avif) You can also check your balance in Phantom. ![nebula06](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/nebula06.avif) Now your Devnet SOL and tokens are ready to go!
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/05-Tutorial: Tour de Whirlpool/02-Setting Up Your Environment.md
# Setting Up Your Environment Let's start by setting up the environment we will need for Tour de Whirlpool. ## Preparing a development environment First we will set up the tools needed to create and execute programs. Let's set up the tools in the following order. ### Solana CLI This application allows us to use Solana from the terminal or command line. Refer to the [this page](https://solana.com/docs/intro/installation) to install the command line tools. After installing the tools, verify the Solana CLI version on the command line. There should be no problem with version 1.10.8 or later. ```bash $ solana --version solana-cli 1.10.8 (src:623ac656; feat;1122441720) ``` ### Visual Studio Code This tutorial will use Visual Studio code as a TypeScript development environment. If you already have a preferred environment, feel free to skip installing Visual Studio Code. Download the installer from the official link: https://code.visualstudio.com/download. Verify the installation was successful by starting the application. ### Node.js We will set up Node.js to enable running TypeScript outside of a browser environment. Download the installer from the official link, and choose the recommended LTS version: https://nodejs.org/en/download/package-manager After completing the installation, verify the node version in the terminal or command prompt. There should be no problem with version 16.8.0 or later. ```bash $ node -v v16.8.0 ``` Make sure you can run the `npm` command, which should have been installed at the same time. ``` $ npm -v 7.21.0 ``` ### ts-node The `node` command can execute JavaScript code. We will use the `ts-node` command to make it easy to execute TypeScript with Node.js. Run the following command in the terminal or command prompt to install `ts-node`. ```bash npm install -g ts-node ``` After completing the installation, verify the `ts-node` version in the terminal or command prompt. ```bash ts-node v10.7.0 ``` ## Create the directory structure for development Create a directory (folder) to store the files created during development. ### Create directories Move to a directory where you can freely create new directories. Then, create a directory named `tour_de_whirlpool`. Run the following commands in the terminal or command prompt. ```bash cd somewhere mkdir tour_de_whirlpool cd tour_de_whirlpool mkdir src ``` ### Install the Whirlpools-SDK and other libraries needed for development To interact with Whirlpools we will install the Whirlpools-SDK and its dependency, the Solana library. Run the following commands in the terminal or command prompt from the `tour_de_whirlpool` directory. ```bash npm init -y npm install @orca-so/whirlpools-sdk npm ls ``` You can verify the installation was successful by checking the output of the `npm ls` command, which should show "@orca-so/whirlpools-sdk@0.11.8" There should be no problem if the version is later than 0.11.8. ```bash $ npm init -y Wrote to /tour_de_whirlpool/package.json: { "name": "tour_de_whirlpool", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } $ npm install @orca-so/whirlpools-sdk added 738 packages, and audited 739 packages in 50s 39 packages are looking for funding run `npm fund` for details found 0 vulnerabilities $ npm ls tour_de_whirlpool@1.0.0 .../tour_de_whirlpool └── @orca-so/whirlpools-sdk@0.11.8 ``` We only install "Whirlpools-SDK" explicitly, but its dependency, the Solana library, is installed at the same time, so we are able to use it in our program as well. The `node_modules` directory should have been created in the current directory. Check the directory and verify that several libraries have been installed. ```bash $ ls node_modules @babel @ethersproject @metaplex-foundation @orca-so @project-serum @solana ... ... uuid webidl-conversions whatwg-url ws ``` ### Create a typescript configuration file We will use tsconfig.json to configure TypeScript settings. Create a file named "tsconfig.json" in the `tour_de_whirlpool` directory and add the following contents. ```js { "compilerOptions": { "types": ["mocha", "chai"], "typeRoots": ["./node_modules/@types"], "lib": ["es2015"], "module": "commonjs", "target": "es6", "esModuleInterop": true, "resolveJsonModule": true, "moduleResolution": "node" } } ``` ## Prepare a development wallet Let's create a Solana wallet (account) to use in this tutorial. The wallet will be set up to work with Phantom, Typescript, as well as the Solana CLI. By doing this, we will be able to perform one-off actions and do manual verifications with Phantom and the CLI, but we will also be able to use the same wallet in our programs. Note: Because this wallet will be used in programs, be sure to keep it separate from any wallet holding actual assets. It would be a terrible to see your Solana assets wiped out due to an error in your code. ### Create a Chrome profile Because Phantom can manage multiple wallets, it is possible to add a new wallet to the Phantom wallet you are currently using. However, to avoid accidents, it is recommended that you create a new Chrome profile and keep your Phantom instances separate. Use the [following procedure](https://support.google.com/a/users/answer/9310144?hl=en#2.2) to create a new profile. You can set your profile theme to customize the appearance. Making the appearance different from the profile you normally use, or other development environments, will make it easier to differentiate. Here is an example of a profile for daily use (left) vs a dedicated profile for the tutorial (right). This greatly reduces the risk of mistakenly interacting with the wrong profile. (Red means beware!) ![google workspaces](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/browser.png) Besides using different profiles, using separate browsers is another way to differentiate. If you normally use Chrome, you can try using Edge or Brave for development. The advantage of using this method is that you can avoid the hassle of having to switch profiles. ### Install Phantom Extensions are managed separately for each profile. Because of this, your newly created profile will not include the Phantom extension. Install Phantom again in your new profile. You can install Phantom by clicking on the relevant browser icon link at the bottom of [this page](https://phantom.app/). Once the installation is complete, follow the on-screen instructions to initialize a new wallet. Once the installation is complete, follow the on-screen instructions to initialize a new wallet. Now your new wallet has been initialized. Let's go ahead and change the name of the new wallet to "TourDeWhirlpool". ![phantom01](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/phantom01.png) ### Change the target cluster connection Tour de Whirlpool uses Devnet, a Solana network used for development. Change the target network to Devnet. ![phantom02](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/phantom02.png) ![phantom03](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/phantom03.png) ### Export the wallet created in Phantom Currently, the private key for your wallet only exists inside Phantom. As is, you cannot perform actions with your new wallet from TypeScript programs or the Solana CLI. To solve this, we can export the private key, and save it in a format that can be read in by TypeScript and the Solana CLI. First, save a file named `create_wallet_json.ts` including the following code in your `tour_de_whirlpool` directory. ```tsx // create_wallet_json.ts import bs58 from "bs58"; const wallet_json = "wallet.json"; const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.question('secretKey(base58):', (secret_base58) => { readline.close(); const secret_bytes = Uint8Array.from(bs58.decode(secret_base58.trim())); // write file const fs = require('fs') fs.writeFileSync(wallet_json, `[${secret_bytes.toString()}]`); // verify file const secret_bytes_loaded = JSON.parse(fs.readFileSync(wallet_json)); const secret_base58_loaded = bs58.encode(Uint8Array.from(secret_bytes_loaded)); if ( secret_base58 === secret_base58_loaded ) { console.log(`${wallet_json} created successfully!`); } }); ``` Next, return to Phantom and export your private key. When the key is displayed, copy it to your clipboard. ![phantom04](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/phantom04.png) ![phantom05](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/phantom05.png) In the terminal or command prompt, navigate to the `tour_de_whirlpool` directory and execute `create_wallet_json.ts` using ts-node. When the program displays "secretKey(base58):", paste the private key you copied into your clipboard and press ENTER. Verify that the output says "wallet.json created successfully!" ```bash $ cd tour_de_whirlpool $ ts-node create_wallet_json.ts secretKey(base58):xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx wallet.json created successfully! ``` Use the Solana CLI to display the public key, using the file you just created as a base. Verify that it matches the public key displayed in Phantom. ```bash $ solana address -k wallet.json FptVxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxRAXB ``` In the procedure above we are going out of our way to use a program to convert the key. You may find sites online that will convert the key for you, but do not use these sites! If the site creator is a bad actor they can save your key and use it maliciously. Please perform all key conversions in your own environment. Now your development environment is ready to go!
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/05-Tutorial: Tour de Whirlpool/04-Check Balances.md
# Check Balances In this section let's set up the wallet to enable checking SOL and Token balances. ## Program Implementation We can check the balances for SOL and tokens by opening Phantom. Let's perform the same check using a program. ## Checking SOL Balance Let's start with checking the SOL balance from a program. ### Code Open your `tour_de_whirlpool` folder in Visual Studio Code, or your preferred development environment. Create a file called `011_get_sol_balance.ts` under the src folder with the following contents. ```tsx import { Keypair, Connection } from "@solana/web3.js"; import secret from "../wallet.json"; const RPC_ENDPOINT_URL = "https://api.devnet.solana.com"; const COMMITMENT = 'confirmed'; async function main() { // Create a connection for sending RPC requests to Devnet const connection = new Connection(RPC_ENDPOINT_URL, COMMITMENT); // Read in the private key from wallet.json (The public and private key pair will be managed using the Keypair class) const keypair = Keypair.fromSecretKey(new Uint8Array(secret)); // Display the RPC and the wallet's public key // When displaying the public key, use base58 encoding console.log("endpoint:", connection.rpcEndpoint); console.log("wallet pubkey:", keypair.publicKey.toBase58()); // Obtain the SOL balance // Use the getBalance method from the Connection class // https://solana-labs.github.io/solana-web3.js/v1.x/classes/Connection.html#getBalance const sol_balance = await connection.getBalance(keypair.publicKey); // Display the SOL balance // Since SOL is internally managed as an integer value and denominated in lamports, // divide by 10^9 to obtain a value denominated in SOL. console.log("lamports:", sol_balance); console.log("SOL:", sol_balance / 10**9); } main(); ``` ### Execution Result Run the code, and then verify that the public key and SOL balance match the Phantom UI. ```bash $ ts-node src/011_get_sol_balance.ts endpoint: https://api.devnet.solana.com wallet pubkey: FptVFacYhPrwScJayvKXvwjGeZRbefnnEcgmSQkoRAXB lamports: 2191782899 SOL: 2.191782899 ``` ![balance01](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/balance01.png) ### Key Points - You can interact with Solana's Devnet using the RPC endpoint, "https://api.devnet.solana.com" - Method for reading in a private key (read in wallet.json and create an instance of the Keypair class) - Use the toBase58() method to display the public key in base58 encoding - Use the Connection class's getBalance method to obtain the SOL balance - SOL is denominated in lamports internally - 1 SOL = 1,000,000,000 lamports ### API Used - https://solana-labs.github.io/solana-web3.js/v1.x/classes/Connection.html#getBalance ## Checking Token Balances Next, let's check token balances from a program. ### Code Create a file called `012_get_token_balance.ts` under the src folder with the following contents. ```tsx import { Keypair, Connection } from "@solana/web3.js"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { DecimalUtil } from "@orca-so/common-sdk"; import { unpackAccount } from "@solana/spl-token"; import BN from "bn.js"; import secret from "../wallet.json"; const RPC_ENDPOINT_URL = "https://api.devnet.solana.com"; const COMMITMENT = 'confirmed'; async function main() { // Initialize a connection to the RPC and read in private key const connection = new Connection(RPC_ENDPOINT_URL, COMMITMENT); const keypair = Keypair.fromSecretKey(new Uint8Array(secret)); console.log("endpoint:", connection.rpcEndpoint); console.log("wallet pubkey:", keypair.publicKey.toBase58()); // https://everlastingsong.github.io/nebula/ // devToken specification const token_defs = { "BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k": {name: "devUSDC", decimals: 6}, "H8UekPGwePSmQ3ttuYGPU1szyFfjZR4N53rymSFwpLPm": {name: "devUSDT", decimals: 6}, "Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa": {name: "devSAMO", decimals: 9}, "Afn8YB1p4NsoZeS5XJBZ18LTfEy5NFPwN46wapZcBQr6": {name: "devTMAC", decimals: 6}, }; // Obtain the token accounts from the wallet's public key // // { // context: { apiVersion: '1.10.24', slot: 140791186 }, // value: [ // { account: [Object], pubkey: [PublicKey] }, // { account: [Object], pubkey: [PublicKey] }, // { account: [Object], pubkey: [PublicKey] }, // { account: [Object], pubkey: [PublicKey] } // ] // } const accounts = await connection.getTokenAccountsByOwner( keypair.publicKey, { programId: TOKEN_PROGRAM_ID } ); console.log("getTokenAccountsByOwner:", accounts); // Deserialize token account data for (let i=0; i<accounts.value.length; i++) { const value = accounts.value[i]; // Deserialize const parsed_token_account = unpackAccount(value.pubkey, value.account); // Use the mint address to determine which token account is for which token const mint = parsed_token_account.mint; const token_def = token_defs[mint.toBase58()]; // Ignore non-devToken accounts if ( token_def === undefined ) continue; // The balance is "amount" const amount = parsed_token_account.amount; // The balance is managed as an integer value, so it must be converted for UI display const ui_amount = DecimalUtil.fromBN(new BN(amount.toString()), token_def.decimals); console.log( "TokenAccount:", value.pubkey.toBase58(), "\n mint:", mint.toBase58(), "\n name:", token_def.name, "\n amount:", amount.toString(), "\n ui_amount:", ui_amount.toString() ); } } main(); ``` ### Execution Result Run the code, and then verify that the Phantom UI displays the same token balances. The address displayed after "TokenAccount" will differ for different wallet addresses. ```bash $ ts-node src/012_get_token_balance.ts endpoint: https://api.devnet.solana.com wallet pubkey: FptVFacYhPrwScJayvKXvwjGeZRbefnnEcgmSQkoRAXB getTokenAccountsByOwner: { context: { apiVersion: '1.10.29', slot: 151582140 }, value: [ { account: [Object], pubkey: [PublicKey] }, { account: [Object], pubkey: [PublicKey] }, { account: [Object], pubkey: [PublicKey] }, { account: [Object], pubkey: [PublicKey] } ] } TokenAccount: B3PXuJ7FyXJ9wu97WZ2b3vt1tHoPQayaQbrTpPKRjUky mint: Afn8YB1p4NsoZeS5XJBZ18LTfEy5NFPwN46wapZcBQr6 name: devTMAC amount: 151240169 ui_amount: 151.240169 TokenAccount: FzAVSbhRDnncdqWLUzsxXpRM6wmB1h2Jb6obJZuRgpiw mint: BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k name: devUSDC amount: 15099547 ui_amount: 15.099547 TokenAccount: 2uDMLemoyarwUCrnzzhJ4y5YFfeLpUYusgdDAZ4tv78w mint: H8UekPGwePSmQ3ttuYGPU1szyFfjZR4N53rymSFwpLPm name: devUSDT amount: 17102615 ui_amount: 17.102615 TokenAccount: H5vU48wbEWtxsdqYZtcYLcAaEZ57jjcokoJKMct2LCAE mint: Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa name: devSAMO amount: 1322051824431 ui_amount: 1322.051824431 ``` ![balance02](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/balance02.png) ### Key Points - Use the getTokenAccountsByOwner() method of the Connection class to obtain token balances from a specified account. - The data in the account you obtain is TokenAccount data and needs to be deserialized. - You can deserialize the data using the deserializeTokenAccount method from TokenUtil. - You can determine which TokenAccount is for which Token using the "mint" field. - Just like SOL balances are denominated in lamports, token account balances are converted into integer values by moving the decimal point. - The number of usable digits after the decimal point is defined for each token and can be referred to as "decimal" or "scale". - Use the fromU64 method (convert from U64 format) in DecimalUtil for conversions that include moving the position of the decimal point, including lamports to SOL. ### getTokenAccountsByOwner in depth In Solana, all information is handled by accounts. Programs manage what will be stored inside accounts. The TokenProgram, which manages tokens, defines two types of accounts for storing data, TokenAccount and Mint. Because the token balance is stored in an account that holds TokenAccount information, getTokenAccountsByOwner will search for accounts that meet the criteria below. - The account is owned by the TokenProgram. - The data stored in the account is TokenAccount data. - The token owner address, stored in the TokenAccount owner field, is the address of the specified wallet. Since one TokenAccount can only store one token balance, the account structure looks like the following diagram. ![token-account-structure](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/token-account-structure.png) ### APIs Used - https://solana-labs.github.io/solana-web3.js/v1.x/classes/Connection.html#getTokenAccountsByOwner - TokenUtil.deserializeTokenAccount - DecimalUtil.fromU64 This completes the Basic Wallet Functionality (Checking Balances) section!
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/05-Tutorial: Tour de Whirlpool/05-Send Tokens.md
# Send Tokens In this section let's set up the wallet to enable sending SOL and tokens. ## Program Implementation If you click on SOL or a token, you have the option to send to another wallet. Let's enable this functionality through a program as well. ![send-tokens](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/send-tokens.png) ## Sending SOL Let's try sending SOL from a program. ### Code Create a file called `013_transfer_sol.ts` under the src directory containing the following contents. The destination is defined as `dest_pubkey`, but feel free to change it or leave it the same as desired. ```tsx import { Keypair, Connection, SystemProgram, PublicKey, Transaction } from "@solana/web3.js"; import secret from "../wallet.json"; const RPC_ENDPOINT_URL = "https://api.devnet.solana.com"; const COMMITMENT = 'confirmed'; async function main() { // Initialize a connection to the RPC and read in private key const connection = new Connection(RPC_ENDPOINT_URL, COMMITMENT); const keypair = Keypair.fromSecretKey(new Uint8Array(secret)); console.log("endpoint:", connection.rpcEndpoint); console.log("wallet pubkey:", keypair.publicKey.toBase58()); // SOL destination const dest_pubkey = new PublicKey("vQW71yo6X1FjTwt9gaWtHYeoGMu7W9ehSmNiib7oW5G"); // Amount to send const amount = 10_000_000; // lamports = 0.01 SOL // Build the instruction to send SOL const transfer_ix = SystemProgram.transfer({ fromPubkey: keypair.publicKey, toPubkey: dest_pubkey, lamports: amount, }); // Create a transaction and add the instruction const tx = new Transaction(); tx.add(transfer_ix); // Send the transaction const signers = [keypair]; const signature = await connection.sendTransaction(tx, signers); console.log("signature:", signature); // Wait for the transaction to complete const latestBlockhash = await connection.getLatestBlockhash(); await connection.confirmTransaction({ blockhash: latestBlockhash.blockhash, lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, signature }); } main(); ``` ### Execution Result Execute the script and verify that the transaction was successful. ```bash $ ts-node ./src/013_transfer_sol.ts endpoint: https://api.devnet.solana.com wallet pubkey: FptVFacYhPrwScJayvKXvwjGeZRbefnnEcgmSQkoRAXB signature: 2EiiHe5JqpbJTUChaeZwUiAEtRtvD9BwWHqX5pKaHhMA5hPEyCuQwEDLjtjHZY6QnHybLdfTS9Rv6k75tLisnf8N ``` Open up the [Devnet version of Solscan](https://solscan.io/?cluster=devnet) and enter the transaction Id labeled "signature". Verify that 0.01 was sent. Since the transaction only contains one instruction, #1 is the SOL transfer. If you are unable to find the transaction, make sure that you have the network dropdown in the upper right set to "DEVNET". ![solscan-tx-01](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/solscan-tx01.avif) ### Key Points - The basic flow is to add an instruction to a transaction, then execute the transaction. - You can use the `transfer()` method from `SystemProgram` to create an instruction to send SOL. - The sender must sign the transaction for sending SOL. - You can also verify transaction transactions executed on Devnet using SolScan. ### APIs Used https://solana-labs.github.io/solana-web3.js/v1.x/classes/SystemProgram.html#transfer ## Sending Tokens Next, let's try sending Tokens from a program. ### Code Create a file named `014_transfer_token.ts` under the src directory with the following contents. The destination is defined as `dest_pubkey`, but feel free to change it or leave it the same as desired. ```tsx import { Keypair, Connection, PublicKey, Transaction } from "@solana/web3.js"; import { TOKEN_PROGRAM_ID, AccountLayout, getAssociatedTokenAddressSync, createTransferCheckedInstruction } from "@solana/spl-token"; import { resolveOrCreateATA, ZERO } from "@orca-so/common-sdk"; import secret from "../wallet.json"; const RPC_ENDPOINT_URL = "https://api.devnet.solana.com"; const COMMITMENT = 'confirmed'; async function main() { // Initialize a connection to the RPC and read in private key const connection = new Connection(RPC_ENDPOINT_URL, COMMITMENT); const keypair = Keypair.fromSecretKey(new Uint8Array(secret)); console.log("endpoint:", connection.rpcEndpoint); console.log("wallet pubkey:", keypair.publicKey.toBase58()); // devSAMO // https://everlastingsong.github.io/nebula/ const DEV_SAMO_MINT = new PublicKey("Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa"); const DEV_SAMO_DECIMALS = 9; // Destination wallet for the devSAMO const dest_pubkey = new PublicKey("vQW71yo6X1FjTwt9gaWtHYeoGMu7W9ehSmNiib7oW5G"); // Amount to send const amount = 1_000_000_000; // 1 devSAMO // Obtain the associated token account from the source wallet const src_token_account = getAssociatedTokenAddressSync(DEV_SAMO_MINT, keypair.publicKey); // Obtain the associated token account for the destination wallet. const {address: dest_token_account, ...create_ata_ix} = await resolveOrCreateATA( connection, dest_pubkey, DEV_SAMO_MINT, ()=>connection.getMinimumBalanceForRentExemption(AccountLayout.span), ZERO, keypair.publicKey ); // Create the instruction to send devSAMO const transfer_ix = createTransferCheckedInstruction( src_token_account, DEV_SAMO_MINT, dest_token_account, keypair.publicKey, amount, DEV_SAMO_DECIMALS, [], TOKEN_PROGRAM_ID ); // Create the transaction and add the instruction const tx = new Transaction(); // Create the destination associated token account (if needed) create_ata_ix.instructions.map((ix) => tx.add(ix)); // Send devSAMO tx.add(transfer_ix); // Send the transaction const signers = [keypair]; const signature = await connection.sendTransaction(tx, signers); console.log("signature:", signature); // Wait for the transaction to be confirmed const latest_blockhash = await connection.getLatestBlockhash(); await connection.confirmTransaction({signature, ...latest_blockhash}); } main(); ``` ### Execution Result Run the code, and then verify that the devSAMO token has been sent. ```bash $ ts-node ./src/014_transfer_token.ts endpoint: https://api.devnet.solana.com wallet pubkey: FptVFacYhPrwScJayvKXvwjGeZRbefnnEcgmSQkoRAXB signature: 4NXrCbHJHBqgV4oDnWHCPFe7emiVf9SmRjqGxEgKFRAu2Wc8LrmWScygUfdfzZjCifjj4xsmnVke9EVxixceCXjk ``` ![solscan-tx-02](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/solscan-tx02.png) ### Key Points - You can create an instruction to send a token using the `createTransferCheckedInstruction()` method from the Token class. - The destination address in the `createTransferCheckedInstruction()` method is the associated token account, not the destination wallet. - If a destination associated token account does not exist yet, it needs to be created. (Since SOL is needed to create the account, choosing not to create a new account is also an option) - You can obtain the source associated token account address using the `deriveATA()` function. - You can obtain the destination associated token address and the instructions to create it if needed using the `resolveOrCreateATA()` function. ### Additional Info About Associated Token Accounts When sending SOL, the public key of the destination wallet is specified as the destination, and the account associated with this public key is the one that is updated. On the other hand, when sending tokens, the transfer occurs between associated token accounts (ATA). Normally, the user will not notice this is happening behind the scenes, since wallets, such as Phantom, can handle sending tokens using the public key of the destination wallet. However, when sending tokens from a program, you do need to be concerned with sending tokens from one ATA to another ATA. In addition, if the destination wallet has not previously interacted with the token being sent, it is possible that an ATA has not yet been created. In that case, the source needs to create the account on behalf of the destination, or the destination needs to create the account in advance. ![ata-account-structure](../../../static/img/04-Legacy%20SDK/05-Tour%20de%20Whirlpool/ata-account-structure.png) ### Additional Info About resolveOrCreateATA `resolveOrCreateATA` derives an ATA (use deriveATA if this is all that is needed) in addition to building the instructions required to create an associated token account. One convenient aspect of this function is that it will verify if the ATA already exists, and only build the instructions if they are needed. Because of this, the client can write code to handle this situation without the need for branching. You can handle sending tokens in a similar fashion without using `resolveOrCreateATA`, but because of the convenience they provide alongside the Whirlpools SDK, we highlighted and used the `deriveATA` and `resolveOrCreateATA` functions in this section. ### APIs Used - Token.createTransferCheckedInstruction - deriveATA - resolveOrCreateATA This completes the Basic Wallet Functionality (Sending) section!
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/01-Basic Usage/02-Reading Whirlpool Accounts.md
# Reading Whirlpool Accounts The SDK provides the following methods to fetch and parse data from Whirlpool accounts on-chain. ## Fetching Accounts The Typescript SDK has types setup to help you parse the corresponding accounts on-chain. ### 1. Account Fetcher Use the [AccountFetcher](https://orca-so.github.io/whirlpools/legacy/classes/WhirlpoolAccountFetcher.html) class's get functions to fetch and parse the Whirlpool account that you need. Note that this class also provides caching options. ```tsx const fetcher = new WhirlpoolAccountFetcher(connection); const config: WhirlpoolsConfigData = await fetcher.getConfig(CONFIG_PUBLIC_KEY); const poolAddress = PDAUtil.getPool(...); const pool: WhirlpoolData = await fetcher.getPool(poolAddress); ``` ### 2. Parsing fetched AccountInfo data If you already have the Buffer from fetching the AccountInfo, use the Parsables classes (eg. [ParsableWhirlpool](https://orca-so.github.io/whirlpools/legacy/classes/ParsableWhirlpool.html)) in the SDK to parse account buffer data into readable types. ```tsx const whirlpoolAccountInfo: Buffer = ... const whirlpool: WhirlpoolData = ParsableWhirlpool.parse(accountInfoData) ``` ## Whirlpool Client If you are already using [WhirlpoolClient](https://orca-so.github.io/whirlpools/legacy/interfaces/WhirlpoolClient.html), you can fetch the data from the `Whirlpool` or `Position` class directly. ```tsx const context = new WhirlpoolContext(...); const fetcher = new AccountFetcher(context.provider.connection); const client = buildWhirlpoolClient(context, fetcher); const pool = await client.getPool(poolAddress); const position = await client.getPosition(positionAddress); const poolData: WhirlpoolData = pool.getData(); const positionData: PositionData = position.getData(); // Perform Action... const newestData = pool.refreshData(); ``` ## Deriving Account Addresses Almost all Whirlpools accounts are Program Derived Addresses. Use the [PDAUtil](https://orca-so.github.io/whirlpools/legacy/classes/PDAUtil.html) class to derive the required addresses to access on-chain accounts.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/01-Basic Usage/01-Setup Whirlpool Context.md
# Setup Whirlpool Context The [WhirlpoolContext](https://orca-so.github.io/whirlpools/legacy/classes/WhirlpoolContext.html) object provides the necessary env information to build and send transactions and is core to running many functions in the SDK. (ex. Connection, Wallet, WhirlpoolProgramId etc). ## Setup your context object with one of the following methods: ```tsx const provider = Provider.env() const ctx = WhirlpoolContext.withProvider(provider, ORCA_WHIRLPOOL_PROGRAM_ID); ``` You can feed in the env variables like so in bash: ```bash ANCHOR_PROVIDER_URL=<CLUSTER URL> ANCHOR_WALLET=<WALLET PATH> ts-node index.ts ``` ## Setup for browser applications The context relies on Anchor's Wallet interface. Implement your own wallet interface or find one of the sample implementations in the community and feed it into the context object. ```tsx // Anchor Wallet Definition export interface Wallet { signTransaction(tx: Transaction): Promise<Transaction>; signAllTransactions(txs: Transaction[]): Promise<Transaction[]>; publicKey: PublicKey; } ``` ```tsx const connection = new Connection(url, "confirmed"}; const wallet = new Wallet() const ctx = WhirlpoolContext.from(connection, wallet, whirlpoolProgramId); ``` ## Setup with Whirlpool Anchor test environment Provided you have set up the anchor environment, you can reference the program directly and build from there. ```tsx const provider = anchor.Provider.local(); anchor.setProvider(anchor.Provider.env()); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/01-Basic Usage/03-Building Transactions.mdx
import DocCard from '@theme/DocCard'; # Building Transactions The Typescript SDK provides multiple ways for you to create the transaction needed to execute specific actions on the Whirlpool contract. ## 1. Composing your own Transaction Use the TransactionBuilder class to construct and compose your own Transactions to perform actions on the Whirlpools contract. ### Whirlpools Instruction Set <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/WhirlpoolIx.html', label: 'Whirlpools Instruction Set', description: 'https://orca-so.github.io/whirlpools/legacy/classes/WhirlpoolIx.html' }} /> ```tsx const txBuilder = new TransactionBuilder(ctx.provider); txBuilder.addInstruction(WhirlpoolIx.initializeConfigIx(ctx, configParams)); ... txBuilder.addInstruction(otherIx).addSigner(otherSigner); ... await txBuilder.buildAndExecute(); ``` Use to `toTx` function if you only have one transaction to send out ```tsx const tx = toTx(ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configParams)); await txBuilder.buildAndExecute(); ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/01-Basic Usage/04-Important Util Helpers.mdx
import DocCard from '@theme/DocCard'; # Important Util helpers Reference the following utility types to help you interact with the Whirlpool protocol. ## PDAUtil Utility class to help you derive the PDA for Whirlpool accounts <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/PDAUtil.html', label: 'PDAUtil | @orca-so/whirlpools', description: 'https://orca-so.github.io/whirlpools/legacy/classes/PDAUtil.html' }} /> ## PriceMath Utility methods to help you convert between sqrt-price, price and tick index. <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/PriceMath.html', label: 'PriceMath | @orca-so/whirlpools', description: 'https://orca-so.github.io/whirlpools/legacy/classes/PriceMath.html' }} /> ## TickUtil Utility class hosting Tick utility methods such as finding initializable ticks, deriving tick array start-index etc. <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/TickUtil.html', label: 'TickUtil | @orca-so/whirlpools', description: 'https://orca-so.github.io/whirlpools/legacy/classes/TickUtil.html' }} /> ## TickArrayUtil Utility class to help fetch TickArray data. <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/TickArrayUtil.html', label: 'TickArrayUtil | @orca-so/whirlpools', description: 'https://orca-so.github.io/whirlpools/legacy/classes/TickArrayUtil.html' }} /> ## PoolUtil A collection of utility methods that you may use when interacting with the Whirlpool account. <DocCard item={{ type: 'link', href: 'https://orca-so.github.io/whirlpools/legacy/classes/PoolUtil.html', label: 'PoolUtil | @orca-so/whirlpools', description: 'https://orca-so.github.io/whirlpools/legacy/classes/PoolUtil.html' }} />
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/02-Managing Whirlpools/01-Create a Pool.md
# Creating a Pool Whirlpools is set up such that anyone is able to set up a liquidity pool within a WhirlpoolsConfig space. Follow these steps to initialize a Whirlpool using the `initialize_pool` instruction. ## Determine Whirlpool Parameters **Whirlpool Pda** - The derived address of the Whirlpool account that will be initialized. Can be derived with [`PDAUtil.getWhirlpool()`](https://orca-so.github.io/whirlpools/legacy/classes/PDAUtil.html#getWhirlpool) **Token Mints** - The mints of the tokens for this trading pair. Token A and Token B Mint has to be cardinally ordered. Use the [`orderMints`](https://orca-so.github.io/whirlpools/legacy/classes/PoolUtil.html#orderMints ) function to help you order them. **Tick Spacing** - Consider the effects of fees and tick-spacing when determining your tick spacing value. Note that for optimal compute-budget performance, tick-spacing should be a power of 2. **Token Vault Keypairs** - Empty Keypair accounts that will host deposited tokens for this pool. Once the initialize ix is ran, these accounts will be initialized as a spl-token accounts with the tokenAuthority set to the Whirlpool program. ## Determining initial sqrt-price This determines where the tick will be after initialization. It is recommended that this be set close to the market price, otherwise it will take a series of swap iterations to move the price back to the desired location. The price must be within `MIN_SQRT_PRICE` and `MAX_SQRT_PRICE`, and must be shifted by 64 bits. ```tsx // Current SOL/USDC price const desiredMarketPrice = new Decimal(98); // Invert due to token mint ordering const actualPrice = new Decimal(1).div(desiredMarketPrice); // Shift by 64 bits const initSqrtPrice = MathUtil.toX64(actualPrice); ``` > ℹ️ Reminder to take into account the ordering of the token A / B when determining the price. You may have to invert the value if your traded token is older than base token. ## Determine the appropriate FeeTier The fee tier account determines the initial default fee amount for this pool. There's no hard requirement to use the fee-tier with the same tick-spacing as the pool you are initializing, but it is recommended. If the desired fee rate account for a particular tick-spacing does not exist yet, contact the WhirlpoolConfig's feeAuthority to either: 1. Create the appropriate fee tier for you with the `initialize_fee_tier` ix. 2. Set your desired fee tier for you with the `set_fee_rate` ix. ## Sample Code Create the instruction and invoke it when you are ready. ```tsx const whirlpoolPda = getWhirlpoolPda( programId, whirlpoolConfigKey, toPubKey(tokenMintA), toPubKey(tokenMintB), tickSpacing ); const feeTierKey = getFeeTierPda(programId, whirlpoolConfigKey, tickSpacing).publicKey; const tokenVaultAKeypair = Keypair.generate(); const tokenVaultBKeypair = Keypair.generate(); await WhirlpoolIx.initializePoolIx(ctx, { initSqrtPrice, tickSpacing: 128, tokenMintA, tokenMintB, tokenVaultAKeypair, tokenVaultBKeypair, whirlpoolPda, whirlpoolsConfig, feeTierKey: feeTierPda.publicKey, funder: ctx.wallet.publicKey, }).toTx().buildAndExecute(); ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/03-Position Management/02-Modify Liquidity.md
# Modify Liquidity Whirlpools provide two instructions - [`increase_liquidity`](https://github.com/orca-so/whirlpools/blob/a988854b3c63499835b4be3bda552182842a8aa1/programs/whirlpool/src/lib.rs#L211) and [`decrease_liquidity`](https://github.com/orca-so/whirlpools/blob/a988854b3c63499835b4be3bda552182842a8aa1/programs/whirlpool/src/lib.rs#L234) to allow users to modify their position's liquidity. The SDK also provides quote functions (ex. [`increaseLiquidityQuoteByInputToken`](https://orca-so.github.io/whirlpools/legacy/functions/increaseLiquidityQuoteByInputToken.html), [`decreaseLiquidityQuoteByLiquidity`](https://orca-so.github.io/whirlpools/legacy/functions/decreaseLiquidityQuoteByLiquidity.html)) to help estimate the tokenIn/Out from the liquidity operation. ## Using Whirlpool Client Use the [`Position`](https://orca-so.github.io/whirlpools/legacy/interfaces/Position.html) class from the [`WhirlpoolClient`](https://orca-so.github.io/whirlpools/legacy/interfaces/WhirlpoolClient.html) to fetch and manage your liquidity. Read below for more on the relationship between quote and the transaction. ```tsx const position = await client.getPosition(positionAddress); const preIncreaseData = position.getData(); const increase_quote = increaseLiquidityQuoteByInputToken( poolInitInfo.tokenMintB, new Decimal(70), lowerTick, upperTick, Percentage.fromFraction(1, 100), pool ); await ( await position.increaseLiquidity(increase_quote, ctx.wallet.publicKey, ctx.wallet.publicKey) ).buildAndExecute(); ``` ## The Manual Way For each instruction, calculate the following values: - **liquidityAmount** - The total amount of liquidity you would like to deposit/withdraw into your position. - **tokenMax A, B (increase_liquidity)** - The maximum amount of token X to add to the position. Note the value here is shifted by the decimal places of the token. - **tokenMin A, B (decrease_liquidity)** - The minimum amount of token X to withdraw from the position. Note the value here is shifted by the decimal places of the token. ## Getting a Quote The Typescript SDK provides several quote functions to help generate an estimate based on common user input values. ### Increase liquidity quote by input token amount Given a desired amount of input token (A or B), you can use the quote utility function [`increaseLiquidityQuoteByInputTokenWithParams`](https://orca-so.github.io/whirlpools/legacy/functions/increaseLiquidityQuoteByInputTokenWithParams.html) to calculate the liquidityAmount and other tokenMax value required to deposit the desired amount of token into the position. The quote amount will differ based on the current price (tick) and the desired tick boundaries for the position. The price environment may change from the time of quote to the actual processing of the [`increase_liquidity`](https://github.com/orca-so/whirlpools/blob/a988854b3c63499835b4be3bda552182842a8aa1/programs/whirlpool/src/lib.rs#L211) ix. Use the slippage tolerance to adjust the quote values to balance your risk of ix failure and total tokens to deposit. ```tsx const whirlpool = await fetcher.getPool(...); const position = await fetcher.getPosition(...); // 10 tokens of a token with 6 decimals const depositTokenBAmount = new BN(10_000_000); const quote = await increaseLiquidityQuoteByInputTokenWithParams({ tokenMintA: whirlpool.tokenMintA, tokenMintB: whirlpool.tokenMintB, tickCurrentIndex: whirlpool.tickCurrentIndex, sqrtPrice: whirlpool.sqrtPrice, inputTokenMint: whirlpool.tokenMintB, inputTokenAmount: desiredTokenBAmount, tickLowerIndex: position.tickLowerIndex, tickUpperIndex: position.tickUpperIndex, slippageTolerance: Percentage.fromFraction(1, 1000), }); ``` ### Decrease liquidity quote by input token amount Given the liquidity amount, use the [`decreaseLiquidityQuoteByLiquidityWithParams`](https://orca-so.github.io/whirlpools/legacy/functions/decreaseLiquidityQuoteByLiquidityWithParams.html) util function to get an estimate on what's the minimum token A & B you can expect from the [`decrease_liquidity`](https://github.com/orca-so/whirlpools/blob/a988854b3c63499835b4be3bda552182842a8aa1/programs/whirlpool/src/lib.rs#L234) instruction call. Like [`increase_liquidity`](https://github.com/orca-so/whirlpools/blob/a988854b3c63499835b4be3bda552182842a8aa1/programs/whirlpool/src/lib.rs#L211), use the slippage tolerance to adjust the quote values to balance your risk of ix failure and total tokens to deposit. ```tsx const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); // Example: Withdraw 30% of the position const totalLiquidityInPosition = position.liquidity; const withdrawLiquidityAmount = totalLiquidityInPosition.mul(new BN(30).div(new BN(100))); const depositQuote = decreaseLiquidityQuoteByLiquidityWithParams({ withdrawLiquidityAmount, sqrtPrice: whirlpool.sqrtPrice, tickCurrentIndex: whirpool.tickCurrentIndex, tickLowerIndex: position.tickLowerIndex, tickUpperIndex: position.tickUpperIndex, slippageTolerance: Percentage.fromFraction(1, 100), }); ``` ### Other Parameters - **whirlpool** - PublicKey of the whirlpool the position is a part of - **position** - PublicKey of the position address. Derivable from PDAUtil.getPosition. - **positionTokenAccount** - Associated token address of the position token on the user's wallet. - **tokenOwnerAccount A, B** - Associated token address of the tokenA,B on the user's wallet. - **tokenVaults A, B** - PublicKey of the token vaults for this - **tickArrayLower, Upper** - Lower & upper tick-array accounts that contains the tick indices for the lower, upper bound of the position - **positionAuthority** - The address that hosts the position token. This authority must sign the transaction. ## Sample Code ### Increase liquidity example ```tsx const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); // 10 tokens of a token with 6 decimals const depositTokenBAmount = new BN(10_000_000); const depositQuote = increaseLiquidityQuoteByInputTokenWithParams({depositTokenBAmount, ...}); await toTx(ctx, WhirlpoolIx.increaseLiquidityIx(ctx.program, { ...depositQuote, whirlpool: whirlpoolAddress, positionAuthority: provider.wallet.publicKey, position: positionAddress, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, })).buildAndExecute(); ``` ### Decrease liquidity example ```tsx const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); const removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({...}); await toTx(ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { ...removalQuote, whirlpool: whirlpoolAddress, positionAuthority: provider.wallet.publicKey, position: positionAddress, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, })).buildAndExecute(); ``` ## Common Errors - `LiquidityZero` (0x177c) - Provided liquidity amount is zero. - `LiquidityTooHigh` (0x177d) - Provided liquidity exceeds u128::max. - `TokenMaxExceeded` (0x1781) - The required token to perform this operation exceeds the user defined amount in increase_liquidity. - `TokenMinSubceeded` (0x1782) - The required token to perform this operation subceeds the user defined amount in decrease_liquidity. - `TickNotFound` (0x1779) - The provided tick array accounts do not contain the tick specified in the position. - `ConstraintRaw` (0x7d3) - TokenVault, TokenAccount mints does not match the values in the provided whirlpool.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/03-Position Management/04-Collect Fees and Rewards.md
# Collect Fees and Rewards As the liquidity pool is traded upon, liquidity providers will begin to accrue fees and rewards. Follow the following steps to see how much you are owe and how to collect them. ## Get a quick quote on outstanding fees and rewards There are use-cases where users would like to check the outstanding values before deciding to perform an on-chain update and harvest. In these cases, use the provided `collectFeesQuote` and `collectRewardsQuote` in the Typescript SDK. ```tsx // Fetching necessary on-chain account data. const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress) // Fetching tick array. Note that you may have to fetch two of them // if the upper and lower ticks live on different tick arrays. const tickArrayAddress = TickUtil.getPdaWithTickIndex(tickLowerIndex, ...); const tickArray = await fetcher.getTickArray(tickArrayAddress); // Get the individual TickData on each tickIndex from the fetched TickArray const lowerTick = TickUtil.getTickFromTickArrayData(tickArrayData, tickLowerIndex, tickSpacing); const upperTick = TickUtil.getTickFromTickArrayData(tickArrayData, tickUpperIndex, tickSpacing); const feeQuote = collectFeesQuote({ whirlpool, position, tickLower: lowerTick, tickUpper: upperTick, }); const feesInTokenA = feeQuote.feeOwedA; const feesInTokenB = feeQuote.feeOwedB; const rewardQuote = collectRewardsQuote({ whirlpool, position, tickLower: lowerTick, tickUpper: upperTick, }); const rewardsInReward0 = rewardQuote[0].toNumber(); const rewardsInReward1 = rewardQuote[1].toNumber(); const rewardsInReward2 = rewardQuote[2].toNumber(); ``` ## Update on-chain position with the latest accrued fees Before you fetch your owed fees, you must update the on-chain position with the latest values by calling `increase_liquidity` or `decrease_liquidity`. Alternatively, you can call `update_fee_and_rewards` to update without modifying liquidity. If this step is skipped, the collect instructions will only fetch the last updated values of the position. In many cases, this will be 0. Sample code on using `update_fee_and_rewards`: ```tsx const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); const tickArrayLower = getTickArrayPda(ctx.program.programId, whirlpoolAddress, position.tickLowerIndex); const tickArrayUpper = getTickArrayPda(ctx.program.programId, whirlpoolAddress, position.tickUpperIndex); await toTx(ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: position.whirlpool, position: positionAddress, tickArrayLower, tickArrayUpper, })).buildAndExecute(); ``` ## Collect Fees and Rewards Once the position has been updated, you can use `collect_fees` and `collect_reward` to harvest the position. ### Collect fee ```tsx const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); const positionTokenAccount = await deriveATA(provider.wallet.publicKey, position.positionMint); const tokenOwnerAccountA = await deriveATA(provider.wallet.publicKey, whirlpool.tokenMintA); const tokenOwnerAccountB = await deriveATA(provider.wallet.publicKey, whirlpool.tokenMintB); await toTx(ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolAddress, positionAuthority: provider.wallet.publicKey, position: positionAddress, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB })).buildAndExecute(); ``` ### Collect rewards ```tsx // Fetching rewards at reward index 0 const whirlpool = await fetcher.getPool(whirlpoolAddress); const position = await fetcher.getPosition(positionAddress); const rewardTokenMint = whirlpool.rewardInfos[0].mint; const rewardOwnerAccount = await deriveATA(provider.wallet.publicKey, rewardTokenMint); const positionTokenAccount = await deriveATA(provider.wallet.publicKey, position.positionMint); await toTx(ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolAddress, positionAuthority: provider.wallet.publicKey, position: positionAddress, positionTokenAccount, rewardOwnerAccount: rewardOwnerAccount, rewardVault: whirlpool.rewardInfo[0].vault, rewardIndex: 0, })).buildAndExecute(); ```
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/03-Position Management/01-Opening a Position.md
# Opening a Position Positions in Whirlpools are tracked with a minted NFT in the user's wallet. The usual action of opening a position consists of two instruction calls - `initializeTickArray` to initialize the tick arrays that would host your desired ticks for your position if they do not exist yet. - `Whirlpool.openPosition` or `Whirlpool.openPositionWithMetadata` to mint the position and define the tick range - `increaseLiquidity` to transfer tokens from your wallet into a position. The `Whirlpool.openPosition` function now supports both traditional and Token2022-based position NFTs. To utilize Token2022, provide the Token2022 ProgramId as the `tokenProgramId` parameter when calling `openPosition`. This will mint the NFT using Token2022, which leverages the MetadataPointer and TokenMetadata extensions, eliminating the need for Metaplex metadata accounts. ## Opening Position with Metadata By using `Whirlpool.openPositionWithMetadata`, users have the option of appending [Metaplex metadata](https://www.metaplex.com/learn-developers) onto the Token Program position NFT. Doing so will allow the token to be identifiable in tracking websites or wallets as a Whirlpool NFT. The drawback is it will require more compute-budget and will incurr Metaplex fees of 0.01 SOL. ## Initialize Tick Array accounts if needed For liquidity to exist in the Whirlpool, the tick-array that contains that particular tick must be initialized. Calculate the start_index of the required tick array and use the `initialize_tick_array` instruction to initialize it. More often than not, tick-arrays are already created. But if you want your code to be defensive, you should do a check prior to invoking `open_position`. To understand more on how Tick-Arrays work in Whirlpools, read here. ```tsx const tickArrayPda = PDAUtil.getTickArray( this.ctx.program.programId, this.address, startTick ); // Check if tick array exists const fetcher = new AccountFetcher(...); const ta = await fetcher.getTickArray(tickArrayPda.publicKey, true); // Exit if it exists if (!!ta) { return; } // Construct Init Tick Array Ix const tx = toTx(ctx, WhirlpoolIx.initTickArrayIx(this.ctx.program, { startTick, tickArrayPda, whirlpool: this.address, funder: !!funder ? AddressUtil.toPubKey(funder) : this.ctx.wallet.publicKey, })); await tx.buildAndExecute(); ``` ## Open Position with WhirlpoolClient WhirlpoolClient's `openPosition` method bundles the open and increase liquidity instructions into a single transaction for you. Below is a code sample to create a position for the SOL/USDC pool at the price between $98 - $150, with the intention to deposit 50 SOL into the position. ```tsx // Derive the Whirlpool address const poolAddress = PDAUtil.getWhirlpool( WHIRLPOOL_PROGRAM_ID, ORCA_WHIRLPOOLS_CONFIG, SOL_MINT, USDC_MINT, 64 ); // Load everything that you need const client = buildWhirlpoolClient(context, fetcher); const pool = await client.getPool(poolAddress.publicKey); const poolData = pool.getData(); const poolTokenAInfo = pool.getTokenAInfo(); const poolTokenBInfo = pool.getTokenBInfo(); // Derive the tick-indices based on a human-readable price const tokenADecimal = poolTokenAInfo.decimals; const tokenBDecimal = poolTokenBInfo.decimals; const tickLower = TickUtil.getInitializableTickIndex( PriceMath.priceToTickIndex(new Decimal(98), tokenADecimal, tokenBDecimal), poolData.tickSpacing ); const tickUpper = TickUtil.getInitializableTickIndex( PriceMath.priceToTickIndex(new Decimal(150), tokenADecimal, tokenBDecimal), poolData.tickSpacing ); // Get a quote on the estimated liquidity and tokenIn (50 tokenA) const quote = increaseLiquidityQuoteByInputToken( poolTokenAInfo.mint, new Decimal(50), tickLower, tickUpper, Percentage.fromFraction(1, 100), pool ); // Evaluate the quote if you need const {tokenMaxA, tokenMaxB} = quote // Construct the open position & increase_liquidity ix and execute the transaction. const { positionMint, tx } = await pool.openPosition( lowerTick, upperTick, quote ); const txId = await tx.buildAndExecute(); // Fetch the newly created position with liquidity const position = await client.getPosition( PDAUtil.getPosition(WHIRLPOOL_PROGRAM_ID, positionMint).publicKey ) ``` ## The Manual way Follow the instructions below if you would like to have more control over your instruction building process. Note that `open_position` does not add liquidity to a position. Follow the next article "Modify Liquidity" to add liquidity. ## Determine position parameters To open a position against a Whirlpool, you must first define certain parameters of your position to invoke the `open_position` instruction. - `WhirlpoolKey` - The public key for the Whirlpool that the position will host liquidity in. - `tickLowerIndex`, `tickUpperIndex` - The tick index bounds for the position. Must be an initializable index. - `positionMintAddress` - A generated empty Keypair that will be initialized to a token mint. - `positionPda` - Derived address of the position account via `getPositionPda` - `positionTokenAccountAddress` - This is the account that will hold the minted position token. It is the associated token address of the position-mint. ```tsx const positionMintKeypair = Keypair.generate(); const positionPda = getPositionPda(programId, positionMintKeypair.publicKey); const metadataPda = getPositionMetadataPda(positionMintKeypair.publicKey); const positionTokenAccountAddress = await deriveATA( provider.wallet.publicKey, positionMintKeypair.publicKey ); const positionIx = toTx(ctx, WhirlpoolIx.openPositionWithMetadataIx(ctx.program, { funder: provider.wallet.publicKey, ownerKey: provider.wallet.publicKey, positionPda, metadataPda, positionMintAddress: positionMintKeypair.publicKey, positionTokenAccountAddress, whirlpoolKey: toPubKey(poolAddress), tickLowerIndex, tickUpperIndex, })).addSigner(positionMintKeypair).buildAndExecute(); ``` Once your position is open, proceed to the next section to add liquidity. ## Common Errors - `InvalidTickIndex` (0x177a) - tickLowerIndex is higher than upper tickUpperIndex - Some tick indices is not an initializable index (not a multiple of tickSpacing). Use `TickUtil.getInitializableTickIndex` to get the closest initializable tick to your index. - Some tick indices is out of bounds - `NotRentExempt` (0x0) - Usually, the TickArray that houses your tickLowerIndex or tickUpperIndex has not been initialized. Use the `WhirlpoolClient.initTickArrayForTicks` or `WhirlpoolIx.initTickArrayIx` to initialize the array at the derived startTickIndex. - Alternatively, if this failure is from `init_tick_array`, the tick array has already been initialized.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/03-Position Management/05-Identifying Wallet Positions.md
# Identifying Wallet Positions To fetch all position accounts of a wallet, you can use [`getAllPositionAccountsByOwner`](https://orca-so.github.io/whirlpools/legacy/functions/getAllPositionAccountsByOwner.html).
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/04-Legacy SDK/03-Position Management/03-Closing a Position.md
# Closing a Position To close a position, you must first withdraw all liquidity and collect all fees and rewards from the position. You can then call the [`closePosition`](https://orca-so.github.io/whirlpools/legacy/interfaces/Whirlpool.html#closePosition) instruction to close and burn the position NFT. The parameters of `closePosition` are identical to the ones in `openPosition`. ## Whirlpool Client - Sample Code The [`WhirlpoolClient`](https://orca-so.github.io/whirlpools/legacy/interfaces/WhirlpoolClient.html) version of [`closePosition`](https://orca-so.github.io/whirlpools/legacy/interfaces/Whirlpool.html#closePosition) will automatically call `decrease_liquidity` and `close_position` for you. Note that you still have to manually call `collect_fees` and `collect_reward` to make sure the position is empty. ```tsx const client = new WhirlpoolClient(context, fetcher); const poolAddress = PDAUtil.getPool(...) const positionAddress = PDAUtil.getPosition(...); const pool = client.getPool(poolAddress); // Must manually call update_fee_and_rewards -> collect_fees -> collect_rewards // Convienience function coming soon. const tx = await pool.closePosition(positionAddress, Percentage.fromFraction(1, 100)) await tx.buildAndExecute(); ``` ## Instruction - Sample Code ```tsx const poolAddress = PDAUtil.getPool(...) const positionAddress = PDAUtil.getPosition(...); const position = await fetcher.getPosition(positionAddress); // Must manually call decrease_liquidity here const tx = await toTx(ctx, WhirlpoolIx.closePositionTx(ctx, { positionAuthority: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, positionTokenAccount, position: positionAddress, positionMint: position.positionMint, })) await tx.buildAndExecute(); ``` ## Common Errors - `ClosePositionNotEmpty` (0x1775) - Position still has liquidity in it. Withdraw all before calling this instruction.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/02-Whirlpools Core.mdx
--- sidebar_label: Whirlpools Core --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Orca Whirlpools Core SDK This package provides developers with advanced functionalities for interacting with the Whirlpool Program on Solana. Originally written in Rust, it has been compiled to WebAssembly (Wasm). This compilation makes the SDK accessible in JavaScript/TypeScript environments, offering developers the same core features and calculations for their Typescript projects. The SDK exposes convenient methods for math calculations, quotes, and other utilities, enabling seamless integration within web-based projects. ## Key Features - **Math Library**: Contains a variety of functions for math operations related to bundles, positions, prices, ticks, and tokens, including calculations such as determining position status or price conversions. - **Quote Library**: Provides utility functions for generating quotes, such as increasing liquidity, collecting fees or rewards, and swapping, to help developers make informed decisions regarding liquidity management. ## Installation: <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```bash npm install @orca-so/whirlpools-core ``` </TabItem> <TabItem value="rust" label="Rust"> ```bash cargo add orca_whirlpools_core ``` </TabItem> </Tabs> ## Usage Here are some basic examples of how to use the package: ### Math Example The following example demonstrates how to use the `isPositionInRange` function to determine whether a position is currently in range. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { isPositionInRange } from "@orca-so/whirlpools-core"; const currentSqrtPrice = 7448043534253661173n; const tickIndex1 = -18304; const tickIndex2 = -17956; const inRange = isPositionInRange(currentSqrtPrice, tickIndex1, tickIndex2); console.log("Position in range:", inRange); ``` Expected output: ``` Position in range? true ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools_core::is_position_in_range; fn main() { let current_sqrt_price = 7448043534253661173u128; let tick_index_1 = -18304; let tick_index_2 = -17956; let in_range = is_position_in_range(current_sqrt_price.into(), tick_index_1, tick_index_2); println!("Position in range? {:?}", in_range); } ``` Expected output: ``` Position in range? true ``` </TabItem> </Tabs> ### Quote Example The following example demonstrates how to use the `increaseLiquidityQuoteA` function to calculate a quote for increasing liquidity given a token A amount. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { increaseLiquidityQuoteA } from "@orca-so/whirlpools-core"; const tokenAmountA = 1000000000n; const slippageToleranceBps = 100; const currentSqrtPrice = 7437568627975669726n; const tickIndex1 = -18568; const tickIndex2 = -17668; const transferFeeA = { feeBps: 200, maxFee: 1000000000n }; const quote = increaseLiquidityQuoteA( tokenAmountA, slippageToleranceBps, currentSqrtPrice, tickIndex1, tickIndex2, transferFeeA, ); console.log(quote); ``` Expected output: ``` { liquidityDelta: 16011047470n, tokenEstA: 1000000000n, tokenEstB: 127889169n, tokenMaxA: 1010000000n, tokenMaxB: 129168061n } ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools_core::increase_liquidity_quote_a; use orca_whirlpools_core::TransferFee; fn main() { let token_amount_a = 1000000000u64; let slippage_tolerance_bps = 100u16; let current_sqrt_price = 7437568627975669726u128; let tick_index_1 = -18568; let tick_index_2 = -17668; let transfer_fee_a = Some(TransferFee::new(200)); let transfer_fee_b = None; let quote = increase_liquidity_quote_a( token_amount_a, slippage_tolerance_bps, current_sqrt_price.into(), tick_index_1, tick_index_2, transfer_fee_a, transfer_fee_b, ).unwrap(); println!("{:?}", quote); } ``` Expected output: ``` IncreaseLiquidityQuote { liquidity_delta: 16011047470, token_est_a: 1000000000, token_est_b: 127889169, token_max_a: 1010000000, token_max_b: 129168061, } ``` </TabItem> </Tabs>
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/03-Whirlpools Client.mdx
--- sidebar_label: Whirlpools Client --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Orca Whirlpools Client SDK ## Overview This SDK provides developers with low-level functionalities for interacting with the Whirlpool Program on Solana. It serves as a foundational tool that allows developers to manage and integrate detailed operations into their Typescript projects, particularly those related to Orca's Whirlpool Program. While a high-level SDK is available for easier integration, this package offers more granular control for advanced use cases. ## Key Features - **Codama Client**: The package includes a set of generated client code based on the Whirlpool Program IDL. This ensures all the necessary program information is easily accessible in a structured format and handles all decoding and encoding of instructions and account data, making it much easier to interact with the program. - **GPA (Get Program Accounts) Filters**: This feature contains utilities to add filters to program accounts, allowing developers to fetch program account data more selectively and efficiently. - **PDA (Program Derived Addresses) Utilities**: This feature contains utility functions that help derive Program Derived Addresses (PDAs) for accounts within the Whirlpool Program, simplifying address generation for developers. ## Installation: <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> **NOTE**: This SDK requires Solana Web3.js SDK v2. It is not compatible with the widely used v1.x.x version. ```bash npm install @orca-so/whirlpools-client ``` </TabItem> <TabItem value="rust" label="Rust"> **NOTE**: This SDK requires Solana SDK v1. You can use this crate for cross-program-invocation (CPI) but you will have to disable the default features. ```bash cargo add orca_whirlpools_client ``` </TabItem> </Tabs> ## Usage Here are some basic examples of how to use the package. ### Fetching Whirlpool Accounts with Filters The following example demonstrates how to fetch Whirlpools accounts based on specific filters, using the GPA utilities: <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { createSolanaRpc, address, devnet } from '@solana/web3.js'; import { fetchAllWhirlpoolWithFilter, whirlpoolTokenMintAFilter } from "@orca-so/whirlpools-client"; const rpc = createSolanaRpc(devnet("https://api.devnet.solana.com")); const tokenMintA = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //DevUSDC const filter = whirlpoolTokenMintAFilter(tokenMintA); const accounts = await fetchAllWhirlpoolWithFilter(rpc, filter); console.log(accounts); ``` </TabItem> <TabItem value="rust" label="Rust"> `orca_whirlpools_client` currently does not support fetching accounts with filters. </TabItem> </Tabs> ### Deriving a PDA To derive a PDA for a Whirlpool account, you can use the `getWhirlpoolAddress` PDA utility. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { getWhirlpoolAddress } from "@orca-so/whirlpools-client"; import { address } from '@solana/web3.js'; const whirlpoolConfigAddress = address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR"); const tokenMintA = address("So11111111111111111111111111111111111111112"); //wSOL const tokenMintB = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //DevUSDC const tickSpacing = 64; const whirlpoolPda = await getWhirlpoolAddress( whirlpoolConfigAddress, tokenMintA, tokenMintB, tickSpacing, ); console.log(whirlpoolPda); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools_client::get_whirlpool_address; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; fn main() { let whirlpool_config_address = Pubkey::from_str("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR").unwrap(); let token_mint_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); // wSOL let token_mint_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // DevUSDC let tick_spacing = 64; let (whirlpool_pda, _bump) = get_whirlpool_address(&whirlpool_config_address, &token_mint_a, &token_mint_b, tick_spacing).unwrap(); println!("{:?}", whirlpool_pda); } ``` </TabItem> </Tabs> ### Example: Initialize Pool Instruction The following example demonstrates how to create an InitializePool instruction using the Codama-IDL autogenerated code: <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { getInitializePoolV2Instruction, getTokenBadgeAddress, getWhirlpoolAddress, getFeeTierAddress } from "@orca-so/whirlpools-client"; import { address, generateKeyPairSigner } from '@solana/web3.js'; const whirlpoolConfigAddress = address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR"); const tokenMintA = address("So11111111111111111111111111111111111111112"); // wSOL const tokenMintB = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // DevUSDC const tokenBadgeA = await getTokenBadgeAddress(whirlpoolConfigAddress, tokenMintA) const tokenBadgeB = await getTokenBadgeAddress(whirlpoolConfigAddress, tokenMintB) const wallet = await generateKeyPairSigner(); // CAUTION: this wallet is not persistent const tickSpacing = 8; const whirlpool = await getWhirlpoolAddress(whirlpoolConfigAddress, tokenMintA, tokenMintB, tickSpacing); const tokenVaultA = await generateKeyPairSigner(); const tokenVaultB = await generateKeyPairSigner(); const feeTier = await getFeeTierAddress(whirlpoolConfigAddress, tickSpacing); const tokenProgramA = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"); const tokenProgramB = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"); const initialSqrtPrice = BigInt(7459106261056563200n); const initializePoolInstruction = getInitializePoolV2Instruction({ whirlpoolsConfig: whirlpoolConfigAddress, tokenMintA, tokenMintB, tokenBadgeA, tokenBadgeB, funder: wallet, whirlpool, tokenVaultA, tokenVaultB, feeTier, whirlpoolBump: 1, tickSpacing, tokenProgramA, tokenProgramB, initialSqrtPrice }); console.log(initializePoolInstruction); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools_client::{ instructions::InitializePoolV2Builder, get_fee_tier_address, get_token_badge_address, get_whirlpool_address, }; use solana_sdk::{ pubkey::Pubkey, signer::{keypair::Keypair, Signer}, }; use std::str::FromStr; fn main() { let whirlpool_config_address = Pubkey::from_str("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR").unwrap(); let token_mint_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); // wSOL let token_mint_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // DevUSDC let (token_badge_a, _bump) = get_token_badge_address(&whirlpool_config_address, &token_mint_a).unwrap(); let (token_badge_b, _bump) = get_token_badge_address(&whirlpool_config_address, &token_mint_b).unwrap(); let wallet = Keypair::new(); // CAUTION: this wallet is not persistent let tick_spacing = 8; let (whirlpool_pda, _bump) = get_whirlpool_address(&whirlpool_config_address, &token_mint_a, &token_mint_b, tick_spacing).unwrap(); let token_vault_a = Keypair::new(); let token_vault_b = Keypair::new(); let (fee_tier, _bump) = get_fee_tier_address(&whirlpool_config_address, tick_spacing).unwrap(); let token_program_a = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap(); let token_program_b = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap(); let initial_sqrt_price = 7459106261056563200u128; let initialize_pool_v2_instruction = InitializePoolV2Builder::new() .whirlpools_config(whirlpool_config_address) .token_mint_a(token_mint_a) .token_mint_b(token_mint_b) .token_badge_a(token_badge_a) .token_badge_b(token_badge_b) .funder(wallet.pubkey()) .whirlpool(whirlpool_pda) .token_vault_a(token_vault_a.pubkey()) .token_vault_b(token_vault_b.pubkey()) .fee_tier(fee_tier) .token_program_a(token_program_a) .token_program_b(token_program_b) .tick_spacing(tick_spacing) .initial_sqrt_price(initial_sqrt_price) .instruction(); println!("{:?}", initialize_pool_v2_instruction); } ``` </TabItem> </Tabs>
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/05-Trade.mdx
--- sidebar_label: Trade --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Executing a Token Swap You can use the SDK to execute a token swap on Orca. Whether you're swapping a specific amount of input tokens or looking to receive a precise amount of output tokens, this function handles the preparation of token accounts, liquidity data, and instruction assembly. It also manages slippage tolerance to ensure that swaps are executed within acceptable price changes. This guide explains how to use the SDK to perform a token swap in an Orca Whirlpool. ## 1. Overview of Executing a Token Swap The SDK allows you to swap tokens between different pools on Orca. It handles the calculation of token amounts, manages slippage, and assembles the necessary instructions for executing the swap. With this function, you can: - Swap an exact amount of input tokens for the maximum possible output. - Specify the desired amount of output tokens and determine the necessary input. - Control slippage to manage your risk during volatile market conditions. ## 2. Getting Started Guide Before creating a Splash Pool or a Concentrated Liquidity Pool, ensure you have completed the environment setup: - **RPC Setup**: Use a Solana RPC client to communicate with the blockchain. - **Wallet Creation**: Create a wallet to interact with the Solana network. - **Devnet Airdrop**: Fund your wallet with a Solana devnet airdrop to cover transaction fees. For more details, refer to our [Environment Setup Guide](./02-Environment%20Setup.mdx) ### Executing a Token Swap To execute a token swap in an Orca Whirlpool, follow these steps: 1. **RPC Client**: Use a Solana RPC client to interact with the blockchain. 2. **Pool Address**: Provide the address of the Orca Whirlpool pool where the swap will take place. 3. **Swap Parameters**: Define the swap parameters. You only need to provide one of these parameters, and the function will compute the others in the returned quote based on the current price of the pool: - `inputAmount`: Specify the amount of tokens to swap (if exact input). - `outputAmount`: Specify the desired amount of tokens to receive (if exact output). - `mint`: Provide the mint address of the token you want to swap out. 4. **Slippage tolerance**: Set the maximum slippage tolerance (optional, defaults to 1%). Slippage refers to the difference between the expected amounts of tokens received or sent during the swap and the actual amounts executed. A lower slippage tolerance reduces the risk of receiving fewer tokens than expected, but may lead to failed transactions if the market moves too quickly. For example, if you expect to receive 1,000 units of Token B for 100 units of Token A, with a 1% slippage tolerance, the maximum Token A spent will be 101, and the minimum Token B received will be 990. 5. **Signer**: This can be your wallet, which will fund the pool initialization. If a signer is not specified, the default wallet will be used. You can configure the default wallet through the SDK. 6. **Create Instructions**: Use the appropriate function to generate the necessary instructions for the swap. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { setWhirlpoolsConfig, swapInstructions } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; import { loadWallet } from './utils'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await loadWallet(); // CAUTION: This wallet is not persistent. const whirlpoolAddress = address("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt"); const mintAddress = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); const inputAmount = 1_000_000n; const { instructions, quote } = await swapInstructions( devnetRpc, { inputAmount, mint: mintAddress }, whirlpoolAddress, 100, wallet ); console.log(`Quote estimated token out: ${quote.tokenEstOut}`); console.log(`Number of instructions:, ${instructions.length}`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use crate::utils::load_wallet; use orca_whirlpools::{ set_whirlpools_config_address, swap_instructions, SwapType, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let wallet = load_wallet(); let whirlpool_address = Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); let mint_address = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); let input_amount = 1_000_000; let result = swap_instructions( &rpc, whirlpool_address, input_amount, mint_address, SwapType::ExactIn, Some(100), Some(wallet.pubkey()), ) .await .unwrap(); println!("Quote estimated token out: {:?}", result.quote); println!("Number of Instructions: {}", result.instructions.len()); } ``` </TabItem> </Tabs> 7. **Submit Transaction**: Include the generated instructions in a Solana transaction and send it to the network using the Solana SDK. ### 3. Example Usage Suppose you are developing an arbitrage bot that looks for price discrepancies between different liquidity pools on Orca. By using the SDK, the bot can retrieve the quote object for a potential swap, which includes details about the token amounts and expected output. The bot can quickly compare quotes from multiple pools to identify arbitrage opportunities and execute profitable swaps.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/01-Overview.md
# Overview This High-Level SDK is our top recommendation for anyone who wants to integrate with the Whirlpool Program. It builds upon the Low-Level and Core SDKs to provide an easy-to-use interface for interacting with the Whirlpool Program. This SDK abstracts many of the underlying complexities, such as tick array management, and makes managing pools and positions, and executing swaps much simpler. It is suitable for developers who need efficient, high-level functionalities and want to minimize manual configuration and management.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/02-Environment Setup.mdx
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Environment setup This document covers the essential setup required to start building on Orca’s SDK using the Whirlpools protocol. It includes wallet setup, RPC client configuration, airdropping tokens for testing, and the basics of interacting with the Solana ecosystem. ## Prerequisites <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> Before you start, ensure you have Node.js version 20 or higher installed on your machine. Download it from the official website: https://nodejs.org/. </TabItem> <TabItem value="rust" label="Rust"> Before you start, ensure you have Rust installed. To ensure compatibility with the Solana SDK v1.18, we recommend using `rustc 1.78.0`. </TabItem> </Tabs> ## 1. Initialize a new project <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> Create a new project directory: ```bash mkdir <project-name> cd <project-name> ``` Initialize a new Node.js project: ```bash npm init -y ``` Install the necessary packages: ```bash npm install typescript @orca-so/whirlpools @solana/web3.js@rc ``` Initialize the project as a TypeScript project: ```bash npx tsc --init ``` </TabItem> <TabItem value="rust" label="Rust"> Initialize a new Rust project: ```bash cargo new <project-name> ``` Add the necessary dependencies to your project: ```bash cargo add orca_whirlpools solana-sdk@1.18 solana-client@1.18 tokio serde_json ``` </TabItem> </Tabs> ## 2. Wallet Management You can [generate a file system wallet using the Solana CLI](https://docs.solanalabs.com/cli/wallets/file-system) and load it in your program. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { createKeyPairSignerFromBytes } from '@solana/web3.js'; import fs from 'fs'; const keyPairBytes = new Uint8Array(JSON.parse(fs.readFileSync('path/to/solana-keypair.json', 'utf8'))); const wallet = await createKeyPairSignerFromBytes(keyPairBytes); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use solana_sdk::signer::keypair::Keypair; use solana_sdk::signature::Signer; use std::fs; fn main() { let wallet_string = fs::read_to_string("path/to/wallet.json").unwrap(); let keypair_bytes: Vec<u8> = serde_json::from_str(&wallet_string).unwrap(); let wallet = Keypair::from_bytes(&keypair_bytes).unwrap(); } ``` </TabItem> </Tabs> > ⚠️ Important: Never share your private key publicly. ## 3. Configure the Whirlpools SDK for Your Network Orca's Whirlpools SDK supports several networks: Solana Mainnet, Solana Devnet, Eclipse Mainnet, and Eclipse Testnet. To select a network, use the `setWhirlpoolsConfig` function. This ensures compatibility with the network you’re deploying on. #### Example: Setting the SDK Configuration to Solana Devnet <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { setWhirlpoolsConfig } from '@orca-so/whirlpools'; await setWhirlpoolsConfig('solanaDevnet'); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{WhirlpoolsConfigInput, set_whirlpools_config_address}; fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); // Rest of the code } ``` </TabItem> </Tabs> Available networks are: - solanaMainnet - solanaDevnet - eclipseMainnet - eclipseTestnet > ℹ️ The `setWhirlpoolsConfig` function accepts either one of Orca's default network keys or a custom `Address`. This allows you to specify a WhirlpoolsConfig account of your choice, including configurations not owned by Orca. To learn more about WhirlpoolsConfig read our [Account Architecture](../../02-Architecture%20Overview/01-Account%20Architecture.md) documentation. ## 4. Airdrop SOL to Your Wallet Once your wallet is created, you will need some SOL to pay for transactions. You can request an airdrop of SOL from the network, but this is only available on **Solana Devnet** and **Ecipse Testnet**. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { generateKeyPair, createSolanaRpc, devnet, getAddressFromPublicKey } from '@solana/web3.js'; const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await generateKeyPairSigner(); devnetRpc.requestAirdrop( wallet.address, lamports(1000000000n) ).send() ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use solana_client::rpc_client::RpcClient; use solana_sdk::signature::Signer; fn main() { // Rest of the code let rpc_client = RpcClient::new("https://api.devnet.solana.com"); match rpc_client.request_airdrop(&wallet.pubkey(), 1_000_000_000) { Ok(signature) => println!("Airdrop successful. Transactoin signature: {:?}", signature), Err(e) => println!("Error: {:?}", e), } } ``` </TabItem> </Tabs> ## 5. Set the default funder for Transactions After funding your wallet, you can set the wallet as the **FUNDER** for future transactions within the SDK. The funder is the account that will cover the transaction costs for initializing pools, providing liquidity, etc. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { setDefaultFunder } from '@orca-so/whirlpools'; setDefaultFunder(wallet); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{set_funder}; use solana_sdk::signature::Signer; fn main() { // Rest of the code set_funder(wallet.pubkey()).unwrap(); } ``` </TabItem> </Tabs> ## Next steps Once you’ve completed the setup, you can move on to building more complex functionalities using the Orca SDK, such as creating and managing pools, providing liquidity, etc. Refer to individual function documentation to use this wallet setup in action.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/03-Whirlpool Management/02-Fetch Pools.mdx
--- sidebar_label: Fetch Liquidity Pools --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Fetching Liquidity Pools on Orca Monitoring and fetching details about liquidity pools on Orca is crucial for understanding their current state, whether you want to gather insights in a Splash Pool, a Concentrated Liquidity Pool, or all pools between specific token pairs. This guide will explain how to interact with the available functions to retrieve these details. ## 1. Overview of Pool Fetching Fetching liquidity pool details helps developers gain insight into the current state of the pool, whether it is initialized or uninitialized, and retrieve relevant metrics like liquidity, price, and fee rates. The SDKs offer three main functions to help developers monitor the pools: - **Fetch Splash Pool**: Fetches the details of a specific Splash Pool. - **Fetch Concentrated Liquidity Pool**: Fetches the details of a specific Concentrated Liquidity Pool. - **Fetch Pools**: Fetches all possible liquidity pools between two token mints, with various tick spacings. ### Initialized vs. Uninitialized Pools Each token pair can have multiple pools based on different tick spacings, corresponding to various fee tiers. When using the Fetch Concentrated Liquidity Pool function, it’s possible to request a pool with a tick spacing that hasn't been used to create a pool for the given token pair. In this case, you’ll receive a pool object with default parameters and an additional field `initialized = false`, indicating that the pool has not been set up. Similarly, when using Fetch Pools, which iterates through all possible tick spacings for a given token pair, uninitialized pools can also be returned in this manner. The function will return both initialized and uninitialized pools, allowing you to identify pools that have not yet been created. ## 2. Getting Started Guide ### Fetching a Splash Pool 1. **Token Mint Addresses**: Provide the mint addresses of the two tokens that make up the liquidity pool. 2. **Fetch Pool Details**: Use the appropriate function to fetch the details of the specified Splash Pool. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { fetchSplashPool, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const tokenMintOne = address("So11111111111111111111111111111111111111112"); const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //devUSDC const poolInfo = await fetchSplashPool( devnetRpc, tokenMintOne, tokenMintTwo ); if (poolInfo.initialized) { console.log("Pool is initialized:", poolInfo); } else { console.log("Pool is not initialized:", poolInfo); }; ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ fetch_splash_pool, set_whirlpools_config_address, PoolInfo, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC let pool_info = fetch_splash_pool(&rpc, token_a, token_b).await.unwrap(); match pool_info { PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), } } ``` </TabItem> </Tabs> ### Fetching a Concentrated Liquidity Pool 1. **Token Mint Addresses**: Provide the mint addresses of the two tokens that make up the liquidity pool. 2. **Tick Spacing**: Specify the tick spacing, which defines the intervals for price ticks. 3. **Fetch Pool Details**: Use the appropriate function to fetch the details of the specified Concentrated Liquidity Pool. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { fetchConcentratedLiquidityPool, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const tokenMintOne = address("So11111111111111111111111111111111111111112"); const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); const tickSpacing = 64; const poolInfo = await fetchConcentratedLiquidityPool( devnetRpc, tokenMintOne, tokenMintTwo, tickSpacing ); if (poolInfo.initialized) { console.log("Pool is initialized:", poolInfo); } else { console.log("Pool is not initialized:", poolInfo); }; ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ fetch_concentrated_liquidity_pool, set_whirlpools_config_address, PoolInfo, WhirlpoolsConfigInput }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC let tick_spacing = 64; let pool_info = fetch_concentrated_liquidity_pool(&rpc, token_a, token_b, tick_spacing).await.unwrap(); match pool_info { PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), } } ``` </TabItem> </Tabs> ### Fetching Pools by Token Pairs 1. **Token Mint Addresses**: Provide the mint addresses of the two tokens that make up the liquidity pool. 2. **Fetch Pool Details**: Use the appropriate function to fetch the details of the specified pools. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { fetchWhirlpoolsByTokenPair, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const tokenMintOne = address("So11111111111111111111111111111111111111112"); const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); const poolInfos = await fetchWhirlpoolsByTokenPair( devnetRpc, tokenMintOne, tokenMintTwo ); poolInfos.forEach((poolInfo) => { if (poolInfo.initialized) { console.log("Pool is initialized:", poolInfo); } else { console.log("Pool is not initialized:", poolInfo); } }); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ fetch_whirlpools_by_token_pair, set_whirlpools_config_address, PoolInfo, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC let pool_infos = fetch_whirlpools_by_token_pair(&rpc, token_a, token_b) .await .unwrap(); for pool_info in pool_infos { match pool_info { PoolInfo::Initialized(pool) => println!("Pool is initialized: {:?}", pool), PoolInfo::Uninitialized(pool) => println!("Pool is not initialized: {:?}", pool), } } } ``` </TabItem> </Tabs>
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/03-Whirlpool Management/01-Create Pool.mdx
--- sidebar_label: Create Liquidity Pools --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Creating Liquidity Pools on Orca Creating liquidity pools on Orca is an essential step for launching your token and enabling trading. In this guide, we'll explore two types of liquidity pools available in the Orca ecosystem, **Splash Pools** and **Concentrated Liquidity Pools**, and help you understand how to create them, their differences, and which one best suits your needs. ## 1. Introduction to Pool Types ### Overview Liquidity pools are a foundational concept in DeFi, enabling users to trade tokens without relying on traditional order books. On Orca, liquidity pools provide the means for traders to swap between two tokens, while liquidity providers earn fees by supplying the tokens to the pool. ### Splash Pools vs. Concentrated Liquidity Pools - **Splash Pools**: Splash Pools are the simplest type of liquidity pool. They are ideal for those looking to launch a new token with minimal parameters. You only need to provide the mint addresses of the two tokens and set the initial price. Splash Pools offer an easy entry point into liquidity provision, making them especially appealing for community-driven projects like memecoins. These projects often prioritize community engagement over technical complexity, and Splash Pools provide a straightforward way to get started. - **Concentrated Liquidity Pools:** Concentrated Liquidity Pools are more advanced and allow liquidity providers to concentrate their liquidity within specific price ranges. This results in higher capital efficiency but requires a deeper understanding of how to manage liquidity. Concentrated Liquidity Pools are better suited for experienced users who want greater control over their liquidity. ## 2. Getting Started Guide Before creating a Splash Pool or a Concentrated Liquidity Pool, ensure you have completed the environment setup: - **RPC Setup**: Use a Solana RPC client to communicate with the blockchain. - **Wallet Creation**: Create a wallet to interact with the Solana network. - **Devnet Airdrop**: Fund your wallet with a Solana devnet airdrop to cover transaction fees. For more details, refer to our [Environment Setup Guide](../02-Environment%20Setup.mdx) ### Creating Splash Pools Splash Pools are the easiest way to get started: 1. **Token Mint Addresses**: Provide the mint addresses of the two tokens that will make up the liquidity pool. The order of the tokens is important: the first token will be priced in terms of the second token. This means that the price you set will reflect how many units of the second token are needed to equal one unit of the first token. For example, if you set the price to 0.0001 SOL, this means that one unit of the first token is worth 0.0001 units of the second token (SOL). Make sure to verify the order of your tokens. 2. **Initial Price**: Set the initial price of token 1 in terms of token 2. 3. **Funder**: This will be your wallet, which will fund the initialization process. 4. **Create Instructions**: Use the appropriate function to generate the required pool creation instructions. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { createSplashPoolInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent. const tokenMintOne = address("So11111111111111111111111111111111111111112"); const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // devUSDC const initialPrice = 0.01; const { poolAddress, instructions, initializationCost } = await createSplashPoolInstructions( devnetRpc, tokenMintOne, tokenMintTwo, initialPrice, wallet ); console.log(`Pool Address: ${poolAddress}`); console.log(`Initialization Cost: ${initializationCost} lamports`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ create_splash_pool_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{pubkey::Pubkey, signature::Signer, signer::keypair::Keypair}; use std::str::FromStr; use tokio; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC let initial_price = Some(0.01); let wallet = Keypair::new(); // CAUTION: This wallet is not persistent. let funder = Some(wallet.pubkey()); let result = create_splash_pool_instructions(&rpc, token_a, token_b, initial_price, funder) .await .unwrap(); println!("Pool Address: {:?}", result.pool_address); println!( "Initialization Cost: {} lamports", result.initialization_cost ); } ``` </TabItem> </Tabs> 5. Submit Transaction: Include the generated pool creation instructions in a Solana transaction and send it to the network using the Solana SDK. ### Creating Concentrated Liquidity Pools Concentrated Liquidity Pools offer more flexibility: 1. **Token Mint Addresses**: Provide the two token mints. 2. **Tick Spacing**: Set the tick spacing, which defines the intervals for price ticks. Visit the [Whirlpools Parameters](../../../02-Architecture%20Overview/06-Whirlpool%20Parameters.mdx) page to learn more about the available values of tick spacing and their corresponding fee rates. 3. **Initial Price**: Specify the initial price of token 1 in terms of token 2. 4. **Funder**: This can be your wallet, which will fund the pool initialization. If the funder is not specified, the default wallet will be used. You can configure the default wallet through the SDK. 5. **Create instructions**: Use the appropriate function to create the pool. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { createConcentratedLiquidityPoolInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent. const tokenMintOne = address("So11111111111111111111111111111111111111112"); const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // devUSDC const tickSpacing = 64; const initialPrice = 0.01; const { poolAddress, instructions, initializationCost } = await createConcentratedLiquidityPoolInstructions( devnetRpc, tokenMintOne, tokenMintTwo, tickSpacing, initialPrice, wallet ); console.log(`Pool Address: ${poolAddress}`); console.log(`Initialization Cost: ${initializationCost} lamports`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ create_concentrated_liquidity_pool_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{pubkey::Pubkey, signature::Signer, signer::keypair::Keypair}; use std::str::FromStr; use tokio; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let token_a = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap(); let token_b = Pubkey::from_str("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k").unwrap(); // devUSDC let tick_spacing = 64; let initial_price = Some(0.01); let wallet = Keypair::new(); // CAUTION: This wallet is not persistent. let funder = Some(wallet.pubkey()); let result = create_concentrated_liquidity_pool_instructions( &rpc, token_a, token_b, tick_spacing, initial_price, funder, ) .await .unwrap(); println!("Pool Address: {:?}", result.pool_address); println!( "Initialization Cost: {} lamports", result.initialization_cost ); } ``` </TabItem> </Tabs> 6. **Submit Transaction**: Include the generated pool creation instructions in a Solana transaction and send it to the network using the Solana SDK. ### Comparison | Feature | Splash Pools | Concentrated Liquidity Pools | | ------------------ | ------------------ | -------------------------------- | | Complexity | Low | High | | Initial Parameters | Token mints, price | Token mints, tick spacing, price | | Capital Efficiency | Moderate | High | | Ideal For | Beginners | Advanced Users | ## 3. Usage Examples ### Launching a Token Pair with a Splash Pool Suppose you want to launch a new memecoin and pair it with USDC. You can leverage the simplicity of Splash Pools to quickly set up the pool with an initial price. This is ideal if you want to keep things simple and start earning trading fees with minimal configuration. For example, if a development team is building a launchpad for memecoins, Splash Pools are an ideal solution. ### Creating a Concentrated Liquidity Pool for Efficiency If you want to maximize capital efficiency, you can use the flexibility of Concentrated Liquidity Pools to define specific price ranges for your liquidity. This approach is beneficial when you expect price movements within certain bounds and want to concentrate liquidity accordingly. For example, a DeFi protocol might use a Concentrated Liquidity Pool to facilitate a stablecoin-stablecoin pair, where the price is expected to remain within a tight range. By concentrating liquidity in this range, the protocol can maximize returns for liquidity providers and reduce slippage for traders. ## 4. Next Steps After creating a liquidity pool, the pool is still empty and requires liquidity for people to trade against. To make the pool functional, open a position and add liquidity. This enables traders to swap between tokens and helps you start earning fees.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/04-Position Management/01-Open Position.mdx
--- sidebar_label: Open a position --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Opening a Position Opening a position in liquidity pools on Orca is a fundamental step for providing liquidity and earning fees. In this guide, we'll explore how to open a position in both **Splash Pools** and **Concentrated Liquidity Pools**, their differences, and which approach is suitable for different use cases. ## 1. Introduction to Positions in Pools A position in a liquidity pool represents your contribution of liquidity, which allows traders to swap between tokens while you earn a share of the trading fees. When you open a position, you decide how much liquidity to add, and this liquidity can later be adjusted or removed. - **Splash Pools**: Provide liquidity without specifying a price range. Ideal for those seeking a simple way to start providing liquidity. - **Concentrated Liquidity Pools**: Allow you to provide liquidity within a specified price range, enabling higher capital efficiency but requiring more advanced management. Upon creation of the position, an NFT will be minted to represent ownership of the position. This NFT is used by the program to verify your ownership when adjusting liquidity, harvesting rewards, or closing the position. For more information, refer to [Tokenized Positions](../../../02-Architecture%20Overview/04-Tokenized%20Positions.md). > ⚠️ **Risk of Divergence loss**: The ratio of Token A to Token B that you deposit as liquidity is determined by several factors, including the current price. As trades occur against the pool, the amounts of Token A and Token B in the pool — and in your position — will change, which affects the price of the tokens relative to each other. This can work to your advantage, but it may also result in the combined value of your tokens (including any earned fees and rewards) being lower than when you initially provided liquidity. > ⚠️ Do not burn the position NFT, as burning it will result in the indefinite loss of your position and liquidity. ## 2. Getting Started Guide Before opening a position, ensure you have completed the environment setup: - **RPC Setup**: Use a Solana RPC client to communicate with the blockchain. - **Wallet Creation**: Create a wallet to interact with the Solana network. - **Devnet Airdrop**: Fund your wallet with a Solana Devnet airdrop to cover transaction fees. For more details, refer to our [Environment Setup Guide](../02-Environment%20Setup.mdx) ### Opening a Position in Splash Pools 1. **Pool Address**: Provide the address of the Splash Pool where you want to open a position. 2. **Liquidity Parameters**: Choose how you want to provide liquidity. You only need to provide one of these parameters, and the function will compute the others in the returned quote based on the current price of the pool: - `liquidity`: Specify the liquidity value to provide. - `tokenA`: Specify the amount of token A (first token in the pool). - `tokenB`: Specify the amount of token B (second token in the pool). 3. **Slippage Tolerance**: Set the maximum slippage tolerance (optional, defaults to 1%). Slippage refers to the difference between the expected price and the actual price at which the transaction is executed. A lower slippage tolerance reduces the risk of price changes during the transaction but may lead to failed transactions if the market moves too quickly. 4. **Funder**: This will be your wallet, which will fund the transaction. 5. **Create Instructions**: Use the appropriate function to generate the necessary instructions. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { openFullRangePositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; import { loadWallet } from './utils'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await loadWallet(); // load your wallet const whirlpoolAddress = address("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt"); // SOL/devUSDC const param = { tokenA: 10n }; const { quote, instructions, initializationCost, positionMint } = await openFullRangePositionInstructions( devnetRpc, whirlpoolAddress, param, 100, wallet ); console.log(`Quote token max B: ${quote.tokenMaxB}`); console.log(`Initialization cost: ${initializationCost}`); console.log(`Position mint: ${positionMint}`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ open_full_range_position_instructions, set_whirlpools_config_address, IncreaseLiquidityParam, WhirlpoolsConfigInput }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; use crate::utils::load_wallet; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let wallet = load_wallet(); let whirlpool_address = Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); let param = IncreaseLiquidityParam::TokenA(10); let result = open_full_range_position_instructions( &rpc, whirlpool_address, param, Some(100), Some(wallet.pubkey()) ).await.unwrap(); println!("Quote token mac B: {:?}", result.quote.token_max_b); println!("Initialization cost: {:?}", result.initialization_cost); println!("Position mint: {:?}", result.position_mint); } ``` </TabItem> </Tabs> 6. **Submit Transaction**: Include the generated instructions in a Solana transaction and send it to the network using the Solana SDK. Ensure that you have enough of both Token A and Token B as calculated in the quote, or the transaction will fail. ### Opening a Position in Concentrated Liquidity Pools 1. **Pool Address**: Provide the address of the Concentrated Liquidity Pool where you want to open a position. 2. **Liquidity Parameters**: Choose how you want to provide liquidity. You only need to provide one of these parameters, and the function will compute the others in the returned quote based on the price range and the current price of the pool: - `liquidity`: Specify the liquidity value to provide. - `tokenA`: Specify the amount of token A (first token in the pool). - `tokenB`: Specify the amount of token B (second token in the pool). 3. **Price Range**: Set the lower and upper bounds of the price range within which your liquidity will be active. The current price and the specified price range will influence the quote amounts. If the current price is in the middle of your price range, the ratio of token A to token B will reflect that price. However, if the current price is outside your range, you will only deposit one token, resulting in one-sided liquidity. Note that your position will only earn fees when the price falls within your selected price range, so it’s important to choose a range where you expect the price to remain active. 3. **Slippage Tolerance**: Set the maximum slippage tolerance (optional, defaults to 1%). Slippage refers to the difference between the expected token amounts and the actual amounts deposited into the liquidity pool. A lower slippage tolerance reduces the risk of depositing more tokens than expected but may lead to failed transactions if the market moves too quickly. For example, if you expect to deposit 100 units of Token A and 1,000 units of Token B, with a 1% slippage tolerance, the maximum amounts would be 101 Token A and 1,010 Token B. 4. **Funder**: This can be your wallet, which will fund the pool initialization. If the funder is not specified, the default wallet will be used. You can configure the default wallet through the SDK. 5. **Create Instructions**: Use the appropriate function to generate the necessary instructions. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { openPositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; import { loadWallet } from './utils'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await loadWallet(); // load your wallet const whirlpoolAddress = address("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt"); // SOL/devUSDC const param = { tokenA: 10n }; const { quote, instructions, initializationCost, positionMint } = await openPositionInstructions( devnetRpc, whirlpoolAddress, param, 0.001, 100.0, 100, wallet ); console.log(`Quote token max B: ${quote.tokenEstB}`); console.log(`Initialization cost: ${initializationCost}`); console.log(`Position mint: ${positionMint}`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ open_position_instructions, set_whirlpools_config_address, IncreaseLiquidityParam, WhirlpoolsConfigInput }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; use crate::utils::load_wallet; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let wallet = load_wallet(); let whirlpool_address = Pubkey::from_str("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt").unwrap(); let param = IncreaseLiquidityParam::TokenA(10); let result = open_position_instructions( &rpc, whirlpool_address, 0.001, 100.0, param, Some(100), Some(wallet.pubkey()) ).await.unwrap(); println!("Quote token max B: {:?}", result.quote.token_est_b); println!("Initialization cost: {:?}", result.initialization_cost); println!("Position mint: {:?}", result.position_mint); } ``` </TabItem> </Tabs> 6. **Submit Transaction**: Include the generated instructions in a Solana transaction and send it to the network using the Solana SDK. Ensure that you have enough of both Token A and Token B as calculated in the quote, or the transaction will fail. > ⚠️ You cannot use this function on Splash Pools, as this function is specifically for Concentrated Liquidity Pools. ## 3. Usage examples ### Opening a Position in a Splash Pool Suppose you want to provide 1,000,000 tokens of Token A at a price of 0.0001 SOL. You will also need to provide 100 SOL as Token B to match the price. By using the SDK to open full range positions, you ensure that your liquidity is spread evenly across all price levels. This approach is ideal if you are launching a new token and want to facilitate easy swaps for traders. ### Opening a Position in a Concentrated Liquidity Pool If you want to maximize capital efficiency, you can open a position in a Concentrated Liquidity Pool. For example, if the current price is at 0.01 and you want to maximize profitability, you could use the SDK to deposit liquidity between the price range of 0.009 and 0.011. This approach allows you to focus your liquidity in a narrow range, making it more effective and potentially more profitable. ## Next Steps After opening a position, you can: - [Add or Remove Liquidity](03-Adjust%20Liquidity.mdx): Adjust the amount of liquidity in your position based on market conditions. - [Harvest Rewards](04-Harvest.mdx): Collect rewards and fees without closing the position. - [Monitor Performance](02-Fetch%20Positions.mdx): Track your position's performance and earned fees. - [Close Position](05-Close%20Position.mdx): When you decide to exit, close the position and withdraw the provided tokens along with any earned fees.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/04-Position Management/05-Close Position.mdx
--- sidebar_label: Close Position --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Close a Position Once you've provided liquidity in a pool, there may come a time when you want to close your position entirely. The SDK allows you to fully remove liquidity from the pool, collect any outstanding fees and rewards, and close the position. This is useful when you want to exit the pool, either to realize profits or to reallocate capital to other opportunities. This guide explains how to use the SDK to close a position. ## 1. Overview of Closing a Position When using the SDK to fully close a liquidity position, you generate all the necessary instructions. It performs the following key actions: 1. Collect Fees: Retrieves any fees earned from trades involving your liquidity. 2. Collect Rewards: Retrieves any rewards you've accumulated for the pool. 3. Decrease Liquidity: Removes any remaining liquidity in the position. 4. Close Position: Closes the position and returns the tokens in your account. ## 2. Getting Started Guide ### Closing a Position To close a position and withdraw all liquidity, follow these steps: 1. **RPC Client**: Use a Solana RPC client to interact with the blockchain. 2. **Position Mint**: Provide the mint address of the NFT representing your position. This NFT serves as proof of ownership and represents the liquidity in the position. 3. **Parameters for Liquidity**: Define the parameters for decreasing liquidity. This can be specified as a liquidity amount or as specific token amounts. 4. **Slippage Tolerance**: Set the maximum slippage tolerance (optional, defaults to 1%). Slippage refers to the difference between the expected token amounts you receive when closing a position and the actual amounts returned to your wallet. A lower slippage tolerance reduces the risk of receiving fewer tokens than expected but may lead to failed transactions if the market moves too quickly. For example, if you expect to receive 100 units of Token A and 1,000 units of Token B when closing your position, with a 1% slippage tolerance, the minimum amounts returned would be 99 Token A and 990 Token B. 5. **Authority**: This can be your wallet, which will fund the pool initialization. If the authority is not specified, the default wallet will be used. You can configure the default wallet through the SDK. 6. **Create Instructions**: Use the appropriate function to generate the necessary instructions. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { closePositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; import { loadWallet } from './utils'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await loadWallet(); const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K"); const { instructions, quote, feesQuote, rewardsQuote } = await closePositionInstructions( devnetRpc, positionMint, 100, wallet ); console.log(`Quote token max B: ${quote.tokenEstB}`); console.log(`Fees owed token A: ${feesQuote.feeOwedA}`); console.log(`Rewards '1' owed: ${rewardsQuote.rewards[0].rewardsOwed}`); console.log(`Number of instructions:, ${instructions.length}`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use crate::utils::load_wallet; use orca_whirlpools::{ close_position_instructions, set_whirlpools_config_address, WhirlpoolsConfigInput, }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let wallet = load_wallet(); let position_mint_address = Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); let result = close_position_instructions( &rpc, position_mint_address, Some(100), Some(wallet.pubkey()), ) .await .unwrap(); println!("Quote token max B: {:?}", result.quote.token_est_b); println!("Fees Quote: {:?}", result.fees_quote); println!("Rewards Quote: {:?}", result.rewards_quote); println!("Number of Instructions: {}", result.instructions.len()); } ``` </TabItem> </Tabs> ```tsx const { instructions, quote, feesQuote, rewardsQuote } = await closePositionInstructions( rpc, positionMint, slippageTolerance, wallet ); ``` 7. **Submit Transaction**: Include the generated instructions in a Solana transaction and send it to the network using the Solana SDK. ## 3. Usage Example Suppose your trading strategy predicts that the current price range will lead to divergence loss, and you need to close the position to avoid further losses. Using the SDK, you can generate the instructions to collect all accumulated fees, rewards, and remove liquidity to prevent further losses.
0
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools
solana_public_repos/orca-so/whirlpools/docs/whirlpool/docs/03-Whirlpools SDKs/01-Whirlpools/04-Position Management/03-Adjust Liquidity.mdx
--- sidebar_label: Adjust Liquidity --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Adjusting Liquidity in Your Positions Once you’ve opened a position in an Orca Whirlpool, you may need to adjust the amount of liquidity you've provided to align with market conditions or your strategy. Whether you want to add more liquidity to capture additional fees or withdraw liquidity to reduce exposure or realize profits, the Whirlpools SDK provides functions for both. This guide explains how to use the SDK functions to increase and decrease the liquidity in your position. ## 1. Overview of Adjusting Liquidity The SDK functions for increasing or decreasing liquidity work similarly, enabling you to modify the liquidity of an existing position. You can specify the liquidity directly or provide amounts of token A or token B to increase or decrease liquidity. With these functions, you can: - Increase liquidity to potentially earn more fees as trading volume grows. - Decrease liquidity to reduce exposure or withdraw profits. ## 2. Getting Started Guide ### Adjusting Liquidity in a Position Adjusting liquidity in an existing position can be done as follows: 1. **RPC Client**: Use a Solana RPC client to interact with the blockchain. 2. **Position Mint**: Provide the mint address of the NFT representing your position. This NFT serves as proof of ownership of the position you want to adjust. 3. **Liquidity Parameters**: Choose how you want to adjust liquidity. You only need to provide one of these parameters, and the function will compute the others in the returned quote based on the current price of the pool and the price range of the position: - `liquidity`: Specify the liquidity value to add or remove. - `tokenA`: Specify the amount of token A to add or withdraw. - `tokenB`: Specify the amount of token B to add or withdraw. 4. **Slippage tolerance**: Set the maximum slippage tolerance (optional, defaults to 1%). Slippage refers to the difference between the expected token amounts added or removed when adjusting liquidity and the actual amounts that are ultimately deposited or withdrawn. A lower slippage tolerance reduces the risk of depositing or withdrawing more or fewer tokens than intended, but it may lead to failed transactions if the market moves too quickly. 5. **Funder**: This can be your wallet, which will fund the pool initialization. If a funder is not specified, the default wallet will be used. You can configure the default wallet through the SDK. 6. **Create Instructions**: Use the appropriate function to generate the necessary instructions. <Tabs groupId="programming-languages"> <TabItem value="ts" label="Typescript" default> ```tsx import { decreaseLiquidityInstructions, increaseLiquidityInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools'; import { createSolanaRpc, devnet, address } from '@solana/web3.js'; import { loadWallet } from './utils'; await setWhirlpoolsConfig('solanaDevnet'); const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com')); const wallet = await loadWallet(); const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K"); const param = { tokenA: 10n }; const { quote: increaseQuote, instructions: increaseInstructions } = await increaseLiquidityInstructions( devnetRpc, positionMint, param, 100, wallet ); const { quote: decreaseQuote, instructions: decreaseInstructions } = await decreaseLiquidityInstructions( devnetRpc, positionMint, param, 100, wallet ); console.log(`Increase quote token max B: ${increaseQuote.tokenEstB}`); console.log(`Decrease quote token max B: ${decreaseQuote.tokenEstB}`); ``` </TabItem> <TabItem value="rust" label="Rust"> ```rust use orca_whirlpools::{ decrease_liquidity_instructions, increase_liquidity_instructions, set_whirlpools_config_address, DecreaseLiquidityParam, IncreaseLiquidityParam, WhirlpoolsConfigInput }; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::str::FromStr; use crate::utils::load_wallet; #[tokio::main] async fn main() { set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaDevnet).unwrap(); let rpc = RpcClient::new("https://api.devnet.solana.com".to_string()); let wallet = load_wallet(); let position_mint_address = Pubkey::from_str("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K").unwrap(); let increase_param = IncreaseLiquidityParam::TokenA(1_000_000); let decrease_param = DecreaseLiquidityParam::TokenA(1_000_000); let increase_result = increase_liquidity_instructions( &rpc, position_mint_address, increase_param, Some(100), Some(wallet.pubkey()), ) .await.unwrap(); let decrease_result = decrease_liquidity_instructions( &rpc, position_mint_address, decrease_param, Some(100), Some(wallet.pubkey()), ) .await.unwrap(); println!("Liquidity Increase Quote: {:?}", increase_result.quote); println!("Liquidity Decrease Quote: {:?}", decrease_result.quote); println!("Number of Instructions: {}", increase_result.instructions.len()); } ``` </TabItem> </Tabs> 7. **Submit Transaction**: Include the generated instructions in a Solana transaction and send it to the network using the Solana SDK. ## 3. Usage example You are creating a bot to manage investors' funds and want to optimize returns. Such a bot could rebalance liquidity based on market signals to maintain a specific target price range or to optimize fee collection during periods of high volatility. ## 4. Next steps After adjusting liquidity, you can: - [Monitor Performance](02-Fetch%20Positions.mdx): Track your adjusted position to evaluate its performance and earned fees. - [Harvest Rewards](04-Harvest.mdx): Collect any earned fees and rewards without closing your position. - Make Further Adjustments: Depending on market conditions, continue to adjust liquidity as needed to maximize returns or manage risk. By using the SDK to adjust liquidity, you gain flexibility in managing your positions and optimizing your liquidity provision strategy.
0