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/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/state/fee_tier.rs
use crate::state::WhirlpoolsConfig; use crate::{errors::ErrorCode, math::MAX_FEE_RATE}; use anchor_lang::prelude::*; #[account] pub struct FeeTier { pub whirlpools_config: Pubkey, pub tick_spacing: u16, pub default_fee_rate: u16, } impl FeeTier { pub const LEN: usize = 8 + 32 + 4; pub fn initialize( &mut self, whirlpools_config: &Account<WhirlpoolsConfig>, tick_spacing: u16, default_fee_rate: u16, ) -> Result<()> { self.whirlpools_config = whirlpools_config.key(); self.tick_spacing = tick_spacing; self.update_default_fee_rate(default_fee_rate)?; Ok(()) } pub fn update_default_fee_rate(&mut self, default_fee_rate: u16) -> Result<()> { if default_fee_rate > MAX_FEE_RATE { return Err(ErrorCode::FeeRateMaxExceeded.into()); } self.default_fee_rate = default_fee_rate; Ok(()) } } #[cfg(test)] mod data_layout_tests { use anchor_lang::Discriminator; use super::*; #[test] fn test_fee_tier_data_layout() { let fee_tier_whirlpools_config = Pubkey::new_unique(); let fee_tier_tick_spacing = 0xffu16; let fee_tier_default_fee_rate = 0x22u16; let mut fee_tier_data = [0u8; FeeTier::LEN]; let mut offset = 0; fee_tier_data[offset..offset + 8].copy_from_slice(&FeeTier::discriminator()); offset += 8; fee_tier_data[offset..offset + 32].copy_from_slice(&fee_tier_whirlpools_config.to_bytes()); offset += 32; fee_tier_data[offset..offset + 2].copy_from_slice(&fee_tier_tick_spacing.to_le_bytes()); offset += 2; fee_tier_data[offset..offset + 2].copy_from_slice(&fee_tier_default_fee_rate.to_le_bytes()); offset += 2; assert_eq!(offset, FeeTier::LEN); // deserialize let deserialized = FeeTier::try_deserialize(&mut fee_tier_data.as_ref()).unwrap(); assert_eq!(fee_tier_whirlpools_config, deserialized.whirlpools_config); assert_eq!(fee_tier_tick_spacing, deserialized.tick_spacing); assert_eq!(fee_tier_default_fee_rate, deserialized.default_fee_rate); // serialize let mut serialized = Vec::new(); deserialized.try_serialize(&mut serialized).unwrap(); assert_eq!(serialized.as_slice(), fee_tier_data.as_ref()); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/state/position_bundle.rs
use crate::errors::ErrorCode; use anchor_lang::prelude::*; pub const POSITION_BITMAP_USIZE: usize = 32; pub const POSITION_BUNDLE_SIZE: u16 = 8 * POSITION_BITMAP_USIZE as u16; #[account] #[derive(Default)] pub struct PositionBundle { pub position_bundle_mint: Pubkey, // 32 pub position_bitmap: [u8; POSITION_BITMAP_USIZE], // 32 // 64 RESERVE } impl PositionBundle { pub const LEN: usize = 8 + 32 + 32 + 64; pub fn initialize(&mut self, position_bundle_mint: Pubkey) -> Result<()> { self.position_bundle_mint = position_bundle_mint; // position_bitmap is initialized using Default trait Ok(()) } pub fn is_deletable(&self) -> bool { for bitmap in self.position_bitmap.iter() { if *bitmap != 0 { return false; } } true } pub fn open_bundled_position(&mut self, bundle_index: u16) -> Result<()> { self.update_bitmap(bundle_index, true) } pub fn close_bundled_position(&mut self, bundle_index: u16) -> Result<()> { self.update_bitmap(bundle_index, false) } fn update_bitmap(&mut self, bundle_index: u16, open: bool) -> Result<()> { if !PositionBundle::is_valid_bundle_index(bundle_index) { return Err(ErrorCode::InvalidBundleIndex.into()); } let bitmap_index = bundle_index / 8; let bitmap_offset = bundle_index % 8; let bitmap = self.position_bitmap[bitmap_index as usize]; let mask = 1 << bitmap_offset; let bit = bitmap & mask; let opened = bit != 0; if open && opened { // UNREACHABLE // Anchor should reject with AccountDiscriminatorAlreadySet return Err(ErrorCode::BundledPositionAlreadyOpened.into()); } if !open && !opened { // UNREACHABLE // Anchor should reject with AccountNotInitialized return Err(ErrorCode::BundledPositionAlreadyClosed.into()); } let updated_bitmap = bitmap ^ mask; self.position_bitmap[bitmap_index as usize] = updated_bitmap; Ok(()) } fn is_valid_bundle_index(bundle_index: u16) -> bool { bundle_index < POSITION_BUNDLE_SIZE } } #[cfg(test)] mod position_bundle_initialize_tests { use super::*; use std::str::FromStr; #[test] fn test_default() { let position_bundle = PositionBundle { ..Default::default() }; assert_eq!(position_bundle.position_bundle_mint, Pubkey::default()); for bitmap in position_bundle.position_bitmap.iter() { assert_eq!(*bitmap, 0); } } #[test] fn test_initialize() { let mut position_bundle = PositionBundle { ..Default::default() }; let position_bundle_mint = Pubkey::from_str("orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE").unwrap(); let result = position_bundle.initialize(position_bundle_mint); assert!(result.is_ok()); assert_eq!(position_bundle.position_bundle_mint, position_bundle_mint); for bitmap in position_bundle.position_bitmap.iter() { assert_eq!(*bitmap, 0); } } } #[cfg(test)] mod position_bundle_is_deletable_tests { use super::*; #[test] fn test_default_is_deletable() { let position_bundle = PositionBundle { ..Default::default() }; assert!(position_bundle.is_deletable()); } #[test] fn test_each_bit_detectable() { let mut position_bundle = PositionBundle { ..Default::default() }; for bundle_index in 0..POSITION_BUNDLE_SIZE { let index = bundle_index / 8; let offset = bundle_index % 8; position_bundle.position_bitmap[index as usize] = 1 << offset; assert!(!position_bundle.is_deletable()); position_bundle.position_bitmap[index as usize] = 0; assert!(position_bundle.is_deletable()); } } } #[cfg(test)] mod position_bundle_open_and_close_tests { use super::*; #[test] fn test_open_and_close_zero() { let mut position_bundle = PositionBundle { ..Default::default() }; let r1 = position_bundle.open_bundled_position(0); assert!(r1.is_ok()); assert_eq!(position_bundle.position_bitmap[0], 1); let r2 = position_bundle.close_bundled_position(0); assert!(r2.is_ok()); assert_eq!(position_bundle.position_bitmap[0], 0); } #[test] fn test_open_and_close_middle() { let mut position_bundle = PositionBundle { ..Default::default() }; let r1 = position_bundle.open_bundled_position(130); assert!(r1.is_ok()); assert_eq!(position_bundle.position_bitmap[16], 4); let r2 = position_bundle.close_bundled_position(130); assert!(r2.is_ok()); assert_eq!(position_bundle.position_bitmap[16], 0); } #[test] fn test_open_and_close_max() { let mut position_bundle = PositionBundle { ..Default::default() }; let r1 = position_bundle.open_bundled_position(POSITION_BUNDLE_SIZE - 1); assert!(r1.is_ok()); assert_eq!( position_bundle.position_bitmap[POSITION_BITMAP_USIZE - 1], 128 ); let r2 = position_bundle.close_bundled_position(POSITION_BUNDLE_SIZE - 1); assert!(r2.is_ok()); assert_eq!( position_bundle.position_bitmap[POSITION_BITMAP_USIZE - 1], 0 ); } #[test] fn test_double_open_should_be_failed() { let mut position_bundle = PositionBundle { ..Default::default() }; let r1 = position_bundle.open_bundled_position(0); assert!(r1.is_ok()); let r2 = position_bundle.open_bundled_position(0); assert!(r2.is_err()); } #[test] fn test_double_close_should_be_failed() { let mut position_bundle = PositionBundle { ..Default::default() }; let r1 = position_bundle.open_bundled_position(0); assert!(r1.is_ok()); let r2 = position_bundle.close_bundled_position(0); assert!(r2.is_ok()); let r3 = position_bundle.close_bundled_position(0); assert!(r3.is_err()); } #[test] fn test_all_open_and_all_close() { let mut position_bundle = PositionBundle { ..Default::default() }; for bundle_index in 0..POSITION_BUNDLE_SIZE { let r = position_bundle.open_bundled_position(bundle_index); assert!(r.is_ok()); } for bitmap in position_bundle.position_bitmap.iter() { assert_eq!(*bitmap, 255); } for bundle_index in 0..POSITION_BUNDLE_SIZE { let r = position_bundle.close_bundled_position(bundle_index); assert!(r.is_ok()); } for bitmap in position_bundle.position_bitmap.iter() { assert_eq!(*bitmap, 0); } } #[test] fn test_open_bundle_index_out_of_bounds() { let mut position_bundle = PositionBundle { ..Default::default() }; for bundle_index in POSITION_BUNDLE_SIZE..u16::MAX { let r = position_bundle.open_bundled_position(bundle_index); assert!(r.is_err()); } } #[test] fn test_close_bundle_index_out_of_bounds() { let mut position_bundle = PositionBundle { ..Default::default() }; for bundle_index in POSITION_BUNDLE_SIZE..u16::MAX { let r = position_bundle.close_bundled_position(bundle_index); assert!(r.is_err()); } } } #[cfg(test)] mod data_layout_tests { use anchor_lang::Discriminator; use super::*; #[test] fn test_position_bundle_data_layout() { let position_bundle_position_bundle_mint = Pubkey::new_unique(); let position_bundle_position_bitmap = [0xFFu8; POSITION_BITMAP_USIZE]; let position_bundle_reserved = [0u8; 64]; let mut position_bundle_data = [0u8; PositionBundle::LEN]; let mut offset = 0; position_bundle_data[offset..offset + 8].copy_from_slice(&PositionBundle::discriminator()); offset += 8; position_bundle_data[offset..offset + 32] .copy_from_slice(&position_bundle_position_bundle_mint.to_bytes()); offset += 32; position_bundle_data[offset..offset + POSITION_BITMAP_USIZE] .copy_from_slice(&position_bundle_position_bitmap); offset += POSITION_BITMAP_USIZE; position_bundle_data[offset..offset + position_bundle_reserved.len()] .copy_from_slice(&position_bundle_reserved); offset += position_bundle_reserved.len(); assert_eq!(offset, PositionBundle::LEN); // deserialize let deserialized = PositionBundle::try_deserialize(&mut position_bundle_data.as_ref()).unwrap(); assert_eq!( position_bundle_position_bundle_mint, deserialized.position_bundle_mint ); assert_eq!( position_bundle_position_bitmap, deserialized.position_bitmap ); // serialize let mut serialized = Vec::new(); deserialized.try_serialize(&mut serialized).unwrap(); serialized.extend_from_slice(&position_bundle_reserved); assert_eq!(serialized.as_slice(), position_bundle_data.as_ref()); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/state/position.rs
use anchor_lang::prelude::*; use crate::{errors::ErrorCode, math::FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD, state::NUM_REWARDS}; use super::{Tick, Whirlpool}; #[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Copy)] pub struct OpenPositionBumps { pub position_bump: u8, } #[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Copy)] pub struct OpenPositionWithMetadataBumps { pub position_bump: u8, pub metadata_bump: u8, } #[account] #[derive(Default)] pub struct Position { pub whirlpool: Pubkey, // 32 pub position_mint: Pubkey, // 32 pub liquidity: u128, // 16 pub tick_lower_index: i32, // 4 pub tick_upper_index: i32, // 4 // Q64.64 pub fee_growth_checkpoint_a: u128, // 16 pub fee_owed_a: u64, // 8 // Q64.64 pub fee_growth_checkpoint_b: u128, // 16 pub fee_owed_b: u64, // 8 pub reward_infos: [PositionRewardInfo; NUM_REWARDS], // 72 } impl Position { pub const LEN: usize = 8 + 136 + 72; pub fn is_position_empty(position: &Position) -> bool { let fees_not_owed = position.fee_owed_a == 0 && position.fee_owed_b == 0; let mut rewards_not_owed = true; for i in 0..NUM_REWARDS { rewards_not_owed = rewards_not_owed && position.reward_infos[i].amount_owed == 0 } position.liquidity == 0 && fees_not_owed && rewards_not_owed } pub fn update(&mut self, update: &PositionUpdate) { self.liquidity = update.liquidity; self.fee_growth_checkpoint_a = update.fee_growth_checkpoint_a; self.fee_growth_checkpoint_b = update.fee_growth_checkpoint_b; self.fee_owed_a = update.fee_owed_a; self.fee_owed_b = update.fee_owed_b; self.reward_infos = update.reward_infos; } pub fn open_position( &mut self, whirlpool: &Account<Whirlpool>, position_mint: Pubkey, tick_lower_index: i32, tick_upper_index: i32, ) -> Result<()> { if !Tick::check_is_usable_tick(tick_lower_index, whirlpool.tick_spacing) || !Tick::check_is_usable_tick(tick_upper_index, whirlpool.tick_spacing) || tick_lower_index >= tick_upper_index { return Err(ErrorCode::InvalidTickIndex.into()); } // On tick spacing >= 2^15, should only be able to open full range positions if whirlpool.tick_spacing >= FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD { let (full_range_lower_index, full_range_upper_index) = Tick::full_range_indexes(whirlpool.tick_spacing); if tick_lower_index != full_range_lower_index || tick_upper_index != full_range_upper_index { return Err(ErrorCode::FullRangeOnlyPool.into()); } } self.whirlpool = whirlpool.key(); self.position_mint = position_mint; self.tick_lower_index = tick_lower_index; self.tick_upper_index = tick_upper_index; Ok(()) } pub fn reset_fees_owed(&mut self) { self.fee_owed_a = 0; self.fee_owed_b = 0; } pub fn update_reward_owed(&mut self, index: usize, amount_owed: u64) { self.reward_infos[index].amount_owed = amount_owed; } } #[derive(Copy, Clone, AnchorSerialize, AnchorDeserialize, Default, Debug, PartialEq)] pub struct PositionRewardInfo { // Q64.64 pub growth_inside_checkpoint: u128, pub amount_owed: u64, } #[derive(Default, Debug, PartialEq)] pub struct PositionUpdate { pub liquidity: u128, pub fee_growth_checkpoint_a: u128, pub fee_owed_a: u64, pub fee_growth_checkpoint_b: u128, pub fee_owed_b: u64, pub reward_infos: [PositionRewardInfo; NUM_REWARDS], } #[cfg(test)] mod is_position_empty_tests { use super::*; use crate::constants::test_constants::*; pub fn build_test_position( liquidity: u128, fee_owed_a: u64, fee_owed_b: u64, reward_owed_0: u64, reward_owed_1: u64, reward_owed_2: u64, ) -> Position { Position { whirlpool: test_program_id(), position_mint: test_program_id(), liquidity, tick_lower_index: 0, tick_upper_index: 0, fee_growth_checkpoint_a: 0, fee_owed_a, fee_growth_checkpoint_b: 0, fee_owed_b, reward_infos: [ PositionRewardInfo { growth_inside_checkpoint: 0, amount_owed: reward_owed_0, }, PositionRewardInfo { growth_inside_checkpoint: 0, amount_owed: reward_owed_1, }, PositionRewardInfo { growth_inside_checkpoint: 0, amount_owed: reward_owed_2, }, ], } } #[test] fn test_position_empty() { let pos = build_test_position(0, 0, 0, 0, 0, 0); assert!(Position::is_position_empty(&pos)); } #[test] fn test_liquidity_non_zero() { let pos = build_test_position(100, 0, 0, 0, 0, 0); assert!(!Position::is_position_empty(&pos)); } #[test] fn test_fee_a_non_zero() { let pos = build_test_position(0, 100, 0, 0, 0, 0); assert!(!Position::is_position_empty(&pos)); } #[test] fn test_fee_b_non_zero() { let pos = build_test_position(0, 0, 100, 0, 0, 0); assert!(!Position::is_position_empty(&pos)); } #[test] fn test_reward_0_non_zero() { let pos = build_test_position(0, 0, 0, 100, 0, 0); assert!(!Position::is_position_empty(&pos)); } #[test] fn test_reward_1_non_zero() { let pos = build_test_position(0, 0, 0, 0, 100, 0); assert!(!Position::is_position_empty(&pos)); } #[test] fn test_reward_2_non_zero() { let pos = build_test_position(0, 0, 0, 0, 0, 100); assert!(!Position::is_position_empty(&pos)); } } #[cfg(test)] pub mod position_builder { use anchor_lang::prelude::Pubkey; use super::{Position, PositionRewardInfo}; use crate::state::NUM_REWARDS; #[derive(Default)] pub struct PositionBuilder { liquidity: u128, tick_lower_index: i32, tick_upper_index: i32, // Q64.64 fee_growth_checkpoint_a: u128, fee_owed_a: u64, // Q64.64 fee_growth_checkpoint_b: u128, fee_owed_b: u64, // Size should equal state::NUM_REWARDS reward_infos: [PositionRewardInfo; NUM_REWARDS], } impl PositionBuilder { pub fn new(tick_lower_index: i32, tick_upper_index: i32) -> Self { Self { tick_lower_index, tick_upper_index, reward_infos: [PositionRewardInfo::default(); NUM_REWARDS], ..Default::default() } } pub fn liquidity(mut self, liquidity: u128) -> Self { self.liquidity = liquidity; self } pub fn fee_growth_checkpoint_a(mut self, fee_growth_checkpoint_a: u128) -> Self { self.fee_growth_checkpoint_a = fee_growth_checkpoint_a; self } pub fn fee_growth_checkpoint_b(mut self, fee_growth_checkpoint_b: u128) -> Self { self.fee_growth_checkpoint_b = fee_growth_checkpoint_b; self } pub fn fee_owed_a(mut self, fee_owed_a: u64) -> Self { self.fee_owed_a = fee_owed_a; self } pub fn fee_owed_b(mut self, fee_owed_b: u64) -> Self { self.fee_owed_b = fee_owed_b; self } pub fn reward_info(mut self, index: usize, reward_info: PositionRewardInfo) -> Self { self.reward_infos[index] = reward_info; self } pub fn reward_infos(mut self, reward_infos: [PositionRewardInfo; NUM_REWARDS]) -> Self { self.reward_infos = reward_infos; self } pub fn build(self) -> Position { Position { whirlpool: Pubkey::new_unique(), position_mint: Pubkey::new_unique(), liquidity: self.liquidity, fee_growth_checkpoint_a: self.fee_growth_checkpoint_a, fee_growth_checkpoint_b: self.fee_growth_checkpoint_b, fee_owed_a: self.fee_owed_a, fee_owed_b: self.fee_owed_b, reward_infos: self.reward_infos, tick_lower_index: self.tick_lower_index, tick_upper_index: self.tick_upper_index, } } } } #[cfg(test)] mod data_layout_tests { use anchor_lang::Discriminator; use super::*; #[test] fn test_position_data_layout() { let position_whirlpool = Pubkey::new_unique(); let position_position_mint = Pubkey::new_unique(); let position_liquidity = 0x11223344556677889900aabbccddeeffu128; let position_tick_lower_index = 0x11002233i32; let position_tick_upper_index = 0x22003344i32; let position_fee_growth_checkpoint_a = 0x11002233445566778899aabbccddeeffu128; let position_fee_owed_a = 0x11ff223344556677u64; let position_fee_growth_checkpoint_b = 0x11220033445566778899aabbccddeeffu128; let position_fee_owed_b = 0x1122ff3344556677u64; let position_reward_info_growth_inside_checkpoint = 0x112233445566778899ffaabbccddee00u128; let position_reward_info_amount_owed = 0x1122334455667788u64; // manually build the expected data layout let mut position_reward_data = [0u8; 24]; let mut offset = 0; position_reward_data[offset..offset + 16] .copy_from_slice(&position_reward_info_growth_inside_checkpoint.to_le_bytes()); offset += 16; position_reward_data[offset..offset + 8] .copy_from_slice(&position_reward_info_amount_owed.to_le_bytes()); let mut position_data = [0u8; Position::LEN]; let mut offset = 0; position_data[offset..offset + 8].copy_from_slice(&Position::discriminator()); offset += 8; position_data[offset..offset + 32].copy_from_slice(&position_whirlpool.to_bytes()); offset += 32; position_data[offset..offset + 32].copy_from_slice(&position_position_mint.to_bytes()); offset += 32; position_data[offset..offset + 16].copy_from_slice(&position_liquidity.to_le_bytes()); offset += 16; position_data[offset..offset + 4].copy_from_slice(&position_tick_lower_index.to_le_bytes()); offset += 4; position_data[offset..offset + 4].copy_from_slice(&position_tick_upper_index.to_le_bytes()); offset += 4; position_data[offset..offset + 16] .copy_from_slice(&position_fee_growth_checkpoint_a.to_le_bytes()); offset += 16; position_data[offset..offset + 8].copy_from_slice(&position_fee_owed_a.to_le_bytes()); offset += 8; position_data[offset..offset + 16] .copy_from_slice(&position_fee_growth_checkpoint_b.to_le_bytes()); offset += 16; position_data[offset..offset + 8].copy_from_slice(&position_fee_owed_b.to_le_bytes()); offset += 8; for _ in 0..NUM_REWARDS { position_data[offset..offset + position_reward_data.len()] .copy_from_slice(&position_reward_data); offset += position_reward_data.len(); } assert_eq!(offset, Position::LEN); // deserialize let deserialized = Position::try_deserialize(&mut position_data.as_ref()).unwrap(); assert_eq!(position_whirlpool, deserialized.whirlpool); assert_eq!(position_position_mint, deserialized.position_mint); assert_eq!(position_liquidity, deserialized.liquidity); assert_eq!(position_tick_lower_index, deserialized.tick_lower_index); assert_eq!(position_tick_upper_index, deserialized.tick_upper_index); assert_eq!( position_fee_growth_checkpoint_a, deserialized.fee_growth_checkpoint_a ); assert_eq!(position_fee_owed_a, deserialized.fee_owed_a); assert_eq!( position_fee_growth_checkpoint_b, deserialized.fee_growth_checkpoint_b ); assert_eq!(position_fee_owed_b, deserialized.fee_owed_b); for i in 0..NUM_REWARDS { assert_eq!( position_reward_info_growth_inside_checkpoint, deserialized.reward_infos[i].growth_inside_checkpoint ); assert_eq!( position_reward_info_amount_owed, deserialized.reward_infos[i].amount_owed ); } // serialize let mut serialized = Vec::new(); deserialized.try_serialize(&mut serialized).unwrap(); assert_eq!(serialized.as_slice(), position_data.as_ref()); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/state/tick.rs
use crate::errors::ErrorCode; use crate::state::NUM_REWARDS; use anchor_lang::prelude::*; use super::Whirlpool; // Max & min tick index based on sqrt(1.0001) & max.min price of 2^64 pub const MAX_TICK_INDEX: i32 = 443636; pub const MIN_TICK_INDEX: i32 = -443636; // We have two consts because most of our code uses it as a i32. However, // for us to use it in tick array declarations, anchor requires it to be a usize. pub const TICK_ARRAY_SIZE: i32 = 88; pub const TICK_ARRAY_SIZE_USIZE: usize = 88; #[zero_copy(unsafe)] #[repr(C, packed)] #[derive(Default, Debug, PartialEq)] pub struct Tick { // Total 137 bytes pub initialized: bool, // 1 pub liquidity_net: i128, // 16 pub liquidity_gross: u128, // 16 // Q64.64 pub fee_growth_outside_a: u128, // 16 // Q64.64 pub fee_growth_outside_b: u128, // 16 // Array of Q64.64 pub reward_growths_outside: [u128; NUM_REWARDS], // 48 = 16 * 3 } impl Tick { pub const LEN: usize = 113; /// Apply an update for this tick /// /// # Parameters /// - `update` - An update object to update the values in this tick pub fn update(&mut self, update: &TickUpdate) { self.initialized = update.initialized; self.liquidity_net = update.liquidity_net; self.liquidity_gross = update.liquidity_gross; self.fee_growth_outside_a = update.fee_growth_outside_a; self.fee_growth_outside_b = update.fee_growth_outside_b; self.reward_growths_outside = update.reward_growths_outside; } /// Check that the tick index is within the supported range of this contract /// /// # Parameters /// - `tick_index` - A i32 integer representing the tick index /// /// # Returns /// - `true`: The tick index is not within the range supported by this contract /// - `false`: The tick index is within the range supported by this contract pub fn check_is_out_of_bounds(tick_index: i32) -> bool { !(MIN_TICK_INDEX..=MAX_TICK_INDEX).contains(&tick_index) } /// Check that the tick index is a valid start tick for a tick array in this whirlpool /// A valid start-tick-index is a multiple of tick_spacing & number of ticks in a tick-array. /// /// # Parameters /// - `tick_index` - A i32 integer representing the tick index /// - `tick_spacing` - A u8 integer of the tick spacing for this whirlpool /// /// # Returns /// - `true`: The tick index is a valid start-tick-index for this whirlpool /// - `false`: The tick index is not a valid start-tick-index for this whirlpool /// or the tick index not within the range supported by this contract pub fn check_is_valid_start_tick(tick_index: i32, tick_spacing: u16) -> bool { let ticks_in_array = TICK_ARRAY_SIZE * tick_spacing as i32; if Tick::check_is_out_of_bounds(tick_index) { // Left-edge tick-array can have a start-tick-index smaller than the min tick index if tick_index > MIN_TICK_INDEX { return false; } let min_array_start_index = MIN_TICK_INDEX - (MIN_TICK_INDEX % ticks_in_array + ticks_in_array); return tick_index == min_array_start_index; } tick_index % ticks_in_array == 0 } /// Check that the tick index is within bounds and is a usable tick index for the given tick spacing. /// /// # Parameters /// - `tick_index` - A i32 integer representing the tick index /// - `tick_spacing` - A u8 integer of the tick spacing for this whirlpool /// /// # Returns /// - `true`: The tick index is within max/min index bounds for this protocol and is a usable tick-index given the tick-spacing /// - `false`: The tick index is out of bounds or is not a usable tick for this tick-spacing pub fn check_is_usable_tick(tick_index: i32, tick_spacing: u16) -> bool { if Tick::check_is_out_of_bounds(tick_index) { return false; } tick_index % tick_spacing as i32 == 0 } pub fn full_range_indexes(tick_spacing: u16) -> (i32, i32) { let lower_index = MIN_TICK_INDEX / tick_spacing as i32 * tick_spacing as i32; let upper_index = MAX_TICK_INDEX / tick_spacing as i32 * tick_spacing as i32; (lower_index, upper_index) } /// Bound a tick-index value to the max & min index value for this protocol /// /// # Parameters /// - `tick_index` - A i32 integer representing the tick index /// /// # Returns /// - `i32` The input tick index value but bounded by the max/min value of this protocol. pub fn bound_tick_index(tick_index: i32) -> i32 { tick_index.clamp(MIN_TICK_INDEX, MAX_TICK_INDEX) } } #[derive(Default, Debug, PartialEq)] pub struct TickUpdate { pub initialized: bool, pub liquidity_net: i128, pub liquidity_gross: u128, pub fee_growth_outside_a: u128, pub fee_growth_outside_b: u128, pub reward_growths_outside: [u128; NUM_REWARDS], } impl TickUpdate { pub fn from(tick: &Tick) -> TickUpdate { TickUpdate { initialized: tick.initialized, liquidity_net: tick.liquidity_net, liquidity_gross: tick.liquidity_gross, fee_growth_outside_a: tick.fee_growth_outside_a, fee_growth_outside_b: tick.fee_growth_outside_b, reward_growths_outside: tick.reward_growths_outside, } } } pub trait TickArrayType { fn start_tick_index(&self) -> i32; fn get_next_init_tick_index( &self, tick_index: i32, tick_spacing: u16, a_to_b: bool, ) -> Result<Option<i32>>; fn get_tick(&self, tick_index: i32, tick_spacing: u16) -> Result<&Tick>; fn update_tick( &mut self, tick_index: i32, tick_spacing: u16, update: &TickUpdate, ) -> Result<()>; /// Checks that this array holds the next tick index for the current tick index, given the pool's tick spacing & search direction. /// /// unshifted checks on [start, start + TICK_ARRAY_SIZE * tick_spacing) /// shifted checks on [start - tick_spacing, start + (TICK_ARRAY_SIZE - 1) * tick_spacing) (adjusting range by -tick_spacing) /// /// shifted == !a_to_b /// /// For a_to_b swaps, price moves left. All searchable ticks in this tick-array's range will end up in this tick's usable ticks. /// The search range is therefore the range of the tick-array. /// /// For b_to_a swaps, this tick-array's left-most ticks can be the 'next' usable tick-index of the previous tick-array. /// The right-most ticks also points towards the next tick-array. The search range is therefore shifted by 1 tick-spacing. fn in_search_range(&self, tick_index: i32, tick_spacing: u16, shifted: bool) -> bool { let mut lower = self.start_tick_index(); let mut upper = self.start_tick_index() + TICK_ARRAY_SIZE * tick_spacing as i32; if shifted { lower -= tick_spacing as i32; upper -= tick_spacing as i32; } tick_index >= lower && tick_index < upper } fn check_in_array_bounds(&self, tick_index: i32, tick_spacing: u16) -> bool { self.in_search_range(tick_index, tick_spacing, false) } fn is_min_tick_array(&self) -> bool { self.start_tick_index() <= MIN_TICK_INDEX } fn is_max_tick_array(&self, tick_spacing: u16) -> bool { self.start_tick_index() + TICK_ARRAY_SIZE * (tick_spacing as i32) > MAX_TICK_INDEX } fn tick_offset(&self, tick_index: i32, tick_spacing: u16) -> Result<isize> { if tick_spacing == 0 { return Err(ErrorCode::InvalidTickSpacing.into()); } Ok(get_offset( tick_index, self.start_tick_index(), tick_spacing, )) } } fn get_offset(tick_index: i32, start_tick_index: i32, tick_spacing: u16) -> isize { // TODO: replace with i32.div_floor once not experimental let lhs = tick_index - start_tick_index; let rhs = tick_spacing as i32; let d = lhs / rhs; let r = lhs % rhs; let o = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { d - 1 } else { d }; o as isize } #[account(zero_copy(unsafe))] #[repr(C, packed)] pub struct TickArray { pub start_tick_index: i32, pub ticks: [Tick; TICK_ARRAY_SIZE_USIZE], pub whirlpool: Pubkey, } impl Default for TickArray { #[inline] fn default() -> TickArray { TickArray { whirlpool: Pubkey::default(), ticks: [Tick::default(); TICK_ARRAY_SIZE_USIZE], start_tick_index: 0, } } } impl TickArray { pub const LEN: usize = 8 + 36 + (Tick::LEN * TICK_ARRAY_SIZE_USIZE); /// Initialize the TickArray object /// /// # Parameters /// - `whirlpool` - the tick index the desired Tick object is stored in /// - `start_tick_index` - A u8 integer of the tick spacing for this whirlpool /// /// # Errors /// - `InvalidStartTick`: - The provided start-tick-index is not an initializable tick index in this Whirlpool w/ this tick-spacing. pub fn initialize( &mut self, whirlpool: &Account<Whirlpool>, start_tick_index: i32, ) -> Result<()> { if !Tick::check_is_valid_start_tick(start_tick_index, whirlpool.tick_spacing) { return Err(ErrorCode::InvalidStartTick.into()); } self.whirlpool = whirlpool.key(); self.start_tick_index = start_tick_index; Ok(()) } } impl TickArrayType for TickArray { fn start_tick_index(&self) -> i32 { self.start_tick_index } /// Search for the next initialized tick in this array. /// /// # Parameters /// - `tick_index` - A i32 integer representing the tick index to start searching for /// - `tick_spacing` - A u8 integer of the tick spacing for this whirlpool /// - `a_to_b` - If the trade is from a_to_b, the search will move to the left and the starting search tick is inclusive. /// If the trade is from b_to_a, the search will move to the right and the starting search tick is not inclusive. /// /// # Returns /// - `Some(i32)`: The next initialized tick index of this array /// - `None`: An initialized tick index was not found in this array /// - `InvalidTickArraySequence` - error if `tick_index` is not a valid search tick for the array /// - `InvalidTickSpacing` - error if the provided tick spacing is 0 fn get_next_init_tick_index( &self, tick_index: i32, tick_spacing: u16, a_to_b: bool, ) -> Result<Option<i32>> { if !self.in_search_range(tick_index, tick_spacing, !a_to_b) { return Err(ErrorCode::InvalidTickArraySequence.into()); } let mut curr_offset = match self.tick_offset(tick_index, tick_spacing) { Ok(value) => value as i32, Err(e) => return Err(e), }; // For a_to_b searches, the search moves to the left. The next possible init-tick can be the 1st tick in the current offset // For b_to_a searches, the search moves to the right. The next possible init-tick cannot be within the current offset if !a_to_b { curr_offset += 1; } while (0..TICK_ARRAY_SIZE).contains(&curr_offset) { let curr_tick = self.ticks[curr_offset as usize]; if curr_tick.initialized { return Ok(Some( (curr_offset * tick_spacing as i32) + self.start_tick_index, )); } curr_offset = if a_to_b { curr_offset - 1 } else { curr_offset + 1 }; } Ok(None) } /// Get the Tick object at the given tick-index & tick-spacing /// /// # Parameters /// - `tick_index` - the tick index the desired Tick object is stored in /// - `tick_spacing` - A u8 integer of the tick spacing for this whirlpool /// /// # Returns /// - `&Tick`: A reference to the desired Tick object /// - `TickNotFound`: - The provided tick-index is not an initializable tick index in this Whirlpool w/ this tick-spacing. fn get_tick(&self, tick_index: i32, tick_spacing: u16) -> Result<&Tick> { if !self.check_in_array_bounds(tick_index, tick_spacing) || !Tick::check_is_usable_tick(tick_index, tick_spacing) { return Err(ErrorCode::TickNotFound.into()); } let offset = self.tick_offset(tick_index, tick_spacing)?; if offset < 0 { return Err(ErrorCode::TickNotFound.into()); } Ok(&self.ticks[offset as usize]) } /// Updates the Tick object at the given tick-index & tick-spacing /// /// # Parameters /// - `tick_index` - the tick index the desired Tick object is stored in /// - `tick_spacing` - A u8 integer of the tick spacing for this whirlpool /// - `update` - A reference to a TickUpdate object to update the Tick object at the given index /// /// # Errors /// - `TickNotFound`: - The provided tick-index is not an initializable tick index in this Whirlpool w/ this tick-spacing. fn update_tick( &mut self, tick_index: i32, tick_spacing: u16, update: &TickUpdate, ) -> Result<()> { if !self.check_in_array_bounds(tick_index, tick_spacing) || !Tick::check_is_usable_tick(tick_index, tick_spacing) { return Err(ErrorCode::TickNotFound.into()); } let offset = self.tick_offset(tick_index, tick_spacing)?; if offset < 0 { return Err(ErrorCode::TickNotFound.into()); } self.ticks.get_mut(offset as usize).unwrap().update(update); Ok(()) } } pub(crate) struct ZeroedTickArray { pub start_tick_index: i32, zeroed_tick: Tick, } impl ZeroedTickArray { pub fn new(start_tick_index: i32) -> Self { ZeroedTickArray { start_tick_index, zeroed_tick: Tick::default(), } } } impl TickArrayType for ZeroedTickArray { fn start_tick_index(&self) -> i32 { self.start_tick_index } fn get_next_init_tick_index( &self, tick_index: i32, tick_spacing: u16, a_to_b: bool, ) -> Result<Option<i32>> { if !self.in_search_range(tick_index, tick_spacing, !a_to_b) { return Err(ErrorCode::InvalidTickArraySequence.into()); } self.tick_offset(tick_index, tick_spacing)?; // no initialized tick Ok(None) } fn get_tick(&self, tick_index: i32, tick_spacing: u16) -> Result<&Tick> { if !self.check_in_array_bounds(tick_index, tick_spacing) || !Tick::check_is_usable_tick(tick_index, tick_spacing) { return Err(ErrorCode::TickNotFound.into()); } let offset = self.tick_offset(tick_index, tick_spacing)?; if offset < 0 { return Err(ErrorCode::TickNotFound.into()); } // always return the zeroed tick Ok(&self.zeroed_tick) } fn update_tick( &mut self, _tick_index: i32, _tick_spacing: u16, _update: &TickUpdate, ) -> Result<()> { panic!("ZeroedTickArray must not be updated"); } } #[cfg(test)] pub mod tick_builder { use super::Tick; use crate::state::NUM_REWARDS; #[derive(Default)] pub struct TickBuilder { initialized: bool, liquidity_net: i128, liquidity_gross: u128, fee_growth_outside_a: u128, fee_growth_outside_b: u128, reward_growths_outside: [u128; NUM_REWARDS], } impl TickBuilder { pub fn initialized(mut self, initialized: bool) -> Self { self.initialized = initialized; self } pub fn liquidity_net(mut self, liquidity_net: i128) -> Self { self.liquidity_net = liquidity_net; self } pub fn liquidity_gross(mut self, liquidity_gross: u128) -> Self { self.liquidity_gross = liquidity_gross; self } pub fn fee_growth_outside_a(mut self, fee_growth_outside_a: u128) -> Self { self.fee_growth_outside_a = fee_growth_outside_a; self } pub fn fee_growth_outside_b(mut self, fee_growth_outside_b: u128) -> Self { self.fee_growth_outside_b = fee_growth_outside_b; self } pub fn reward_growths_outside( mut self, reward_growths_outside: [u128; NUM_REWARDS], ) -> Self { self.reward_growths_outside = reward_growths_outside; self } pub fn build(self) -> Tick { Tick { initialized: self.initialized, liquidity_net: self.liquidity_net, liquidity_gross: self.liquidity_gross, fee_growth_outside_a: self.fee_growth_outside_a, fee_growth_outside_b: self.fee_growth_outside_b, reward_growths_outside: self.reward_growths_outside, } } } } #[cfg(test)] mod fuzz_tests { use super::*; use proptest::prelude::*; proptest! { #[test] fn test_get_search_and_offset( tick_index in 2 * MIN_TICK_INDEX..2 * MAX_TICK_INDEX, start_tick_index in 2 * MIN_TICK_INDEX..2 * MAX_TICK_INDEX, tick_spacing in 1u16..u16::MAX, a_to_b in proptest::bool::ANY, ) { let array = TickArray { start_tick_index, ..TickArray::default() }; let in_search = array.in_search_range(tick_index, tick_spacing, !a_to_b); let mut lower_bound = start_tick_index; let mut upper_bound = start_tick_index + TICK_ARRAY_SIZE * tick_spacing as i32; let mut offset_lower = 0; let mut offset_upper = TICK_ARRAY_SIZE as isize; // If we are doing b_to_a, we shift the index bounds by -tick_spacing // and the offset bounds by -1 if !a_to_b { lower_bound -= tick_spacing as i32; upper_bound -= tick_spacing as i32; offset_lower = -1; offset_upper -= 1; } // in_bounds should be identical to search let in_bounds = tick_index >= lower_bound && tick_index < upper_bound; assert!(in_bounds == in_search); if in_search { let offset = get_offset(tick_index, start_tick_index, tick_spacing); assert!(offset >= offset_lower && offset < offset_upper) } } #[test] fn test_get_offset( tick_index in 2 * MIN_TICK_INDEX..2 * MAX_TICK_INDEX, start_tick_index in 2 * MIN_TICK_INDEX..2 * MAX_TICK_INDEX, tick_spacing in 1u16..u16::MAX, ) { let offset = get_offset(tick_index, start_tick_index, tick_spacing); let rounded = start_tick_index >= tick_index; let raw = (tick_index - start_tick_index) / tick_spacing as i32; let d = raw as isize; if !rounded { assert_eq!(offset, d); } else { assert!(offset == d || offset == (raw - 1) as isize); } } } } #[cfg(test)] mod check_is_valid_start_tick_tests { use super::*; const TS_8: u16 = 8; const TS_128: u16 = 128; #[test] fn test_start_tick_is_zero() { assert!(Tick::check_is_valid_start_tick(0, TS_8)); } #[test] fn test_start_tick_is_valid_ts8() { assert!(Tick::check_is_valid_start_tick(704, TS_8)); } #[test] fn test_start_tick_is_valid_ts128() { assert!(Tick::check_is_valid_start_tick(337920, TS_128)); } #[test] fn test_start_tick_is_valid_negative_ts8() { assert!(Tick::check_is_valid_start_tick(-704, TS_8)); } #[test] fn test_start_tick_is_valid_negative_ts128() { assert!(Tick::check_is_valid_start_tick(-337920, TS_128)); } #[test] fn test_start_tick_is_not_valid_ts8() { assert!(!Tick::check_is_valid_start_tick(2353573, TS_8)); } #[test] fn test_start_tick_is_not_valid_ts128() { assert!(!Tick::check_is_valid_start_tick(-2353573, TS_128)); } #[test] fn test_min_tick_array_start_tick_is_valid_ts8() { let expected_array_index: i32 = (MIN_TICK_INDEX / TICK_ARRAY_SIZE / TS_8 as i32) - 1; let expected_start_index_for_last_array: i32 = expected_array_index * TICK_ARRAY_SIZE * TS_8 as i32; assert!(Tick::check_is_valid_start_tick( expected_start_index_for_last_array, TS_8 )) } #[test] fn test_min_tick_array_sub_1_start_tick_is_invalid_ts8() { let expected_array_index: i32 = (MIN_TICK_INDEX / TICK_ARRAY_SIZE / TS_8 as i32) - 2; let expected_start_index_for_last_array: i32 = expected_array_index * TICK_ARRAY_SIZE * TS_8 as i32; assert!(!Tick::check_is_valid_start_tick( expected_start_index_for_last_array, TS_8 )) } #[test] fn test_min_tick_array_start_tick_is_valid_ts128() { let expected_array_index: i32 = (MIN_TICK_INDEX / TICK_ARRAY_SIZE / TS_128 as i32) - 1; let expected_start_index_for_last_array: i32 = expected_array_index * TICK_ARRAY_SIZE * TS_128 as i32; assert!(Tick::check_is_valid_start_tick( expected_start_index_for_last_array, TS_128 )) } #[test] fn test_min_tick_array_sub_1_start_tick_is_invalid_ts128() { let expected_array_index: i32 = (MIN_TICK_INDEX / TICK_ARRAY_SIZE / TS_128 as i32) - 2; let expected_start_index_for_last_array: i32 = expected_array_index * TICK_ARRAY_SIZE * TS_128 as i32; assert!(!Tick::check_is_valid_start_tick( expected_start_index_for_last_array, TS_128 )) } } #[cfg(test)] mod check_is_out_of_bounds_tests { use super::*; #[test] fn test_min_tick_index() { assert!(!Tick::check_is_out_of_bounds(MIN_TICK_INDEX)); } #[test] fn test_max_tick_index() { assert!(!Tick::check_is_out_of_bounds(MAX_TICK_INDEX)); } #[test] fn test_min_tick_index_sub_1() { assert!(Tick::check_is_out_of_bounds(MIN_TICK_INDEX - 1)); } #[test] fn test_max_tick_index_add_1() { assert!(Tick::check_is_out_of_bounds(MAX_TICK_INDEX + 1)); } } #[cfg(test)] mod full_range_indexes_tests { use crate::math::FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD; use super::*; #[test] fn test_min_tick_spacing() { assert_eq!( Tick::full_range_indexes(1), (MIN_TICK_INDEX, MAX_TICK_INDEX) ); } #[test] fn test_standard_tick_spacing() { assert_eq!(Tick::full_range_indexes(128), (-443520, 443520)); } #[test] fn test_full_range_only_tick_spacing() { assert_eq!( Tick::full_range_indexes(FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD), (-425984, 425984) ); } #[test] fn test_max_tick_spacing() { assert_eq!(Tick::full_range_indexes(u16::MAX), (-393210, 393210)); } } #[cfg(test)] mod array_update_tests { use super::*; #[test] fn update_applies_successfully() { let mut array = TickArray::default(); let tick_index = 8; let original = Tick { initialized: true, liquidity_net: 2525252i128, liquidity_gross: 2525252u128, fee_growth_outside_a: 28728282u128, fee_growth_outside_b: 22528728282u128, reward_growths_outside: [124272242u128, 1271221u128, 966958u128], }; array.ticks[1] = original; let update = TickUpdate { initialized: true, liquidity_net: 24128472184712i128, liquidity_gross: 353873892732u128, fee_growth_outside_a: 3928372892u128, fee_growth_outside_b: 12242u128, reward_growths_outside: [53264u128, 539282u128, 98744u128], }; let tick_spacing = 8; array .update_tick(tick_index, tick_spacing, &update) .unwrap(); let expected = Tick { initialized: true, liquidity_net: 24128472184712i128, liquidity_gross: 353873892732u128, fee_growth_outside_a: 3928372892u128, fee_growth_outside_b: 12242u128, reward_growths_outside: [53264u128, 539282u128, 98744u128], }; let result = array.get_tick(tick_index, tick_spacing).unwrap(); assert_eq!(*result, expected); } } #[cfg(test)] mod data_layout_tests { use super::*; #[test] fn test_tick_array_data_layout() { let tick_array_start_tick_index = 0x70e0d0c0i32; let tick_array_whirlpool = Pubkey::new_unique(); let tick_initialized = true; let tick_liquidity_net = 0x11002233445566778899aabbccddeeffi128; let tick_liquidity_gross = 0xff00eeddccbbaa998877665544332211u128; let tick_fee_growth_outside_a = 0x11220033445566778899aabbccddeeffu128; let tick_fee_growth_outside_b = 0xffee00ddccbbaa998877665544332211u128; let tick_reward_growths_outside = [ 0x11223300445566778899aabbccddeeffu128, 0x11223344005566778899aabbccddeeffu128, 0x11223344550066778899aabbccddeeffu128, ]; // manually build the expected Tick data layout let mut tick_data = [0u8; Tick::LEN]; let mut offset = 0; tick_data[offset] = tick_initialized as u8; offset += 1; tick_data[offset..offset + 16].copy_from_slice(&tick_liquidity_net.to_le_bytes()); offset += 16; tick_data[offset..offset + 16].copy_from_slice(&tick_liquidity_gross.to_le_bytes()); offset += 16; tick_data[offset..offset + 16].copy_from_slice(&tick_fee_growth_outside_a.to_le_bytes()); offset += 16; tick_data[offset..offset + 16].copy_from_slice(&tick_fee_growth_outside_b.to_le_bytes()); offset += 16; for i in 0..NUM_REWARDS { tick_data[offset..offset + 16] .copy_from_slice(&tick_reward_growths_outside[i].to_le_bytes()); offset += 16; } // manually build the expected TickArray data layout // note: no discriminator let mut tick_array_data = [0u8; TickArray::LEN - 8]; let mut offset = 0; tick_array_data[offset..offset + 4] .copy_from_slice(&tick_array_start_tick_index.to_le_bytes()); offset += 4; for _ in 0..TICK_ARRAY_SIZE_USIZE { tick_array_data[offset..offset + Tick::LEN].copy_from_slice(&tick_data); offset += Tick::LEN; } tick_array_data[offset..offset + 32].copy_from_slice(&tick_array_whirlpool.to_bytes()); offset += 32; assert_eq!(offset, tick_array_data.len()); assert_eq!(tick_array_data.len(), core::mem::size_of::<TickArray>()); // cast from bytes to TickArray (re-interpret) let tick_array: &TickArray = bytemuck::from_bytes(&tick_array_data); // check that the data layout matches the expected layout let read_start_tick_index = tick_array.start_tick_index; assert_eq!(read_start_tick_index, tick_array_start_tick_index); for i in 0..TICK_ARRAY_SIZE_USIZE { let read_tick = tick_array.ticks[i]; let read_initialized = read_tick.initialized; assert_eq!(read_initialized, tick_initialized); let read_liquidity_net = read_tick.liquidity_net; assert_eq!(read_liquidity_net, tick_liquidity_net); let read_liquidity_gross = read_tick.liquidity_gross; assert_eq!(read_liquidity_gross, tick_liquidity_gross); let read_fee_growth_outside_a = read_tick.fee_growth_outside_a; assert_eq!(read_fee_growth_outside_a, tick_fee_growth_outside_a); let read_fee_growth_outside_b = read_tick.fee_growth_outside_b; assert_eq!(read_fee_growth_outside_b, tick_fee_growth_outside_b); let read_reward_growths_outside = read_tick.reward_growths_outside; assert_eq!(read_reward_growths_outside, tick_reward_growths_outside); } let read_whirlpool = tick_array.whirlpool; assert_eq!(read_whirlpool, tick_array_whirlpool); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/swap_math.rs
use std::convert::TryInto; use crate::errors::ErrorCode; use crate::math::*; pub const NO_EXPLICIT_SQRT_PRICE_LIMIT: u128 = 0u128; #[derive(PartialEq, Debug)] pub struct SwapStepComputation { pub amount_in: u64, pub amount_out: u64, pub next_price: u128, pub fee_amount: u64, } pub fn compute_swap( amount_remaining: u64, fee_rate: u16, liquidity: u128, sqrt_price_current: u128, sqrt_price_target: u128, amount_specified_is_input: bool, a_to_b: bool, ) -> Result<SwapStepComputation, ErrorCode> { // Since SplashPool (aka FullRange only pool) has only 2 initialized ticks at both ends, // the possibility of exceeding u64 when calculating "delta amount" is higher than concentrated pools. // This problem occurs with ExactIn. // The reason is that in ExactOut, "fixed delta" never exceeds the amount of tokens present in the pool and is clearly within the u64 range. // On the other hand, for ExactIn, "fixed delta" may exceed u64 because it calculates the amount of tokens needed to move the price to the end. // However, the primary purpose of initial calculation of "fixed delta" is to determine whether or not the iteration is "max swap" or not. // So the info that “the amount of tokens required exceeds the u64 range” is sufficient to determine that the iteration is NOT "max swap". // // delta <= u64::MAX: AmountDeltaU64::Valid // delta > u64::MAX: AmountDeltaU64::ExceedsMax let initial_amount_fixed_delta = try_get_amount_fixed_delta( sqrt_price_current, sqrt_price_target, liquidity, amount_specified_is_input, a_to_b, )?; let mut amount_calc = amount_remaining; if amount_specified_is_input { amount_calc = checked_mul_div( amount_remaining as u128, FEE_RATE_MUL_VALUE - fee_rate as u128, FEE_RATE_MUL_VALUE, )? .try_into()?; } let next_sqrt_price = if initial_amount_fixed_delta.lte(amount_calc) { sqrt_price_target } else { get_next_sqrt_price( sqrt_price_current, liquidity, amount_calc, amount_specified_is_input, a_to_b, )? }; let is_max_swap = next_sqrt_price == sqrt_price_target; let amount_unfixed_delta = get_amount_unfixed_delta( sqrt_price_current, next_sqrt_price, liquidity, amount_specified_is_input, a_to_b, )?; // If the swap is not at the max, we need to readjust the amount of the fixed token we are using let amount_fixed_delta = if !is_max_swap || initial_amount_fixed_delta.exceeds_max() { // next_sqrt_price is calculated by get_next_sqrt_price and the result will be in the u64 range. get_amount_fixed_delta( sqrt_price_current, next_sqrt_price, liquidity, amount_specified_is_input, a_to_b, )? } else { // the result will be in the u64 range. initial_amount_fixed_delta.value() }; let (amount_in, mut amount_out) = if amount_specified_is_input { (amount_fixed_delta, amount_unfixed_delta) } else { (amount_unfixed_delta, amount_fixed_delta) }; // Cap output amount if using output if !amount_specified_is_input && amount_out > amount_remaining { amount_out = amount_remaining; } let fee_amount = if amount_specified_is_input && !is_max_swap { amount_remaining - amount_in } else { checked_mul_div_round_up( amount_in as u128, fee_rate as u128, FEE_RATE_MUL_VALUE - fee_rate as u128, )? .try_into()? }; Ok(SwapStepComputation { amount_in, amount_out, next_price: next_sqrt_price, fee_amount, }) } fn get_amount_fixed_delta( sqrt_price_current: u128, sqrt_price_target: u128, liquidity: u128, amount_specified_is_input: bool, a_to_b: bool, ) -> Result<u64, ErrorCode> { if a_to_b == amount_specified_is_input { get_amount_delta_a( sqrt_price_current, sqrt_price_target, liquidity, amount_specified_is_input, ) } else { get_amount_delta_b( sqrt_price_current, sqrt_price_target, liquidity, amount_specified_is_input, ) } } fn try_get_amount_fixed_delta( sqrt_price_current: u128, sqrt_price_target: u128, liquidity: u128, amount_specified_is_input: bool, a_to_b: bool, ) -> Result<AmountDeltaU64, ErrorCode> { if a_to_b == amount_specified_is_input { try_get_amount_delta_a( sqrt_price_current, sqrt_price_target, liquidity, amount_specified_is_input, ) } else { try_get_amount_delta_b( sqrt_price_current, sqrt_price_target, liquidity, amount_specified_is_input, ) } } fn get_amount_unfixed_delta( sqrt_price_current: u128, sqrt_price_target: u128, liquidity: u128, amount_specified_is_input: bool, a_to_b: bool, ) -> Result<u64, ErrorCode> { if a_to_b == amount_specified_is_input { get_amount_delta_b( sqrt_price_current, sqrt_price_target, liquidity, !amount_specified_is_input, ) } else { get_amount_delta_a( sqrt_price_current, sqrt_price_target, liquidity, !amount_specified_is_input, ) } } #[cfg(test)] mod fuzz_tests { use super::*; use proptest::prelude::*; proptest! { #[test] fn test_compute_swap( amount in 1..u64::MAX, liquidity in 1..u32::MAX as u128, fee_rate in 1..u16::MAX, price_0 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, price_1 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, amount_specified_is_input in proptest::bool::ANY, ) { prop_assume!(price_0 != price_1); // Rather than use logic to correctly input the prices, we just use the distribution to determine direction let a_to_b = price_0 >= price_1; let swap_computation = compute_swap( amount, fee_rate, liquidity, price_0, price_1, amount_specified_is_input, a_to_b, ).ok().unwrap(); let amount_in = swap_computation.amount_in; let amount_out = swap_computation.amount_out; let next_price = swap_computation.next_price; let fee_amount = swap_computation.fee_amount; // Amount_in can not exceed maximum amount assert!(amount_in <= u64::MAX - fee_amount); // Amounts calculated are less than amount specified let amount_used = if amount_specified_is_input { amount_in + fee_amount } else { amount_out }; if next_price != price_1 { assert!(amount_used == amount); } else { assert!(amount_used <= amount); } let (price_lower, price_upper) = increasing_price_order(price_0, price_1); assert!(next_price >= price_lower); assert!(next_price <= price_upper); } #[test] fn test_compute_swap_inversion( amount in 1..u64::MAX, liquidity in 1..u32::MAX as u128, fee_rate in 1..u16::MAX, price_0 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, price_1 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, amount_specified_is_input in proptest::bool::ANY, ) { prop_assume!(price_0 != price_1); // Rather than use logic to correctly input the prices, we just use the distribution to determine direction let a_to_b = price_0 >= price_1; let swap_computation = compute_swap( amount, fee_rate, liquidity, price_0, price_1, amount_specified_is_input, a_to_b, ).ok().unwrap(); let amount_in = swap_computation.amount_in; let amount_out = swap_computation.amount_out; let next_price = swap_computation.next_price; let fee_amount = swap_computation.fee_amount; let inverted_amount = if amount_specified_is_input { amount_out } else { amount_in + fee_amount }; if inverted_amount != 0 { let inverted = compute_swap( inverted_amount, fee_rate, liquidity, price_0, price_1, !amount_specified_is_input, a_to_b, ).ok().unwrap(); // A to B = price decreasing // Case 1 // Normal: is_input, a_to_b // Input is fixed, consume all input to produce amount_out // amount_in = fixed, ceil // amount_out = unfixed, floor // Inverted: !is_input, a_to_b // amount_in = unfixed, ceil // amount_out = fixed, floor // Amount = amount_out, inverted.amount_in and fee <= original input and fee, inverted.amount_out ~~ amount_out, inverted.next_price >= original.next_price // Case 2 // Normal: !is_input, a_to_b // Find amount required to get amount_out // amount_in = unfixed, ceil // amount_out = fixed, floor // Inverted: is_input, a_to_b // amount_in = fixed, ceil // amount_out = unfixed, floor // Get max amount_out for input, inverted.amount_in + fee ~~ original input and fee, inverted.amount_out >= amount_out, inverted.next_price <= original.next_price // Price increasing // Case 3 // Normal: is_input, !a_to_b // Input is fixed, consume all input to produce amount_out // amount_in = fixed, ceil // amount_out = unfixed, floor // Inverted: !is_input, !a_to_b // Amount = amount_out, inverted.amount_in and fee <= original input and fee, inverted.amount_out ~~ amount_out, inverted.next_price <= original.next_price // Case 4 // Normal: !is_input, !a_to_b // Find amount required to get amount_out // amount_in = fixed, floor // amount_out = unfixed, ceil // Inverted: is_input, !a_to_b // Get max amount_out for input, inverted.amount_in + fee ~~ original input and fee, inverted.amount_out >= amount_out // Since inverted.amount_out >= amount_out and amount in is the same, more of token a is being removed, so // inverted.next_price >= original.next_price // Next sqrt price goes from round up to round down // assert!(inverted.next_price + 1 >= next_price); if inverted.next_price != price_1 { if amount_specified_is_input { // If a_to_b, then goes round up => round down, assert!(inverted.amount_in <= amount_in); assert!(inverted.fee_amount <= fee_amount); } else { assert!(inverted.amount_in >= amount_in); assert!(inverted.fee_amount >= fee_amount); } assert!(inverted.amount_out >= amount_out); if a_to_b == amount_specified_is_input { // Next sqrt price goes from round up to round down assert!(inverted.next_price >= next_price); } else { // Next sqrt price goes from round down to round up assert!(inverted.next_price <= next_price); } // Ratio calculations // let ratio_in = (u128::from(inverted.amount_in) << 64) / u128::from(amount_in); // let ratio_out = (u128::from(inverted.amount_out) << 64) / u128::from(amount_out); // println!("RATIO IN/OUT WHEN INVERTED {} \t| {} ", ratio_in, ratio_out); // if ratio_out > (2 << 64) || ratio_in < (1 << 63) { // if ratio_out > (2 << 64) { // println!("OUT > {}", ratio_out / (1 << 64)); // } // if ratio_in < (1 << 63) { // println!("IN < 1/{}", (1 << 64) / ratio_in); // } // println!("liq {} | fee {} | price_0 {} | price_1 {} | a_to_b {}", liquidity, fee_rate, price_0, price_1, a_to_b); // println!("Amount {} | is_input {}", amount, amount_specified_is_input); // println!("Inverted Amount {} | is_input {}", inverted_amount, !amount_specified_is_input); // println!("{:?}", swap_computation); // println!("{:?}", inverted); // } } } } } } #[cfg(test)] mod unit_tests { use super::*; mod test_swap { // Doesn't cross any additional ticks mod no_cross { use super::*; #[test] fn swap_a_to_b_input() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output_partial() { validate_tick_whirlpool(); } } // Crosses single initialized tick mod single_tick { use super::*; #[test] fn swap_a_to_b_input() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output_partial() { validate_tick_whirlpool(); } } // Crosses multiple initialized ticks mod multi_tick { use super::*; #[test] fn swap_a_to_b_input() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output_partial() { validate_tick_whirlpool(); } } // Crosses a multiple ticks with a zone of 0 liquidity mod discontiguous_multi_tick { use super::*; #[test] fn swap_a_to_b_input() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output() { validate_tick_whirlpool(); } #[test] fn swap_a_to_b_output_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_input_partial() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output() { validate_tick_whirlpool(); } #[test] fn swap_b_to_a_output_partial() { validate_tick_whirlpool(); } } mod protocol_rate { use super::*; #[test] fn protocol_rate() { validate_tick_whirlpool(); } #[test] fn protocol_rate_zero() { validate_tick_whirlpool(); } } fn validate_tick_whirlpool() { // Validate tick values // Fee, reward growths // // Validate whirlpool values // liquidity, tick, sqrt_price, fee_growth, reward, protocol fee, token amounts } } mod test_compute_swap { const TWO_PCT: u16 = 20000; use std::convert::TryInto; use super::*; use crate::math::bit_math::Q64_RESOLUTION; #[test] fn swap_a_to_b_input() { // Example calculation let amount = 100u128; let init_liq = 1296; let init_price = 9; let price_limit = 4; // Calculate fee given fee percentage let fee_amount = div_round_up(amount * u128::from(TWO_PCT), 1_000_000) .ok() .unwrap(); // Calculate initial a and b given L and sqrt(P) let init_b = init_liq * init_price; let init_a = init_liq / init_price; // Calculate amount_in given fee_percentage let amount_in = amount - fee_amount; // Swapping a to b => let new_a = init_a + amount_in; // Calculate next price let next_price = div_round_up(init_liq << Q64_RESOLUTION, new_a) .ok() .unwrap(); // b - new_b let amount_out = init_b - div_round_up(init_liq * init_liq, new_a).ok().unwrap(); test_swap( 100, TWO_PCT, // 2 % fee init_liq, // sqrt(ab) // Current // b = 1296 * 9 => 11664 // a = 1296 / 9 => 144 init_price << Q64_RESOLUTION, // sqrt (b/a) // New // a = 144 + 98 => 242 => 1296 / sqrt(P) = 242 => sqrt(P) = 1296 /242 // next b = 1296 * 1296 / 242 => 6940 price_limit << Q64_RESOLUTION, true, true, SwapStepComputation { amount_in: amount_in.try_into().unwrap(), amount_out: amount_out.try_into().unwrap(), next_price, fee_amount: fee_amount.try_into().unwrap(), }, ); } #[test] fn swap_a_to_b_input_zero() { test_swap( 0, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 9 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_a_to_b_input_zero_liq() { test_swap( 100, TWO_PCT, 0, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 4 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_a_to_b_input_max() { test_swap( 1000, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, true, true, SwapStepComputation { amount_in: 180, amount_out: 6480, next_price: 4 << Q64_RESOLUTION, fee_amount: 4, }, ); } #[test] fn swap_a_to_b_input_max_1pct_fee() { test_swap( 1000, TWO_PCT / 2, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, true, true, SwapStepComputation { amount_in: 180, amount_out: 6480, next_price: 4 << Q64_RESOLUTION, fee_amount: 2, }, ); } #[test] fn swap_a_to_b_output() { test_swap( 4723, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, false, true, SwapStepComputation { amount_in: 98, amount_out: 4723, next_price: 98795409425631171116, fee_amount: 2, }, ); } #[test] fn swap_a_to_b_output_max() { test_swap( 10000, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, false, true, SwapStepComputation { amount_in: 180, amount_out: 6480, next_price: 4 << Q64_RESOLUTION, fee_amount: 4, }, ); } #[test] fn swap_a_to_b_output_zero() { test_swap( 0, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, false, true, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 9 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_a_to_b_output_zero_liq() { test_swap( 100, TWO_PCT, 0, 9 << Q64_RESOLUTION, 4 << Q64_RESOLUTION, false, true, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 4 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_b_to_a_input() { test_swap( 2000, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 1960, amount_out: 20, next_price: 193918550355107200012, fee_amount: 40, }, ); } #[test] fn swap_b_to_a_input_max() { test_swap( 20000, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 9072, amount_out: 63, next_price: 16 << Q64_RESOLUTION, fee_amount: 186, }, ); } #[test] fn swap_b_to_a_input_zero() { test_swap( 0, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 9 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_b_to_a_input_zero_liq() { test_swap( 100, TWO_PCT, 0, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, true, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 16 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_b_to_a_output() { test_swap( 20, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, false, false, SwapStepComputation { amount_in: 1882, amount_out: 20, next_price: 192798228383286926568, fee_amount: 39, }, ); } #[test] fn swap_b_to_a_output_max() { test_swap( 80, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, false, false, SwapStepComputation { amount_in: 9072, amount_out: 63, next_price: 16 << Q64_RESOLUTION, fee_amount: 186, }, ); } #[test] fn swap_b_to_a_output_zero() { test_swap( 0, TWO_PCT, 1296, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, false, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 9 << Q64_RESOLUTION, fee_amount: 0, }, ); } #[test] fn swap_b_to_a_output_zero_liq() { test_swap( 100, TWO_PCT, 0, 9 << Q64_RESOLUTION, 16 << Q64_RESOLUTION, false, false, SwapStepComputation { amount_in: 0, amount_out: 0, next_price: 16 << Q64_RESOLUTION, fee_amount: 0, }, ); } } #[allow(clippy::too_many_arguments)] fn test_swap( amount_remaining: u64, fee_rate: u16, liquidity: u128, sqrt_price_current: u128, sqrt_price_target_limit: u128, amount_specified_is_input: bool, a_to_b: bool, expected: SwapStepComputation, ) { let swap_computation = compute_swap( amount_remaining, fee_rate, liquidity, sqrt_price_current, sqrt_price_target_limit, amount_specified_is_input, a_to_b, ); assert_eq!(swap_computation.ok().unwrap(), expected); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/tick_math.rs
use crate::math::u256_math::*; use std::convert::TryInto; // Max/Min sqrt_price derived from max/min tick-index pub const MAX_SQRT_PRICE_X64: u128 = 79226673515401279992447579055; pub const MIN_SQRT_PRICE_X64: u128 = 4295048016; const LOG_B_2_X32: i128 = 59543866431248i128; const BIT_PRECISION: u32 = 14; const LOG_B_P_ERR_MARGIN_LOWER_X64: i128 = 184467440737095516i128; // 0.01 const LOG_B_P_ERR_MARGIN_UPPER_X64: i128 = 15793534762490258745i128; // 2^-precision / log_2_b + 0.01 pub const FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD: u16 = 32768; // 2^15 /// Derive the sqrt-price from a tick index. The precision of this method is only guarranted /// if tick is within the bounds of {max, min} tick-index. /// /// # Parameters /// - `tick` - A i32 integer representing the tick integer /// /// # Returns /// - `Ok`: A u128 Q32.64 representing the sqrt_price pub fn sqrt_price_from_tick_index(tick: i32) -> u128 { if tick >= 0 { get_sqrt_price_positive_tick(tick) } else { get_sqrt_price_negative_tick(tick) } } /// Derive the tick-index from a sqrt-price. The precision of this method is only guarranted /// if sqrt-price is within the bounds of {max, min} sqrt-price. /// /// # Parameters /// - `sqrt_price_x64` - A u128 Q64.64 integer representing the sqrt-price /// /// # Returns /// - An i32 representing the tick_index of the provided sqrt-price pub fn tick_index_from_sqrt_price(sqrt_price_x64: &u128) -> i32 { // Determine log_b(sqrt_ratio). First by calculating integer portion (msb) let msb: u32 = 128 - sqrt_price_x64.leading_zeros() - 1; let log2p_integer_x32 = (msb as i128 - 64) << 32; // get fractional value (r/2^msb), msb always > 128 // We begin the iteration from bit 63 (0.5 in Q64.64) let mut bit: i128 = 0x8000_0000_0000_0000i128; let mut precision = 0; let mut log2p_fraction_x64 = 0; // Log2 iterative approximation for the fractional part // Go through each 2^(j) bit where j < 64 in a Q64.64 number // Append current bit value to fraction result if r^2 Q2.126 is more than 2 let mut r = if msb >= 64 { sqrt_price_x64 >> (msb - 63) } else { sqrt_price_x64 << (63 - msb) }; while bit > 0 && precision < BIT_PRECISION { r *= r; let is_r_more_than_two = r >> 127_u32; r >>= 63 + is_r_more_than_two; log2p_fraction_x64 += bit * is_r_more_than_two as i128; bit >>= 1; precision += 1; } let log2p_fraction_x32 = log2p_fraction_x64 >> 32; let log2p_x32 = log2p_integer_x32 + log2p_fraction_x32; // Transform from base 2 to base b let logbp_x64 = log2p_x32 * LOG_B_2_X32; // Derive tick_low & high estimate. Adjust with the possibility of under-estimating by 2^precision_bits/log_2(b) + 0.01 error margin. let tick_low: i32 = ((logbp_x64 - LOG_B_P_ERR_MARGIN_LOWER_X64) >> 64) .try_into() .unwrap(); let tick_high: i32 = ((logbp_x64 + LOG_B_P_ERR_MARGIN_UPPER_X64) >> 64) .try_into() .unwrap(); if tick_low == tick_high { tick_low } else { // If our estimation for tick_high returns a lower sqrt_price than the input // then the actual tick_high has to be higher than tick_high. // Otherwise, the actual value is between tick_low & tick_high, so a floor value // (tick_low) is returned let actual_tick_high_sqrt_price_x64: u128 = sqrt_price_from_tick_index(tick_high); if actual_tick_high_sqrt_price_x64 <= *sqrt_price_x64 { tick_high } else { tick_low } } } fn mul_shift_96(n0: u128, n1: u128) -> u128 { mul_u256(n0, n1).shift_right(96).try_into_u128().unwrap() } // Performs the exponential conversion with Q64.64 precision fn get_sqrt_price_positive_tick(tick: i32) -> u128 { let mut ratio: u128 = if tick & 1 != 0 { 79232123823359799118286999567 } else { 79228162514264337593543950336 }; if tick & 2 != 0 { ratio = mul_shift_96(ratio, 79236085330515764027303304731); } if tick & 4 != 0 { ratio = mul_shift_96(ratio, 79244008939048815603706035061); } if tick & 8 != 0 { ratio = mul_shift_96(ratio, 79259858533276714757314932305); } if tick & 16 != 0 { ratio = mul_shift_96(ratio, 79291567232598584799939703904); } if tick & 32 != 0 { ratio = mul_shift_96(ratio, 79355022692464371645785046466); } if tick & 64 != 0 { ratio = mul_shift_96(ratio, 79482085999252804386437311141); } if tick & 128 != 0 { ratio = mul_shift_96(ratio, 79736823300114093921829183326); } if tick & 256 != 0 { ratio = mul_shift_96(ratio, 80248749790819932309965073892); } if tick & 512 != 0 { ratio = mul_shift_96(ratio, 81282483887344747381513967011); } if tick & 1024 != 0 { ratio = mul_shift_96(ratio, 83390072131320151908154831281); } if tick & 2048 != 0 { ratio = mul_shift_96(ratio, 87770609709833776024991924138); } if tick & 4096 != 0 { ratio = mul_shift_96(ratio, 97234110755111693312479820773); } if tick & 8192 != 0 { ratio = mul_shift_96(ratio, 119332217159966728226237229890); } if tick & 16384 != 0 { ratio = mul_shift_96(ratio, 179736315981702064433883588727); } if tick & 32768 != 0 { ratio = mul_shift_96(ratio, 407748233172238350107850275304); } if tick & 65536 != 0 { ratio = mul_shift_96(ratio, 2098478828474011932436660412517); } if tick & 131072 != 0 { ratio = mul_shift_96(ratio, 55581415166113811149459800483533); } if tick & 262144 != 0 { ratio = mul_shift_96(ratio, 38992368544603139932233054999993551); } ratio >> 32 } fn get_sqrt_price_negative_tick(tick: i32) -> u128 { let abs_tick = tick.abs(); let mut ratio: u128 = if abs_tick & 1 != 0 { 18445821805675392311 } else { 18446744073709551616 }; if abs_tick & 2 != 0 { ratio = (ratio * 18444899583751176498) >> 64 } if abs_tick & 4 != 0 { ratio = (ratio * 18443055278223354162) >> 64 } if abs_tick & 8 != 0 { ratio = (ratio * 18439367220385604838) >> 64 } if abs_tick & 16 != 0 { ratio = (ratio * 18431993317065449817) >> 64 } if abs_tick & 32 != 0 { ratio = (ratio * 18417254355718160513) >> 64 } if abs_tick & 64 != 0 { ratio = (ratio * 18387811781193591352) >> 64 } if abs_tick & 128 != 0 { ratio = (ratio * 18329067761203520168) >> 64 } if abs_tick & 256 != 0 { ratio = (ratio * 18212142134806087854) >> 64 } if abs_tick & 512 != 0 { ratio = (ratio * 17980523815641551639) >> 64 } if abs_tick & 1024 != 0 { ratio = (ratio * 17526086738831147013) >> 64 } if abs_tick & 2048 != 0 { ratio = (ratio * 16651378430235024244) >> 64 } if abs_tick & 4096 != 0 { ratio = (ratio * 15030750278693429944) >> 64 } if abs_tick & 8192 != 0 { ratio = (ratio * 12247334978882834399) >> 64 } if abs_tick & 16384 != 0 { ratio = (ratio * 8131365268884726200) >> 64 } if abs_tick & 32768 != 0 { ratio = (ratio * 3584323654723342297) >> 64 } if abs_tick & 65536 != 0 { ratio = (ratio * 696457651847595233) >> 64 } if abs_tick & 131072 != 0 { ratio = (ratio * 26294789957452057) >> 64 } if abs_tick & 262144 != 0 { ratio = (ratio * 37481735321082) >> 64 } ratio } #[cfg(test)] mod fuzz_tests { use super::*; use crate::{ math::U256, state::{MAX_TICK_INDEX, MIN_TICK_INDEX}, }; use proptest::prelude::*; fn within_price_approximation(lower: u128, upper: u128) -> bool { let precision = 96; // We increase the resolution of upper to find ratio_x96 let x = U256::from(upper) << precision; let y = U256::from(lower); // (1.0001 ^ 0.5) << 96 (precision) let sqrt_10001_x96 = 79232123823359799118286999567u128; // This ratio should be as close to sqrt_10001_x96 as possible let ratio_x96 = x.div_mod(y).0.as_u128(); // Find absolute error in ratio in x96 let error = if sqrt_10001_x96 > ratio_x96 { sqrt_10001_x96 - ratio_x96 } else { ratio_x96 - sqrt_10001_x96 }; // Calculate number of error bits let error_bits = 128 - error.leading_zeros(); precision - error_bits >= 32 } proptest! { #[test] fn test_tick_index_to_sqrt_price ( tick in MIN_TICK_INDEX..MAX_TICK_INDEX, ) { let sqrt_price = sqrt_price_from_tick_index(tick); // Check bounds assert!(sqrt_price >= MIN_SQRT_PRICE_X64); assert!(sqrt_price <= MAX_SQRT_PRICE_X64); // Check the inverted tick has unique price and within bounds let minus_tick_price = sqrt_price_from_tick_index(tick - 1); let plus_tick_price = sqrt_price_from_tick_index(tick + 1); assert!(minus_tick_price < sqrt_price && sqrt_price < plus_tick_price); // Check that sqrt_price_from_tick_index(tick + 1) approximates sqrt(1.0001) * sqrt_price_from_tick_index(tick) assert!(within_price_approximation(minus_tick_price, sqrt_price)); assert!(within_price_approximation(sqrt_price, plus_tick_price)); } #[test] fn test_tick_index_from_sqrt_price ( sqrt_price in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64 ) { let tick = tick_index_from_sqrt_price(&sqrt_price); // Check bounds assert!(tick >= MIN_TICK_INDEX); assert!(tick < MAX_TICK_INDEX); // Check the inverted price from the calculated tick is within tick boundaries assert!(sqrt_price >= sqrt_price_from_tick_index(tick) && sqrt_price < sqrt_price_from_tick_index(tick + 1)) } #[test] // Verify that both conversion functions are symmetrical. fn test_tick_index_and_sqrt_price_symmetry ( tick in MIN_TICK_INDEX..MAX_TICK_INDEX ) { let sqrt_price_x64 = sqrt_price_from_tick_index(tick); let resolved_tick = tick_index_from_sqrt_price(&sqrt_price_x64); assert!(resolved_tick == tick); } #[test] fn test_sqrt_price_from_tick_index_is_sequence ( tick in MIN_TICK_INDEX-1..MAX_TICK_INDEX ) { let sqrt_price_x64 = sqrt_price_from_tick_index(tick); let last_sqrt_price_x64 = sqrt_price_from_tick_index(tick-1); assert!(last_sqrt_price_x64 < sqrt_price_x64); } #[test] fn test_tick_index_from_sqrt_price_is_sequence ( sqrt_price in (MIN_SQRT_PRICE_X64 + 10)..MAX_SQRT_PRICE_X64 ) { let tick = tick_index_from_sqrt_price(&sqrt_price); let last_tick = tick_index_from_sqrt_price(&(sqrt_price - 10)); assert!(last_tick <= tick); } } } #[cfg(test)] mod test_tick_index_from_sqrt_price { use super::*; use crate::state::{MAX_TICK_INDEX, MIN_TICK_INDEX}; #[test] fn test_sqrt_price_from_tick_index_at_max() { let r = tick_index_from_sqrt_price(&MAX_SQRT_PRICE_X64); assert_eq!(&r, &MAX_TICK_INDEX); } #[test] fn test_sqrt_price_from_tick_index_at_min() { let r = tick_index_from_sqrt_price(&MIN_SQRT_PRICE_X64); assert_eq!(&r, &MIN_TICK_INDEX); } #[test] fn test_sqrt_price_from_tick_index_at_max_add_one() { let sqrt_price_x64_max_add_one = MAX_SQRT_PRICE_X64 + 1; let tick_from_max_add_one = tick_index_from_sqrt_price(&sqrt_price_x64_max_add_one); let sqrt_price_x64_max = MAX_SQRT_PRICE_X64 + 1; let tick_from_max = tick_index_from_sqrt_price(&sqrt_price_x64_max); // We don't care about accuracy over the limit. We just care about it's equality properties. assert!(tick_from_max_add_one >= tick_from_max); } #[test] fn test_sqrt_price_from_tick_index_at_min_add_one() { let sqrt_price_x64 = MIN_SQRT_PRICE_X64 + 1; let r = tick_index_from_sqrt_price(&sqrt_price_x64); assert_eq!(&r, &(MIN_TICK_INDEX)); } #[test] fn test_sqrt_price_from_tick_index_at_max_sub_one() { let sqrt_price_x64 = MAX_SQRT_PRICE_X64 - 1; let r = tick_index_from_sqrt_price(&sqrt_price_x64); assert_eq!(&r, &(MAX_TICK_INDEX - 1)); } #[test] fn test_sqrt_price_from_tick_index_at_min_sub_one() { let sqrt_price_x64_min_sub_one = MIN_SQRT_PRICE_X64 - 1; let tick_from_min_sub_one = tick_index_from_sqrt_price(&sqrt_price_x64_min_sub_one); let sqrt_price_x64_min = MIN_SQRT_PRICE_X64 + 1; let tick_from_min = tick_index_from_sqrt_price(&sqrt_price_x64_min); // We don't care about accuracy over the limit. We just care about it's equality properties. assert!(tick_from_min_sub_one < tick_from_min); } #[test] fn test_sqrt_price_from_tick_index_at_one() { let sqrt_price_x64: u128 = u64::MAX as u128 + 1; let r = tick_index_from_sqrt_price(&sqrt_price_x64); assert_eq!(r, 0); } #[test] fn test_sqrt_price_from_tick_index_at_one_add_one() { let sqrt_price_x64: u128 = u64::MAX as u128 + 2; let r = tick_index_from_sqrt_price(&sqrt_price_x64); assert_eq!(r, 0); } #[test] fn test_sqrt_price_from_tick_index_at_one_sub_one() { let sqrt_price_x64: u128 = u64::MAX.into(); let r = tick_index_from_sqrt_price(&sqrt_price_x64); assert_eq!(r, -1); } } #[cfg(test)] mod sqrt_price_from_tick_index_tests { use super::*; use crate::state::{MAX_TICK_INDEX, MIN_TICK_INDEX}; #[test] #[should_panic(expected = "NumberDownCastError")] // There should never be a use-case where we call this method with an out of bound index fn test_tick_exceed_max() { let sqrt_price_from_max_tick_add_one = sqrt_price_from_tick_index(MAX_TICK_INDEX + 1); let sqrt_price_from_max_tick = sqrt_price_from_tick_index(MAX_TICK_INDEX); assert!(sqrt_price_from_max_tick_add_one > sqrt_price_from_max_tick); } #[test] fn test_tick_below_min() { let sqrt_price_from_min_tick_sub_one = sqrt_price_from_tick_index(MIN_TICK_INDEX - 1); let sqrt_price_from_min_tick = sqrt_price_from_tick_index(MIN_TICK_INDEX); assert!(sqrt_price_from_min_tick_sub_one < sqrt_price_from_min_tick); } #[test] fn test_tick_at_max() { let max_tick = MAX_TICK_INDEX; let r = sqrt_price_from_tick_index(max_tick); assert_eq!(r, MAX_SQRT_PRICE_X64); } #[test] fn test_tick_at_min() { let min_tick = MIN_TICK_INDEX; let r = sqrt_price_from_tick_index(min_tick); assert_eq!(r, MIN_SQRT_PRICE_X64); } #[test] fn test_exact_bit_values() { let conditions = &[ ( 0i32, 18446744073709551616u128, 18446744073709551616u128, "0x0", ), ( 1i32, 18447666387855959850u128, 18445821805675392311u128, "0x1", ), ( 2i32, 18448588748116922571u128, 18444899583751176498u128, "0x2", ), ( 4i32, 18450433606991734263u128, 18443055278223354162u128, "0x4", ), ( 8i32, 18454123878217468680u128, 18439367220385604838u128, "0x8", ), ( 16i32, 18461506635090006701u128, 18431993317065449817u128, "0x10", ), ( 32i32, 18476281010653910144u128, 18417254355718160513u128, "0x20", ), ( 64i32, 18505865242158250041u128, 18387811781193591352u128, "0x40", ), ( 128i32, 18565175891880433522u128, 18329067761203520168u128, "0x80", ), ( 256i32, 18684368066214940582u128, 18212142134806087854u128, "0x100", ), ( 512i32, 18925053041275764671u128, 17980523815641551639u128, "0x200", ), ( 1024i32, 19415764168677886926u128, 17526086738831147013u128, "0x400", ), ( 2048i32, 20435687552633177494u128, 16651378430235024244u128, "0x800", ), ( 4096i32, 22639080592224303007u128, 15030750278693429944u128, "0x1000", ), ( 8192i32, 27784196929998399742u128, 12247334978882834399u128, "0x2000", ), ( 16384i32, 41848122137994986128u128, 8131365268884726200u128, "0x4000", ), ( 32768i32, 94936283578220370716u128, 3584323654723342297u128, "0x8000", ), ( 65536i32, 488590176327622479860u128, 696457651847595233u128, "0x10000", ), ( 131072i32, 12941056668319229769860u128, 26294789957452057u128, "0x20000", ), ( 262144i32, 9078618265828848800676189u128, 37481735321082u128, "0x40000", ), ]; for (p_tick, expected, neg_expected, desc) in conditions { let p_result = sqrt_price_from_tick_index(*p_tick); let n_tick = -p_tick; let n_result = sqrt_price_from_tick_index(n_tick); assert_eq!( p_result, *expected, "Assert positive tick equals expected value on binary fraction bit = {} ", desc ); assert_eq!( n_result, *neg_expected, "Assert negative tick equals expected value on binary fraction bit = {} ", desc ); } } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/token_math.rs
use crate::errors::ErrorCode; use crate::math::{Q64_MASK, Q64_RESOLUTION}; use super::{ div_round_up_if, div_round_up_if_u256, mul_u256, U256Muldiv, MAX_SQRT_PRICE_X64, MIN_SQRT_PRICE_X64, }; // Fee rate is represented as hundredths of a basis point. // Fee amount = total_amount * fee_rate / 1_000_000. // Max fee rate supported is 3%. pub const MAX_FEE_RATE: u16 = 30_000; // Assuming that FEE_RATE is represented as hundredths of a basis point // We want FEE_RATE_MUL_VALUE = 1/FEE_RATE_UNIT, so 1e6 pub const FEE_RATE_MUL_VALUE: u128 = 1_000_000; // Protocol fee rate is represented as a basis point. // Protocol fee amount = fee_amount * protocol_fee_rate / 10_000. // Max protocol fee rate supported is 25% of the fee rate. pub const MAX_PROTOCOL_FEE_RATE: u16 = 2_500; // Assuming that PROTOCOL_FEE_RATE is represented as a basis point // We want PROTOCOL_FEE_RATE_MUL_VALUE = 1/PROTOCOL_FEE_UNIT, so 1e4 pub const PROTOCOL_FEE_RATE_MUL_VALUE: u128 = 10_000; #[derive(Debug)] pub enum AmountDeltaU64 { Valid(u64), ExceedsMax(ErrorCode), } impl AmountDeltaU64 { pub fn lte(&self, other: u64) -> bool { match self { AmountDeltaU64::Valid(value) => *value <= other, AmountDeltaU64::ExceedsMax(_) => false, } } pub fn exceeds_max(&self) -> bool { match self { AmountDeltaU64::Valid(_) => false, AmountDeltaU64::ExceedsMax(_) => true, } } pub fn value(self) -> u64 { match self { AmountDeltaU64::Valid(value) => value, // This should never happen AmountDeltaU64::ExceedsMax(_) => panic!("Called unwrap on AmountDeltaU64::ExceedsMax"), } } } // // Get change in token_a corresponding to a change in price // // 6.16 // Δt_a = Δ(1 / sqrt_price) * liquidity // Replace delta // Δt_a = (1 / sqrt_price_upper - 1 / sqrt_price_lower) * liquidity // Common denominator to simplify // Δt_a = ((sqrt_price_lower - sqrt_price_upper) / (sqrt_price_upper * sqrt_price_lower)) * liquidity // Δt_a = (liquidity * (sqrt_price_lower - sqrt_price_upper)) / (sqrt_price_upper * sqrt_price_lower) pub fn get_amount_delta_a( sqrt_price_0: u128, sqrt_price_1: u128, liquidity: u128, round_up: bool, ) -> Result<u64, ErrorCode> { match try_get_amount_delta_a(sqrt_price_0, sqrt_price_1, liquidity, round_up) { Ok(AmountDeltaU64::Valid(value)) => Ok(value), Ok(AmountDeltaU64::ExceedsMax(error)) => Err(error), Err(error) => Err(error), } } pub fn try_get_amount_delta_a( sqrt_price_0: u128, sqrt_price_1: u128, liquidity: u128, round_up: bool, ) -> Result<AmountDeltaU64, ErrorCode> { let (sqrt_price_lower, sqrt_price_upper) = increasing_price_order(sqrt_price_0, sqrt_price_1); let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower; let numerator = mul_u256(liquidity, sqrt_price_diff) .checked_shift_word_left() .ok_or(ErrorCode::MultiplicationOverflow)?; let denominator = mul_u256(sqrt_price_upper, sqrt_price_lower); let (quotient, remainder) = numerator.div(denominator, round_up); let result = if round_up && !remainder.is_zero() { quotient.add(U256Muldiv::new(0, 1)).try_into_u128() } else { quotient.try_into_u128() }; match result { Ok(result) => { if result > u64::MAX as u128 { return Ok(AmountDeltaU64::ExceedsMax(ErrorCode::TokenMaxExceeded)); } Ok(AmountDeltaU64::Valid(result as u64)) } Err(err) => Ok(AmountDeltaU64::ExceedsMax(err)), } } // // Get change in token_b corresponding to a change in price // // 6.14 // Δt_b = Δ(sqrt_price) * liquidity // Replace delta // Δt_b = (sqrt_price_upper - sqrt_price_lower) * liquidity pub fn get_amount_delta_b( sqrt_price_0: u128, sqrt_price_1: u128, liquidity: u128, round_up: bool, ) -> Result<u64, ErrorCode> { match try_get_amount_delta_b(sqrt_price_0, sqrt_price_1, liquidity, round_up) { Ok(AmountDeltaU64::Valid(value)) => Ok(value), Ok(AmountDeltaU64::ExceedsMax(error)) => Err(error), Err(error) => Err(error), } } pub fn try_get_amount_delta_b( sqrt_price_0: u128, sqrt_price_1: u128, liquidity: u128, round_up: bool, ) -> Result<AmountDeltaU64, ErrorCode> { let (sqrt_price_lower, sqrt_price_upper) = increasing_price_order(sqrt_price_0, sqrt_price_1); // customized checked_mul_shift_right_round_up_if let n0 = liquidity; let n1 = sqrt_price_upper - sqrt_price_lower; if n0 == 0 || n1 == 0 { return Ok(AmountDeltaU64::Valid(0)); } if let Some(p) = n0.checked_mul(n1) { let result = (p >> Q64_RESOLUTION) as u64; let should_round = round_up && (p & Q64_MASK > 0); if should_round && result == u64::MAX { return Ok(AmountDeltaU64::ExceedsMax( ErrorCode::MultiplicationOverflow, )); } Ok(AmountDeltaU64::Valid(if should_round { result + 1 } else { result })) } else { Ok(AmountDeltaU64::ExceedsMax( ErrorCode::MultiplicationShiftRightOverflow, )) } } pub fn increasing_price_order(sqrt_price_0: u128, sqrt_price_1: u128) -> (u128, u128) { if sqrt_price_0 > sqrt_price_1 { (sqrt_price_1, sqrt_price_0) } else { (sqrt_price_0, sqrt_price_1) } } // // Get change in price corresponding to a change in token_a supply // // 6.15 // Δ(1 / sqrt_price) = Δt_a / liquidity // // Replace delta // 1 / sqrt_price_new - 1 / sqrt_price = amount / liquidity // // Move sqrt price to other side // 1 / sqrt_price_new = (amount / liquidity) + (1 / sqrt_price) // // Common denominator for right side // 1 / sqrt_price_new = (sqrt_price * amount + liquidity) / (sqrt_price * liquidity) // // Invert fractions // sqrt_price_new = (sqrt_price * liquidity) / (liquidity + amount * sqrt_price) pub fn get_next_sqrt_price_from_a_round_up( sqrt_price: u128, liquidity: u128, amount: u64, amount_specified_is_input: bool, ) -> Result<u128, ErrorCode> { if amount == 0 { return Ok(sqrt_price); } let product = mul_u256(sqrt_price, amount as u128); let numerator = mul_u256(liquidity, sqrt_price) .checked_shift_word_left() .ok_or(ErrorCode::MultiplicationOverflow)?; // In this scenario the denominator will end up being < 0 let liquidity_shift_left = U256Muldiv::new(0, liquidity).shift_word_left(); if !amount_specified_is_input && liquidity_shift_left.lte(product) { return Err(ErrorCode::DivideByZero); } let denominator = if amount_specified_is_input { liquidity_shift_left.add(product) } else { liquidity_shift_left.sub(product) }; let price = div_round_up_if_u256(numerator, denominator, true)?; if price < MIN_SQRT_PRICE_X64 { return Err(ErrorCode::TokenMinSubceeded); } else if price > MAX_SQRT_PRICE_X64 { return Err(ErrorCode::TokenMaxExceeded); } Ok(price) } // // Get change in price corresponding to a change in token_b supply // // 6.13 // Δ(sqrt_price) = Δt_b / liquidity pub fn get_next_sqrt_price_from_b_round_down( sqrt_price: u128, liquidity: u128, amount: u64, amount_specified_is_input: bool, ) -> Result<u128, ErrorCode> { // We always want square root price to be rounded down, which means // Case 3. If we are fixing input (adding B), we are increasing price, we want delta to be floor(delta) // sqrt_price + floor(delta) < sqrt_price + delta // // Case 4. If we are fixing output (removing B), we are decreasing price, we want delta to be ceil(delta) // sqrt_price - ceil(delta) < sqrt_price - delta // Q64.0 << 64 => Q64.64 let amount_x64 = (amount as u128) << Q64_RESOLUTION; // Q64.64 / Q64.0 => Q64.64 let delta = div_round_up_if(amount_x64, liquidity, !amount_specified_is_input)?; // Q64(32).64 +/- Q64.64 if amount_specified_is_input { // We are adding token b to supply, causing price to increase sqrt_price .checked_add(delta) .ok_or(ErrorCode::SqrtPriceOutOfBounds) } else { // We are removing token b from supply,. causing price to decrease sqrt_price .checked_sub(delta) .ok_or(ErrorCode::SqrtPriceOutOfBounds) } } pub fn get_next_sqrt_price( sqrt_price: u128, liquidity: u128, amount: u64, amount_specified_is_input: bool, a_to_b: bool, ) -> Result<u128, ErrorCode> { if amount_specified_is_input == a_to_b { // We are fixing A // Case 1. amount_specified_is_input = true, a_to_b = true // We are exchanging A to B with at most _amount_ of A (input) // // Case 2. amount_specified_is_input = false, a_to_b = false // We are exchanging B to A wanting to guarantee at least _amount_ of A (output) // // In either case we want the sqrt_price to be rounded up. // // Eq 1. sqrt_price = sqrt( b / a ) // // Case 1. amount_specified_is_input = true, a_to_b = true // We are adding token A to the supply, causing price to decrease (Eq 1.) // Since we are fixing input, we can not exceed the amount that is being provided by the user. // Because a higher price is inversely correlated with an increased supply of A, // a higher price means we are adding less A. Thus when performing math, we wish to round the // price up, since that means that we are guaranteed to not exceed the fixed amount of A provided. // // Case 2. amount_specified_is_input = false, a_to_b = false // We are removing token A from the supply, causing price to increase (Eq 1.) // Since we are fixing output, we want to guarantee that the user is provided at least _amount_ of A // Because a higher price is correlated with a decreased supply of A, // a higher price means we are removing more A to give to the user. Thus when performing math, we wish // to round the price up, since that means we guarantee that user receives at least _amount_ of A get_next_sqrt_price_from_a_round_up( sqrt_price, liquidity, amount, amount_specified_is_input, ) } else { // We are fixing B // Case 3. amount_specified_is_input = true, a_to_b = false // We are exchanging B to A using at most _amount_ of B (input) // // Case 4. amount_specified_is_input = false, a_to_b = true // We are exchanging A to B wanting to guarantee at least _amount_ of B (output) // // In either case we want the sqrt_price to be rounded down. // // Eq 1. sqrt_price = sqrt( b / a ) // // Case 3. amount_specified_is_input = true, a_to_b = false // We are adding token B to the supply, causing price to increase (Eq 1.) // Since we are fixing input, we can not exceed the amount that is being provided by the user. // Because a lower price is inversely correlated with an increased supply of B, // a lower price means that we are adding less B. Thus when performing math, we wish to round the // price down, since that means that we are guaranteed to not exceed the fixed amount of B provided. // // Case 4. amount_specified_is_input = false, a_to_b = true // We are removing token B from the supply, causing price to decrease (Eq 1.) // Since we are fixing output, we want to guarantee that the user is provided at least _amount_ of B // Because a lower price is correlated with a decreased supply of B, // a lower price means we are removing more B to give to the user. Thus when performing math, we // wish to round the price down, since that means we guarantee that the user receives at least _amount_ of B get_next_sqrt_price_from_b_round_down( sqrt_price, liquidity, amount, amount_specified_is_input, ) } } #[cfg(test)] mod fuzz_tests { use super::*; use crate::math::{bit_math::*, tick_math::*, U256}; use proptest::prelude::*; // Cases where the math overflows or errors // // get_next_sqrt_price_from_a_round_up // sqrt_price_new = (sqrt_price * liquidity) / (liquidity + amount * sqrt_price) // // If amount_specified_is_input == false // DivideByZero: (liquidity / liquidity - amount * sqrt_price) // liquidity <= sqrt_price * amount, divide by zero error // TokenMax/MinExceed // (sqrt_price * liquidity) / (liquidity + amount * sqrt_price) > 2^32 - 1 // // get_next_sqrt_price_from_b_round_down // SqrtPriceOutOfBounds // sqrt_price - (amount / liquidity) < 0 // // get_amount_delta_b // TokenMaxExceeded // (price_1 - price_0) * liquidity > 2^64 proptest! { #[test] fn test_get_next_sqrt_price_from_a_round_up ( sqrt_price in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, liquidity in 1..u128::MAX, amount in 0..u64::MAX, ) { prop_assume!(sqrt_price != 0); // Case 1. amount_specified_is_input = true, a_to_b = true // We are adding token A to the supply, causing price to decrease (Eq 1.) // Since we are fixing input, we can not exceed the amount that is being provided by the user. // Because a higher price is inversely correlated with an increased supply of A, // a higher price means we are adding less A. Thus when performing math, we wish to round the // price up, since that means that we are guaranteed to not exceed the fixed amount of A provided let case_1_price = get_next_sqrt_price_from_a_round_up(sqrt_price, liquidity, amount, true); if liquidity.leading_zeros() + sqrt_price.leading_zeros() < Q64_RESOLUTION.into() { assert!(case_1_price.is_err()); } else { assert!(amount >= get_amount_delta_a(sqrt_price, case_1_price.unwrap(), liquidity, true).unwrap()); // Case 2. amount_specified_is_input = false, a_to_b = false // We are removing token A from the supply, causing price to increase (Eq 1.) // Since we are fixing output, we want to guarantee that the user is provided at least _amount_ of A // Because a higher price is correlated with a decreased supply of A, // a higher price means we are removing more A to give to the user. Thus when performing math, we wish // to round the price up, since that means we guarantee that user receives at least _amount_ of A let case_2_price = get_next_sqrt_price_from_a_round_up(sqrt_price, liquidity, amount, false); // We need to expand into U256 space here in order to support large enough values // Q64 << 64 => Q64.64 let liquidity_x64 = U256::from(liquidity) << Q64_RESOLUTION; // Q64.64 * Q64 => Q128.64 let product = U256::from(sqrt_price) * U256::from(amount); if liquidity_x64 <= product { assert!(case_2_price.is_err()); } else { assert!(amount <= get_amount_delta_a(sqrt_price, case_2_price.unwrap(), liquidity, false).unwrap()); assert!(case_2_price.unwrap() >= sqrt_price); } if amount == 0 { assert!(case_1_price.unwrap() == case_2_price.unwrap()); } } } #[test] fn test_get_next_sqrt_price_from_b_round_down ( sqrt_price in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, liquidity in 1..u128::MAX, amount in 0..u64::MAX, ) { prop_assume!(sqrt_price != 0); // Case 3. amount_specified_is_input = true, a_to_b = false // We are adding token B to the supply, causing price to increase (Eq 1.) // Since we are fixing input, we can not exceed the amount that is being provided by the user. // Because a lower price is inversely correlated with an increased supply of B, // a lower price means that we are adding less B. Thus when performing math, we wish to round the // price down, since that means that we are guaranteed to not exceed the fixed amount of B provided. let case_3_price = get_next_sqrt_price_from_b_round_down(sqrt_price, liquidity, amount, true).unwrap(); assert!(case_3_price >= sqrt_price); assert!(amount >= get_amount_delta_b(sqrt_price, case_3_price, liquidity, true).unwrap()); // Case 4. amount_specified_is_input = false, a_to_b = true // We are removing token B from the supply, causing price to decrease (Eq 1.) // Since we are fixing output, we want to guarantee that the user is provided at least _amount_ of B // Because a lower price is correlated with a decreased supply of B, // a lower price means we are removing more B to give to the user. Thus when performing math, we // wish to round the price down, since that means we guarantee that the user receives at least _amount_ of B let case_4_price = get_next_sqrt_price_from_b_round_down(sqrt_price, liquidity, amount, false); // Q64.0 << 64 => Q64.64 let amount_x64 = u128::from(amount) << Q64_RESOLUTION; let delta = div_round_up(amount_x64, liquidity).unwrap(); if sqrt_price < delta { // In Case 4, error if sqrt_price < delta assert!(case_4_price.is_err()); } else { let calc_delta = get_amount_delta_b(sqrt_price, case_4_price.unwrap(), liquidity, false); if calc_delta.is_ok() { assert!(amount <= calc_delta.unwrap()); } // In Case 4, price is decreasing assert!(case_4_price.unwrap() <= sqrt_price); } if amount == 0 { assert!(case_3_price == case_4_price.unwrap()); } } #[test] fn test_get_amount_delta_a( sqrt_price_0 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, sqrt_price_1 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, liquidity in 0..u128::MAX, ) { let (sqrt_price_lower, sqrt_price_upper) = increasing_price_order(sqrt_price_0, sqrt_price_1); let rounded = get_amount_delta_a(sqrt_price_0, sqrt_price_1, liquidity, true); if liquidity.leading_zeros() + (sqrt_price_upper - sqrt_price_lower).leading_zeros() < Q64_RESOLUTION.into() { assert!(rounded.is_err()) } else { let unrounded = get_amount_delta_a(sqrt_price_0, sqrt_price_1, liquidity, false).unwrap(); // Price difference symmetry assert_eq!(rounded.unwrap(), get_amount_delta_a(sqrt_price_1, sqrt_price_0, liquidity, true).unwrap()); assert_eq!(unrounded, get_amount_delta_a(sqrt_price_1, sqrt_price_0, liquidity, false).unwrap()); // Rounded should always be larger assert!(unrounded <= rounded.unwrap()); // Diff should be no more than 1 assert!(rounded.unwrap() - unrounded <= 1); } } #[test] fn test_get_amount_delta_b( sqrt_price_0 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, sqrt_price_1 in MIN_SQRT_PRICE_X64..MAX_SQRT_PRICE_X64, liquidity in 0..u128::MAX, ) { let (price_lower, price_upper) = increasing_price_order(sqrt_price_0, sqrt_price_1); // We need 256 here since we may end up above u128 bits let n_0 = U256::from(liquidity); // Q64.0, not using 64 MSB let n_1 = U256::from(price_upper - price_lower); // Q32.64 - Q32.64 => Q32.64 // Shift by 64 in order to remove fractional bits let m = n_0 * n_1; // Q64.0 * Q32.64 => Q96.64 let delta = m >> Q64_RESOLUTION; // Q96.64 >> 64 => Q96.0 let has_mod = m % TO_Q64 > U256::zero(); let round_up_delta = if has_mod { delta + U256::from(1) } else { delta }; let rounded = get_amount_delta_b(sqrt_price_0, sqrt_price_1, liquidity, true); let unrounded = get_amount_delta_b(sqrt_price_0, sqrt_price_1, liquidity, false); let u64_max_in_u256 = U256::from(u64::MAX); if delta > u64_max_in_u256 { assert!(rounded.is_err()); assert!(unrounded.is_err()); } else if round_up_delta > u64_max_in_u256 { assert!(rounded.is_err()); // Price symmmetry assert_eq!(unrounded.unwrap(), get_amount_delta_b(sqrt_price_1, sqrt_price_0, liquidity, false).unwrap()); } else { // Price difference symmetry assert_eq!(rounded.unwrap(), get_amount_delta_b(sqrt_price_1, sqrt_price_0, liquidity, true).unwrap()); assert_eq!(unrounded.unwrap(), get_amount_delta_b(sqrt_price_1, sqrt_price_0, liquidity, false).unwrap()); // Rounded should always be larger assert!(unrounded.unwrap() <= rounded.unwrap()); // Diff should be no more than 1 assert!(rounded.unwrap() - unrounded.unwrap() <= 1); } } } } #[cfg(test)] mod test_get_amount_delta { // Δt_a = ((liquidity * (sqrt_price_lower - sqrt_price_upper)) / sqrt_price_upper) / sqrt_price_lower use super::get_amount_delta_a; use super::get_amount_delta_b; #[test] fn test_get_amount_delta_ok() { // A assert_eq!(get_amount_delta_a(4 << 64, 2 << 64, 4, true).unwrap(), 1); assert_eq!(get_amount_delta_a(4 << 64, 2 << 64, 4, false).unwrap(), 1); // B assert_eq!(get_amount_delta_b(4 << 64, 2 << 64, 4, true).unwrap(), 8); assert_eq!(get_amount_delta_b(4 << 64, 2 << 64, 4, false).unwrap(), 8); } #[test] fn test_get_amount_delta_price_diff_zero_ok() { // A assert_eq!(get_amount_delta_a(4 << 64, 4 << 64, 4, true).unwrap(), 0); assert_eq!(get_amount_delta_a(4 << 64, 4 << 64, 4, false).unwrap(), 0); // B assert_eq!(get_amount_delta_b(4 << 64, 4 << 64, 4, true).unwrap(), 0); assert_eq!(get_amount_delta_b(4 << 64, 4 << 64, 4, false).unwrap(), 0); } #[test] fn test_get_amount_delta_a_overflow() { assert!(get_amount_delta_a(1 << 64, 2 << 64, u128::MAX, true).is_err()); assert!(get_amount_delta_a(1 << 64, 2 << 64, (u64::MAX as u128) << (1 + 1), true).is_err()); assert!(get_amount_delta_a(1 << 64, 2 << 64, (u64::MAX as u128) << 1, true).is_ok()); assert!(get_amount_delta_a(1 << 64, 2 << 64, u64::MAX as u128, true).is_ok()); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/mod.rs
pub mod bit_math; pub mod bn; pub mod liquidity_math; pub mod swap_math; pub mod tick_math; pub mod token_math; pub mod u256_math; pub use bit_math::*; pub use bn::*; pub use liquidity_math::*; pub use swap_math::*; pub use tick_math::*; pub use token_math::*; pub use u256_math::*;
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/bit_math.rs
use crate::errors::ErrorCode; use super::U256Muldiv; pub const Q64_RESOLUTION: u8 = 64; pub const Q64_MASK: u128 = 0xFFFF_FFFF_FFFF_FFFF; pub const TO_Q64: u128 = 1u128 << Q64_RESOLUTION; pub fn checked_mul_div(n0: u128, n1: u128, d: u128) -> Result<u128, ErrorCode> { checked_mul_div_round_up_if(n0, n1, d, false) } pub fn checked_mul_div_round_up(n0: u128, n1: u128, d: u128) -> Result<u128, ErrorCode> { checked_mul_div_round_up_if(n0, n1, d, true) } pub fn checked_mul_div_round_up_if( n0: u128, n1: u128, d: u128, round_up: bool, ) -> Result<u128, ErrorCode> { if d == 0 { return Err(ErrorCode::DivideByZero); } let p = n0.checked_mul(n1).ok_or(ErrorCode::MulDivOverflow)?; let n = p / d; Ok(if round_up && p % d > 0 { n + 1 } else { n }) } pub fn checked_mul_shift_right(n0: u128, n1: u128) -> Result<u64, ErrorCode> { checked_mul_shift_right_round_up_if(n0, n1, false) } /// Multiplies an integer u128 and a Q64.64 fixed point number. /// Returns a product represented as a u64 integer. pub fn checked_mul_shift_right_round_up_if( n0: u128, n1: u128, round_up: bool, ) -> Result<u64, ErrorCode> { // customized this function is used in try_get_amount_delta_b (token_math.rs) if n0 == 0 || n1 == 0 { return Ok(0); } let p = n0 .checked_mul(n1) .ok_or(ErrorCode::MultiplicationShiftRightOverflow)?; let result = (p >> Q64_RESOLUTION) as u64; let should_round = round_up && (p & Q64_MASK > 0); if should_round && result == u64::MAX { return Err(ErrorCode::MultiplicationOverflow); } Ok(if should_round { result + 1 } else { result }) } pub fn div_round_up(n: u128, d: u128) -> Result<u128, ErrorCode> { div_round_up_if(n, d, true) } pub fn div_round_up_if(n: u128, d: u128, round_up: bool) -> Result<u128, ErrorCode> { if d == 0 { return Err(ErrorCode::DivideByZero); } let q = n / d; Ok(if round_up && n % d > 0 { q + 1 } else { q }) } pub fn div_round_up_if_u256( n: U256Muldiv, d: U256Muldiv, round_up: bool, ) -> Result<u128, ErrorCode> { let (quotient, remainder) = n.div(d, round_up); let result = if round_up && !remainder.is_zero() { quotient.add(U256Muldiv::new(0, 1)) } else { quotient }; result.try_into_u128() } #[cfg(test)] mod fuzz_tests { use crate::math::U256; use super::*; use proptest::prelude::*; proptest! { #[test] fn test_div_round_up_if( n in 0..u128::MAX, d in 0..u128::MAX, ) { let rounded = div_round_up(n, d); if d == 0 { assert!(rounded.is_err()); } else { let unrounded = n / d; let div_unrounded = div_round_up_if(n, d, false).unwrap(); let diff = rounded.unwrap() - unrounded; assert!(unrounded == div_unrounded); assert!(diff <= 1); assert!((diff == 1) == (n % d > 0)); } } #[test] fn test_div_round_up_if_u256( n_hi in 0..u128::MAX, n_lo in 0..u128::MAX, d_hi in 0..u128::MAX, d_lo in 0..u128::MAX, ) { let dividend = U256Muldiv::new(n_hi, n_lo); let divisor = U256Muldiv::new(d_hi, d_lo); let rounded = div_round_up_if_u256(dividend, divisor, true); let (quotient, _) = dividend.div(divisor, true); if quotient.try_into_u128().is_err() { assert!(rounded.is_err()); } else { let other_dividend = (U256::from(n_hi) << 128) + U256::from(n_lo); let other_divisor = (U256::from(d_hi) << 128) + U256::from(d_lo); let other_quotient = other_dividend / other_divisor; let other_remainder = other_dividend % other_divisor; let unrounded = div_round_up_if_u256(dividend, divisor, false); assert!(unrounded.unwrap() == other_quotient.try_into_u128().unwrap()); let diff = rounded.unwrap() - unrounded.unwrap(); assert!(diff <= 1); assert!((diff == 1) == (other_remainder > U256::zero())); } } #[test] fn test_checked_mul_div_round_up_if(n0 in 0..u128::MAX, n1 in 0..u128::MAX, d in 0..u128::MAX) { let result = checked_mul_div_round_up_if(n0, n1, d, true); if d == 0 || n0.checked_mul(n1).is_none() { assert!(result.is_err()); } else { let other_n0 = U256::from(n0); let other_n1 = U256::from(n1); let other_p = other_n0 * other_n1; let other_d = U256::from(d); let other_result = other_p / other_d; let unrounded = checked_mul_div_round_up_if(n0, n1, d, false).unwrap(); assert!(U256::from(unrounded) == other_result); let diff = U256::from(result.unwrap()) - other_result; assert!(diff <= U256::from(1)); assert!((diff == U256::from(1)) == (other_p % other_d > U256::from(0))); } } #[test] fn test_mul_shift_right_round_up_if(n0 in 0..u128::MAX, n1 in 0..u128::MAX) { let result = checked_mul_shift_right_round_up_if(n0, n1, true); if n0.checked_mul(n1).is_none() { assert!(result.is_err()); } else { let p = (U256::from(n0) * U256::from(n1)).try_into_u128().unwrap(); let i = (p >> 64) as u64; assert!(i == checked_mul_shift_right_round_up_if(n0, n1, false).unwrap()); if i == u64::MAX && (p & Q64_MASK > 0) { assert!(result.is_err()); } else { let diff = result.unwrap() - i; assert!(diff <= 1); assert!((diff == 1) == (p % (u64::MAX as u128) > 0)); } } } } } #[cfg(test)] mod test_bit_math { // We arbitrarily select integers a, b, d < 2^128 - 1, such that 2^128 - 1 < (a * b / d) < 2^128 // For simplicity we fix d = 2 and the target to be 2^128 - 0.5 // We then solve for a * b = 2^129 - 1 const MAX_FLOOR: (u128, u128, u128) = (11053036065049294753459639, 61572651155449, 2); mod test_mul_div { use crate::math::checked_mul_div; use super::MAX_FLOOR; #[test] fn test_mul_div_ok() { assert_eq!(checked_mul_div(150, 30, 3).unwrap(), 1500); assert_eq!(checked_mul_div(15, 0, 10).unwrap(), 0); } #[test] fn test_mul_div_shift_ok() { assert_eq!(checked_mul_div(u128::MAX, 1, 2).unwrap(), u128::MAX >> 1); assert_eq!(checked_mul_div(u128::MAX, 1, 4).unwrap(), u128::MAX >> 2); assert_eq!(checked_mul_div(u128::MAX, 1, 8).unwrap(), u128::MAX >> 3); assert_eq!(checked_mul_div(u128::MAX, 1, 16).unwrap(), u128::MAX >> 4); assert_eq!(checked_mul_div(u128::MAX, 1, 32).unwrap(), u128::MAX >> 5); assert_eq!(checked_mul_div(u128::MAX, 1, 64).unwrap(), u128::MAX >> 6); } #[test] fn test_mul_div_large_ok() { assert_eq!( checked_mul_div(u128::MAX, 1, u128::from(u64::MAX) + 1).unwrap(), u64::MAX.into() ); assert_eq!(checked_mul_div(u128::MAX - 1, 1, u128::MAX).unwrap(), 0); } #[test] fn test_mul_div_overflows() { assert!(checked_mul_div(u128::MAX, 2, u128::MAX).is_err()); assert!(checked_mul_div(u128::MAX, u128::MAX, u128::MAX).is_err()); assert!(checked_mul_div(u128::MAX, u128::MAX - 1, u128::MAX).is_err()); assert!(checked_mul_div(u128::MAX, 2, 1).is_err()); assert!(checked_mul_div(MAX_FLOOR.0, MAX_FLOOR.1, MAX_FLOOR.2).is_err()); } #[test] fn test_mul_div_does_not_round() { assert_eq!(checked_mul_div(3, 7, 10).unwrap(), 2); assert_eq!( checked_mul_div(u128::MAX, 1, 7).unwrap(), 48611766702991209066196372490252601636 ); } } mod test_mul_div_round_up { use crate::math::checked_mul_div_round_up; use super::MAX_FLOOR; #[test] fn test_mul_div_ok() { assert_eq!(checked_mul_div_round_up(0, 4, 4).unwrap(), 0); assert_eq!(checked_mul_div_round_up(2, 4, 4).unwrap(), 2); assert_eq!(checked_mul_div_round_up(3, 7, 21).unwrap(), 1); } #[test] fn test_mul_div_rounding_up_rounds_up() { assert_eq!(checked_mul_div_round_up(3, 7, 10).unwrap(), 3); assert_eq!( checked_mul_div_round_up(u128::MAX, 1, 7).unwrap(), 48611766702991209066196372490252601637 ); assert_eq!( checked_mul_div_round_up(u128::MAX - 1, 1, u128::MAX).unwrap(), 1 ); } #[test] #[should_panic] fn test_mul_div_rounding_upfloor_max_panics() { assert_eq!( checked_mul_div_round_up(MAX_FLOOR.0, MAX_FLOOR.1, MAX_FLOOR.2).unwrap(), u128::MAX ); } #[test] fn test_mul_div_overflow_panics() { assert!(checked_mul_div_round_up(u128::MAX, u128::MAX, 1u128).is_err()); } } mod test_div_round_up { use crate::math::div_round_up; #[test] fn test_mul_div_ok() { assert_eq!(div_round_up(0, 21).unwrap(), 0); assert_eq!(div_round_up(21, 21).unwrap(), 1); assert_eq!(div_round_up(8, 4).unwrap(), 2); } #[test] fn test_mul_div_rounding_up_rounds_up() { assert_eq!(div_round_up(21, 10).unwrap(), 3); assert_eq!( div_round_up(u128::MAX, 7).unwrap(), 48611766702991209066196372490252601637 ); assert_eq!(div_round_up(u128::MAX - 1, u128::MAX).unwrap(), 1); } } mod test_mult_shift_right_round_up { use crate::math::checked_mul_shift_right_round_up_if; #[test] fn test_mul_shift_right_ok() { assert_eq!( checked_mul_shift_right_round_up_if(u64::MAX as u128, 1, false).unwrap(), 0 ); assert_eq!( checked_mul_shift_right_round_up_if(u64::MAX as u128, 1, true).unwrap(), 1 ); assert_eq!( checked_mul_shift_right_round_up_if(u64::MAX as u128 + 1, 1, false).unwrap(), 1 ); assert_eq!( checked_mul_shift_right_round_up_if(u64::MAX as u128 + 1, 1, true).unwrap(), 1 ); assert_eq!( checked_mul_shift_right_round_up_if(u32::MAX as u128, u32::MAX as u128, false) .unwrap(), 0 ); assert_eq!( checked_mul_shift_right_round_up_if(u32::MAX as u128, u32::MAX as u128, true) .unwrap(), 1 ); assert_eq!( checked_mul_shift_right_round_up_if( u32::MAX as u128 + 1, u32::MAX as u128 + 2, false ) .unwrap(), 1 ); assert_eq!( checked_mul_shift_right_round_up_if( u32::MAX as u128 + 1, u32::MAX as u128 + 2, true ) .unwrap(), 2 ); } #[test] fn test_mul_shift_right_u64_max() { assert!(checked_mul_shift_right_round_up_if(u128::MAX, 1, true).is_err()); assert_eq!( checked_mul_shift_right_round_up_if(u128::MAX, 1, false).unwrap(), u64::MAX ); } } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/bn.rs
#![allow(clippy::assign_op_pattern)] #![allow(clippy::ptr_offset_with_cast)] #![allow(clippy::manual_range_contains)] /// The following code is referenced from drift-labs: /// https://github.com/drift-labs/protocol-v1/blob/3da78f1f03b66a273fc50818323ac62874abd1d8/programs/clearing_house/src/math/bn.rs /// /// Based on parity's uint crate /// https://github.com/paritytech/parity-common/tree/master/uint /// /// Note: We cannot use U256 from primitive-types (default u256 from parity's uint) because we need to extend the U256 struct to /// support the Borsh serial/deserialize traits. /// /// The reason why this custom U256 impl does not directly impl TryInto traits is because of this: /// https://stackoverflow.com/questions/37347311/how-is-there-a-conflicting-implementation-of-from-when-using-a-generic-type /// /// As a result, we have to define our own custom Into methods /// /// U256 reference: /// https://crates.parity.io/sp_core/struct.U256.html /// use borsh09::{BorshDeserialize, BorshSerialize}; use std::borrow::BorrowMut; use std::convert::TryInto; use std::io::{Error, ErrorKind, Write}; use std::mem::size_of; use uint::construct_uint; use crate::errors::ErrorCode; macro_rules! impl_borsh_serialize_for_bn { ($type: ident) => { impl BorshSerialize for $type { #[inline] fn serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> { let bytes = self.to_le_bytes(); writer.write_all(&bytes) } } }; } macro_rules! impl_borsh_deserialize_for_bn { ($type: ident) => { impl BorshDeserialize for $type { #[inline] fn deserialize(buf: &mut &[u8]) -> std::io::Result<Self> { if buf.len() < size_of::<$type>() { return Err(Error::new( ErrorKind::InvalidInput, "Unexpected length of input", )); } let res = $type::from_le_bytes(buf[..size_of::<$type>()].try_into().unwrap()); *buf = &buf[size_of::<$type>()..]; Ok(res) } } }; } construct_uint! { // U256 of [u64; 4] pub struct U256(4); } impl U256 { pub fn try_into_u64(self) -> Result<u64, ErrorCode> { self.try_into().map_err(|_| ErrorCode::NumberCastError) } pub fn try_into_u128(self) -> Result<u128, ErrorCode> { self.try_into().map_err(|_| ErrorCode::NumberCastError) } pub fn from_le_bytes(bytes: [u8; 32]) -> Self { U256::from_little_endian(&bytes) } pub fn to_le_bytes(self) -> [u8; 32] { let mut buf: Vec<u8> = Vec::with_capacity(size_of::<Self>()); self.to_little_endian(buf.borrow_mut()); let mut bytes: [u8; 32] = [0u8; 32]; bytes.copy_from_slice(buf.as_slice()); bytes } } impl_borsh_deserialize_for_bn!(U256); impl_borsh_serialize_for_bn!(U256); #[cfg(test)] mod test_u256 { use super::*; #[test] fn test_into_u128_ok() { let a = U256::from(2653u128); let b = U256::from(1232u128); let sum = a + b; let d: u128 = sum.try_into_u128().unwrap(); assert_eq!(d, 3885u128); } #[test] fn test_into_u128_error() { let a = U256::from(u128::MAX); let b = U256::from(u128::MAX); let sum = a + b; let c: Result<u128, ErrorCode> = sum.try_into_u128(); assert!(c.is_err()); } #[test] fn test_as_u128_ok() { let a = U256::from(2653u128); let b = U256::from(1232u128); let sum = a + b; let d: u128 = sum.as_u128(); assert_eq!(d, 3885u128); } #[test] #[should_panic(expected = "Integer overflow when casting to u128")] fn test_as_u128_panic() { let a = U256::from(u128::MAX); let b = U256::from(u128::MAX); let sum = a + b; let _: u128 = sum.as_u128(); } #[test] fn test_into_u64_ok() { let a = U256::from(2653u64); let b = U256::from(1232u64); let sum = a + b; let d: u64 = sum.try_into_u64().unwrap(); assert_eq!(d, 3885u64); } #[test] fn test_into_u64_error() { let a = U256::from(u64::MAX); let b = U256::from(u64::MAX); let sum = a + b; let c: Result<u64, ErrorCode> = sum.try_into_u64(); assert!(c.is_err()); } #[test] fn test_as_u64_ok() { let a = U256::from(2653u64); let b = U256::from(1232u64); let sum = a + b; let d: u64 = sum.as_u64(); assert_eq!(d, 3885u64); } #[test] #[should_panic(expected = "Integer overflow when casting to u64")] fn test_as_u64_panic() { let a = U256::from(u64::MAX); let b = U256::from(u64::MAX); let sum = a + b; let _: u64 = sum.as_u64(); // panic overflow } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/u256_math.rs
use std::{ cmp::Ordering, fmt::{Display, Formatter, Result as FmtResult}, str::from_utf8_unchecked, }; use crate::errors::ErrorCode; const NUM_WORDS: usize = 4; #[derive(Copy, Clone, Debug)] pub struct U256Muldiv { pub items: [u64; NUM_WORDS], } impl U256Muldiv { pub fn new(h: u128, l: u128) -> Self { U256Muldiv { items: [l.lo(), l.hi(), h.lo(), h.hi()], } } fn copy(&self) -> Self { let mut items: [u64; NUM_WORDS] = [0; NUM_WORDS]; items.copy_from_slice(&self.items); U256Muldiv { items } } fn update_word(&mut self, index: usize, value: u64) { self.items[index] = value; } fn num_words(&self) -> usize { for i in (0..self.items.len()).rev() { if self.items[i] != 0 { return i + 1; } } 0 } pub fn get_word(&self, index: usize) -> u64 { self.items[index] } pub fn get_word_u128(&self, index: usize) -> u128 { self.items[index] as u128 } // Logical-left shift, does not trigger overflow pub fn shift_word_left(&self) -> Self { let mut result = U256Muldiv::new(0, 0); for i in (0..NUM_WORDS - 1).rev() { result.items[i + 1] = self.items[i]; } result } pub fn checked_shift_word_left(&self) -> Option<Self> { let last_element = self.items.last(); match last_element { None => Some(self.shift_word_left()), Some(element) => { if *element > 0 { None } else { Some(self.shift_word_left()) } } } } // Logical-left shift, does not trigger overflow pub fn shift_left(&self, mut shift_amount: u32) -> Self { // Return 0 if shift is greater than number of bits if shift_amount >= U64_RESOLUTION * (NUM_WORDS as u32) { return U256Muldiv::new(0, 0); } let mut result = self.copy(); while shift_amount >= U64_RESOLUTION { result = result.shift_word_left(); shift_amount -= U64_RESOLUTION; } if shift_amount == 0 { return result; } for i in (1..NUM_WORDS).rev() { result.items[i] = result.items[i] << shift_amount | result.items[i - 1] >> (U64_RESOLUTION - shift_amount); } result.items[0] <<= shift_amount; result } // Logical-right shift, does not trigger overflow pub fn shift_word_right(&self) -> Self { let mut result = U256Muldiv::new(0, 0); for i in 0..NUM_WORDS - 1 { result.items[i] = self.items[i + 1] } result } // Logical-right shift, does not trigger overflow pub fn shift_right(&self, mut shift_amount: u32) -> Self { // Return 0 if shift is greater than number of bits if shift_amount >= U64_RESOLUTION * (NUM_WORDS as u32) { return U256Muldiv::new(0, 0); } let mut result = self.copy(); while shift_amount >= U64_RESOLUTION { result = result.shift_word_right(); shift_amount -= U64_RESOLUTION; } if shift_amount == 0 { return result; } for i in 0..NUM_WORDS - 1 { result.items[i] = result.items[i] >> shift_amount | result.items[i + 1] << (U64_RESOLUTION - shift_amount); } result.items[3] >>= shift_amount; result } #[allow(clippy::should_implement_trait)] pub fn eq(&self, other: U256Muldiv) -> bool { for i in 0..self.items.len() { if self.items[i] != other.items[i] { return false; } } true } pub fn lt(&self, other: U256Muldiv) -> bool { for i in (0..self.items.len()).rev() { match self.items[i].cmp(&other.items[i]) { Ordering::Less => return true, Ordering::Greater => return false, Ordering::Equal => {} } } false } pub fn gt(&self, other: U256Muldiv) -> bool { for i in (0..self.items.len()).rev() { match self.items[i].cmp(&other.items[i]) { Ordering::Less => return false, Ordering::Greater => return true, Ordering::Equal => {} } } false } pub fn lte(&self, other: U256Muldiv) -> bool { for i in (0..self.items.len()).rev() { match self.items[i].cmp(&other.items[i]) { Ordering::Less => return true, Ordering::Greater => return false, Ordering::Equal => {} } } true } pub fn gte(&self, other: U256Muldiv) -> bool { for i in (0..self.items.len()).rev() { match self.items[i].cmp(&other.items[i]) { Ordering::Less => return false, Ordering::Greater => return true, Ordering::Equal => {} } } true } pub fn try_into_u128(&self) -> Result<u128, ErrorCode> { if self.num_words() > 2 { return Err(ErrorCode::NumberDownCastError); } Ok((self.items[1] as u128) << U64_RESOLUTION | (self.items[0] as u128)) } pub fn is_zero(self) -> bool { for i in 0..NUM_WORDS { if self.items[i] != 0 { return false; } } true } // Input: // m = U256::MAX + 1 (which is the amount used for overflow) // n = input value // Output: // r = smallest positive additive inverse of n mod m // // We wish to find r, s.t., r + n ≡ 0 mod m; // We generally wish to find this r since r ≡ -n mod m // and can make operations with n with large number of bits // fit into u256 space without overflow pub fn get_add_inverse(&self) -> Self { // Additive inverse of 0 is 0 if self.eq(U256Muldiv::new(0, 0)) { return U256Muldiv::new(0, 0); } // To ensure we don't overflow, we begin with max and do a subtraction U256Muldiv::new(u128::MAX, u128::MAX) .sub(*self) .add(U256Muldiv::new(0, 1)) } // Result overflows if the result is greater than 2^256-1 pub fn add(&self, other: U256Muldiv) -> Self { let mut result = U256Muldiv::new(0, 0); let mut carry = 0; for i in 0..NUM_WORDS { let x = self.get_word_u128(i); let y = other.get_word_u128(i); let t = x + y + carry; result.update_word(i, t.lo()); carry = t.hi_u128(); } result } // Result underflows if the result is greater than 2^256-1 pub fn sub(&self, other: U256Muldiv) -> Self { let mut result = U256Muldiv::new(0, 0); let mut carry = 0; for i in 0..NUM_WORDS { let x = self.get_word(i); let y = other.get_word(i); let (t0, overflowing0) = x.overflowing_sub(y); let (t1, overflowing1) = t0.overflowing_sub(carry); result.update_word(i, t1); carry = if overflowing0 || overflowing1 { 1 } else { 0 }; } result } // Result overflows if great than 2^256-1 pub fn mul(&self, other: U256Muldiv) -> Self { let mut result = U256Muldiv::new(0, 0); let m = self.num_words(); let n = other.num_words(); for j in 0..n { let mut k = 0; for i in 0..m { let x = self.get_word_u128(i); let y = other.get_word_u128(j); if i + j < NUM_WORDS { let z = result.get_word_u128(i + j); let t = x.wrapping_mul(y).wrapping_add(z).wrapping_add(k); result.update_word(i + j, t.lo()); k = t.hi_u128(); } } // Don't update the carry word if j + m < NUM_WORDS { result.update_word(j + m, k as u64); } } result } // Result returns 0 if divide by zero pub fn div(&self, mut divisor: U256Muldiv, return_remainder: bool) -> (Self, Self) { let mut dividend = self.copy(); let mut quotient = U256Muldiv::new(0, 0); let num_dividend_words = dividend.num_words(); let num_divisor_words = divisor.num_words(); if num_divisor_words == 0 { panic!("divide by zero"); } // Case 0. If either the dividend or divisor is 0, return 0 if num_dividend_words == 0 { return (U256Muldiv::new(0, 0), U256Muldiv::new(0, 0)); } // Case 1. Dividend is smaller than divisor, quotient = 0, remainder = dividend if num_dividend_words < num_divisor_words { if return_remainder { return (U256Muldiv::new(0, 0), dividend); } else { return (U256Muldiv::new(0, 0), U256Muldiv::new(0, 0)); } } // Case 2. Dividend is smaller than u128, divisor <= dividend, perform math in u128 space if num_dividend_words < 3 { let dividend = dividend.try_into_u128().unwrap(); let divisor = divisor.try_into_u128().unwrap(); let quotient = dividend / divisor; if return_remainder { let remainder = dividend % divisor; return (U256Muldiv::new(0, quotient), U256Muldiv::new(0, remainder)); } else { return (U256Muldiv::new(0, quotient), U256Muldiv::new(0, 0)); } } // Case 3. Divisor is single-word, we must isolate this case for correctness if num_divisor_words == 1 { let mut k = 0; for j in (0..num_dividend_words).rev() { let d1 = hi_lo(k.lo(), dividend.get_word(j)); let d2 = divisor.get_word_u128(0); let q = d1 / d2; k = d1 - d2 * q; quotient.update_word(j, q.lo()); } if return_remainder { return (quotient, U256Muldiv::new(0, k)); } else { return (quotient, U256Muldiv::new(0, 0)); } } // Normalize the division by shifting left let s = divisor.get_word(num_divisor_words - 1).leading_zeros(); let b = dividend.get_word(num_dividend_words - 1).leading_zeros(); // Conditional carry space for normalized division let mut dividend_carry_space: u64 = 0; if num_dividend_words == NUM_WORDS && b < s { dividend_carry_space = dividend.items[num_dividend_words - 1] >> (U64_RESOLUTION - s); } dividend = dividend.shift_left(s); divisor = divisor.shift_left(s); for j in (0..num_dividend_words - num_divisor_words + 1).rev() { let result = div_loop( j, num_divisor_words, dividend, &mut dividend_carry_space, divisor, quotient, ); quotient = result.0; dividend = result.1; } if return_remainder { dividend = dividend.shift_right(s); (quotient, dividend) } else { (quotient, U256Muldiv::new(0, 0)) } } } impl Display for U256Muldiv { fn fmt(&self, f: &mut Formatter) -> FmtResult { let mut buf = [0_u8; NUM_WORDS * 20]; let mut i = buf.len() - 1; let ten = U256Muldiv::new(0, 10); let mut current = *self; loop { let (quotient, remainder) = current.div(ten, true); let digit = remainder.get_word(0) as u8; buf[i] = digit + b'0'; current = quotient; if current.is_zero() { break; } i -= 1; } let s = unsafe { from_utf8_unchecked(&buf[i..]) }; f.write_str(s) } } const U64_MAX: u128 = u64::MAX as u128; const U64_RESOLUTION: u32 = 64; pub trait LoHi { fn lo(self) -> u64; fn hi(self) -> u64; fn lo_u128(self) -> u128; fn hi_u128(self) -> u128; } impl LoHi for u128 { fn lo(self) -> u64 { (self & U64_MAX) as u64 } fn lo_u128(self) -> u128 { self & U64_MAX } fn hi(self) -> u64 { (self >> U64_RESOLUTION) as u64 } fn hi_u128(self) -> u128 { self >> U64_RESOLUTION } } pub fn hi_lo(hi: u64, lo: u64) -> u128 { (hi as u128) << U64_RESOLUTION | (lo as u128) } pub fn mul_u256(v: u128, n: u128) -> U256Muldiv { // do 128 bits multiply // nh nl // * vh vl // ---------- // a0 = vl * nl // a1 = vl * nh // b0 = vh * nl // b1 = + vh * nh // ------------------- // c1h c1l c0h c0l // // "a0" is optimized away, result is stored directly in c0. "b1" is // optimized away, result is stored directly in c1. // let mut c0 = v.lo_u128() * n.lo_u128(); let a1 = v.lo_u128() * n.hi_u128(); let b0 = v.hi_u128() * n.lo_u128(); // add the high word of a0 to the low words of a1 and b0 using c1 as // scrach space to capture the carry. the low word of the result becomes // the final high word of c0 let mut c1 = c0.hi_u128() + a1.lo_u128() + b0.lo_u128(); c0 = hi_lo(c1.lo(), c0.lo()); // add the carry from the result above (found in the high word of c1) and // the high words of a1 and b0 to b1, the result is c1. c1 = v.hi_u128() * n.hi_u128() + c1.hi_u128() + a1.hi_u128() + b0.hi_u128(); U256Muldiv::new(c1, c0) } fn div_loop( index: usize, num_divisor_words: usize, mut dividend: U256Muldiv, dividend_carry_space: &mut u64, divisor: U256Muldiv, mut quotient: U256Muldiv, ) -> (U256Muldiv, U256Muldiv) { let use_carry = (index + num_divisor_words) == NUM_WORDS; let div_hi = if use_carry { *dividend_carry_space } else { dividend.get_word(index + num_divisor_words) }; let d0 = hi_lo(div_hi, dividend.get_word(index + num_divisor_words - 1)); let d1 = divisor.get_word_u128(num_divisor_words - 1); let mut qhat = d0 / d1; let mut rhat = d0 - d1 * qhat; let d0_2 = dividend.get_word(index + num_divisor_words - 2); let d1_2 = divisor.get_word_u128(num_divisor_words - 2); let mut cmp1 = hi_lo(rhat.lo(), d0_2); let mut cmp2 = qhat.wrapping_mul(d1_2); while qhat.hi() != 0 || cmp2 > cmp1 { qhat -= 1; rhat += d1; if rhat.hi() != 0 { break; } cmp1 = hi_lo(rhat.lo(), cmp1.lo()); cmp2 -= d1_2; } let mut k = 0; let mut t; for i in 0..num_divisor_words { let p = qhat * (divisor.get_word_u128(i)); t = (dividend.get_word_u128(index + i)) .wrapping_sub(k) .wrapping_sub(p.lo_u128()); dividend.update_word(index + i, t.lo()); k = ((p >> U64_RESOLUTION) as u64).wrapping_sub((t >> U64_RESOLUTION) as u64) as u128; } let d_head = if use_carry { *dividend_carry_space as u128 } else { dividend.get_word_u128(index + num_divisor_words) }; t = d_head.wrapping_sub(k); if use_carry { *dividend_carry_space = t.lo(); } else { dividend.update_word(index + num_divisor_words, t.lo()); } if k > d_head { qhat -= 1; k = 0; for i in 0..num_divisor_words { t = dividend .get_word_u128(index + i) .wrapping_add(divisor.get_word_u128(i)) .wrapping_add(k); dividend.update_word(index + i, t.lo()); k = t >> U64_RESOLUTION; } let new_carry = dividend .get_word_u128(index + num_divisor_words) .wrapping_add(k) .lo(); if use_carry { *dividend_carry_space = new_carry } else { dividend.update_word( index + num_divisor_words, dividend .get_word_u128(index + num_divisor_words) .wrapping_add(k) .lo(), ); } } quotient.update_word(index, qhat.lo()); (quotient, dividend) } #[cfg(test)] mod fuzz_tests { use proptest::prelude::*; use crate::math::{mul_u256, U256Muldiv, U256}; fn assert_equality(n0: U256Muldiv, n1: U256) { assert_eq!(n0.get_word(0), n1.0[0], "failed: 0"); assert_eq!(n0.get_word(1), n1.0[1], "failed: 1"); assert_eq!(n0.get_word(2), n1.0[2], "failed: 2"); assert_eq!(n0.get_word(3), n1.0[3], "failed: 3"); } proptest! { #[test] fn test_lt(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.lt(n1); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); let other_result = other_n0 < other_n1; assert_eq!(result, other_result); } #[test] fn test_gt(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.gt(n1); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); let other_result = other_n0 > other_n1; assert_eq!(result, other_result); } #[test] fn test_lte(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.lte(n1); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); let other_result = other_n0 <= other_n1; assert_eq!(result, other_result); } #[test] fn test_gte(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.gte(n1); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); let other_result = other_n0 >= other_n1; // Should always be >= to itself assert!(n0.gte(n0)); // Should be equivalent to u256 operation assert_eq!(result, other_result); } #[test] fn test_eq(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result_self = n0.eq(n0); let result = n0.eq(n1); let result2 = n1.eq(n0); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); let other_result = other_n0 == other_n1; // Should always be = to itself assert!(result_self); // Should be equivalent to using u256 space assert_eq!(result, other_result); assert_eq!(result2, other_result); // Property should be symmetric, n0.eq(n1) == n1.eq(n0) assert_eq!(result, result2); } #[test] fn test_div(dividend_hi in 0..u128::MAX, dividend_lo in 0..u128::MAX, divisor_hi in 0..u128::MAX, divisor_lo in 0..u128::MAX) { let dividend = U256Muldiv::new(dividend_hi, dividend_lo); let divisor = U256Muldiv::new(divisor_hi, divisor_lo); let result = dividend.div(divisor, false).0; let other_dividend = (U256::from(dividend_hi) << 128) + U256::from(dividend_lo); let other_divisor = (U256::from(divisor_hi) << 128) + U256::from(divisor_lo); let other_result = other_dividend / other_divisor; assert_equality(result, other_result); } #[test] fn test_add(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.add(n1); let result2 = n1.add(n0); let add_zero = n0.add(U256Muldiv::new(0, 0)); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); // Assert addition is symmetric assert!(result.eq(result2)); // Adding 0 is no-op assert!(n0.eq(add_zero)); match other_n0.checked_add(other_n1) { Some(other_result) => { // Assert results equal to addition in U256 space assert_equality(result, other_result); }, None => { // U256 has overflowed, we allow overflow, so the overflow amount should be (n0 + n1) mod (U256::MAX + 1) // Since we know that n0 + n1 >= U256::MAX + 1, their sum of additive inverses must be < U256::MAX + 1 // Thus we calculate neg_sum = -n0 + -n1 mod U256::MAX + 1 let add_inv_0 = n0.get_add_inverse(); let add_inv_1 = n1.get_add_inverse(); let neg_sum = add_inv_0.add(add_inv_1); // We then invert the neg_sum to get the expected overflow which should be the equivalent of n0 + n1 mod U256::MAX // without any overflowing operations let overflow = neg_sum.get_add_inverse(); assert!(result.eq(overflow)); }, } } #[test] fn test_overflow_equality(lo in 0..u128::MAX, hi in 0..u128::MAX) { let n0 = U256Muldiv::new(hi, lo); // Overflowing in either direction should be equivalent let n1 = n0.add(U256Muldiv::new(u128::MAX, u128::MAX)).add(U256Muldiv::new(0, 1)); let n2 = n0.sub(U256Muldiv::new(u128::MAX, u128::MAX)).sub(U256Muldiv::new(0, 1)); assert!(n0.eq(n1)); assert!(n0.eq(n2)); } #[test] fn test_sub(n0_lo in 0..u128::MAX, n0_hi in 0..u128::MAX, n1_lo in 0..u128::MAX, n1_hi in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.sub(n1); let result2 = n0.sub(U256Muldiv::new(0, 0)); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); // Subtracting zero is no-op assert!(result2.eq(n0)); match n0.gt(n1) { true => { let other_result = other_n0 - other_n1; assert_equality(result, other_result); }, false => { // n1 >= n0 so we know that n1 - n0 does not overflow // n1 - n0 ≡ -(n0 - n1) mod U256::MAX + 1 let neg = n1.sub(n0); let overflow = neg.get_add_inverse(); assert!(result.eq(overflow)); } } } #[test] fn test_fmt(n_lo in 0..u128::MAX, n_hi in 0..u128::MAX) { let n = U256Muldiv::new(n_hi, n_lo); let other_n = (U256::from(n_hi) << 128) + U256::from(n_lo); assert_eq!(format!("{}", n), format!("{}", other_n)); } #[test] fn test_mul_u256(n0 in 0..u128::MAX, n1 in 0..u128::MAX) { let result = mul_u256(n0, n1); let other_result = U256::from(n0) * U256::from(n1); assert_equality(result, other_result); } #[test] fn test_get_add_inv(n_hi in 0..u128::MAX, n_lo in 0..u128::MAX) { let n = U256Muldiv::new(n_hi, n_lo); let inverse = n.get_add_inverse(); let result = n.add(inverse); assert!(result.eq(U256Muldiv::new(0, 0))); } #[test] fn test_shift_right(n_hi in 1..u128::MAX, n_lo in 0..u128::MAX, shift_amount in 1u32..128) { let n = U256Muldiv::new(n_hi, n_lo); let result = n.shift_right(shift_amount); let other_n = (U256::from(n_hi) << 128) + U256::from(n_lo); let other_result = other_n >> shift_amount; assert_equality(result, other_result); } #[test] fn test_shift_left(n_hi in 0u128..(u32::MAX as u128), n_lo in 0..u128::MAX, shift_amount in 1u32..96) { let n = U256Muldiv::new(n_hi, n_lo); let result = n.shift_left(shift_amount); let other_n = (U256::from(n_hi) << 128) + U256::from(n_lo); let other_result = other_n << shift_amount; assert_equality(result, other_result); } #[test] fn test_checked_shift_word_left(n_hi in 0u128..(u64::MAX as u128), n_lo in 0..u128::MAX) { let n = U256Muldiv::new(n_hi, n_lo); let result = n.checked_shift_word_left(); let other_n = (U256::from(n_hi) << 128) + U256::from(n_lo); let other_result = other_n << 64; let final_result = result.unwrap(); assert_equality(final_result, other_result); } #[test] fn test_checked_shift_word_left_overflow(n_hi in u64::MAX as u128..u128::MAX, n_lo in 0..u128::MAX) { let n = U256Muldiv::new(n_hi, n_lo); let result = n.checked_shift_word_left(); assert!(result.is_none()) } #[test] fn test_mul(n0_hi in 0..u128::MAX, n0_lo in 0..u128::MAX, n1_hi in 0..u128::MAX, n1_lo in 0..u128::MAX) { let n0 = U256Muldiv::new(n0_hi, n0_lo); let n1 = U256Muldiv::new(n1_hi, n1_lo); let result = n0.mul(n1); let other_n0 = (U256::from(n0_hi) << 128) + U256::from(n0_lo); let other_n1 = (U256::from(n1_hi) << 128) + U256::from(n1_lo); match other_n0.checked_mul(other_n1) { Some(other_result) => { // Assert results equal to addition in U256 space assert_equality(result, other_result); }, None => { // The intention here is to enforce that the total number of bits <= 256 // If either of the values are larger than 2 words, we use the additive inverse // which is congruent to the negative value mod U256::MAX + 1 // We are guaranteed that at least one of the values is > 2 words since we have overflowed let should_inv_n0 = n0.num_words() > 2; let should_inv_n1 = n1.num_words() > 2; let maybe_inv_n0 = if should_inv_n0 { n0.get_add_inverse() } else { n0 }; let maybe_inv_n1 = if should_inv_n1 { n1.get_add_inverse() } else { n1 }; let prod = maybe_inv_n0.mul(maybe_inv_n1); let overflow = if should_inv_n0 == should_inv_n1 { // If we have inverted both n0 and n1, the inversions cancel out prod } else { // Otherwise, invert the product again prod.get_add_inverse() }; assert!(result.eq(overflow)); }, } } } } #[cfg(test)] mod test_add { use crate::math::U256Muldiv; #[test] fn test_add_overflow_0() { let n0 = U256Muldiv::new(u128::MAX, u128::MAX); let n1 = n0.copy(); let result = n0.add(n1); assert!(result.eq(U256Muldiv::new(u128::MAX, u128::MAX - 1))); } #[test] fn test_add_overflow_1() { let n0 = U256Muldiv::new(u128::MAX, u128::MAX); let n1 = U256Muldiv::new(0, 1); let result = n0.add(n1); assert!(result.eq(U256Muldiv::new(0, 0))); } } #[cfg(test)] mod test_sub { use crate::math::U256Muldiv; #[test] fn test_sub_underflow_0() { let n0 = U256Muldiv::new(u128::MAX, u128::MAX - 1); let n1 = U256Muldiv::new(u128::MAX, u128::MAX); let result = n0.sub(n1); assert!(result.eq(U256Muldiv::new(u128::MAX, u128::MAX))); } #[test] fn test_sub_underflow_1() { let n0 = U256Muldiv::new(0, 0); let n1 = U256Muldiv::new(0, 1); let result = n0.sub(n1); assert!(result.eq(U256Muldiv::new(u128::MAX, u128::MAX))); } } #[cfg(test)] mod test_div { use crate::math::U256; use super::U256Muldiv; #[test] fn test_div_0() { let dividend = U256Muldiv::new(50 << 64, 100 << 64); let divisor = U256Muldiv::new(0, 100 << 64); let result = dividend.div(divisor, true); let result2 = ((U256::from(50u128 << 64) << 128) + U256::from(100u128 << 64)) .div_mod(U256::from(100u128 << 64)); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_1() { let dividend = U256Muldiv::new(100, 100); let divisor = U256Muldiv::new(0, 50 << 64); let result = dividend.div(divisor, true); let result2 = ((U256::from(100u128) << 128) + U256::from(100u128)).div_mod(U256::from(50u128 << 64)); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_2() { let dividend = U256Muldiv::new(50, 100 << 64); let divisor = U256Muldiv::new(0, 100 << 64); let result = dividend.div(divisor, true); let result2 = ((U256::from(50u128) << 128) + U256::from(100u128 << 64)) .div_mod(U256::from(100u128 << 64)); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_3() { let dividend = U256Muldiv::new(50, 100 << 64); let divisor = U256Muldiv::new(0, 66); let result = dividend.div(divisor, true); let result2 = ((U256::from(50) << 128) + U256::from(100u128 << 64)).div_mod(U256::from(66u128)); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_4() { let dividend = U256Muldiv::new(100 << 64, 0); let divisor = U256Muldiv::new(1 << 63, u64::MAX as u128); let result = dividend.div(divisor, true); let result2 = (U256::from(100u128 << 64) << 128) .div_mod((U256::from(1u128 << 63) << 128) + U256::from(u64::MAX)); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_5() { let dividend = U256Muldiv::new(100 << 64, 0); let divisor = U256Muldiv::new(1 << 63, 0); let result = dividend.div(divisor, true); let result2 = (U256::from(100u128 << 64) << 128).div_mod(U256::from(1u128 << 63) << 128); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] fn test_div_6() { let dividend = U256Muldiv::new(1 << 63, 0); let divisor = U256Muldiv::new(1 << 63, 1); let result = dividend.div(divisor, true); let result2 = (U256::from(1u128 << 63) << 128).div_mod((U256::from(1u128 << 63) << 128) + 1); assert!(format!("{}", result.0) == format!("{}", result2.0)); assert!(format!("{}", result.1) == format!("{}", result2.1)); } #[test] #[should_panic(expected = "divide by zero")] fn test_div_7() { let dividend = U256Muldiv::new(1 << 63, 0); let divisor = U256Muldiv::new(0, 0); let _ = dividend.div(divisor, true); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/math/liquidity_math.rs
use crate::errors::ErrorCode; // Adds a signed liquidity delta to a given integer liquidity amount. // Errors on overflow or underflow. pub fn add_liquidity_delta(liquidity: u128, delta: i128) -> Result<u128, ErrorCode> { if delta == 0 { return Ok(liquidity); } if delta > 0 { liquidity .checked_add(delta as u128) .ok_or(ErrorCode::LiquidityOverflow) } else { liquidity .checked_sub(delta.unsigned_abs()) .ok_or(ErrorCode::LiquidityUnderflow) } } // Converts an unsigned liquidity amount to a signed liquidity delta pub fn convert_to_liquidity_delta( liquidity_amount: u128, positive: bool, ) -> Result<i128, ErrorCode> { if liquidity_amount > i128::MAX as u128 { // The liquidity_amount is converted to a liquidity_delta that is represented as an i128 // By doing this conversion we lose the most significant bit in the u128 // Here we enforce a max value of i128::MAX on the u128 to prevent loss of data. return Err(ErrorCode::LiquidityTooHigh); } Ok(if positive { liquidity_amount as i128 } else { -(liquidity_amount as i128) }) } #[cfg(test)] mod liquidity_math_tests { use super::add_liquidity_delta; use super::ErrorCode; #[test] fn test_valid_add_liquidity_delta() { assert_eq!(add_liquidity_delta(100, 100).unwrap(), 200); assert_eq!(add_liquidity_delta(100, 0).unwrap(), 100); assert_eq!(add_liquidity_delta(100, -100).unwrap(), 0); } #[test] fn test_invalid_add_liquidity_delta_overflow() { let result = add_liquidity_delta(u128::MAX, 1); assert_eq!(result.unwrap_err(), ErrorCode::LiquidityOverflow); } #[test] fn test_invalid_add_liquidity_delta_underflow() { let result = add_liquidity_delta(u128::MIN, -1); assert_eq!(result.unwrap_err(), ErrorCode::LiquidityUnderflow); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/tick_manager.rs
use crate::{ errors::ErrorCode, math::add_liquidity_delta, state::{Tick, TickUpdate, WhirlpoolRewardInfo, NUM_REWARDS}, }; pub fn next_tick_cross_update( tick: &Tick, fee_growth_global_a: u128, fee_growth_global_b: u128, reward_infos: &[WhirlpoolRewardInfo; NUM_REWARDS], ) -> Result<TickUpdate, ErrorCode> { let mut update = TickUpdate::from(tick); update.fee_growth_outside_a = fee_growth_global_a.wrapping_sub(tick.fee_growth_outside_a); update.fee_growth_outside_b = fee_growth_global_b.wrapping_sub(tick.fee_growth_outside_b); for (i, reward_info) in reward_infos.iter().enumerate() { if !reward_info.initialized() { continue; } update.reward_growths_outside[i] = reward_info .growth_global_x64 .wrapping_sub(tick.reward_growths_outside[i]); } Ok(update) } #[allow(clippy::too_many_arguments)] pub fn next_tick_modify_liquidity_update( tick: &Tick, tick_index: i32, tick_current_index: i32, fee_growth_global_a: u128, fee_growth_global_b: u128, reward_infos: &[WhirlpoolRewardInfo; NUM_REWARDS], liquidity_delta: i128, is_upper_tick: bool, ) -> Result<TickUpdate, ErrorCode> { // noop if there is no change in liquidity if liquidity_delta == 0 { return Ok(TickUpdate::from(tick)); } let liquidity_gross = add_liquidity_delta(tick.liquidity_gross, liquidity_delta)?; // Update to an uninitialized tick if remaining liquidity is being removed if liquidity_gross == 0 { return Ok(TickUpdate::default()); } let (fee_growth_outside_a, fee_growth_outside_b, reward_growths_outside) = if tick.liquidity_gross == 0 { // By convention, assume all prior growth happened below the tick if tick_current_index >= tick_index { ( fee_growth_global_a, fee_growth_global_b, WhirlpoolRewardInfo::to_reward_growths(reward_infos), ) } else { (0, 0, [0; NUM_REWARDS]) } } else { ( tick.fee_growth_outside_a, tick.fee_growth_outside_b, tick.reward_growths_outside, ) }; let liquidity_net = if is_upper_tick { tick.liquidity_net .checked_sub(liquidity_delta) .ok_or(ErrorCode::LiquidityNetError)? } else { tick.liquidity_net .checked_add(liquidity_delta) .ok_or(ErrorCode::LiquidityNetError)? }; Ok(TickUpdate { initialized: true, liquidity_net, liquidity_gross, fee_growth_outside_a, fee_growth_outside_b, reward_growths_outside, }) } // Calculates the fee growths inside of tick_lower and tick_upper based on their // index relative to tick_current_index. pub fn next_fee_growths_inside( tick_current_index: i32, tick_lower: &Tick, tick_lower_index: i32, tick_upper: &Tick, tick_upper_index: i32, fee_growth_global_a: u128, fee_growth_global_b: u128, ) -> (u128, u128) { // By convention, when initializing a tick, all fees have been earned below the tick. let (fee_growth_below_a, fee_growth_below_b) = if !tick_lower.initialized { (fee_growth_global_a, fee_growth_global_b) } else if tick_current_index < tick_lower_index { ( fee_growth_global_a.wrapping_sub(tick_lower.fee_growth_outside_a), fee_growth_global_b.wrapping_sub(tick_lower.fee_growth_outside_b), ) } else { ( tick_lower.fee_growth_outside_a, tick_lower.fee_growth_outside_b, ) }; // By convention, when initializing a tick, no fees have been earned above the tick. let (fee_growth_above_a, fee_growth_above_b) = if !tick_upper.initialized { (0, 0) } else if tick_current_index < tick_upper_index { ( tick_upper.fee_growth_outside_a, tick_upper.fee_growth_outside_b, ) } else { ( fee_growth_global_a.wrapping_sub(tick_upper.fee_growth_outside_a), fee_growth_global_b.wrapping_sub(tick_upper.fee_growth_outside_b), ) }; ( fee_growth_global_a .wrapping_sub(fee_growth_below_a) .wrapping_sub(fee_growth_above_a), fee_growth_global_b .wrapping_sub(fee_growth_below_b) .wrapping_sub(fee_growth_above_b), ) } // Calculates the reward growths inside of tick_lower and tick_upper based on their positions // relative to tick_current_index. An uninitialized reward will always have a reward growth of zero. pub fn next_reward_growths_inside( tick_current_index: i32, tick_lower: &Tick, tick_lower_index: i32, tick_upper: &Tick, tick_upper_index: i32, reward_infos: &[WhirlpoolRewardInfo; NUM_REWARDS], ) -> [u128; NUM_REWARDS] { let mut reward_growths_inside = [0; NUM_REWARDS]; for i in 0..NUM_REWARDS { if !reward_infos[i].initialized() { continue; } // By convention, assume all prior growth happened below the tick let reward_growths_below = if !tick_lower.initialized { reward_infos[i].growth_global_x64 } else if tick_current_index < tick_lower_index { reward_infos[i] .growth_global_x64 .wrapping_sub(tick_lower.reward_growths_outside[i]) } else { tick_lower.reward_growths_outside[i] }; // By convention, assume all prior growth happened below the tick, not above let reward_growths_above = if !tick_upper.initialized { 0 } else if tick_current_index < tick_upper_index { tick_upper.reward_growths_outside[i] } else { reward_infos[i] .growth_global_x64 .wrapping_sub(tick_upper.reward_growths_outside[i]) }; reward_growths_inside[i] = reward_infos[i] .growth_global_x64 .wrapping_sub(reward_growths_below) .wrapping_sub(reward_growths_above); } reward_growths_inside } #[cfg(test)] mod tick_manager_tests { use anchor_lang::prelude::Pubkey; use crate::{ errors::ErrorCode, manager::tick_manager::{ next_fee_growths_inside, next_tick_cross_update, next_tick_modify_liquidity_update, TickUpdate, }, math::Q64_RESOLUTION, state::{tick_builder::TickBuilder, Tick, WhirlpoolRewardInfo, NUM_REWARDS}, }; use super::next_reward_growths_inside; fn create_test_whirlpool_reward_info( emissions_per_second_x64: u128, growth_global_x64: u128, initialized: bool, ) -> WhirlpoolRewardInfo { WhirlpoolRewardInfo { mint: if initialized { Pubkey::new_unique() } else { Pubkey::default() }, emissions_per_second_x64, growth_global_x64, ..Default::default() } } #[test] fn test_next_fee_growths_inside() { struct Test<'a> { name: &'a str, tick_current_index: i32, tick_lower: Tick, tick_lower_index: i32, tick_upper: Tick, tick_upper_index: i32, fee_growth_global_a: u128, fee_growth_global_b: u128, expected_fee_growths_inside: (u128, u128), } for test in [ Test { name: "current tick index below ticks", tick_current_index: -200, tick_lower: Tick { initialized: true, fee_growth_outside_a: 2000, fee_growth_outside_b: 1000, ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, fee_growth_outside_a: 1000, fee_growth_outside_b: 1000, ..Default::default() }, tick_upper_index: 100, fee_growth_global_a: 3000, fee_growth_global_b: 3000, expected_fee_growths_inside: (1000, 0), }, Test { name: "current tick index between ticks", tick_current_index: -20, tick_lower: Tick { initialized: true, fee_growth_outside_a: 2000, fee_growth_outside_b: 1000, ..Default::default() }, tick_lower_index: -20, tick_upper: Tick { initialized: true, fee_growth_outside_a: 1500, fee_growth_outside_b: 1000, ..Default::default() }, tick_upper_index: 100, fee_growth_global_a: 4000, fee_growth_global_b: 3000, expected_fee_growths_inside: (500, 1000), }, Test { name: "current tick index above ticks", tick_current_index: 200, tick_lower: Tick { initialized: true, fee_growth_outside_a: 2000, fee_growth_outside_b: 1000, ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, fee_growth_outside_a: 2500, fee_growth_outside_b: 2000, ..Default::default() }, tick_upper_index: 100, fee_growth_global_a: 3000, fee_growth_global_b: 3000, expected_fee_growths_inside: (500, 1000), }, ] { // System under test let (fee_growth_inside_a, fee_growth_inside_b) = next_fee_growths_inside( test.tick_current_index, &test.tick_lower, test.tick_lower_index, &test.tick_upper, test.tick_upper_index, test.fee_growth_global_a, test.fee_growth_global_b, ); assert_eq!( fee_growth_inside_a, test.expected_fee_growths_inside.0, "{} - fee_growth_inside_a", test.name ); assert_eq!( fee_growth_inside_b, test.expected_fee_growths_inside.1, "{} - fee_growth_inside_b", test.name ); } } #[test] fn test_next_reward_growths_inside() { struct Test<'a> { name: &'a str, tick_current_index: i32, tick_lower: Tick, tick_lower_index: i32, tick_upper: Tick, tick_upper_index: i32, reward_infos: [WhirlpoolRewardInfo; NUM_REWARDS], expected_reward_growths_inside: [u128; NUM_REWARDS], } for test in [ Test { name: "current tick index below ticks zero rewards", tick_lower: Tick { initialized: true, reward_growths_outside: [100, 666, 69420], ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, reward_growths_outside: [100, 666, 69420], ..Default::default() }, tick_upper_index: 100, tick_current_index: -200, reward_infos: [ create_test_whirlpool_reward_info(1, 500, true), create_test_whirlpool_reward_info(1, 1000, true), create_test_whirlpool_reward_info(1, 70000, true), ], expected_reward_growths_inside: [0, 0, 0], }, Test { name: "current tick index between ticks", tick_lower: Tick { initialized: true, reward_growths_outside: [200, 134, 480], ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, reward_growths_outside: [100, 666, 69420], ..Default::default() }, tick_upper_index: 100, tick_current_index: 10, reward_infos: [ create_test_whirlpool_reward_info(1, 1000, true), create_test_whirlpool_reward_info(1, 2000, true), create_test_whirlpool_reward_info(1, 80000, true), ], expected_reward_growths_inside: [700, 1200, 10100], }, Test { name: "current tick index above ticks", tick_lower: Tick { reward_growths_outside: [200, 134, 480], initialized: true, ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, reward_growths_outside: [900, 1334, 10580], ..Default::default() }, tick_upper_index: 100, tick_current_index: 250, reward_infos: [ create_test_whirlpool_reward_info(1, 1000, true), create_test_whirlpool_reward_info(1, 2000, true), create_test_whirlpool_reward_info(1, 80000, true), ], expected_reward_growths_inside: [700, 1200, 10100], }, Test { name: "uninitialized rewards no-op", tick_lower: Tick { initialized: true, reward_growths_outside: [200, 134, 480], ..Default::default() }, tick_lower_index: -100, tick_upper: Tick { initialized: true, reward_growths_outside: [900, 1334, 10580], ..Default::default() }, tick_upper_index: 100, tick_current_index: 250, reward_infos: [ create_test_whirlpool_reward_info(1, 1000, true), create_test_whirlpool_reward_info(1, 2000, false), create_test_whirlpool_reward_info(1, 80000, false), ], expected_reward_growths_inside: [700, 0, 0], }, ] { // System under test let results = next_reward_growths_inside( test.tick_current_index, &test.tick_lower, test.tick_lower_index, &test.tick_upper, test.tick_upper_index, &test.reward_infos, ); for (i, result) in results.iter().enumerate() { assert_eq!( *result, test.expected_reward_growths_inside[i], "[{}] {} - reward growth value not equal", i, test.name ); assert_eq!( *result, test.expected_reward_growths_inside[i], "[{}] {} - reward growth initialized flag not equal", i, test.name ); } } } #[test] fn test_next_tick_modify_liquidity_update() { #[derive(Default)] struct Test<'a> { name: &'a str, tick: Tick, tick_index: i32, tick_current_index: i32, fee_growth_global_a: u128, fee_growth_global_b: u128, reward_infos: [WhirlpoolRewardInfo; NUM_REWARDS], liquidity_delta: i128, is_upper_tick: bool, expected_update: TickUpdate, } // Whirlpool rewards re-used in the tests let reward_infos = [ WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1 << Q64_RESOLUTION, growth_global_x64: 100 << Q64_RESOLUTION, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1 << Q64_RESOLUTION, growth_global_x64: 100 << Q64_RESOLUTION, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1 << Q64_RESOLUTION, growth_global_x64: 100 << Q64_RESOLUTION, ..Default::default() }, ]; for test in [ Test { name: "initialize lower tick with +liquidity, current < tick.index, growths not set", tick: Tick::default(), tick_index: 200, tick_current_index: 100, liquidity_delta: 42069, is_upper_tick: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos, expected_update: TickUpdate { initialized: true, liquidity_net: 42069, liquidity_gross: 42069, ..Default::default() }, }, Test { name: "initialize lower tick with +liquidity, current >= tick.index, growths get set", tick: Tick::default(), tick_index: 200, tick_current_index: 300, liquidity_delta: 42069, is_upper_tick: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos, expected_update: TickUpdate { initialized: true, liquidity_net: 42069, liquidity_gross: 42069, fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [ 100 << Q64_RESOLUTION, 100 << Q64_RESOLUTION, 100 << Q64_RESOLUTION, ], }, }, Test { name: "lower tick +liquidity already initialized, growths not set", tick: TickBuilder::default() .initialized(true) .liquidity_net(100) .liquidity_gross(100) .build(), tick_index: 200, tick_current_index: 100, liquidity_delta: 42069, is_upper_tick: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos, expected_update: TickUpdate { initialized: true, liquidity_net: 42169, liquidity_gross: 42169, ..Default::default() }, }, Test { name: "upper tick +liquidity already initialized, growths not set, liquidity net should be subtracted", tick: TickBuilder::default() .initialized(true) .liquidity_net(100000) .liquidity_gross(100000) .build(), tick_index: 200, tick_current_index: 100, liquidity_delta: 42069, is_upper_tick: true, expected_update: TickUpdate { initialized: true, liquidity_net:57931, liquidity_gross: 142069, ..Default::default() }, ..Default::default() }, Test { name: "upper tick -liquidity, growths not set, uninitialize tick", tick: TickBuilder::default() .initialized(true) .liquidity_net(-100000) .liquidity_gross(100000) .build(), tick_index: 200, tick_current_index: 100, liquidity_delta: -100000, is_upper_tick: true, expected_update: TickUpdate { initialized: false, liquidity_net: 0, liquidity_gross: 0, ..Default::default() }, ..Default::default() }, Test { name: "lower tick -liquidity, growths not set, initialized no change", tick: TickBuilder::default() .initialized(true) .liquidity_net(100000) .liquidity_gross(200000) .build(), tick_index: 200, tick_current_index: 100, liquidity_delta: -100000, is_upper_tick: false, expected_update: TickUpdate { initialized: true, liquidity_net: 0, liquidity_gross: 100000, ..Default::default() }, ..Default::default() }, Test { name: "liquidity delta zero is no-op", tick: TickBuilder::default() .initialized(true) .liquidity_net(100000) .liquidity_gross(200000) .build(), tick_index: 200, tick_current_index: 100, liquidity_delta: 0, is_upper_tick: false, expected_update: TickUpdate { initialized: true, liquidity_net: 100000, liquidity_gross: 200000, ..Default::default() }, ..Default::default() }, Test { name: "uninitialized rewards get set to zero values", tick: TickBuilder::default() .initialized(true) .reward_growths_outside([100, 200, 50]) .build(), tick_index: 200, tick_current_index: 1000, liquidity_delta: 42069, is_upper_tick: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: [ WhirlpoolRewardInfo{ ..Default::default() }, WhirlpoolRewardInfo{ mint: Pubkey::new_unique(), emissions_per_second_x64: 1, growth_global_x64: 250, ..Default::default() }, WhirlpoolRewardInfo{ ..Default::default() } ], expected_update: TickUpdate { initialized: true, fee_growth_outside_a: 100, fee_growth_outside_b: 100, liquidity_net: 42069, liquidity_gross: 42069, reward_growths_outside: [0, 250, 0] }, } ] { // System under test let update = next_tick_modify_liquidity_update( &test.tick, test.tick_index, test.tick_current_index, test.fee_growth_global_a, test.fee_growth_global_b, &test.reward_infos, test.liquidity_delta, test.is_upper_tick, ) .unwrap(); assert_eq!( update.initialized, test.expected_update.initialized, "{}: initialized invalid", test.name ); assert_eq!( update.liquidity_net, test.expected_update.liquidity_net, "{}: liquidity_net invalid", test.name ); assert_eq!( update.liquidity_gross, test.expected_update.liquidity_gross, "{}: liquidity_gross invalid", test.name ); assert_eq!( update.fee_growth_outside_a, test.expected_update.fee_growth_outside_a, "{}: fee_growth_outside_a invalid", test.name ); assert_eq!( update.fee_growth_outside_b, test.expected_update.fee_growth_outside_b, "{}: fee_growth_outside_b invalid", test.name ); assert_eq!( update.reward_growths_outside, test.expected_update.reward_growths_outside, "{}: reward_growths_outside invalid", test.name ); } } #[test] fn test_next_tick_modify_liquidity_update_errors() { struct Test<'a> { name: &'a str, tick: Tick, tick_index: i32, tick_current_index: i32, liquidity_delta: i128, is_upper_tick: bool, expected_error: ErrorCode, } for test in [ Test { name: "liquidity gross overflow", tick: TickBuilder::default().liquidity_gross(u128::MAX).build(), tick_index: 0, tick_current_index: 10, liquidity_delta: i128::MAX, is_upper_tick: false, expected_error: ErrorCode::LiquidityOverflow, }, Test { name: "liquidity gross underflow", tick: Tick::default(), tick_index: 0, tick_current_index: 10, liquidity_delta: -100, is_upper_tick: false, expected_error: ErrorCode::LiquidityUnderflow, }, Test { name: "liquidity net overflow from subtracting negative delta", tick: TickBuilder::default() .liquidity_gross(i128::MAX as u128) .liquidity_net(i128::MAX) .build(), tick_index: 0, tick_current_index: 10, liquidity_delta: -(i128::MAX - 1), is_upper_tick: true, expected_error: ErrorCode::LiquidityNetError, }, Test { name: "liquidity net underflow", tick: TickBuilder::default() .liquidity_gross(10000) .liquidity_net(i128::MAX) .build(), tick_index: 0, tick_current_index: 10, liquidity_delta: i128::MAX, is_upper_tick: false, expected_error: ErrorCode::LiquidityNetError, }, ] { // System under test let err = next_tick_modify_liquidity_update( &test.tick, test.tick_index, test.tick_current_index, 0, 0, &[WhirlpoolRewardInfo::default(); NUM_REWARDS], test.liquidity_delta, test.is_upper_tick, ) .unwrap_err(); assert_eq!(err, test.expected_error, "{}", test.name); } } #[test] fn test_next_tick_cross_update() { struct Test<'a> { name: &'a str, tick: Tick, fee_growth_global_a: u128, fee_growth_global_b: u128, reward_infos: [WhirlpoolRewardInfo; NUM_REWARDS], expected_update: TickUpdate, } for test in [Test { name: "growths set properly (inverted)", tick: TickBuilder::default() .fee_growth_outside_a(1000) .fee_growth_outside_b(1000) .reward_growths_outside([500, 250, 100]) .build(), fee_growth_global_a: 2500, fee_growth_global_b: 6750, reward_infos: [ WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1, growth_global_x64: 1000, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1, growth_global_x64: 1000, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1, growth_global_x64: 1000, ..Default::default() }, ], expected_update: TickUpdate { fee_growth_outside_a: 1500, fee_growth_outside_b: 5750, reward_growths_outside: [500, 750, 900], ..Default::default() }, }] { // System under test let update = next_tick_cross_update( &test.tick, test.fee_growth_global_a, test.fee_growth_global_b, &test.reward_infos, ) .unwrap(); assert_eq!( update.fee_growth_outside_a, test.expected_update.fee_growth_outside_a, "{}: fee_growth_outside_a invalid", test.name ); assert_eq!( update.fee_growth_outside_b, test.expected_update.fee_growth_outside_b, "{}: fee_growth_outside_b invalid", test.name ); let reward_growths_outside = update.reward_growths_outside; let expected_growths_outside = test.expected_update.reward_growths_outside; for i in 0..NUM_REWARDS { assert_eq!( reward_growths_outside[i], expected_growths_outside[i], "{}: reward_growth[{}] invalid", test.name, i ); } } } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/liquidity_manager.rs
use super::{ position_manager::next_position_modify_liquidity_update, tick_manager::{ next_fee_growths_inside, next_reward_growths_inside, next_tick_modify_liquidity_update, }, whirlpool_manager::{next_whirlpool_liquidity, next_whirlpool_reward_infos}, }; use crate::{ errors::ErrorCode, math::{get_amount_delta_a, get_amount_delta_b, sqrt_price_from_tick_index}, state::*, }; use anchor_lang::prelude::{AccountLoader, *}; #[derive(Debug)] pub struct ModifyLiquidityUpdate { pub whirlpool_liquidity: u128, pub tick_lower_update: TickUpdate, pub tick_upper_update: TickUpdate, pub reward_infos: [WhirlpoolRewardInfo; NUM_REWARDS], pub position_update: PositionUpdate, } // Calculates state after modifying liquidity by the liquidity_delta for the given positon. // Fee and reward growths will also be calculated by this function. // To trigger only calculation of fee and reward growths, use calculate_fee_and_reward_growths. pub fn calculate_modify_liquidity<'info>( whirlpool: &Whirlpool, position: &Position, tick_array_lower: &AccountLoader<'info, TickArray>, tick_array_upper: &AccountLoader<'info, TickArray>, liquidity_delta: i128, timestamp: u64, ) -> Result<ModifyLiquidityUpdate> { let tick_array_lower = tick_array_lower.load()?; let tick_lower = tick_array_lower.get_tick(position.tick_lower_index, whirlpool.tick_spacing)?; let tick_array_upper = tick_array_upper.load()?; let tick_upper = tick_array_upper.get_tick(position.tick_upper_index, whirlpool.tick_spacing)?; _calculate_modify_liquidity( whirlpool, position, tick_lower, tick_upper, position.tick_lower_index, position.tick_upper_index, liquidity_delta, timestamp, ) } pub fn calculate_fee_and_reward_growths<'info>( whirlpool: &Whirlpool, position: &Position, tick_array_lower: &AccountLoader<'info, TickArray>, tick_array_upper: &AccountLoader<'info, TickArray>, timestamp: u64, ) -> Result<(PositionUpdate, [WhirlpoolRewardInfo; NUM_REWARDS])> { let tick_array_lower = tick_array_lower.load()?; let tick_lower = tick_array_lower.get_tick(position.tick_lower_index, whirlpool.tick_spacing)?; let tick_array_upper = tick_array_upper.load()?; let tick_upper = tick_array_upper.get_tick(position.tick_upper_index, whirlpool.tick_spacing)?; // Pass in a liquidity_delta value of 0 to trigger only calculations for fee and reward growths. // Calculating fees and rewards for positions with zero liquidity will result in an error. let update = _calculate_modify_liquidity( whirlpool, position, tick_lower, tick_upper, position.tick_lower_index, position.tick_upper_index, 0, timestamp, )?; Ok((update.position_update, update.reward_infos)) } // Calculates the state changes after modifying liquidity of a whirlpool position. #[allow(clippy::too_many_arguments)] fn _calculate_modify_liquidity( whirlpool: &Whirlpool, position: &Position, tick_lower: &Tick, tick_upper: &Tick, tick_lower_index: i32, tick_upper_index: i32, liquidity_delta: i128, timestamp: u64, ) -> Result<ModifyLiquidityUpdate> { // Disallow only updating position fee and reward growth when position has zero liquidity if liquidity_delta == 0 && position.liquidity == 0 { return Err(ErrorCode::LiquidityZero.into()); } let next_reward_infos = next_whirlpool_reward_infos(whirlpool, timestamp)?; let next_global_liquidity = next_whirlpool_liquidity( whirlpool, position.tick_upper_index, position.tick_lower_index, liquidity_delta, )?; let tick_lower_update = next_tick_modify_liquidity_update( tick_lower, tick_lower_index, whirlpool.tick_current_index, whirlpool.fee_growth_global_a, whirlpool.fee_growth_global_b, &next_reward_infos, liquidity_delta, false, )?; let tick_upper_update = next_tick_modify_liquidity_update( tick_upper, tick_upper_index, whirlpool.tick_current_index, whirlpool.fee_growth_global_a, whirlpool.fee_growth_global_b, &next_reward_infos, liquidity_delta, true, )?; let (fee_growth_inside_a, fee_growth_inside_b) = next_fee_growths_inside( whirlpool.tick_current_index, tick_lower, tick_lower_index, tick_upper, tick_upper_index, whirlpool.fee_growth_global_a, whirlpool.fee_growth_global_b, ); let reward_growths_inside = next_reward_growths_inside( whirlpool.tick_current_index, tick_lower, tick_lower_index, tick_upper, tick_upper_index, &next_reward_infos, ); let position_update = next_position_modify_liquidity_update( position, liquidity_delta, fee_growth_inside_a, fee_growth_inside_b, &reward_growths_inside, )?; Ok(ModifyLiquidityUpdate { whirlpool_liquidity: next_global_liquidity, reward_infos: next_reward_infos, position_update, tick_lower_update, tick_upper_update, }) } pub fn calculate_liquidity_token_deltas( current_tick_index: i32, sqrt_price: u128, position: &Position, liquidity_delta: i128, ) -> Result<(u64, u64)> { if liquidity_delta == 0 { return Err(ErrorCode::LiquidityZero.into()); } let mut delta_a: u64 = 0; let mut delta_b: u64 = 0; let liquidity: u128 = liquidity_delta.unsigned_abs(); let round_up = liquidity_delta > 0; let lower_price = sqrt_price_from_tick_index(position.tick_lower_index); let upper_price = sqrt_price_from_tick_index(position.tick_upper_index); if current_tick_index < position.tick_lower_index { // current tick below position delta_a = get_amount_delta_a(lower_price, upper_price, liquidity, round_up)?; } else if current_tick_index < position.tick_upper_index { // current tick inside position delta_a = get_amount_delta_a(sqrt_price, upper_price, liquidity, round_up)?; delta_b = get_amount_delta_b(lower_price, sqrt_price, liquidity, round_up)?; } else { // current tick above position delta_b = get_amount_delta_b(lower_price, upper_price, liquidity, round_up)?; } Ok((delta_a, delta_b)) } pub fn sync_modify_liquidity_values<'info>( whirlpool: &mut Whirlpool, position: &mut Position, tick_array_lower: &AccountLoader<'info, TickArray>, tick_array_upper: &AccountLoader<'info, TickArray>, modify_liquidity_update: ModifyLiquidityUpdate, reward_last_updated_timestamp: u64, ) -> Result<()> { position.update(&modify_liquidity_update.position_update); tick_array_lower.load_mut()?.update_tick( position.tick_lower_index, whirlpool.tick_spacing, &modify_liquidity_update.tick_lower_update, )?; tick_array_upper.load_mut()?.update_tick( position.tick_upper_index, whirlpool.tick_spacing, &modify_liquidity_update.tick_upper_update, )?; whirlpool.update_rewards_and_liquidity( modify_liquidity_update.reward_infos, modify_liquidity_update.whirlpool_liquidity, reward_last_updated_timestamp, ); Ok(()) } #[cfg(test)] mod calculate_modify_liquidity_unit_tests { // Test position start => end state transitions after applying possible liquidity_delta values. // x => position has no liquidity // o => position has non-zero liquidity // x => tick is not initialized // o => tick is initialized // ox_position indicates position with liquidity has zero liquidity after modifying liquidity // xo_lower indicates lower tick was initialized after modifying liquidity // Position with zero liquidity remains in zero liquidity state // Only possible with negative and zero liquidity delta values which all result in errors // Current tick index location relative to position does not matter mod xx_position { use crate::{manager::liquidity_manager::_calculate_modify_liquidity, util::*}; // Zero liquidity delta on position with zero liquidity is not allowed #[test] #[should_panic(expected = "LiquidityZero")] fn zero_delta_on_empty_position_not_allowed() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: 0, fee_growth_global_b: 0, reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 100, ) .unwrap(); } // Removing liquidity from position with zero liquidity results in error // LiquidityUnderflow from lower tick (xx_oo) #[test] #[should_panic(expected = "LiquidityUnderflow")] fn neg_delta_lower_tick_liquidity_underflow() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: 0, fee_growth_global_b: 0, reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); } // Removing liquidity from position with zero liquidity results in error // LiquidityUnderflow from upper tick (oo_xx) #[test] #[should_panic(expected = "LiquidityUnderflow")] fn neg_delta_upper_tick_liquidity_underflow() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 0, fee_growth_global_a: 0, fee_growth_global_b: 0, reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); } // Removing liquidity from position with zero liquidity results in error // LiquidityUnderflow from updating position (oo_oo - not ticks) #[test] #[should_panic(expected = "LiquidityUnderflow")] fn neg_delta_position_liquidity_underflow() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: 0, fee_growth_global_b: 0, reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); } } // Position with zero liquidity transitions to positive liquidity // Only possible with positive liquidity delta values mod xo_position { // Current tick below position // Whirlpool virtual liquidity does not change mod current_tick_below { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; // Position liquidity increase, checkpoint zero values // Lower tick initialized, liquidity increase, checkpoint zero values // Upper tick initialized, liquidity increase, checkpoint zero values #[test] fn pos_delta_current_tick_below_xo_lower_xo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, ..Default::default() }, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint zero values // Lower tick initialized, liquidity increase, checkpoint zero values // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_below_xo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint underflowed values // Lower tick initialized, liquidity increase, checkpoint zero values // Upper tick already initialized, has non-zero checkpoint values // Simulates two left tick crossings in order to reach underflow edge case #[test] fn pos_delta_current_tick_below_xo_lower_oo_upper_underflow() { // Underflow occurs when the lower tick is newly initialized and the upper tick // is already initialized with non-zero growth checkpoints. // The upper tick only has non-zero checkpoints when it was either 1) initialized // when current tick is above or 2) when it was crossed after some global fee growth // occurred. // This test simulates two tick crossings from right to left before adding liquidity // to the position. let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(10), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); test.increment_whirlpool_reward_growths_by_time(100); test.cross_tick(TickLabel::Upper, Direction::Left); // Check crossing an upper tick with liquidity added new whirlpool liquidity assert_eq!(test.whirlpool.liquidity, 110); // 1 = 0 + (100/100) assert_whirlpool_reward_growths(&test.whirlpool.reward_infos, to_x64(1)); test.increment_whirlpool_fee_growths(to_x64(10), to_x64(10)); test.increment_whirlpool_reward_growths_by_time(100); test.cross_tick(TickLabel::Lower, Direction::Left); // Lower tick has 0 net liquidity, so crossing does not affect whirlpool liquidity assert_eq!(test.whirlpool.liquidity, 110); // 1.909 = 1 + (100/110) assert_whirlpool_reward_growths(&test.whirlpool.reward_infos, 35216511413445507630); // Create position which initializes the lower tick let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 300, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { // Current tick below position, so does not add to whirlpool liquidity whirlpool_liquidity: 110, // 2.8181 = 1.909 + 0.909 whirlpool_reward_growths: create_reward_growths(51986278753181463644), position_update: PositionUpdate { liquidity: 10, // Wrapped underflow -10 = 20 - (20 - 0) - (10) fee_growth_checkpoint_a: 340282366920938463278907166694672695296, // Wrapped underflow -10 fee_growth_checkpoint_b: 340282366920938463278907166694672695296, reward_infos: create_position_reward_infos( 340282366920938463444927863358058659840, 0, ), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), reward_growths_outside: create_reward_growths(to_x64(1)), }, }, ); } // Position liquidity increase, checkpoint zero values // Lower tick already initialized, liquidity increase // Upper tick already initialized, liquidity increase, checkpoint zero values #[test] fn pos_delta_current_tick_below_oo_lower_xo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 0, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint zero values // Lower tick already initialized, liquidity increase // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_below_oo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } } // Current tick inside position // Whirlpool virtual liquidity increases mod current_tick_inside { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; // Position liquidity increase, checkpoint zero values // Lower tick initialized, liquidity increase, checkpoint current values // Upper tick initialized, liquidity increase, checkpoint zero values #[test] fn pos_delta_current_tick_inside_xo_lower_xo_upper() { // Both ticks are uninitialized. This is the first position to use this tick range let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: 0, fee_growth_global_b: 0, reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 110, whirlpool_reward_growths: create_reward_growths(to_x64(1)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, reward_growths_outside: create_reward_growths(to_x64(1)), ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint zero values // Lower tick initialized, liquidity increase, checkpoint current values // Upper already initialized, liquidity increase #[test] fn pos_delta_current_tick_inside_xo_lower_oo_upper() { // This is the first position to use this tick range let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 110, whirlpool_reward_growths: create_reward_growths(to_x64(1)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(1)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint underflowed values // Lower tick initialized, liquidity increase, checkpoint current values // Upper already initialized, liquidity increase // Simulates one left tick crossings in order to reach underflow edge case #[test] fn pos_delta_current_tick_inside_xo_lower_oo_upper_underflow() { // Underflow occurs when the lower tick is newly initialized and the upper tick // is already initialized with non-zero growth checkpoints. // The upper tick only has non-zero checkpoints when it was either 1) initialized // when current tick is above or 2) when it was crossed after some global fee growth // occurred. // This test simulates one tick crossing from left to right before adding liquidity // to the position. let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(10), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); test.increment_whirlpool_reward_growths_by_time(100); test.cross_tick(TickLabel::Upper, Direction::Left); // Check crossing an upper tick with liquidity added new whirlpool liquidity assert_eq!(test.whirlpool.liquidity, 110); // 1 = 0 + (100/100) assert_whirlpool_reward_growths(&test.whirlpool.reward_infos, to_x64(1)); // Create position which initializes the lower tick let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 200, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { // Current tick inside position, so whirlpool liquidity increases whirlpool_liquidity: 120, // 1.909 = 1 + 0.909 whirlpool_reward_growths: create_reward_growths(35216511413445507630), position_update: PositionUpdate { liquidity: 10, // Wrapped underflow -10 fee_growth_checkpoint_a: 340282366920938463278907166694672695296, // Wrapped underflow -10 fee_growth_checkpoint_b: 340282366920938463278907166694672695296, reward_infos: create_position_reward_infos( 340282366920938463444927863358058659840, 0, ), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), // 1.909 reward_growths_outside: create_reward_growths(35216511413445507630), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), reward_growths_outside: create_reward_growths(to_x64(1)), }, }, ); } // Position liquidity increase, checkpoint current inside growth values // Lower tick already initialized, liquidity increase // Upper tick initialized, liquidity increase, checkpoint zero values #[test] fn pos_delta_current_tick_inside_oo_lower_xo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 0, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 110, whirlpool_reward_growths: create_reward_growths(to_x64(1)), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(10), fee_growth_checkpoint_b: to_x64(20), reward_infos: create_position_reward_infos(to_x64(1), 0), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, ..Default::default() }, }, ); } // Position liquidity increase, checkpoint current inside growth values // Lower tick already initialized, liquidity increase // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_inside_oo_lower_oo_upper() { // Ticks already initialized with liquidity from other position let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 110, whirlpool_reward_growths: create_reward_growths(to_x64(1)), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(10), fee_growth_checkpoint_b: to_x64(20), reward_infos: create_position_reward_infos(to_x64(1), 0), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } } // Current tick above position // Whirlpool virtual liquidity does not change mod current_tick_above { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; // Position liquidity increase, checkpoint zero values // Lower tick initialized, liquidity increase, checkpoint current values // Upper tick initialized, liquidity increase, checkpoint current values #[test] fn pos_delta_current_tick_above_xo_lower_xo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(3)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(3)), }, }, ); } // Position liquidity increase, checkpoint underflowed values // Lower tick initialized, liquidity increase, checkpoint current values // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_above_xo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, // Wrapped underflow -10 fee_growth_checkpoint_a: 340282366920938463278907166694672695296, // Wrapped underflow -20 fee_growth_checkpoint_b: 340282366920938463094439725957577179136, reward_infos: create_position_reward_infos( 340282366920938463408034375210639556608, 0, ), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(3)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } // Adds liquidity to a new position where the checkpoints underflow. // Simulates the whirlpool current tick moving below the upper tick, accruing fees // and rewards, and then moving back above the tick. The calculated owed token amounts // are verified to be correct with underflowed checkpoints. #[test] fn pos_delta_current_tick_above_xo_lower_oo_upper_underflow_owed_amounts_ok() { // l < u < c, t = 0 to 100 // global fee growth a: 10, fee growth b: 10, rewards: 1 // create new position with 10 liquidity // lower tick initialized now - checkpoint current growths // upper tick already initialized with zero value checkpoints let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(10), reward_infos: create_whirlpool_reward_infos(to_x64(1), 0), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(1)), position_update: PositionUpdate { liquidity: 10, // Wrapped underflow -10 fee_growth_checkpoint_a: 340282366920938463278907166694672695296, // Wrapped underflow -10 fee_growth_checkpoint_b: 340282366920938463278907166694672695296, reward_infos: create_position_reward_infos( 340282366920938463444927863358058659840, 0, ), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), reward_growths_outside: create_reward_growths(to_x64(1)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); test.apply_update(&update, 100); // l < c < u, t = 100 to 200 // simulate crossing upper tick from right to left (price decrease) // global fee growth a: 20, fee growth b: 20 // upper tick checkpoints are inverted // -120, 0, 120 test.increment_whirlpool_fee_growths(to_x64(10), to_x64(10)); test.increment_whirlpool_reward_growths_by_time(100); test.cross_tick(TickLabel::Upper, Direction::Left); assert_whirlpool_reward_growths(&test.whirlpool.reward_infos, to_x64(2)); assert_eq!( test.tick_upper, Tick { initialized: true, liquidity_net: -20, liquidity_gross: 20, // 20 = 20 - 0 fee_growth_outside_a: to_x64(20), // 20 = 20 - 0 fee_growth_outside_b: to_x64(20), // 2 = (1 + (100/100)) - 0 reward_growths_outside: create_reward_growths(to_x64(2)), } ); // l < u < c, t = 200 to 300 // simulate crossing upper tick from left to right (price increase) // global fee growth a: 35, fee growth b: 35 // upper tick checkpoints are inverted test.increment_whirlpool_fee_growths(to_x64(15), to_x64(15)); test.increment_whirlpool_reward_growths_by_time(100); // 2.83 = 2 + 100/120 assert_whirlpool_reward_growths(&test.whirlpool.reward_infos, 52265774875510396245); test.cross_tick(TickLabel::Upper, Direction::Right); assert_eq!( test.tick_upper, Tick { initialized: true, liquidity_net: -20, liquidity_gross: 20, // 15 = 35 - 20 fee_growth_outside_a: to_x64(15), // 15 = 35 - 20 fee_growth_outside_b: to_x64(15), // 0.83 = 2.83 - 2 reward_growths_outside: create_reward_growths(15372286728091293013), } ); // t = 300 to 400, recalculate position fees/rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 400, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, // 3.83 = 2.83 + 100/100 whirlpool_reward_growths: create_reward_growths(70712518949219947861), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(5), fee_owed_a: 150, fee_growth_checkpoint_b: to_x64(5), fee_owed_b: 150, reward_infos: create_position_reward_infos( 340282366920938463460300150086149952853, // 8 = 0.83 * 10 8, ), }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), reward_growths_outside: create_reward_growths(to_x64(1)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -20, liquidity_gross: 20, // 15 fee_growth_outside_a: to_x64(15), // 15 fee_growth_outside_b: to_x64(15), // 0.83 reward_growths_outside: create_reward_growths(15372286728091293013), }, }, ); } // Position liquidity increase, checkpoint current values // Lower tick already initialized, liquidity increase // Upper tick initialized, liquidity increase, checkpoint current values #[test] fn pos_delta_current_tick_above_oo_lower_xo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 0, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(10), fee_growth_checkpoint_b: to_x64(20), reward_infos: create_position_reward_infos(to_x64(3), 0), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(3)), }, }, ); } // Position liquidity increase, checkpoint zero values // Lower tick already initialized, liquidity increase // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_above_oo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, ..Default::default() }, }, ); } // Use non-zero checkpoints for already initialized ticks // Position liquidity increase, checkpoint current fee growth inside values // Lower tick already initialized, liquidity increase // Upper tick already initialized, liquidity increase #[test] fn pos_delta_current_tick_above_oo_lower_oo_upper_non_zero_checkpoints() { // Test fixture is set up to simulate whirlpool at state T1. // T0 - current tick inside position, global fees at 10, rewards at 1. // - Some other position already exists using these tick bounds. // - Price gets pushed above upper tick. // T1 - current tick above position, global fees at 20, rewards at 2. // - Deposit liquidity into new position. let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(20), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); test.whirlpool.reward_last_updated_timestamp = 200; test.tick_lower.fee_growth_outside_a = to_x64(10); test.tick_lower.fee_growth_outside_b = to_x64(10); test.tick_lower.reward_growths_outside = create_reward_growths(to_x64(1)); test.tick_upper.fee_growth_outside_a = to_x64(20); test.tick_upper.fee_growth_outside_b = to_x64(20); test.tick_upper.reward_growths_outside = create_reward_growths(to_x64(2)); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 300, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(10), fee_growth_checkpoint_b: to_x64(10), reward_infos: create_position_reward_infos(to_x64(1), 0), ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: 20, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(10), reward_growths_outside: create_reward_growths(to_x64(1)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 20, liquidity_net: -20, fee_growth_outside_a: to_x64(20), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(2)), }, }, ); } } } // Position with positive liquidity transitions to zero liquidity // Only possible with negative liquidity delta values mod ox_position { mod current_tick_below { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; #[test] fn neg_delta_current_tick_below_ox_lower_ox_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate::default(), tick_lower_update: TickUpdate::default(), tick_upper_update: TickUpdate::default(), }, ); } #[test] fn neg_delta_current_tick_below_oo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 20, tick_upper_liquidity_gross: 20, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate::default(), tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } #[test] fn neg_delta_current_tick_below_oo_lower_oo_upper_non_zero_checkpoints() { // Test fixture is set up to simulate whirlpool at state T2. // T0 - current tick above position, global fees at 100, rewards at 10. // - Deposit liquidity into new position. // T1 - current tick inside position, global fees at 150, rewards at 20. // T2 - current tick below position, global fees at 200, rewards at 30. // - Remove all liquidity. let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 1000, position_liquidity: 10, tick_lower_liquidity_gross: 20, tick_upper_liquidity_gross: 20, fee_growth_global_a: to_x64(200), fee_growth_global_b: to_x64(200), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(30)), }); // Time starts at 30_000. Increments of 10_000 seconds with 1000 whirlpool liquidity // equate to increments of 10 global rewards. test.whirlpool.reward_last_updated_timestamp = 30_000; test.tick_lower.reward_growths_outside = create_reward_growths(to_x64(30)); test.tick_lower.fee_growth_outside_a = to_x64(100); test.tick_lower.fee_growth_outside_b = to_x64(100); test.tick_upper.reward_growths_outside = create_reward_growths(to_x64(10)); test.tick_upper.fee_growth_outside_a = to_x64(50); test.tick_upper.fee_growth_outside_b = to_x64(50); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 40_000, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 1000, // 40 = 30 + (10000 / 1000) whirlpool_reward_growths: create_reward_growths(737869762948382064640), position_update: PositionUpdate { liquidity: 0, fee_growth_checkpoint_a: to_x64(50), fee_owed_a: 500, fee_growth_checkpoint_b: to_x64(50), fee_owed_b: 500, reward_infos: create_position_reward_infos(to_x64(20), 200), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, fee_growth_outside_a: to_x64(100), fee_growth_outside_b: to_x64(100), reward_growths_outside: create_reward_growths(to_x64(30)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, fee_growth_outside_a: to_x64(50), fee_growth_outside_b: to_x64(50), reward_growths_outside: create_reward_growths(to_x64(10)), }, }, ); } } mod current_tick_inside { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; #[test] fn neg_delta_current_tick_inside_ox_lower_ox_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 90, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 0, fee_growth_checkpoint_a: to_x64(10), fee_owed_a: 100, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 200, reward_infos: create_position_reward_infos(to_x64(3), 30), }, tick_lower_update: TickUpdate::default(), tick_upper_update: TickUpdate::default(), }, ); } #[test] fn neg_delta_current_tick_inside_oo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 20, tick_upper_liquidity_gross: 20, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 90, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 0, fee_growth_checkpoint_a: to_x64(10), fee_owed_a: 100, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 200, reward_infos: create_position_reward_infos(to_x64(3), 30), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } } mod current_tick_above { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; #[test] fn neg_delta_current_tick_above_ox_lower_ox_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate::default(), tick_lower_update: TickUpdate::default(), tick_upper_update: TickUpdate::default(), }, ); } #[test] fn neg_delta_current_tick_above_oo_lower_oo_upper() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 20, tick_upper_liquidity_gross: 20, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate::default(), tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } } } // Position with positive liquidity remains in positive liquidity state // Only possible with lower and upper ticks that are already initialized (oo, oo) mod oo_position { use crate::{manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*}; // Liquidity + tick states remain the same // Only fee + reward growth changes #[test] fn zero_delta_current_tick_below() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } #[test] fn zero_delta_current_tick_inside() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, fee_growth_checkpoint_a: to_x64(10), fee_owed_a: 100, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 200, reward_infos: create_position_reward_infos(to_x64(3), 30), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } #[test] fn zero_delta_current_tick_above() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 10, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 10, liquidity_gross: 10, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -10, liquidity_gross: 10, ..Default::default() }, }, ); } // Position liquidity increases #[test] fn pos_delta_current_tick_below() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 20, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 20, liquidity_gross: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -20, liquidity_gross: 20, ..Default::default() }, }, ); } #[test] fn pos_delta_current_tick_inside() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 110, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 20, fee_growth_checkpoint_a: to_x64(10), fee_owed_a: 100, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 200, reward_infos: create_position_reward_infos(to_x64(3), 30), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 20, liquidity_gross: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -20, liquidity_gross: 20, ..Default::default() }, }, ); } #[test] fn pos_delta_current_tick_above() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 10, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 20, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 20, liquidity_gross: 20, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -20, liquidity_gross: 20, ..Default::default() }, }, ); } // Position liquidity decreases by partial amount #[test] fn neg_delta_current_tick_below() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -5, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 5, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 5, liquidity_gross: 5, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -5, liquidity_gross: 5, ..Default::default() }, }, ); } #[test] fn neg_delta_current_tick_inside() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -5, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 95, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 5, fee_growth_checkpoint_a: to_x64(10), fee_owed_a: 100, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 200, reward_infos: create_position_reward_infos(to_x64(3), 30), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 5, liquidity_gross: 5, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -5, liquidity_gross: 5, ..Default::default() }, }, ); } #[test] fn neg_delta_current_tick_above() { let test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 100, position_liquidity: 10, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(10), fee_growth_global_b: to_x64(20), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(2)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -5, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 100, whirlpool_reward_growths: create_reward_growths(to_x64(3)), position_update: PositionUpdate { liquidity: 5, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 5, liquidity_gross: 5, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -5, liquidity_gross: 5, ..Default::default() }, }, ); } } mod fees_and_rewards { use crate::{manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*}; // Add liquidity to new position, accrue fees and rewards, remove all liquidity. // This test checks that accrued fees and rewards are properly accounted even when all // liquidity has been removed from a position and the ticks are still initialized. #[test] fn accrued_tokens_ok_closed_position_ticks_remain_initialized() { // Whirlpool with 1000 liquidity, fees (a: 100, b: 200) and reward (20) // Lower Tick with 10 liquidity, existing fee checkpoints (a: 10, b: 20) and reward (2) // Upper Tick with 10 liquidity, existing fee checkpoints (a: 1, b: 2) and reward (1) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 1000, position_liquidity: 0, tick_lower_liquidity_gross: 10, tick_upper_liquidity_gross: 10, fee_growth_global_a: to_x64(100), fee_growth_global_b: to_x64(200), reward_infos: create_whirlpool_reward_infos(to_x64(1), to_x64(20)), }); test.tick_lower.fee_growth_outside_a = to_x64(10); test.tick_lower.fee_growth_outside_b = to_x64(20); test.tick_lower.reward_growths_outside = create_reward_growths(to_x64(2)); test.tick_upper.fee_growth_outside_a = to_x64(1); test.tick_upper.fee_growth_outside_b = to_x64(2); test.tick_upper.reward_growths_outside = create_reward_growths(to_x64(1)); // Add 100 liquidity let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 100, 100, ) .unwrap(); // 20.1 = 20 + (100 / 1000) assert_whirlpool_reward_growths(&update.reward_infos, 370779555881561987481); assert_eq!( update.position_update, PositionUpdate { liquidity: 100, fee_growth_checkpoint_a: to_x64(89), // 100 - 10 - 1 fee_growth_checkpoint_b: to_x64(178), // 200 - 20 - 2 reward_infos: create_position_reward_infos(315439323660433332633, 0), ..Default::default() } ); test.apply_update(&update, 100); // Add 50 more liquidity test.increment_whirlpool_fee_growths(to_x64(10), to_x64(20)); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 50, 200, ) .unwrap(); // 20.19090 = 20.1 + (100 / 1100) assert_whirlpool_reward_growths(&update.reward_infos, 372456532615535583082); assert_eq!( update.position_update, PositionUpdate { liquidity: 150, fee_growth_checkpoint_a: to_x64(99), // 110 - 10 - 1 fee_owed_a: 1000, fee_growth_checkpoint_b: to_x64(198), // 220 - 20 - 2 fee_owed_b: 2000, reward_infos: create_position_reward_infos(317116300394406928234, 9), } ); test.apply_update(&update, 200); // Remove all 150 liquidity test.increment_whirlpool_fee_growths(to_x64(10), to_x64(20)); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, -150, 300, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 1000, // 20.277865 = 20.19090 + (100 / 1150) whirlpool_reward_growths: create_reward_growths(374060597317597283222), position_update: PositionUpdate { liquidity: 0, fee_growth_checkpoint_a: to_x64(109), // 120 - 10 - 1 fee_owed_a: 2500, fee_growth_checkpoint_b: to_x64(218), // 240 - 20 - 2 fee_owed_b: 5000, reward_infos: create_position_reward_infos(318720365096468628374, 22), }, tick_lower_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: 10, fee_growth_outside_a: to_x64(10), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(2)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_gross: 10, liquidity_net: -10, fee_growth_outside_a: to_x64(1), fee_growth_outside_b: to_x64(2), reward_growths_outside: create_reward_growths(to_x64(1)), }, }, ); } // Test overflow accounting of global fee and reward accumulators mod global_accumulators_overflow { use crate::{ manager::liquidity_manager::_calculate_modify_liquidity, state::*, util::*, }; // t1 |---c1---l----------------u--------| open position (checkpoint) // t2 |--------l-------c2-------u--------| cross right, accrue tokens // t3 |---c3---l----------------u--------| cross left, overflow #[test] fn overflow_below_checkpoint_below() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at -4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, u128::MAX - to_x64(3), ); // t2 - cross right, accrue tokens in position test.cross_tick(TickLabel::Lower, Direction::Right); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -60 test.increment_whirlpool_reward_growths_by_time(100); // 300 // time: 300, rewards at -2.0909 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463424804142550375512621, ); // t3 - cross left, overflow test.cross_tick(TickLabel::Lower, Direction::Left); test.increment_whirlpool_fee_growths(to_x64(70), to_x64(70)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -2.0909 + 3 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: to_x64(20), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(16769767339735956014), // 0.9090909 }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l-------c1-------u--------| open position (checkpoint) // t2 |--------l-------c2-------u--------| accrue tokens, cross left // t3 |---c3---l----------------u--------| overflow #[test] fn overflow_below_checkpoint_inside() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 11000, // time: 100, rewards at MAX - 4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); // t2 - accrue tokens, cross left test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3.0909 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463406357398476665961005, ); test.cross_tick(TickLabel::Lower, Direction::Left); // t3 - overflow test.increment_whirlpool_fee_growths(to_x64(90), to_x64(90)); // fees overflow to 10 test.increment_whirlpool_reward_growths_by_time(400); // 600 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -3.0909 + 4 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: to_x64(20), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(16769767339735956014), // 0.9090909 }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l----------------u---c1---| open position (checkpoint), cross left // t2 |--------l-------c2-------u--------| accrue tokens, cross left // t3 |---c3---l----------------u--------| overflow #[test] fn overflow_below_checkpoint_above() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at MAX - 4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, u128::MAX - to_x64(3), ); test.cross_tick(TickLabel::Upper, Direction::Left); // t2 - accrue tokens, cross left test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -60 test.increment_whirlpool_reward_growths_by_time(100); // time: 300, rewards at MAX - 2.0909 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463424804142550375512621, ); test.cross_tick(TickLabel::Lower, Direction::Left); // t3 - overflow test.increment_whirlpool_fee_growths(to_x64(70), to_x64(70)); // fees overflow to 10 test.increment_whirlpool_reward_growths_by_time(300); // 600 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -3.0909 + 4 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: to_x64(40), fee_growth_outside_b: to_x64(40), reward_growths_outside: create_reward_growths(35216511413445507630), // 1.9090909 }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: to_x64(20), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(to_x64(1)), // 1 }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |---c1---l----------------u--------| open position (checkpoint), cross right // t2 |--------l-------c2-------u--------| accrue tokens, overflow #[test] fn overflow_inside_checkpoint_below() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at MAX - 4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, u128::MAX - to_x64(3), ); test.cross_tick(TickLabel::Lower, Direction::Right); // t2 - accrue tokens, overflow test.increment_whirlpool_fee_growths(to_x64(90), to_x64(90)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 11000, // time: 600, rewards at 0.6363 = -3 + (400 * 100 / 11000) whirlpool_reward_growths: create_reward_growths(11738837137815169209), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(90), fee_owed_a: 90000, fee_growth_checkpoint_b: to_x64(90), fee_owed_b: 90000, reward_infos: create_position_reward_infos(67079069358943824058, 3636), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(80), fee_growth_outside_b: u128::MAX - to_x64(80), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(3)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l-------c1-------u--------| open position (checkpoint) // t2 |--------l-------c2-------u--------| accrue tokens, overflow #[test] fn overflow_inside_checkpoint_inside() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 9000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at -3.888 = -5 + (100 * 100 / 9000) whirlpool_reward_growths: create_reward_growths( 340282366920938463391637269367342177392, ), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths( 340282366920938463391637269367342177392, ), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); // t2 - accrue tokens, overflow test.increment_whirlpool_fee_growths(to_x64(110), to_x64(110)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 1.111 = -3.888 + (500 * 100 / 10000) whirlpool_reward_growths: create_reward_growths(20496382304121724016), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(110), fee_owed_a: 110000, fee_growth_checkpoint_b: to_x64(110), fee_owed_b: 110000, reward_infos: create_position_reward_infos(to_x64(5), 5000), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths( 340282366920938463391637269367342177392, ), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l----------------u---c1---| open position (checkpoint), cross left // t2 |--------l-------c2-------u--------| accrue tokens, overflow #[test] fn overflow_inside_checkpoint_above() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 9000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 9000, // time: 100, rewards at -3.888 = -5 + (100 * 100 / 9000) whirlpool_reward_growths: create_reward_growths( 340282366920938463391637269367342177392, ), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths( 340282366920938463391637269367342177392, ), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths( 340282366920938463391637269367342177392, ), }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // -2.777 = -3.888 + (100 * 100 / 9000) assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463412133651671463901409, ); test.cross_tick(TickLabel::Upper, Direction::Left); // t2 - accrue tokens, overflow test.increment_whirlpool_fee_growths(to_x64(90), to_x64(90)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 1.222 = -2.777 + (400 * 100 / 10000) whirlpool_reward_growths: create_reward_growths(22546020534533896417), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(90), fee_owed_a: 90000, fee_growth_checkpoint_b: to_x64(90), fee_owed_b: 90000, reward_infos: create_position_reward_infos(to_x64(4), 4000), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths( 340282366920938463391637269367342177392, ), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: to_x64(20), fee_growth_outside_b: to_x64(20), reward_growths_outside: create_reward_growths(20496382304121724017), }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |---c1---l----------------u--------| open position (checkpoint), cross right // t2 |--------l-------c2-------u--------| accrue tokens, cross right // t3 |--------l----------------u---c3---| overflow #[test] fn overflow_above_checkpoint_below() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Below, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at -4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, ..Default::default() }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at -3 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, u128::MAX - to_x64(3), ); test.cross_tick(TickLabel::Lower, Direction::Right); // // t2 - accrue tokens, cross right test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -60 test.increment_whirlpool_reward_growths_by_time(100); // time: 300, rewards at -2.0909 = assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463424804142550375512621, ); test.cross_tick(TickLabel::Upper, Direction::Right); // t3 - overflow test.increment_whirlpool_fee_growths(to_x64(70), to_x64(70)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -2.0909 + 3 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, // 20 = 10 - (-80) - (10 - (-60)) fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, // 0.909 = 0.909 - (-3) - (0.909 - -2.0909) reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(80), fee_growth_outside_b: u128::MAX - to_x64(80), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(3)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(60), fee_growth_outside_b: u128::MAX - to_x64(60), reward_growths_outside: create_reward_growths( 340282366920938463424804142550375512621, ), }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l-------c1-------u--------| open position (checkpoint) // t2 |--------l-------c2-------u--------| accrue tokens, cross right // t3 |--------l----------------u---c3---| overflow #[test] fn overflow_above_checkpoint_inside() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Inside, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 11000, // time: 100, rewards at -4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, ..Default::default() }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); // t2 -accrue tokens, cross right test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3.0909 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463406357398476665961005, ); test.cross_tick(TickLabel::Upper, Direction::Right); // t3 - overflow test.increment_whirlpool_fee_growths(to_x64(90), to_x64(90)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -3.0909 + 4 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(80), fee_growth_outside_b: u128::MAX - to_x64(80), reward_growths_outside: create_reward_growths( 340282366920938463406357398476665961005, ), }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } // t1 |--------l----------------u---c1---| open position (checkpoint), cross left // t2 |--------l-------c2-------u--------| accrue tokens, cross right // t3 |--------l----------------u---c3---| overflow #[test] fn overflow_above_checkpoint_above() { // t1 - open position (checkpoint) let mut test = LiquidityTestFixture::new(LiquidityTestFixtureInfo { curr_index_loc: CurrIndex::Above, whirlpool_liquidity: 10000, position_liquidity: 0, tick_lower_liquidity_gross: 0, tick_upper_liquidity_gross: 0, fee_growth_global_a: u128::MAX - to_x64(100), fee_growth_global_b: u128::MAX - to_x64(100), // rewards start at MAX - 5 reward_infos: create_whirlpool_reward_infos(to_x64(100), u128::MAX - to_x64(5)), }); let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 1000, 100, ) .unwrap(); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 100, rewards at -4 whirlpool_reward_growths: create_reward_growths(u128::MAX - to_x64(4)), position_update: PositionUpdate { liquidity: 1000, ..Default::default() }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, }, ); assert_eq!(test.whirlpool.fee_growth_global_a, u128::MAX - to_x64(100)); assert_eq!(test.whirlpool.fee_growth_global_b, u128::MAX - to_x64(100)); test.apply_update(&update, 100); test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -80 test.increment_whirlpool_reward_growths_by_time(100); // time: 200, rewards at MAX - 3 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, u128::MAX - to_x64(3), ); test.cross_tick(TickLabel::Upper, Direction::Left); // t2 - accrue tokens, cross right test.increment_whirlpool_fee_growths(to_x64(20), to_x64(20)); // fees at -60 test.increment_whirlpool_reward_growths_by_time(100); // time: 300, rewards at MAX - 2.0909 assert_whirlpool_reward_growths( &test.whirlpool.reward_infos, 340282366920938463424804142550375512621, ); test.cross_tick(TickLabel::Upper, Direction::Right); // t3 - overflow test.increment_whirlpool_fee_growths(to_x64(70), to_x64(70)); // fees overflow to 10 // Calculate fees and rewards let update = _calculate_modify_liquidity( &test.whirlpool, &test.position, &test.tick_lower, &test.tick_upper, test.position.tick_lower_index, test.position.tick_upper_index, 0, 600, ) .unwrap(); test.apply_update(&update, 600); assert_modify_liquidity( &update, &ModifyLiquidityExpectation { whirlpool_liquidity: 10000, // time: 600, rewards at 0.909 = -2.0909 + 3 whirlpool_reward_growths: create_reward_growths(16769767339735956013), position_update: PositionUpdate { liquidity: 1000, // 20 = 10 - (-100) - (10 - (-80)) fee_growth_checkpoint_a: to_x64(20), fee_owed_a: 20000, fee_growth_checkpoint_b: to_x64(20), fee_owed_b: 20000, // 0.909 = 0.909 - (-4) - (0.909 - (-3.0909)) reward_infos: create_position_reward_infos(16769767339735956014, 909), }, tick_lower_update: TickUpdate { initialized: true, liquidity_net: 1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(100), fee_growth_outside_b: u128::MAX - to_x64(100), reward_growths_outside: create_reward_growths(u128::MAX - to_x64(4)), }, tick_upper_update: TickUpdate { initialized: true, liquidity_net: -1000, liquidity_gross: 1000, fee_growth_outside_a: u128::MAX - to_x64(80), fee_growth_outside_b: u128::MAX - to_x64(80), reward_growths_outside: create_reward_growths( 340282366920938463406357398476665961005, ), }, }, ); // 10 assert_eq!(test.whirlpool.fee_growth_global_a, 184467440737095516159); assert_eq!(test.whirlpool.fee_growth_global_b, 184467440737095516159); } } } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/mod.rs
pub mod liquidity_manager; pub mod position_manager; pub mod swap_manager; pub mod tick_manager; pub mod whirlpool_manager;
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/whirlpool_manager.rs
use crate::errors::ErrorCode; use crate::math::{add_liquidity_delta, checked_mul_div}; use crate::state::*; // Calculates the next global reward growth variables based on the given timestamp. // The provided timestamp must be greater than or equal to the last updated timestamp. pub fn next_whirlpool_reward_infos( whirlpool: &Whirlpool, next_timestamp: u64, ) -> Result<[WhirlpoolRewardInfo; NUM_REWARDS], ErrorCode> { let curr_timestamp = whirlpool.reward_last_updated_timestamp; if next_timestamp < curr_timestamp { return Err(ErrorCode::InvalidTimestamp); } // No-op if no liquidity or no change in timestamp if whirlpool.liquidity == 0 || next_timestamp == curr_timestamp { return Ok(whirlpool.reward_infos); } // Calculate new global reward growth let mut next_reward_infos = whirlpool.reward_infos; let time_delta = u128::from(next_timestamp - curr_timestamp); for reward_info in next_reward_infos.iter_mut() { if !reward_info.initialized() { continue; } // Calculate the new reward growth delta. // If the calculation overflows, set the delta value to zero. // This will halt reward distributions for this reward. let reward_growth_delta = checked_mul_div( time_delta, reward_info.emissions_per_second_x64, whirlpool.liquidity, ) .unwrap_or(0); // Add the reward growth delta to the global reward growth. let curr_growth_global = reward_info.growth_global_x64; reward_info.growth_global_x64 = curr_growth_global.wrapping_add(reward_growth_delta); } Ok(next_reward_infos) } // Calculates the next global liquidity for a whirlpool depending on its position relative // to the lower and upper tick indexes and the liquidity_delta. pub fn next_whirlpool_liquidity( whirlpool: &Whirlpool, tick_upper_index: i32, tick_lower_index: i32, liquidity_delta: i128, ) -> Result<u128, ErrorCode> { if whirlpool.tick_current_index < tick_upper_index && whirlpool.tick_current_index >= tick_lower_index { add_liquidity_delta(whirlpool.liquidity, liquidity_delta) } else { Ok(whirlpool.liquidity) } } #[cfg(test)] mod whirlpool_manager_tests { use anchor_lang::prelude::Pubkey; use crate::manager::whirlpool_manager::next_whirlpool_reward_infos; use crate::math::Q64_RESOLUTION; use crate::state::whirlpool::WhirlpoolRewardInfo; use crate::state::whirlpool::NUM_REWARDS; use crate::state::whirlpool_builder::WhirlpoolBuilder; use crate::state::Whirlpool; // Initializes a whirlpool for testing with all the rewards initialized fn init_test_whirlpool(liquidity: u128, reward_last_updated_timestamp: u64) -> Whirlpool { WhirlpoolBuilder::new() .liquidity(liquidity) .reward_last_updated_timestamp(reward_last_updated_timestamp) // Jan 1 2021 EST .reward_infos([ WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 10 << Q64_RESOLUTION, growth_global_x64: 100 << Q64_RESOLUTION, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 0b11 << (Q64_RESOLUTION - 1), // 1.5 growth_global_x64: 200 << Q64_RESOLUTION, ..Default::default() }, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1 << (Q64_RESOLUTION - 1), // 0.5 growth_global_x64: 300 << Q64_RESOLUTION, ..Default::default() }, ]) .build() } #[test] fn test_next_whirlpool_reward_infos_zero_liquidity_no_op() { let whirlpool = init_test_whirlpool(0, 1577854800); let result = next_whirlpool_reward_infos(&whirlpool, 1577855800); assert_eq!( WhirlpoolRewardInfo::to_reward_growths(&result.unwrap()), [ 100 << Q64_RESOLUTION, 200 << Q64_RESOLUTION, 300 << Q64_RESOLUTION ] ); } #[test] fn test_next_whirlpool_reward_infos_same_timestamp_no_op() { let whirlpool = init_test_whirlpool(100, 1577854800); let result = next_whirlpool_reward_infos(&whirlpool, 1577854800); assert_eq!( WhirlpoolRewardInfo::to_reward_growths(&result.unwrap()), [ 100 << Q64_RESOLUTION, 200 << Q64_RESOLUTION, 300 << Q64_RESOLUTION ] ); } #[test] #[should_panic(expected = "InvalidTimestamp")] fn test_next_whirlpool_reward_infos_invalid_timestamp() { let whirlpool = &WhirlpoolBuilder::new() .liquidity(100) .reward_last_updated_timestamp(1577854800) // Jan 1 2020 EST .build(); // New timestamp is earlier than the last updated timestamp next_whirlpool_reward_infos(whirlpool, 1577768400).unwrap(); // Dec 31 2019 EST } #[test] fn test_next_whirlpool_reward_infos_no_initialized_rewards() { let whirlpool = &WhirlpoolBuilder::new() .liquidity(100) .reward_last_updated_timestamp(1577854800) // Jan 1 2021 EST .build(); let new_timestamp = 1577854800 + 300; let result = next_whirlpool_reward_infos(whirlpool, new_timestamp).unwrap(); assert_eq!(WhirlpoolRewardInfo::to_reward_growths(&result), [0, 0, 0]); } #[test] fn test_next_whirlpool_reward_infos_some_initialized_rewards() { let whirlpool = &WhirlpoolBuilder::new() .liquidity(100) .reward_last_updated_timestamp(1577854800) // Jan 1 2021 EST .reward_info( 0, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: 1 << Q64_RESOLUTION, ..Default::default() }, ) .build(); let new_timestamp = 1577854800 + 300; let result = next_whirlpool_reward_infos(whirlpool, new_timestamp).unwrap(); assert_eq!(result[0].growth_global_x64, 3 << Q64_RESOLUTION); for i in 1..NUM_REWARDS { assert_eq!(whirlpool.reward_infos[i].growth_global_x64, 0); } } #[test] fn test_next_whirlpool_reward_infos_delta_zero_on_overflow() { let whirlpool = &WhirlpoolBuilder::new() .liquidity(100) .reward_last_updated_timestamp(0) .reward_info( 0, WhirlpoolRewardInfo { mint: Pubkey::new_unique(), emissions_per_second_x64: u128::MAX, growth_global_x64: 100, ..Default::default() }, ) .build(); let new_timestamp = i64::MAX as u64; let result = next_whirlpool_reward_infos(whirlpool, new_timestamp).unwrap(); assert_eq!(result[0].growth_global_x64, 100); } #[test] fn test_next_whirlpool_reward_infos_all_initialized_rewards() { let whirlpool = init_test_whirlpool(100, 1577854800); let new_timestamp = 1577854800 + 300; let result = next_whirlpool_reward_infos(&whirlpool, new_timestamp).unwrap(); assert_eq!(result[0].growth_global_x64, 130 << Q64_RESOLUTION); assert_eq!( result[1].growth_global_x64, 0b110011001 << (Q64_RESOLUTION - 1) // 204.5 ); assert_eq!( result[2].growth_global_x64, 0b1001011011 << (Q64_RESOLUTION - 1) // 301.5 ); } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/position_manager.rs
use crate::{ errors::ErrorCode, math::{add_liquidity_delta, checked_mul_shift_right}, state::{Position, PositionUpdate, NUM_REWARDS}, }; pub fn next_position_modify_liquidity_update( position: &Position, liquidity_delta: i128, fee_growth_inside_a: u128, fee_growth_inside_b: u128, reward_growths_inside: &[u128; NUM_REWARDS], ) -> Result<PositionUpdate, ErrorCode> { let mut update = PositionUpdate::default(); // Calculate fee deltas. // If fee deltas overflow, default to a zero value. This means the position loses // all fees earned since the last time the position was modified or fees collected. let growth_delta_a = fee_growth_inside_a.wrapping_sub(position.fee_growth_checkpoint_a); let fee_delta_a = checked_mul_shift_right(position.liquidity, growth_delta_a).unwrap_or(0); let growth_delta_b = fee_growth_inside_b.wrapping_sub(position.fee_growth_checkpoint_b); let fee_delta_b = checked_mul_shift_right(position.liquidity, growth_delta_b).unwrap_or(0); update.fee_growth_checkpoint_a = fee_growth_inside_a; update.fee_growth_checkpoint_b = fee_growth_inside_b; // Overflows allowed. Must collect fees owed before overflow. update.fee_owed_a = position.fee_owed_a.wrapping_add(fee_delta_a); update.fee_owed_b = position.fee_owed_b.wrapping_add(fee_delta_b); for (i, update) in update.reward_infos.iter_mut().enumerate() { let reward_growth_inside = reward_growths_inside[i]; let curr_reward_info = position.reward_infos[i]; // Calculate reward delta. // If reward delta overflows, default to a zero value. This means the position loses all // rewards earned since the last time the position was modified or rewards were collected. let reward_growth_delta = reward_growth_inside.wrapping_sub(curr_reward_info.growth_inside_checkpoint); let amount_owed_delta = checked_mul_shift_right(position.liquidity, reward_growth_delta).unwrap_or(0); update.growth_inside_checkpoint = reward_growth_inside; // Overflows allowed. Must collect rewards owed before overflow. update.amount_owed = curr_reward_info.amount_owed.wrapping_add(amount_owed_delta); } update.liquidity = add_liquidity_delta(position.liquidity, liquidity_delta)?; Ok(update) } #[cfg(test)] mod position_manager_unit_tests { use crate::{ math::{add_liquidity_delta, Q64_RESOLUTION}, state::{position_builder::PositionBuilder, Position, PositionRewardInfo, NUM_REWARDS}, }; use super::next_position_modify_liquidity_update; #[test] fn ok_positive_liquidity_delta_fee_growth() { let position = PositionBuilder::new(-10, 10) .liquidity(0) .fee_owed_a(10) .fee_owed_b(500) .fee_growth_checkpoint_a(100 << Q64_RESOLUTION) .fee_growth_checkpoint_b(100 << Q64_RESOLUTION) .build(); let update = next_position_modify_liquidity_update( &position, 1000, 1000 << Q64_RESOLUTION, 2000 << Q64_RESOLUTION, &[0, 0, 0], ) .unwrap(); assert_eq!(update.liquidity, 1000); assert_eq!(update.fee_growth_checkpoint_a, 1000 << Q64_RESOLUTION); assert_eq!(update.fee_growth_checkpoint_b, 2000 << Q64_RESOLUTION); assert_eq!(update.fee_owed_a, 10); assert_eq!(update.fee_owed_b, 500); for i in 0..NUM_REWARDS { assert_eq!(update.reward_infos[i].amount_owed, 0); assert_eq!(update.reward_infos[i].growth_inside_checkpoint, 0); } } #[test] fn ok_negative_liquidity_delta_fee_growth() { let position = PositionBuilder::new(-10, 10) .liquidity(10000) .fee_growth_checkpoint_a(100 << Q64_RESOLUTION) .fee_growth_checkpoint_b(100 << Q64_RESOLUTION) .build(); let update = next_position_modify_liquidity_update( &position, -5000, 120 << Q64_RESOLUTION, 250 << Q64_RESOLUTION, &[0, 0, 0], ) .unwrap(); assert_eq!(update.liquidity, 5000); assert_eq!(update.fee_growth_checkpoint_a, 120 << Q64_RESOLUTION); assert_eq!(update.fee_growth_checkpoint_b, 250 << Q64_RESOLUTION); assert_eq!(update.fee_owed_a, 200_000); assert_eq!(update.fee_owed_b, 1_500_000); for i in 0..NUM_REWARDS { assert_eq!(update.reward_infos[i].amount_owed, 0); assert_eq!(update.reward_infos[i].growth_inside_checkpoint, 0); } } #[test] #[should_panic(expected = "LiquidityUnderflow")] fn liquidity_underflow() { let position = PositionBuilder::new(-10, 10).build(); next_position_modify_liquidity_update(&position, -100, 0, 0, &[0, 0, 0]).unwrap(); } #[test] #[should_panic(expected = "LiquidityOverflow")] fn liquidity_overflow() { let position = PositionBuilder::new(-10, 10).liquidity(u128::MAX).build(); next_position_modify_liquidity_update(&position, i128::MAX, 0, 0, &[0, 0, 0]).unwrap(); } #[test] fn fee_delta_overflow_defaults_zero() { let position = PositionBuilder::new(-10, 10) .liquidity(i64::MAX as u128) .fee_owed_a(10) .fee_owed_b(20) .build(); let update = next_position_modify_liquidity_update( &position, i64::MAX as i128, u128::MAX, u128::MAX, &[0, 0, 0], ) .unwrap(); assert_eq!(update.fee_growth_checkpoint_a, u128::MAX); assert_eq!(update.fee_growth_checkpoint_b, u128::MAX); assert_eq!(update.fee_owed_a, 10); assert_eq!(update.fee_owed_b, 20); } #[test] fn ok_reward_growth() { struct Test<'a> { name: &'a str, position: &'a Position, liquidity_delta: i128, reward_growths_inside: [u128; NUM_REWARDS], expected_reward_infos: [PositionRewardInfo; NUM_REWARDS], } let position = &PositionBuilder::new(-10, 10) .liquidity(2500) .reward_infos([ PositionRewardInfo { growth_inside_checkpoint: 100 << Q64_RESOLUTION, amount_owed: 50, }, PositionRewardInfo { growth_inside_checkpoint: 250 << Q64_RESOLUTION, amount_owed: 100, }, PositionRewardInfo { growth_inside_checkpoint: 10 << Q64_RESOLUTION, amount_owed: 0, }, ]) .build(); for test in [ Test { name: "all initialized reward growths update", position, liquidity_delta: 2500, reward_growths_inside: [ 200 << Q64_RESOLUTION, 500 << Q64_RESOLUTION, 1000 << Q64_RESOLUTION, ], expected_reward_infos: [ PositionRewardInfo { growth_inside_checkpoint: 200 << Q64_RESOLUTION, amount_owed: 250_050, }, PositionRewardInfo { growth_inside_checkpoint: 500 << Q64_RESOLUTION, amount_owed: 625_100, }, PositionRewardInfo { growth_inside_checkpoint: 1000 << Q64_RESOLUTION, amount_owed: 2_475_000, }, ], }, Test { name: "reward delta overflow defaults to zero", position: &PositionBuilder::new(-10, 10) .liquidity(i64::MAX as u128) .reward_infos([ PositionRewardInfo { ..Default::default() }, PositionRewardInfo { amount_owed: 100, ..Default::default() }, PositionRewardInfo { amount_owed: 200, ..Default::default() }, ]) .build(), liquidity_delta: 2500, reward_growths_inside: [u128::MAX, 500 << Q64_RESOLUTION, 1000 << Q64_RESOLUTION], expected_reward_infos: [ PositionRewardInfo { growth_inside_checkpoint: u128::MAX, amount_owed: 0, }, PositionRewardInfo { growth_inside_checkpoint: 500 << Q64_RESOLUTION, amount_owed: 100, }, PositionRewardInfo { growth_inside_checkpoint: 1000 << Q64_RESOLUTION, amount_owed: 200, }, ], }, ] { let update = next_position_modify_liquidity_update( test.position, test.liquidity_delta, 0, 0, &test.reward_growths_inside, ) .unwrap(); assert_eq!( update.liquidity, add_liquidity_delta(test.position.liquidity, test.liquidity_delta).unwrap(), "{} - assert liquidity delta", test.name, ); for i in 0..NUM_REWARDS { assert_eq!( update.reward_infos[i].growth_inside_checkpoint, test.expected_reward_infos[i].growth_inside_checkpoint, "{} - assert growth_inside_checkpoint", test.name, ); assert_eq!( update.reward_infos[i].amount_owed, test.expected_reward_infos[i].amount_owed, "{} - assert amount_owed", test.name ); } } } #[test] fn reward_delta_overflow_defaults_zero() { let position = PositionBuilder::new(-10, 10) .liquidity(i64::MAX as u128) .reward_infos([ PositionRewardInfo { growth_inside_checkpoint: 100, amount_owed: 1000, }, PositionRewardInfo { growth_inside_checkpoint: 100, amount_owed: 1000, }, PositionRewardInfo { growth_inside_checkpoint: 100, amount_owed: 1000, }, ]) .build(); let update = next_position_modify_liquidity_update( &position, i64::MAX as i128, 0, 0, &[u128::MAX, u128::MAX, u128::MAX], ) .unwrap(); assert_eq!( update.reward_infos, [ PositionRewardInfo { growth_inside_checkpoint: u128::MAX, amount_owed: 1000, }, PositionRewardInfo { growth_inside_checkpoint: u128::MAX, amount_owed: 1000, }, PositionRewardInfo { growth_inside_checkpoint: u128::MAX, amount_owed: 1000, }, ] ) } }
0
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src
solana_public_repos/orca-so/whirlpools/programs/whirlpool/src/manager/swap_manager.rs
use solana_program::msg; use crate::{ errors::ErrorCode, manager::{ tick_manager::next_tick_cross_update, whirlpool_manager::next_whirlpool_reward_infos, }, math::*, state::*, util::SwapTickSequence, }; use anchor_lang::prelude::*; use std::convert::TryInto; #[derive(Debug)] pub struct PostSwapUpdate { pub amount_a: u64, pub amount_b: u64, pub next_liquidity: u128, pub next_tick_index: i32, pub next_sqrt_price: u128, pub next_fee_growth_global: u128, pub next_reward_infos: [WhirlpoolRewardInfo; NUM_REWARDS], pub next_protocol_fee: u64, } pub fn swap( whirlpool: &Whirlpool, swap_tick_sequence: &mut SwapTickSequence, amount: u64, sqrt_price_limit: u128, amount_specified_is_input: bool, a_to_b: bool, timestamp: u64, ) -> Result<PostSwapUpdate> { let adjusted_sqrt_price_limit = if sqrt_price_limit == NO_EXPLICIT_SQRT_PRICE_LIMIT { if a_to_b { MIN_SQRT_PRICE_X64 } else { MAX_SQRT_PRICE_X64 } } else { sqrt_price_limit }; if !(MIN_SQRT_PRICE_X64..=MAX_SQRT_PRICE_X64).contains(&adjusted_sqrt_price_limit) { return Err(ErrorCode::SqrtPriceOutOfBounds.into()); } if a_to_b && adjusted_sqrt_price_limit > whirlpool.sqrt_price || !a_to_b && adjusted_sqrt_price_limit < whirlpool.sqrt_price { return Err(ErrorCode::InvalidSqrtPriceLimitDirection.into()); } if amount == 0 { return Err(ErrorCode::ZeroTradableAmount.into()); } let tick_spacing = whirlpool.tick_spacing; let fee_rate = whirlpool.fee_rate; let protocol_fee_rate = whirlpool.protocol_fee_rate; let next_reward_infos = next_whirlpool_reward_infos(whirlpool, timestamp)?; let mut amount_remaining: u64 = amount; let mut amount_calculated: u64 = 0; let mut curr_sqrt_price = whirlpool.sqrt_price; let mut curr_tick_index = whirlpool.tick_current_index; let mut curr_liquidity = whirlpool.liquidity; let mut curr_protocol_fee: u64 = 0; let mut curr_array_index: usize = 0; let mut curr_fee_growth_global_input = if a_to_b { whirlpool.fee_growth_global_a } else { whirlpool.fee_growth_global_b }; while amount_remaining > 0 && adjusted_sqrt_price_limit != curr_sqrt_price { let (next_array_index, next_tick_index) = swap_tick_sequence .get_next_initialized_tick_index( curr_tick_index, tick_spacing, a_to_b, curr_array_index, )?; let (next_tick_sqrt_price, sqrt_price_target) = get_next_sqrt_prices(next_tick_index, adjusted_sqrt_price_limit, a_to_b); let swap_computation = compute_swap( amount_remaining, fee_rate, curr_liquidity, curr_sqrt_price, sqrt_price_target, amount_specified_is_input, a_to_b, )?; if amount_specified_is_input { amount_remaining = amount_remaining .checked_sub(swap_computation.amount_in) .ok_or(ErrorCode::AmountRemainingOverflow)?; amount_remaining = amount_remaining .checked_sub(swap_computation.fee_amount) .ok_or(ErrorCode::AmountRemainingOverflow)?; amount_calculated = amount_calculated .checked_add(swap_computation.amount_out) .ok_or(ErrorCode::AmountCalcOverflow)?; } else { amount_remaining = amount_remaining .checked_sub(swap_computation.amount_out) .ok_or(ErrorCode::AmountRemainingOverflow)?; amount_calculated = amount_calculated .checked_add(swap_computation.amount_in) .ok_or(ErrorCode::AmountCalcOverflow)?; amount_calculated = amount_calculated .checked_add(swap_computation.fee_amount) .ok_or(ErrorCode::AmountCalcOverflow)?; } let (next_protocol_fee, next_fee_growth_global_input) = calculate_fees( swap_computation.fee_amount, protocol_fee_rate, curr_liquidity, curr_protocol_fee, curr_fee_growth_global_input, ); curr_protocol_fee = next_protocol_fee; curr_fee_growth_global_input = next_fee_growth_global_input; if swap_computation.next_price == next_tick_sqrt_price { let (next_tick, next_tick_initialized) = swap_tick_sequence .get_tick(next_array_index, next_tick_index, tick_spacing) .map_or_else(|_| (None, false), |tick| (Some(tick), tick.initialized)); if next_tick_initialized { let (fee_growth_global_a, fee_growth_global_b) = if a_to_b { (curr_fee_growth_global_input, whirlpool.fee_growth_global_b) } else { (whirlpool.fee_growth_global_a, curr_fee_growth_global_input) }; let (update, next_liquidity) = calculate_update( next_tick.unwrap(), a_to_b, curr_liquidity, fee_growth_global_a, fee_growth_global_b, &next_reward_infos, )?; curr_liquidity = next_liquidity; swap_tick_sequence.update_tick( next_array_index, next_tick_index, tick_spacing, &update, )?; } let tick_offset = swap_tick_sequence.get_tick_offset( next_array_index, next_tick_index, tick_spacing, )?; // Increment to the next tick array if either condition is true: // - Price is moving left and the current tick is the start of the tick array // - Price is moving right and the current tick is the end of the tick array curr_array_index = if (a_to_b && tick_offset == 0) || (!a_to_b && tick_offset == TICK_ARRAY_SIZE as isize - 1) { next_array_index + 1 } else { next_array_index }; // The get_init_tick search is inclusive of the current index in an a_to_b trade. // We therefore have to shift the index by 1 to advance to the next init tick to the left. curr_tick_index = if a_to_b { next_tick_index - 1 } else { next_tick_index }; } else if swap_computation.next_price != curr_sqrt_price { curr_tick_index = tick_index_from_sqrt_price(&swap_computation.next_price); } curr_sqrt_price = swap_computation.next_price; } // Reject partial fills if no explicit sqrt price limit is set and trade is exact out mode if amount_remaining > 0 && !amount_specified_is_input && sqrt_price_limit == NO_EXPLICIT_SQRT_PRICE_LIMIT { return Err(ErrorCode::PartialFillError.into()); } let (amount_a, amount_b) = if a_to_b == amount_specified_is_input { (amount - amount_remaining, amount_calculated) } else { (amount_calculated, amount - amount_remaining) }; let fee_growth = if a_to_b { curr_fee_growth_global_input - whirlpool.fee_growth_global_a } else { curr_fee_growth_global_input - whirlpool.fee_growth_global_b }; // Log delta in fee growth to track pool usage over time with off-chain analytics msg!("fee_growth: {}", fee_growth); Ok(PostSwapUpdate { amount_a, amount_b, next_liquidity: curr_liquidity, next_tick_index: curr_tick_index, next_sqrt_price: curr_sqrt_price, next_fee_growth_global: curr_fee_growth_global_input, next_reward_infos, next_protocol_fee: curr_protocol_fee, }) } fn calculate_fees( fee_amount: u64, protocol_fee_rate: u16, curr_liquidity: u128, curr_protocol_fee: u64, curr_fee_growth_global_input: u128, ) -> (u64, u128) { let mut next_protocol_fee = curr_protocol_fee; let mut next_fee_growth_global_input = curr_fee_growth_global_input; let mut global_fee = fee_amount; if protocol_fee_rate > 0 { let delta = calculate_protocol_fee(global_fee, protocol_fee_rate); global_fee -= delta; next_protocol_fee = next_protocol_fee.wrapping_add(delta); } if curr_liquidity > 0 { next_fee_growth_global_input = next_fee_growth_global_input .wrapping_add(((global_fee as u128) << Q64_RESOLUTION) / curr_liquidity); } (next_protocol_fee, next_fee_growth_global_input) } fn calculate_protocol_fee(global_fee: u64, protocol_fee_rate: u16) -> u64 { ((global_fee as u128) * (protocol_fee_rate as u128) / PROTOCOL_FEE_RATE_MUL_VALUE) .try_into() .unwrap() } fn calculate_update( tick: &Tick, a_to_b: bool, liquidity: u128, fee_growth_global_a: u128, fee_growth_global_b: u128, reward_infos: &[WhirlpoolRewardInfo; NUM_REWARDS], ) -> Result<(TickUpdate, u128)> { // Use updated fee_growth for crossing tick // Use -liquidity_net if going left, +liquidity_net going right let signed_liquidity_net = if a_to_b { -tick.liquidity_net } else { tick.liquidity_net }; let update = next_tick_cross_update(tick, fee_growth_global_a, fee_growth_global_b, reward_infos)?; // Update the global liquidity to reflect the new current tick let next_liquidity = add_liquidity_delta(liquidity, signed_liquidity_net)?; Ok((update, next_liquidity)) } fn get_next_sqrt_prices( next_tick_index: i32, sqrt_price_limit: u128, a_to_b: bool, ) -> (u128, u128) { let next_tick_price = sqrt_price_from_tick_index(next_tick_index); let next_sqrt_price_limit = if a_to_b { sqrt_price_limit.max(next_tick_price) } else { sqrt_price_limit.min(next_tick_price) }; (next_tick_price, next_sqrt_price_limit) } #[cfg(test)] mod swap_liquidity_tests { use super::*; use crate::util::{create_whirlpool_reward_infos, test_utils::swap_test_fixture::*}; #[test] /// A rightward swap on a pool with zero liquidity across the range with initialized ticks. /// |____c1___p1________|____p1___________|______________c2| /// /// Expectation: /// The swap will swap 0 assets but the next tick index will end at the end of tick-range. fn zero_l_across_tick_range_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 0, curr_tick_index: 255, // c1 start_tick_index: 0, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(1720), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![TestTickInfo { // p1 index: 448, liquidity_net: 0, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { // p1 index: 720, liquidity_net: 0, ..Default::default() }]), array_3_ticks: Some(&vec![]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: 1720, end_liquidity: 0, end_reward_growths: [10, 10, 10], }, ); let tick_lower = tick_sequence.get_tick(0, 448, TS_8).unwrap(); assert_swap_tick_state( tick_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); let tick_upper = tick_sequence.get_tick(1, 720, TS_8).unwrap(); assert_swap_tick_state( tick_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A leftward swap on a pool with zero liquidity across the range with initialized ticks. /// |____c2___p1________|____p1___________|______________c1| /// /// Expectation: /// The swap will swap 0 assets but the next tick index will end at the end of tick-range. fn zero_l_across_tick_range_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 0, curr_tick_index: 1720, // c1 start_tick_index: 1408, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(100), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![], array_2_ticks: Some(&vec![TestTickInfo { // p1 index: 720, liquidity_net: 0, ..Default::default() }]), array_3_ticks: Some(&vec![TestTickInfo { // p1 index: 448, liquidity_net: 0, ..Default::default() }]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: 100, end_liquidity: 0, end_reward_growths: [10, 10, 10], }, ); let lower_tick = tick_sequence.get_tick(1, 720, TS_8).unwrap(); assert_swap_tick_state( lower_tick, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); let lower_tick = tick_sequence.get_tick(2, 448, TS_8).unwrap(); assert_swap_tick_state( lower_tick, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A rightward swap on a pool with zero liquidity at the end of the tick-range. /// |_____c1__p1________|_______________|_______________c2| /// /// Expectation: /// The swap will swap some assets up to the last initialized tick and /// the next tick index will end at the end of tick-range. fn zero_l_after_first_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 255, // c1 start_tick_index: 0, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(1720), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![TestTickInfo { // p1 index: 448, liquidity_net: -100_000, ..Default::default() }], array_2_ticks: Some(&vec![]), array_3_ticks: Some(&vec![]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 948, traded_amount_b: 983, end_tick_index: 1720, end_liquidity: 0, end_reward_growths: [10, 10, 10], }, ); let tick = tick_sequence.get_tick(0, 448, TS_8).unwrap(); assert_swap_tick_state( tick, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A leftward swap on a pool with zero liquidity at the end of the tick-range. /// |c2_______p1________|_______________|_____c1_________| /// /// Expectation: /// The swap will swap some assets up to the last initialized tick and /// the next tick index will end at the end of tick-range. fn zero_l_after_first_tick_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 1720, // c1 start_tick_index: 1408, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(0), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![], array_2_ticks: Some(&vec![]), array_3_ticks: Some(&vec![TestTickInfo { // p1 index: 448, liquidity_net: 100_000, ..Default::default() }]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 6026, traded_amount_b: 6715, end_tick_index: -1, // -1 a-to-b decrements by one when target price reached end_liquidity: 0, end_reward_growths: [10, 10, 10], }, ); let tick = tick_sequence.get_tick(2, 448, TS_8).unwrap(); assert_swap_tick_state( tick, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A rightward swap that traverses an empty gap with no liquidity. /// |_______p1____c1___|____p1_______p2__|___c2__p2________| /// /// Expectation: /// The swap will swap some assets up to the end of p1, jump through the gap /// and continue swapping assets in p2 until the expected trade amount is satisfied. fn zero_l_between_init_ticks_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 500, // c1 start_tick_index: 0, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(1430), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![TestTickInfo { // p1 index: 448, liquidity_net: 100_000, ..Default::default() }], array_2_ticks: Some(&vec![ TestTickInfo { // p1 index: 768, liquidity_net: -100_000, ..Default::default() }, TestTickInfo { // p2 index: 1120, liquidity_net: 100_000, ..Default::default() }, ]), array_3_ticks: Some(&vec![TestTickInfo { // p2 index: 1536, liquidity_net: -100_000, ..Default::default() }]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 2752, traded_amount_b: 3036, end_tick_index: 1430, end_liquidity: 100000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(0, 448, TS_8).unwrap(); let p1_upper = tick_sequence.get_tick(1, 768, TS_8).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state( p1_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); let p2_lower = tick_sequence.get_tick(1, 1120, TS_8).unwrap(); let p2_upper = tick_sequence.get_tick(2, 1536, TS_8).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state(p2_upper, &TickExpectation::default()); } #[test] /// A leftward swap that traverses an empty gap with no liquidity. /// |_______p1____c2___|____p1_______p2__|___c1__p2________| /// /// Expectation: /// The swap will swap some assets up to the end of p2, jump through the gap /// and continue swapping assets in p1 until the expected trade amount is satisfied. fn zero_l_between_init_ticks_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 1440, // c1 start_tick_index: 1408, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(500), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![TestTickInfo { // p2 index: 1448, liquidity_net: -100_000, ..Default::default() }], array_2_ticks: Some(&vec![ TestTickInfo { // p1 index: 720, liquidity_net: -100_000, ..Default::default() }, TestTickInfo { // p2 index: 1120, liquidity_net: 100_000, ..Default::default() }, ]), array_3_ticks: Some(&vec![TestTickInfo { // p1 index: 448, liquidity_net: 100_000, ..Default::default() }]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 2568, traded_amount_b: 2839, end_tick_index: 500, end_liquidity: 100000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(2, 448, TS_8).unwrap(); let p1_upper = tick_sequence.get_tick(1, 720, TS_8).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state( p1_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); let p2_lower = tick_sequence.get_tick(1, 1120, TS_8).unwrap(); let p2_upper = tick_sequence.get_tick(0, 1448, TS_8).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state(p2_upper, &TickExpectation::default()); } #[test] /// A swap that moves the price to the right to another initialized /// tick within the same array. /// |_c1__p1___p2____p2__c2__p1__| /// /// Expectation: /// The swap will traverse through all initialized ticks (some of p1, p2) and /// exit until the expected trade amount is satisfied. fn next_initialized_tick_in_same_array_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 5, // c1 start_tick_index: 0, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(400), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![ TestTickInfo { // p1 index: 8, liquidity_net: 100_000, ..Default::default() }, TestTickInfo { // p2 index: 128, liquidity_net: 200_000, ..Default::default() }, TestTickInfo { // p2 index: 320, liquidity_net: -200_000, ..Default::default() }, TestTickInfo { // p1 index: 448, liquidity_net: -100_000, ..Default::default() }, ], fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new(swap_test_info.tick_arrays[0].borrow_mut(), None, None); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 5791, traded_amount_b: 5920, end_tick_index: 400, end_liquidity: 200000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(0, 8, TS_8).unwrap(); let p1_upper = tick_sequence.get_tick(0, 448, TS_8).unwrap(); assert_swap_tick_state( p1_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state(p1_upper, &TickExpectation::default()); let p2_lower = tick_sequence.get_tick(0, 128, TS_8).unwrap(); let p2_upper = tick_sequence.get_tick(0, 320, TS_8).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves the price to the left to another initialized /// tick within the same array. /// |_c2__p1___p2____p2__p1__c1_| /// /// Expectation: /// The swap will traverse through all initialized ticks (some of p1, p2) and /// exit until the expected trade amount is satisfied. fn next_initialized_tick_in_same_array_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 100_000, curr_tick_index: 568, // c1 start_tick_index: 0, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(5), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![ TestTickInfo { // p1 index: 8, liquidity_net: 100_000, ..Default::default() }, TestTickInfo { // p2 index: 128, liquidity_net: 200_000, ..Default::default() }, TestTickInfo { // p2 index: 320, liquidity_net: -200_000, ..Default::default() }, TestTickInfo { // p1 index: 448, liquidity_net: -100_000, ..Default::default() }, ], fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new(swap_test_info.tick_arrays[0].borrow_mut(), None, None); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 6850, traded_amount_b: 7021, end_tick_index: 5, end_liquidity: 100000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(0, 8, TS_8).unwrap(); let p1_upper = tick_sequence.get_tick(0, 448, TS_8).unwrap(); assert_swap_tick_state( p1_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p1_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); let p2_lower = tick_sequence.get_tick(0, 128, TS_8).unwrap(); let p2_upper = tick_sequence.get_tick(0, 320, TS_8).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves the price to the right from 1 tick-array to the next tick-array. /// |____p1____c1____p2__|__p2__c2____p1______| /// /// Expectation: /// The swap loop will traverse across the two tick-arrays on each initialized-tick and /// at the end of the first tick-array. It will complete the swap and the next tick index /// is in tick-array 2. fn next_initialized_tick_in_next_array_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: 25000, // c1 start_tick_index: 22528, trade_amount: 11_000_000, sqrt_price_limit: sqrt_price_from_tick_index(37000), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![ TestTickInfo { // p1 index: 23168, liquidity_net: 5_000_000, ..Default::default() }, TestTickInfo { // p2 index: 28416, liquidity_net: 6_000_000, ..Default::default() }, ], array_2_ticks: Some(&vec![ TestTickInfo { // p2 index: 33920, liquidity_net: -6_000_000, ..Default::default() }, TestTickInfo { // p1 index: 37504, liquidity_net: -5_000_000, ..Default::default() }, ]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), None, ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 1770620, traded_amount_b: 39429146, end_tick_index: 37000, end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(0, 23168, TS_128).unwrap(); let p1_upper = tick_sequence.get_tick(1, 37504, TS_128).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state(p1_upper, &TickExpectation::default()); let p2_lower = tick_sequence.get_tick(0, 28416, TS_128).unwrap(); let p2_upper = tick_sequence.get_tick(1, 33920, TS_128).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves the price to the left from 1 tick-array to the next tick-array. /// |____p1____c2____p2__|__p2__c1____p1______| /// /// Expectation: /// The swap loop will traverse across the two tick-arrays on each initialized-tick and /// at the end of tick-array 2. It will complete the swap and the next tick index /// is in tick-array 1. fn next_initialized_tick_in_next_array_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: 37000, // c1 start_tick_index: 29824, trade_amount: 110_000_000, sqrt_price_limit: sqrt_price_from_tick_index(25000), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![ TestTickInfo { // p2 index: 30720, liquidity_net: -6_000_000, ..Default::default() }, TestTickInfo { // p1 index: 37504, liquidity_net: -5_000_000, ..Default::default() }, ], array_2_ticks: Some(&vec![ TestTickInfo { // p1 index: 23168, liquidity_net: 5_000_000, ..Default::default() }, TestTickInfo { // p2 index: 28416, liquidity_net: 6_000_000, ..Default::default() }, ]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), None, ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 1579669, traded_amount_b: 34593019, end_tick_index: 25000, end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(1, 23168, TS_128).unwrap(); let p1_upper = tick_sequence.get_tick(0, 37504, TS_128).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state(p1_upper, &TickExpectation::default()); let p2_lower = tick_sequence.get_tick(1, 28416, TS_128).unwrap(); let p2_upper = tick_sequence.get_tick(0, 30720, TS_128).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves the price to the right, jumping a tick-array with 0 /// initialized tick in between. /// |____p1____c1____p2__|_________________|__p2___c2__p1______| /// /// Expectation: /// The swap loop will traverse across the tick-range on each initialized-tick and /// at the end of all traversed tick-arrays. It will complete the swap and the next tick index /// is in tick-array 3. fn next_initialized_tick_not_in_adjacent_array_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: 30080, // c1 start_tick_index: 29824, trade_amount: 10_000_000, sqrt_price_limit: sqrt_price_from_tick_index(57000), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![ TestTickInfo { // p1 index: 29952, liquidity_net: 5_000_000, ..Default::default() }, TestTickInfo { // p2 index: 30336, liquidity_net: 6_000_000, ..Default::default() }, ], array_2_ticks: Some(&vec![]), // 41,088 array_3_ticks: Some(&vec![ // 52,352 TestTickInfo { // p2 index: 56192, liquidity_net: -6_000_000, ..Default::default() }, TestTickInfo { // p1 index: 57216, liquidity_net: -5_000_000, ..Default::default() }, ]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 2763589, traded_amount_b: 212908090, end_tick_index: 57000, end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(0, 29952, TS_128).unwrap(); let p1_upper = tick_sequence.get_tick(2, 57216, TS_128).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state(p1_upper, &TickExpectation::default()); let p2_lower = tick_sequence.get_tick(0, 30336, TS_128).unwrap(); let p2_upper = tick_sequence.get_tick(2, 56192, TS_128).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves the price to the left, jumping a tick-array with 0 /// initialized tick in between. /// |____p1____c2____p2__|_________________|__p2___c1__p1______| /// /// Expectation: /// The swap loop will traverse across the tick-range on each initialized-tick and /// at the end of all traversed tick-arrays. It will complete the swap and the next tick index /// is in tick-array 1. fn next_initialized_tick_not_in_adjacent_array_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: 48896, // c1 start_tick_index: 48256, trade_amount: 117_900_000, sqrt_price_limit: sqrt_price_from_tick_index(0), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![ TestTickInfo { // p2 index: 48512, liquidity_net: -6_000_000, ..Default::default() }, TestTickInfo { // p1 index: 49280, liquidity_net: -5_000_000, ..Default::default() }, ], array_2_ticks: Some(&vec![]), array_3_ticks: Some(&vec![ TestTickInfo { // p1 index: 29952, liquidity_net: 5_000_000, ..Default::default() }, TestTickInfo { // p2 index: 30336, liquidity_net: 6_000_000, ..Default::default() }, ]), fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 2281190, traded_amount_b: 117900000, end_tick_index: 30041, end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); let p1_lower = tick_sequence.get_tick(2, 29952, TS_128).unwrap(); let p1_upper = tick_sequence.get_tick(0, 49280, TS_128).unwrap(); assert_swap_tick_state(p1_lower, &TickExpectation::default()); assert_swap_tick_state(p1_upper, &TickExpectation::default()); let p2_lower = tick_sequence.get_tick(2, 30336, TS_128).unwrap(); let p2_upper = tick_sequence.get_tick(0, 48512, TS_128).unwrap(); assert_swap_tick_state( p2_lower, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); assert_swap_tick_state( p2_upper, &TickExpectation { fee_growth_outside_a: 100, fee_growth_outside_b: 100, reward_growths_outside: [10, 10, 10], }, ); } #[test] /// A swap that moves across towards the right on all tick-arrays /// with no initialized-ticks in the tick-range, but has the liquidity to support it /// as long as sqrt_price or amount stops in the tick-range. /// |c1_____________|_________________|________________c2|...limit /// /// Expectation: /// The swap loop will traverse across the tick-range on the last index of each tick-array. /// It will complete the swap at the end of the tick-range. fn no_initialized_tick_range_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500_000, curr_tick_index: -322176, // c1 start_tick_index: -322176, trade_amount: 1_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(0), amount_specified_is_input: false, a_to_b: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 1_000_000_000_000, traded_amount_b: 1, end_tick_index: -317663, end_liquidity: 500000, end_reward_growths: [10, 10, 10], }, ); } #[test] /// A swap that moves across towards the right on all tick-arrays /// with no initialized-ticks in the tick-range, but has the liquidity to support it. /// |c1_____________|_________________|_________________|...limit /// /// Expectation: /// The swap loop will fail if the sqrt_price exceeds the last tick of the last array #[should_panic(expected = "TickArraySequenceInvalidIndex")] fn sqrt_price_exceeds_tick_range_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500_000, curr_tick_index: -322176, // c1 start_tick_index: -322176, trade_amount: 100_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(0), amount_specified_is_input: false, a_to_b: false, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 1_000_000_000_000, traded_amount_b: 1, end_tick_index: -317663, end_liquidity: 500000, end_reward_growths: [10, 10, 10], }, ); } #[test] /// A swap that moves across towards the left on all tick-arrays /// with no initialized-ticks in the tick-range, but has the liquidity to support it, /// as long as sqrt_price or amount stops in the tick-range. /// |limit, c2____________|_________________|____c1__________| /// -326656 -315,392 -304,128 -292,864 /// /// Expectation: /// The swap loop will traverse across the tick-range on the last index of each tick-array. /// It will complete the swap at the start of the tick-range. /// fn no_initialized_tick_range_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: -302080, // c1 start_tick_index: -304128, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(-326656), amount_specified_is_input: false, a_to_b: true, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 96362985379416, traded_amount_b: 2, end_tick_index: -326657, // -1 because swap crossed 340608 and is an initialized tick end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); } #[test] /// A swap that moves across towards past the left on all tick-arrays /// with no initialized-ticks in the tick-range, but has the liquidity to support it. /// limit |____________|_________________|____c1__________| /// -326656 -315,392 -304,128 -292,864 /// /// Expectation: /// The swap loop will fail if the sqrt_price exceeds the last tick of the last array #[should_panic(expected = "TickArraySequenceInvalidIndex")] fn sqrt_price_exceeds_tick_range_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 11_000_000, curr_tick_index: -302080, // c1 start_tick_index: -304128, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(-326657), amount_specified_is_input: false, a_to_b: true, fee_growth_global_a: 100, fee_growth_global_b: 100, reward_infos: create_whirlpool_reward_infos(100, 10), ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 96362985379416, traded_amount_b: 2, end_tick_index: -326657, // -1 because swap crossed 340608 and is an initialized tick end_liquidity: 11000000, end_reward_growths: [10, 10, 10], }, ); } #[test] #[should_panic(expected = "MultiplicationShiftRightOverflow")] /// A swap in a pool with maximum liquidity that reaches the maximum tick /// |__p1_____c1______p1_c2|max /// /// Expectation: /// The swap will error on `TokenMaxExceeded` as it is not possible to increment more than the maximum token allowed. fn max_l_at_max_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: u64::MAX as u128, curr_tick_index: 442500, // c1 start_tick_index: 442368, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(443636), amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![ TestTickInfo { // p1 index: 442496, liquidity_net: 500_000_000, ..Default::default() }, TestTickInfo { // p1 index: 443520, liquidity_net: -500_000_000, ..Default::default() }, ], array_2_ticks: None, array_3_ticks: None, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let _post_swap = swap_test_info.run(&mut tick_sequence, 100); } #[test] /// A swap in a pool that reaches the minimum tick /// l = 0 /// min|c2_p1_____c1___p1| /// /// Expectation: /// The swap will not trade anything and end of the min-tick-index. fn min_l_at_min_sqrt_price_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500_000_000, curr_tick_index: -442500, // c1 start_tick_index: -451584, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(-443636), amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![ TestTickInfo { // p1 index: -442496, liquidity_net: -500_000_000, ..Default::default() }, TestTickInfo { // p1 index: -443520, liquidity_net: 500_000_000, ..Default::default() }, ], array_2_ticks: None, array_3_ticks: None, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 106151097514387301, traded_amount_b: 0, end_tick_index: -443637, end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ) } #[test] /// The swap crosses the last tick of a tick array and then continues /// into the next tick array. /// /// |__________c1|t1|________c2____|_____________| /// -33792 -22528 -11264 fn traversal_from_last_tick_in_array_to_next_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -22657, // c1 start_tick_index: -33792, trade_amount: 10_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-22300), amount_specified_is_input: true, a_to_b: false, array_1_ticks: &vec![TestTickInfo { // p1 index: -22656, liquidity_net: 100, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { // p1 index: -22400, liquidity_net: -100, ..Default::default() }]), array_3_ticks: Some(&vec![]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 95975095232, traded_amount_b: 10000000000, end_tick_index: -22576, end_liquidity: 7587362620457, end_reward_growths: [10, 10, 10], }, ); } #[test] /// The swap crosses the first tick of the tick array and then continues /// into the next tick array. /// /// |__________|________c2____|t1|c1___________| /// -33792 -22528 -11264 fn traversal_from_last_tick_in_array_to_next_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -11135, // c1 start_tick_index: -11264, trade_amount: 100_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-22300), amount_specified_is_input: true, a_to_b: true, array_1_ticks: &vec![TestTickInfo { // p1 index: -11264, liquidity_net: 100, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { // p1 index: -22400, liquidity_net: -100, ..Default::default() }]), array_3_ticks: Some(&vec![]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 9897370858896, traded_amount_b: 1860048818693, end_tick_index: -22300, end_liquidity: 7587362620257, end_reward_growths: [10, 10, 10], }, ); } #[test] /// /// |_______c1___t1|__________t2|__________t3,c2| /// -33792 -22528 -11264 fn traversal_to_last_tick_in_next_array_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -22784, // c1 start_tick_index: -33792, trade_amount: 10_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-2), amount_specified_is_input: true, a_to_b: false, array_1_ticks: &vec![TestTickInfo { index: -22784, liquidity_net: 100, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { index: -11392, liquidity_net: 100, ..Default::default() }]), array_3_ticks: Some(&vec![TestTickInfo { index: -256, liquidity_net: -100, ..Default::default() }]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 16115482403568, traded_amount_b: 5157940702072, end_tick_index: -2, end_liquidity: 7587362620357, end_reward_growths: [10, 10, 10], }, ); } #[test] /// /// |_______c1___t1|__________t2|__________t3,c2| /// -33792 -22528 -11264 fn traversal_to_last_tick_in_last_array_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -22784, // c1 start_tick_index: -33792, trade_amount: 10_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-128), amount_specified_is_input: true, a_to_b: false, array_1_ticks: &vec![TestTickInfo { index: -22784, liquidity_net: 100, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { index: -11392, liquidity_net: 100, ..Default::default() }]), array_3_ticks: Some(&vec![TestTickInfo { index: -128, liquidity_net: -100, ..Default::default() }]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 16067528741228, traded_amount_b: 5110297712223, end_tick_index: -128, end_liquidity: 7587362620357, end_reward_growths: [10, 10, 10], }, ); } #[test] /// /// |t1c1__________|t2___________|_________t1c1| /// -33792 -22528 -11264 fn traversal_to_last_tick_in_next_array_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -256, // c1 start_tick_index: -11264, trade_amount: 100_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-33791), amount_specified_is_input: true, a_to_b: true, array_1_ticks: &vec![TestTickInfo { index: -256, liquidity_net: -100, ..Default::default() }], array_2_ticks: Some(&vec![TestTickInfo { index: -22528, liquidity_net: 100, ..Default::default() }]), array_3_ticks: Some(&vec![TestTickInfo { index: -33792, liquidity_net: 100, ..Default::default() }]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 33412493784228, traded_amount_b: 6090103077425, end_tick_index: -33791, end_liquidity: 7587362620357, end_reward_growths: [10, 10, 10], }, ); } #[test] /// /// |t1c1__________|t2___________|_________t1c1| /// -33792 -22528 -11264 fn traversal_to_last_tick_in_last_array_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 7587362620357, curr_tick_index: -256, // c1 start_tick_index: -11264, trade_amount: 100_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-33792), amount_specified_is_input: true, a_to_b: true, array_1_ticks: &vec![TestTickInfo { index: -256, liquidity_net: -100, ..Default::default() }], array_2_ticks: Some(&vec![]), array_3_ticks: Some(&vec![TestTickInfo { index: -33792, liquidity_net: 100, ..Default::default() }]), reward_infos: create_whirlpool_reward_infos(100, 10), fee_growth_global_a: 100, fee_growth_global_b: 100, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 33414548612789, traded_amount_b: 6090173110437, end_tick_index: -33793, end_liquidity: 7587362620357, end_reward_growths: [10, 10, 10], }, ); } } #[cfg(test)] mod swap_sqrt_price_tests { use super::*; use crate::util::test_utils::swap_test_fixture::*; #[test] #[should_panic(expected = "SqrtPriceOutOfBounds")] /// A swap with the price limit over the max price limit. /// |__p1_____p1_____c1___max|...limit| /// /// Expectation: /// Fail on out of bounds sqrt-price-limit. fn sqrt_price_limit_over_max_tick() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500, curr_tick_index: 442500, // c1 start_tick_index: 442368, trade_amount: 100_000_000_000_000_000, sqrt_price_limit: MAX_SQRT_PRICE_X64 + 1, amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// An attempt to swap to the maximum tick without the last initializable tick /// being initialized /// |__p1_____p1_____c1___c2,max,limit| /// /// Expectation: /// Successfully swap to the maximum tick / maximum sqrt-price fn sqrt_price_limit_at_max_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 10, curr_tick_index: 443635, // c1 start_tick_index: 442368, trade_amount: 100_000_000_000_000_000, sqrt_price_limit: MAX_SQRT_PRICE_X64, amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 2147283, end_tick_index: 443636, end_liquidity: 10, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A rightward swap that is limited by the max price limit. /// |____p1______c1______p1_c2,max,limit| /// /// Expectation: /// The swap will complete at the maximum tick index fn sqrt_price_limit_at_max_with_last_init_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500, curr_tick_index: 442500, // c1 start_tick_index: 442368, trade_amount: 100_000_000_000_000_000, sqrt_price_limit: MAX_SQRT_PRICE_X64, // c2, limit amount_specified_is_input: false, a_to_b: false, array_1_ticks: &vec![ TestTickInfo { // p1 index: 442496, liquidity_net: 500, ..Default::default() }, TestTickInfo { // p2 index: 443520, liquidity_net: -500, ..Default::default() }, ], array_2_ticks: None, array_3_ticks: None, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 106151097576, end_tick_index: 443636, end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ) } #[test] #[should_panic(expected = "SqrtPriceOutOfBounds")] /// A swap with the price limit under the min price limit. /// |limit...|min____c2____c1____| /// /// Expectation: /// Fail on out of bounds sqrt-price-limit. fn sqrt_price_limit_under_min_tick() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500, curr_tick_index: -443500, // c1 start_tick_index: -451584, trade_amount: 100_000_000_000_000_000, sqrt_price_limit: MIN_SQRT_PRICE_X64 - 1, amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![], array_2_ticks: None, array_3_ticks: None, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// A leftward swap into the min price with the price limit set at min price. /// |limit,min,p1,c2______c1______| /// /// Expectation: /// The swap will succeed and exits at the minimum tick index fn sqrt_price_limit_at_min_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 50_000_000, curr_tick_index: -442620, // c1 start_tick_index: -451584, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(-443636), // c2, limit amount_specified_is_input: false, a_to_b: true, array_1_ticks: &vec![ TestTickInfo { // p1 index: -442624, liquidity_net: -500_000_000, ..Default::default() }, TestTickInfo { // p1 index: -443520, liquidity_net: 550_000_000, ..Default::default() }, ], array_2_ticks: None, array_3_ticks: None, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 102927825595253698, traded_amount_b: 0, end_tick_index: -443637, end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A leftward swap with the sqrt-price limit lower than the swap-target. /// |______limit____c2_____c1_| /// /// Expectation: /// The swap will succeed and exits when expected trade amount is swapped. fn sqrt_price_limit_under_current_tick_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(-226000), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 613293650976, traded_amount_b: 100, end_tick_index: -225397, end_liquidity: 5_000_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A leftward swap with the sqrt-price limit higher than the swap target. /// |______c2____limit______c1_| /// /// Expectation: /// Swap will be stopped at the sqrt-price-limit fn sqrt_price_limit_under_current_tick_stop_limit_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(-225380), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 293539494127, traded_amount_b: 47, end_tick_index: -225380, end_liquidity: 5_000_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] #[should_panic(expected = "InvalidSqrtPriceLimitDirection")] /// A rightward swap with the sqrt-price below the current tick index. /// |______limit____c1_____c2_| /// /// Expectation: /// Swap will fail because the sqrt-price limit is in the opposite direction. fn sqrt_price_limit_under_current_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(-225790), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// A leftward swap with the sqrt-price limit at the current tick index. /// |__c2____limit,c1_______| /// /// Expectation: /// Swap will not swap and exit on the price limit since it cannot proceed into the price limit. fn sqrt_price_limit_at_current_tick_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(-225365), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: -225365, end_liquidity: 5_000_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A rightward swap with the sqrt-price limit at the current tick index. /// |____c1,limit__c2__| /// /// Expectation: /// Swap will not swap and exit on the price limit since it cannot proceed into the price limit. fn sqrt_price_limit_at_current_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(-225365), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: -225365, end_liquidity: 5_000_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] #[should_panic(expected = "InvalidSqrtPriceLimitDirection")] /// A leftward swap with the sqrt-price limit higher than the current tick index. /// |____c2___c1___limit__| /// /// Expectation: /// Swap will fail because price limit is in the wrong direction. fn sqrt_price_limit_over_current_tick_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000, curr_tick_index: 64900, // c1 start_tick_index: 64512, trade_amount: 100_000, sqrt_price_limit: sqrt_price_from_tick_index(65000), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// A rightward swap with the sqrt-price limit higher than the current tick index. /// |__c1_____c2___limit__| /// /// Expectataion: /// The swap will succeed and exits when expected trade amount is swapped. fn sqrt_price_limit_over_current_tick_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000, curr_tick_index: 64900, // c1 start_tick_index: 64512, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(65388), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 100, traded_amount_b: 65865, end_tick_index: 64910, end_liquidity: 5_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A rightward swap with the sqrt-price limit lower than the next tick index. /// |____c1____limit__c2__| /// /// Expectataion: /// The swap will succeed and exits at the sqrt-price limit. fn sqrt_price_limit_over_current_tick_stop_limit_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000, curr_tick_index: 64900, // c1 start_tick_index: 64512, trade_amount: 100, sqrt_price_limit: sqrt_price_from_tick_index(64905), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 48, traded_amount_b: 32075, end_tick_index: 64905, end_liquidity: 5_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] #[should_panic(expected = "TickArraySequenceInvalidIndex")] /// An attempt to swap walking over 3 tick arrays /// |c1_____|_______|_______|c2 limit(0) /// /// Expectation: /// Swap will fail due to over run fn sqrt_price_limit_0_b_to_a_map_to_max() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: 1, // c1 start_tick_index: 0, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit = over run = TickArraySequenceInvalidIndex amount_specified_is_input: false, // exact out a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "TickArraySequenceInvalidIndex")] /// An attempt to swap walking over 3 tick arrays /// limit(0) c2|_______|_______|_____c1| /// /// Expectation: /// Swap will fail due to over run fn sqrt_price_limit_0_a_to_b_map_to_min() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: 256, start_tick_index: 0, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit = over run = TickArraySequenceInvalidIndex amount_specified_is_input: false, // exact out a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "PartialFillError")] /// An attempt to swap to the maximum tick implicitly without the last initializable tick /// being initialized /// |c1_______________c2,max,limit(0)| /// /// Expectation: /// Swap will fail due to partial fill. fn sqrt_price_limit_0_b_to_a_exact_out() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: 442369, // c1 start_tick_index: 442368, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit amount_specified_is_input: false, // exact out a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "PartialFillError")] /// An attempt to swap to the minimum tick implicitly without the last initializable tick /// being initialized /// |limit(0),min,c2____________c1| /// /// Expectation: /// Swap will fail due to partial fill. fn sqrt_price_limit_0_a_to_b_exact_out() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: -440321, // c1 start_tick_index: -451584, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit amount_specified_is_input: false, // exact out a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// An attempt to swap to the maximum tick explicitly without the last initializable tick /// being initialized /// |c1_______________c2,max,limit(MAX_SQRT_PRICE_X64)| /// /// Expectation: /// Swap will succeed with partial fill. fn sqrt_price_limit_explicit_max_b_to_a_exact_out() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: 442369, // c1 start_tick_index: 442368, trade_amount: 1_000_000_000, sqrt_price_limit: MAX_SQRT_PRICE_X64, // explicit limit amount_specified_is_input: false, // exact out a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: 443636, // MAX end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ); } #[test] /// An attempt to swap to the minimum tick explicitly without the last initializable tick /// being initialized /// |limit(MIN_SQRT_PRICE_X64),min,c2____________c1| /// /// Expectation: /// Swap will succeed with partial fill. fn sqrt_price_limit_explicit_min_a_to_b_exact_out() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: -440321, // c1 start_tick_index: -451584, trade_amount: 1_000_000_000, sqrt_price_limit: MIN_SQRT_PRICE_X64, // explicit limit amount_specified_is_input: false, // exact out a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: -443636 - 1, // MIN - 1 (shifted) end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ); } #[test] /// An attempt to swap to the maximum tick implicitly without the last initializable tick /// being initialized /// |c1_______________c2,max,limit(0)| /// /// Expectation: /// The swap will succeed and exits at the maximum tick index. /// In exact in mode, partial fill may be allowed if other_amount_threshold is satisfied. fn sqrt_price_limit_0_b_to_a_exact_in() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: 442369, // c1 start_tick_index: 442368, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit amount_specified_is_input: true, // exact in a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: 443636, // MAX end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ); } #[test] /// An attempt to swap to the minimum tick implicitly without the last initializable tick /// being initialized /// |limit(0),min,c2____________c1| /// /// Expectation: /// The swap will succeed and exits at the minimum tick index. /// In exact in mode, partial fill may be allowed if other_amount_threshold is satisfied. fn sqrt_price_limit_0_a_to_b_exact_in() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 0, curr_tick_index: -440321, // c1 start_tick_index: -451584, trade_amount: 1_000_000_000, sqrt_price_limit: 0, // no explicit limit amount_specified_is_input: true, // exact in a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 0, traded_amount_b: 0, end_tick_index: -443636 - 1, // MIN - 1 (shifted) end_liquidity: 0, end_reward_growths: [0, 0, 0], }, ); } } #[cfg(test)] mod swap_error_tests { use super::*; use crate::util::test_utils::swap_test_fixture::*; #[test] #[should_panic(expected = "TickArraySequenceInvalidIndex")] /// A swap with a price limit outside of the tick-range and a large /// enough expected trade amount to move the next tick-index out of the tick-range /// limit,c2...|____________|_________________|____c1__________| /// /// Expectation: /// Fail on InvalidTickSequence as the tick-range is insufficent for the trade request. fn insufficient_tick_array_range_test_a_to_b() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000, curr_tick_index: 0, // c1 start_tick_index: 0, trade_amount: 1_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(-5576), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "TickArraySequenceInvalidIndex")] /// A swap with a price limit outside of the tick-range and a large /// enough expected trade amount to move the next tick-index out of the tick-range /// |__c1__________|_________________|______________|...limit,c2 /// /// Expectation: /// Fail on InvalidTickSequence as the tick-range is insufficent for the trade request. fn insufficient_tick_array_range_test_b_to_a() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000, curr_tick_index: 0, // c1 start_tick_index: 0, trade_amount: 1_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(5576), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] /// A swap with the pool's current tick index at sqrt-price 0. /// /// Expectation: /// The swap should succeed without dividing by 0. fn swap_starts_from_sqrt_price_0() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: 0, // c1 start_tick_index: 0, trade_amount: 1_000_000, sqrt_price_limit: sqrt_price_from_tick_index(576), // limit amount_specified_is_input: false, a_to_b: false, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 1000000, traded_amount_b: 1000201, end_tick_index: 4, end_liquidity: 5_000_000_000, end_reward_growths: [0, 0, 0], }, ) } #[test] /// A swap with the pool's next tick index at sqrt-price 0. /// /// Expectation: /// The swap should succeed without dividing by 0. fn swap_ends_at_sqrt_price_0() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 119900, curr_tick_index: 10, // c1 start_tick_index: 0, trade_amount: 59, sqrt_price_limit: sqrt_price_from_tick_index(-5), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); let post_swap = swap_test_info.run(&mut tick_sequence, 100); assert_swap( &post_swap, &SwapTestExpectation { traded_amount_a: 59, traded_amount_b: 59, end_tick_index: 0, end_liquidity: 119900, end_reward_growths: [0, 0, 0], }, ) } #[test] #[should_panic(expected = "ZeroTradableAmount")] /// A swap with zero tradable amount. /// /// Expectation /// The swap should go through without moving the price and swappping anything. fn swap_zero_tokens() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_8, liquidity: 5_000_000_000, curr_tick_index: -225365, // c1 start_tick_index: -225792, trade_amount: 0, sqrt_price_limit: sqrt_price_from_tick_index(-225380), // limit amount_specified_is_input: false, a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "InvalidTimestamp")] /// A swap with an invalid timestamp. /// /// Expectation /// The swap should fail due to the current timestamp being stale. fn swap_invalid_timestamp() { let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: 500_000, curr_tick_index: -322176, start_tick_index: -322176, trade_amount: 1_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(0), amount_specified_is_input: false, a_to_b: false, reward_last_updated_timestamp: 1000, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } #[test] #[should_panic(expected = "AmountCalcOverflow")] // Swapping at high liquidity/price can lead to an amount calculated // overflow u64 // // Expectation // The swap should fail to do amount calculated overflowing. fn swap_does_not_overflow() { // Use filled arrays to minimize the overflow from calculations, rather than accumulation let array_1_ticks: Vec<TestTickInfo> = build_filled_tick_array(439296, TS_128); let array_2_ticks: Vec<TestTickInfo> = build_filled_tick_array(439296 - 88 * 128, TS_128); let array_3_ticks: Vec<TestTickInfo> = build_filled_tick_array(439296 - 2 * 88 * 128, TS_128); let swap_test_info = SwapTestFixture::new(SwapTestFixtureInfo { tick_spacing: TS_128, liquidity: (u32::MAX as u128) << 2, curr_tick_index: MAX_TICK_INDEX - 1, // c1 start_tick_index: 439296, trade_amount: 1_000_000_000_000, sqrt_price_limit: sqrt_price_from_tick_index(0), // limit amount_specified_is_input: true, array_1_ticks: &array_1_ticks, array_2_ticks: Some(&array_2_ticks), array_3_ticks: Some(&array_3_ticks), a_to_b: true, ..Default::default() }); let mut tick_sequence = SwapTickSequence::new( swap_test_info.tick_arrays[0].borrow_mut(), Some(swap_test_info.tick_arrays[1].borrow_mut()), Some(swap_test_info.tick_arrays[2].borrow_mut()), ); swap_test_info.run(&mut tick_sequence, 100); } }
0
solana_public_repos/orca-so/whirlpools
solana_public_repos/orca-so/whirlpools/examples/README.md
# Whirlpools SDK Examples This directory contains example projects showcasing how to use the Whirlpools SDK suite in different environments. Each project demonstrates specific functionalities, providing a starting point for developers. ## Building the Examples To build the examples, run the following commands from the root of the monorepo: ```bash yarn install yarn build ``` ### General Note on Dependencies All examples in this directory use local versions of the Orca SDK dependencies from this monorepo. If you plan to move an example project outside of the monorepo, you must update the dependencies to ensure compatibility. ## Available Examples ### Rust #### 1. Whirlpool Repositioning Bot - Path: examples/rust-sdk/whirlpools-repositioning-bot - Description: A CLI tool to automatically reposition positions based on configurable thresholds. - Highlights: - Utilizes the Whirlpools Rust SDKs. - Dynamically fetches on-chain data to manage LP positions. ### Typescript #### 2. Next.js Integration - Path: examples/ts-sdk/whirlpools-next - Description: Demonstrates how to integrate the Whirlpools TS SDK `@orca-so/whirlpools` with a Next.js application. - Highlights: - Configures WebAssembly (`asyncWebAssembly`) support in Next.js. - Provides a working setup to query and interact with Orca's whirlpools.
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/next.config.js
import NextBundleAnalyzer from "@next/bundle-analyzer"; import CopyWebpackPlugin from "copy-webpack-plugin"; const nextConfig = { serverExternalPackages: ["@orca-so/whirlpools-core"], webpack(config, { isServer }) { config.experiments.asyncWebAssembly = true; // Copy `orca_whirlpools_core_js_bindings_bg.wasm` file // This is only needed because of the monorepo setup // (local dependencies are symlinked and next doesn't like that) config.plugins.push( new CopyWebpackPlugin({ patterns: [ { from: "../../../ts-sdk/core/dist/nodejs/orca_whirlpools_core_js_bindings_bg.wasm", to: "./server/app", }, ], }), ); // The following supresses a warning about using top-level-await and is optional if (!isServer) { config.output.environment = { ...config.output.environment, asyncFunction: true, }; } return config; }, eslint: { ignoreDuringBuilds: true, }, reactStrictMode: true, }; const withBundleAnalyzer = NextBundleAnalyzer({ enabled: process.env.ANALYZE === "true", }); export default withBundleAnalyzer(nextConfig);
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/next-env.d.ts
/// <reference types="next" /> /// <reference types="next/image-types/global" /> // NOTE: This file should not be edited // see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/README.md
# Whirlpools Next.js Example This example demonstrates how to use the Whirlpools SDK in a Next.js application. Since the Orca SDK suite uses WebAssembly, the `experiments.asyncWebAssembly` feature of webpack must be enabled and `@orca-so/whirlpools-core` needs to be added as a `serverExternalPackages`. See `next.config.js` for more details.
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/package.json
{ "name": "@orca-so/whirlpools-example-ts-next", "version": "0.1.0", "type": "module", "scripts": { "start": "next dev", "build": "next build", "clean": "rimraf .next" }, "dependencies": { "@orca-so/whirlpools": "*", "@solana/web3.js": "^2.0.0", "next": "^15.1.0", "react": "^18.3.1", "react-dom": "^18.3.1" }, "devDependencies": { "@next/bundle-analyzer": "^15.1.0", "@types/node": "^22.10.2", "@types/react": "^18.3.13", "copy-webpack-plugin": "^12.0.2", "typescript": "^5.7.2" } }
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/tsconfig.json
{ "extends": "../../../tsconfig.json", "compilerOptions": { "outDir": "./dist", "jsx": "preserve", "plugins": [ { "name": "next" } ], "noEmit": true, "incremental": true }, "include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/app/layout.tsx
import { ReactNode } from "react"; export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ); }
0
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next
solana_public_repos/orca-so/whirlpools/examples/ts-sdk/next/app/page.tsx
"use client"; import { fetchPositionsForOwner, PositionOrBundle } from "@orca-so/whirlpools"; import { tickIndexToSqrtPrice } from "@orca-so/whirlpools-core"; import { useCallback, useMemo, useState } from "react"; import { createSolanaRpc, mainnet, address, devnet } from "@solana/web3.js"; export default function Page() { const [positions, setPositions] = useState<PositionOrBundle[]>([]); const [owner, setOwner] = useState<string>(""); const [tickIndex, setTickIndex] = useState<string>(""); const [sqrtPrice, setSqrtPrice] = useState<bigint>(); const rpc = useMemo(() => { if (!process.env.NEXT_PUBLIC_RPC_URL) { console.error("NEXT_PUBLIC_RPC_URL is not set"); return createSolanaRpc(devnet("https://api.devnet.solana.com")); } return createSolanaRpc(mainnet(process.env.NEXT_PUBLIC_RPC_URL)); }, [process.env.NEXT_PUBLIC_RPC_URL]); const fetchPositions = useCallback(async () => { const positions = await fetchPositionsForOwner(rpc, address(owner)); setPositions(positions); }, [owner]); const convertTickIndex = useCallback(() => { const index = parseInt(tickIndex); setSqrtPrice(tickIndexToSqrtPrice(index)); }, [tickIndex]); return ( <div> <p> <input type="number" value={tickIndex} onChange={(e) => setTickIndex(e.target.value)} />{" "} <button onClick={() => convertTickIndex()}>Convert</button>{" "} {sqrtPrice !== undefined && <>Sqrt Price: {sqrtPrice.toString()}</>} </p> <p> <input type="text" value={owner} onChange={(e) => setOwner(e.target.value)} />{" "} <button onClick={() => fetchPositions()}>Fetch Positions</button>{" "} {positions.length > 0 && <>{positions.length} positions found</>} </p> </div> ); }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/Cargo.toml
[package] name = "whirlpool_repositioning_bot" version = "0.1.0" edition = "2021" [dependencies] clap = { version = "^4.5.21", features = ["derive"] } colored = { version = "^2.0" } orca_whirlpools = { path = '../../../rust-sdk/whirlpool' } orca_whirlpools_client = { path = '../../../rust-sdk/client' } orca_whirlpools_core = { path = '../../../rust-sdk/core' } serde_json = { version = "^1.0" } solana-client = { version = "^1.18" } solana-sdk = { version = "^1.18" } spl-token-2022 = { version = "^3.0" } spl-associated-token-account = { version = "^3.0" } tokio = { version = "^1.41.1" } tokio-retry = { version = "^0.3.0" } dotenv = { version = "^0.15.0"}
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/README.md
# Whirlpool Repositioning Bot A Rust-based CLI bot for interacting with the Orca Whirlpools program on Solana. This bot monitors and rebalances a liquidity position by closing and reopening positions when price deviations exceed a user-defined threshold. --- ## Features - **Automated Position Monitoring**: Monitors price deviation of a liquidity position on Orca Whirlpool by calculating the center of the position's price range and comparing it to the current pool price. If the deviation exceeds the specified threshold (in percentage), the bot initiates rebalancing. - **Automated Rebalancing**: Closes and reopens liquidity positions by centering the new position around the current pool price, maintaining the same width (distance between the lower and upper price bounds) as the initial position. - **Customizable Priority Fees**: Integrates compute budget priority fees to enhance transaction speed and landing, with options ranging from `none` to `turbo` for different levels of prioritization. --- ## Prerequisites 1. **Solana Wallet**: - Place a `wallet.json` file in the working directory with the keypair that owns the positions. - Ensure the wallet has sufficient funds for transactions. 2. **Existing Position**: - You must have an active position on Orca Whirlpools. You can open a position using our SDKs or through our UI at https://www.orca.so/pools. 3. **Rust**: - Install Rust using [rustup](https://rustup.rs/). --- ## Installation 1. Clone this repository: ```bash git clone https://github.com/orca-so/whirlpools.git cd examples/rust-sdk/lp-bot ``` 2. Build the bot: ```bash cargo build --release ``` 3. The executable will be located in target/release/lp-bot > NOTE: This project uses the local version of the dependency. If you want to move this example project outside of this monorepo, make sure you install the necessary dependecies: ```bash cargo add orca_whirlpools orca_whirlpools_client orca_whirlpools_core ``` --- ## RPC Configuration The bot connects to an SVM network by using an RPC URL. Make a local copy of `.env.template` to `.env` and set your RPC URL there. It is strongly recommended to you use a URL from an RPC provider, or your own RPC node. ```bash RPC_URL="https://your-rpc-url.com" ``` --- ## Usage Run the bot with the following arguments ```bash ./target/release/lp-bot \ --position-mint-address <POSITION_MINT_ADDRESS> \ --threshold <THRESHOLD_BPS> \ --interval <INTERVAL_IN_SECONDS> \ --priority-fee-tier <PRIORITY_FEE_TIER> \ --max-priority-fee-lamports <MAX_PRIORITY_FEE_LAMPORTS> \ --slippage-tolerance-bps <SLIPPAGE_TOLERANCE_BPS> ``` ### Arguments - `--position-mint-address` (required): The mint address of the position to monitor and rebalance. - `--threshold` (optional): TThe threshold for triggering rebalancing, defined by how far the position's center deviates from the current price. Default: 100. - `--interval` (optional): The time interval (in seconds) between checks. Default: 60. - `--priority-fee-tier` (optional): The priority fee tier for transaction processing. Options: - `none`: No priority fee. - `low`: Lower 25th quartile prioritization fee. - `medium`: Median prioritization fee (default). - `high`: Upper 80th quartile prioritization fee. - `turbo`: Upper 99th quartile prioritization fee. - `max_priority_fee_lamports` (optional): Maximum total priority fee in lamports. Default: 10_000_000 (0.01 SOL). - `slippage_tolerance_bps` (optional): Slippage tolerance in basis points (bps). Default: 100. ### Example Usage Monitor and rebalance with default settings: ```bash ./target/release/lp-bot \ --position-mint-address 5m1izNWC3ioBaKm63e3gSNFeZ44o13ncre5QknTXBJUS ``` Monitor with custom threshold and interval: ```bash ./target/release/lp-bot \ --position-mint-address 5m1izNWC3ioBaKm63e3gSNFeZ44o13ncre5QknTXBJUS \ --threshold 50 \ --interval 30 ``` Monitor with turbo priority fees: ```bash ./target/release/lp-bot \ --position-mint-address 5m1izNWC3ioBaKm63e3gSNFeZ44o13ncre5QknTXBJUS \ --priority-fee-tier turbo ``` --- ## Directory Structure ```bash examples/ ├── rust-sdk/ └── lp-bot/ └── src/ ├── main.rs # Entry point ├── cli.rs # CLI argument parsing ├── wallet.rs # Wallet management ├── position_manager.rs # Position monitoring and rebalancing ├── solana_utils.rs # RPC utilities ```
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/.env.template
RPC_URL="https://api.mainnet-beta.solana.com"
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/package.json
{ "name": "@orca-so/whirlpools-example-rust-repositioning-bot", "version": "0.0.1", "scripts": { "build": "cargo build", "format": "cargo clippy --fix --allow-dirty --allow-staged && cargo fmt", "lint": "cargo clippy && cargo fmt --check", "clean": "cargo clean" }, "devDependencies": { "@orca-so/whirlpools-rust": "*", "@orca-so/whirlpools-rust-client": "*", "@orca-so/whirlpools-rust-core": "*" } }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/src/wallet.rs
use solana_sdk::{signature::Keypair, signer::Signer}; use std::fs; pub fn load_wallet() -> Box<dyn Signer> { let wallet_string = fs::read_to_string("wallet.json").unwrap(); let keypair_bytes: Vec<u8> = serde_json::from_str(&wallet_string).unwrap(); let wallet = Keypair::from_bytes(&keypair_bytes).unwrap(); Box::new(wallet) }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/src/main.rs
mod cli; mod position_manager; mod utils; mod wallet; use clap::Parser; use cli::Args; use colored::Colorize; use dotenv::dotenv; use orca_whirlpools::{set_funder, set_whirlpools_config_address, WhirlpoolsConfigInput}; use orca_whirlpools_client::get_position_address; use position_manager::run_position_manager; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; use std::env; use std::str::FromStr; use tokio::time::{sleep, Duration}; use utils::{ display_position_balances, display_wallet_balances, fetch_mint, fetch_position, fetch_whirlpool, }; #[tokio::main] async fn main() { let args = Args::parse(); dotenv().ok(); let rpc_url = env::var("RPC_URL").unwrap(); let rpc = RpcClient::new(rpc_url.to_string()); set_whirlpools_config_address(WhirlpoolsConfigInput::SolanaMainnet) .expect("Failed to set Whirlpools config address for specified network."); let wallet = wallet::load_wallet(); set_funder(wallet.pubkey()).expect("Failed to set funder address."); let position_mint_address = Pubkey::from_str(&args.position_mint_address) .expect("Invalid position mint address provided."); println!( "\n\ ====================\n\ 🌀 Whirlpool LP BOT \n\ ====================\n" ); println!("Configuration:"); println!( " Position Mint Address: {}\n Threshold: {:.2}bps\n Interval: {} seconds\n Priority Fee Tier: {:?}\n Slippage tolerance bps: {:?}\n", args.position_mint_address, args.threshold, args.interval, args.priority_fee_tier, args.slippage_tolerance_bps ); println!("-------------------------------------\n"); let (position_address, _) = get_position_address(&position_mint_address).expect("Failed to derive position address."); let mut position = fetch_position(&rpc, &position_address) .await .expect("Failed to fetch position data."); let whirlpool = fetch_whirlpool(&rpc, &position.whirlpool) .await .expect("Failed to fetch Whirlpool data."); let token_mint_a = fetch_mint(&rpc, &whirlpool.token_mint_a) .await .expect("Failed to fetch Token Mint A data."); let token_mint_b = fetch_mint(&rpc, &whirlpool.token_mint_b) .await .expect("Failed to fetch Token Mint B data."); display_wallet_balances( &rpc, &wallet.pubkey(), &whirlpool.token_mint_a, &whirlpool.token_mint_b, ) .await .expect("Failed to display wallet balances."); display_position_balances( &rpc, &position, &whirlpool.token_mint_a, &whirlpool.token_mint_b, token_mint_a.decimals, token_mint_b.decimals, args.slippage_tolerance_bps, ) .await .expect("Failed to display position balances."); loop { if let Err(err) = run_position_manager( &rpc, &args, &wallet, &mut position, &token_mint_a, &token_mint_b, ) .await { eprintln!("{}", format!("Error: {}", err).to_string().red()); } sleep(Duration::from_secs(args.interval)).await; } }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/src/position_manager.rs
use crate::{ cli::Args, utils::{ display_position_balances, display_wallet_balances, fetch_position, fetch_whirlpool, send_transaction, }, }; use colored::Colorize; use orca_whirlpools::{ close_position_instructions, open_position_instructions, IncreaseLiquidityParam, }; use orca_whirlpools_client::{get_position_address, Position}; use orca_whirlpools_core::{sqrt_price_to_price, tick_index_to_price, tick_index_to_sqrt_price}; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::signer::Signer; use spl_token_2022::state::Mint; pub async fn run_position_manager( rpc: &RpcClient, args: &Args, wallet: &Box<dyn Signer>, position: &mut Position, token_mint_a: &Mint, token_mint_b: &Mint, ) -> Result<(), Box<dyn std::error::Error>> { println!("Checking position."); let whirlpool_address = position.whirlpool; let whirlpool = fetch_whirlpool(rpc, &whirlpool_address) .await .map_err(|_| "Failed to fetch Whirlpool data.")?; let current_sqrt_price = whirlpool.sqrt_price; let position_lower_sqrt_price = tick_index_to_sqrt_price(position.tick_lower_index); let position_upper_sqrt_price = tick_index_to_sqrt_price(position.tick_upper_index); let position_center_sqrt_price = (position_lower_sqrt_price + position_upper_sqrt_price) / 2; let deviation_amount_sqrt = if current_sqrt_price > position_center_sqrt_price { current_sqrt_price - position_center_sqrt_price } else { position_center_sqrt_price - current_sqrt_price }; let deviation_bps = (deviation_amount_sqrt * 10000) / (position_center_sqrt_price); let current_price = sqrt_price_to_price( whirlpool.sqrt_price, token_mint_a.decimals, token_mint_b.decimals, ); let position_lower_price = tick_index_to_price( position.tick_lower_index, token_mint_a.decimals, token_mint_b.decimals, ); let position_upper_price = tick_index_to_price( position.tick_upper_index, token_mint_a.decimals, token_mint_b.decimals, ); let position_center_price = (position_lower_price + position_upper_price) / 2.0; println!("Current pool price: {:.6}", current_price); println!( "Position price range: [{:.6}, {:.6}]", position_lower_price, position_upper_price ); println!("Position center price: {:.6}", position_center_price); println!("Price deviation from center: {:.2} bps", deviation_bps); if deviation_bps as u16 >= args.threshold { println!( "{}", "Deviation exceeds threshold. Rebalancing position." .to_string() .yellow() ); let close_position_instructions = close_position_instructions( rpc, position.position_mint, Some(args.slippage_tolerance_bps), None, ) .await .map_err(|_| "Failed to generate close position instructions.")?; let new_lower_price = current_price - (position_upper_price - position_lower_price) / 2.0; let new_upper_price = current_price + (position_upper_price - position_lower_price) / 2.0; let increase_liquidity_param = IncreaseLiquidityParam::Liquidity(close_position_instructions.quote.liquidity_delta); let open_position_instructions = open_position_instructions( rpc, whirlpool_address, new_lower_price, new_upper_price, increase_liquidity_param, Some(100), None, ) .await .map_err(|_| "Failed to generate open position instructions.")?; let mut all_instructions = vec![]; all_instructions.extend(close_position_instructions.instructions); all_instructions.extend(open_position_instructions.instructions); let mut signers: Vec<&dyn Signer> = vec![wallet.as_ref()]; signers.extend( open_position_instructions .additional_signers .iter() .map(|kp| kp as &dyn Signer), ); signers.extend( close_position_instructions .additional_signers .iter() .map(|kp| kp as &dyn Signer), ); let signature = send_transaction( rpc, wallet.as_ref(), &whirlpool_address, all_instructions, signers, args.priority_fee_tier, args.max_priority_fee_lamports, ) .await .map_err(|_| "Failed to send rebalancing transaction.")?; println!("Rebalancing transaction signature: {}", signature); let position_mint_address = open_position_instructions.position_mint; println!("New position mint address: {}", position_mint_address); let (position_address, _) = get_position_address(&position_mint_address) .map_err(|_| "Failed to derive new position address.")?; *position = fetch_position(rpc, &position_address) .await .map_err(|_| "Failed to fetch new position data.")?; display_wallet_balances( rpc, &wallet.pubkey(), &whirlpool.token_mint_a, &whirlpool.token_mint_b, ) .await .map_err(|_| "Failed to display wallet balances.")?; display_position_balances( rpc, position, &whirlpool.token_mint_a, &whirlpool.token_mint_b, token_mint_a.decimals, token_mint_b.decimals, args.slippage_tolerance_bps, ) .await .map_err(|_| "Failed to display position balances.")?; } else { println!( "{}", "Current price is within range. No repositioning needed." .to_string() .green() ); } Ok(()) }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/src/utils.rs
use clap::ValueEnum; use orca_whirlpools::close_position_instructions; use orca_whirlpools_client::{Position, Whirlpool}; use solana_client::nonblocking::rpc_client::RpcClient; use solana_client::rpc_config::RpcSendTransactionConfig; use solana_sdk::commitment_config::CommitmentLevel; use solana_sdk::compute_budget::ComputeBudgetInstruction; use solana_sdk::{ message::Message, program_pack::Pack, pubkey::Pubkey, signature::Signature, signer::Signer, transaction::Transaction, }; use spl_associated_token_account::get_associated_token_address_with_program_id; use spl_token_2022::state::Mint; use std::error::Error; use tokio::time::{sleep, Duration, Instant}; use tokio_retry::strategy::ExponentialBackoff; use tokio_retry::Retry; pub async fn display_position_balances( rpc: &RpcClient, position: &Position, token_mint_a_address: &Pubkey, token_mint_b_address: &Pubkey, decimals_a: u8, decimals_b: u8, slippage_tolerance_bps: u16, ) -> Result<(), Box<dyn Error>> { let close_position_instructions = close_position_instructions( rpc, position.position_mint, Some(slippage_tolerance_bps), None, ) .await?; let positon_balance_token_a = close_position_instructions.quote.token_est_a as f64 / 10u64.pow(decimals_a as u32) as f64; let positon_balance_token_b = close_position_instructions.quote.token_est_b as f64 / 10u64.pow(decimals_b as u32) as f64; println!( "Position Balances: \n\ - Token A ({:?}): {} \n\ - Token B ({:?}): {} \n", token_mint_a_address, positon_balance_token_a, token_mint_b_address, positon_balance_token_b ); Ok(()) } pub async fn display_wallet_balances( rpc: &RpcClient, wallet_address: &Pubkey, token_mint_a_address: &Pubkey, token_mint_b_address: &Pubkey, ) -> Result<(), Box<dyn Error>> { let token_a_balance = fetch_token_balance(rpc, wallet_address, token_mint_a_address).await?; let token_b_balance = fetch_token_balance(rpc, wallet_address, token_mint_b_address).await?; println!( "Wallet Balances: \n\ - Token A ({:?}): {} \n\ - Token B ({:?}): {}", token_mint_a_address, token_a_balance, token_mint_b_address, token_b_balance ); Ok(()) } pub async fn fetch_token_balance( rpc: &RpcClient, wallet_address: &Pubkey, token_mint_address: &Pubkey, ) -> Result<String, Box<dyn Error>> { let mint_account = rpc.get_account(token_mint_address).await?; let token_program_id = mint_account.owner; let token_address = get_associated_token_address_with_program_id( wallet_address, token_mint_address, &token_program_id, ); let balance = rpc.get_token_account_balance(&token_address).await?; Ok(balance.ui_amount_string) } pub async fn fetch_position( rpc: &RpcClient, position_address: &Pubkey, ) -> Result<Position, Box<dyn Error>> { Retry::spawn( ExponentialBackoff::from_millis(500) .max_delay(Duration::from_secs(5)) .take(5), || async { let position_account = rpc.get_account(position_address).await?; let position = Position::from_bytes(&position_account.data)?; Ok(position) }, ) .await } pub async fn fetch_whirlpool( rpc: &RpcClient, whirlpool_address: &Pubkey, ) -> Result<Whirlpool, Box<dyn Error>> { let whirlpool_account = rpc.get_account(whirlpool_address).await?; let whirlpool = Whirlpool::from_bytes(&whirlpool_account.data)?; Ok(whirlpool) } pub async fn fetch_mint(rpc: &RpcClient, mint_address: &Pubkey) -> Result<Mint, Box<dyn Error>> { let mint_account = rpc.get_account(mint_address).await?; let mint = Mint::unpack(&mint_account.data)?; Ok(mint) } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] pub enum PriorityFeeTier { None, Low, Medium, High, Turbo, } pub async fn send_transaction( rpc: &RpcClient, wallet: &dyn Signer, whirlpool_address: &Pubkey, instructions: Vec<solana_sdk::instruction::Instruction>, additional_signers: Vec<&dyn Signer>, tier: PriorityFeeTier, max_priority_fee: u64, ) -> Result<Signature, Box<dyn Error>> { let mut all_instructions = vec![]; let recent_blockhash = rpc.get_latest_blockhash().await?; let compute_unit_instructions = get_compute_unit_instructions( rpc, &instructions, wallet, whirlpool_address, &additional_signers, tier, max_priority_fee, recent_blockhash, ) .await?; all_instructions.extend(compute_unit_instructions); all_instructions.extend(instructions.clone()); let message = Message::new(&all_instructions, Some(&wallet.pubkey())); let mut all_signers = vec![wallet]; all_signers.extend(additional_signers.clone()); let transaction = Transaction::new(&all_signers, message, recent_blockhash); let transaction_config = RpcSendTransactionConfig { skip_preflight: true, preflight_commitment: Some(CommitmentLevel::Confirmed), max_retries: Some(0), ..Default::default() }; let start_time = Instant::now(); let timeout = Duration::from_secs(90); let send_transaction_result = loop { if start_time.elapsed() >= timeout { break Err(Box::<dyn std::error::Error>::from("Transaction timed out")); } let signature: Signature = rpc .send_transaction_with_config(&transaction, transaction_config) .await?; let statuses = rpc.get_signature_statuses(&[signature]).await?.value; if let Some(status) = statuses[0].clone() { break Ok((status, signature)); } sleep(Duration::from_millis(100)).await; }; send_transaction_result.and_then(|(status, signature)| { if let Some(err) = status.err { Err(Box::new(err)) } else { Ok(signature) } }) } async fn get_compute_unit_instructions( rpc: &RpcClient, instructions: &[solana_sdk::instruction::Instruction], wallet: &dyn Signer, whirlpool_address: &Pubkey, additional_signers: &[&dyn Signer], tier: PriorityFeeTier, max_priority_fee_lamports: u64, recent_blockhash: solana_sdk::hash::Hash, ) -> Result<Vec<solana_sdk::instruction::Instruction>, Box<dyn Error>> { let mut compute_unit_instructions = vec![]; let message = Message::new(instructions, Some(&wallet.pubkey())); let mut signers = vec![wallet]; signers.extend(additional_signers); let transaction = Transaction::new(&signers, message, recent_blockhash); let simulated_transaction = rpc.simulate_transaction(&transaction).await?; if let Some(units_consumed) = simulated_transaction.value.units_consumed { let units_margin = std::cmp::max(100_000, (units_consumed as f32 * 0.2).ceil() as u32); let units_consumed_safe = units_consumed as u32 + units_margin; let compute_limit_instruction = ComputeBudgetInstruction::set_compute_unit_limit(units_consumed_safe); compute_unit_instructions.push(compute_limit_instruction); if let Some(priority_fee_micro_lamports) = calculate_priority_fee(rpc, tier, whirlpool_address).await? { let mut compute_unit_price = priority_fee_micro_lamports; let total_priority_fee_lamports = (units_consumed_safe as u64 * priority_fee_micro_lamports) / 1_000_000; if total_priority_fee_lamports > max_priority_fee_lamports { compute_unit_price = (max_priority_fee_lamports * 1_000_000) / units_consumed_safe as u64; } display_priority_fee_details( compute_unit_price, units_consumed_safe, (units_consumed_safe as u64 * compute_unit_price) / 1_000_000, ); let priority_fee_instruction = ComputeBudgetInstruction::set_compute_unit_price(compute_unit_price); compute_unit_instructions.push(priority_fee_instruction); } } Ok(compute_unit_instructions) } fn display_priority_fee_details( compute_unit_price: u64, units_consumed: u32, total_priority_fee_lamports: u64, ) { println!( "Priority Fee Details:\n\ - Compute unit price: {} microlamports\n\ - Estimated compute units: {}\n\ - Total priority fee: {} lamports", compute_unit_price, units_consumed, total_priority_fee_lamports ); } async fn calculate_priority_fee( rpc: &RpcClient, tier: PriorityFeeTier, whirlpool_address: &Pubkey, ) -> Result<Option<u64>, Box<dyn Error>> { let prioritization_fees = rpc .get_recent_prioritization_fees(&[*whirlpool_address]) .await .unwrap(); if prioritization_fees.is_empty() || matches!(tier, PriorityFeeTier::None) { return Ok(None); } let mut fees: Vec<u64> = prioritization_fees .iter() .map(|fee| fee.prioritization_fee) .collect(); fees.sort_unstable(); let fee = match tier { PriorityFeeTier::Low => fees.get(fees.len() / 4).cloned(), PriorityFeeTier::Medium => fees.get(fees.len() / 2).cloned(), PriorityFeeTier::High => fees.get((fees.len() * 4) / 5).cloned(), PriorityFeeTier::Turbo => fees.get((fees.len() * 99) / 100).cloned(), PriorityFeeTier::None => None, }; Ok(fee) }
0
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot
solana_public_repos/orca-so/whirlpools/examples/rust-sdk/whirlpool_repositioning_bot/src/cli.rs
use clap::Parser; use crate::utils::PriorityFeeTier; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] pub struct Args { #[arg( short = 'p', long, help = "The position mint address to monitor and rebalance." )] pub position_mint_address: String, #[arg( short = 't', long, default_value_t = 100, help = "Threshold for repositioning in bps.\n" )] pub threshold: u16, #[arg( short = 'i', long, default_value_t = 60, help = "Time interval for checking in seconds.\n" )] pub interval: u64, #[arg( short = 'f', long, value_enum, default_value_t = PriorityFeeTier::Medium, help = "Priority fee tier for transaction processing based on recently paid priority fees. Options:\n \ - `none`: No priority fee\n \ - `low`: Lower 25th quartile prioritization fee\n \ - `medium`: Median prioritization fee\n \ - `high`: Upper 80th quartile prioritization fee\n \ - `turbo`: Upper 99th quartile prioritization fee\n" )] pub priority_fee_tier: PriorityFeeTier, #[arg( short = 'm', long, default_value_t = 10_000_000, help = "Maximum total priority fee in lamports.\n" )] pub max_priority_fee_lamports: u64, #[arg( short = 's', long, default_value_t = 100, help = "Slippage tolerance in basis points (bps).\n" )] pub slippage_tolerance_bps: u16, }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/README.md
# Setting up your script environment ```bash yarn ``` # Set your RPC and wallet ```bash export ANCHOR_PROVIDER_URL=<RPC URL> export ANCHOR_WALLET=<WALLET JSON PATH> ``` Example: ```bash export ANCHOR_PROVIDER_URL=http://localhost:8899 export ANCHOR_WALLET=~/.config/solana/id.json ``` # Supported commands Token-2022 tokens are acceptable 👍 ## Config & FeeTier ### initialize - `yarn start initializeConfig`: initialize new WhirlpoolsConfig account - `yarn start initializeConfigExtension`: initialize new WhirlpoolsConfigExtension account - `yarn start initializeFeeTier`: initialize new FeeTier account ### update - `yarn start setTokenBadgeAuthority`: set new TokenBadge authority on WhirlpoolsConfigExtension - `yarn start setDefaultProtocolFeeRate`: set new default protocol fee rate on WhirlpoolsConfig - `yarn start setFeeAuthority`: set new fee authority on WhirlpoolsConfig - `yarn start setCollectProtocolFeesAuthority`: set new collect protocol fees authority on WhirlpoolsConfig - `yarn start setRewardEmissionsSuperAuthority`: set new reward emissions super authority on WhirlpoolsConfig - TODO: set config extension authority ## Whirlpool & TickArray - `yarn start initializeWhirlpool`: initialize new Whirlpool account - `yarn start initializeTickArray`: initialize new TickArray account ## TokenBadge - `yarn start initializeTokenBadge`: initialize new TokenBadge account - `yarn start deleteTokenBadge`: delete TokenBadge account ## Reward - `yarn start setRewardAuthority`: set new reward authority of rewards on a whirlpool - `yarn start initializeReward`: initialize new reward for a whirlpool - TODO: set reward emission ## Position - `yarn start openPosition`: open a new position - `yarn start increaseLiquidity`: deposit to a position - `yarn start decreaseLiquidity`: withdraw from a position - `yarn start collectFees`: collect fees from a position - `yarn start collectRewards`: collect rewards from a position - `yarn start closePosition`: close an empty position ## Swap - `yarn start pushPrice`: adjust pool price (possible if pool liquidity is zero or very small) ## WSOL and ATA creation TODO: WSOL handling & create ATA if needed (workaround exists, please see the following) ### workaround for WSOL `whirlpool-mgmt-tools` works well with ATA, so using WSOL on ATA is workaround. - wrap 1 SOL: `spl-token wrap 1` (ATA for WSOL will be initialized with 1 SOL) - unwrap: `spl-token unwrap` (ATA for WSOL will be closed) - add 1 WSOL: `solana transfer <WSOL ATA address> 1` then `spl-token sync-native` (transfer & sync are needed) ### workaround for ATA We can easily initialize ATA with spl-token CLI. ``` spl-token create-account <mint address> ```
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/package.json
{ "name": "@orca-so/whirlpools-sdk-cli", "private": true, "version": "1.0.0", "type": "module", "scripts": { "build": "tsc --noEmit", "start": "tsx src/index.ts" }, "dependencies": { "@coral-xyz/anchor": "0.29.0", "@orca-so/common-sdk": "0.6.4", "@orca-so/orca-sdk": "0.2.0", "@orca-so/whirlpools-sdk": "*", "@solana/spl-token": "0.4.1", "@solana/web3.js": "^1.90.0", "@types/bn.js": "^5.1.0", "bs58": "^6.0.0", "decimal.js": "^10.4.3", "js-convert-case": "^4.2.0", "prompts": "^2.4.2" }, "devDependencies": { "@types/prompts": "^2.4.9", "tsx": "^4.19.0", "typescript": "^5.7.2" } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/tsconfig.json
{ "extends": "../../tsconfig.json", "compilerOptions": { "module": "ESNext", "outDir": "./dist" }, "include": ["./src/**/*.ts"] }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/index.ts
import { readdirSync } from "fs"; import { promptChoice } from "./utils/prompt"; import { toSnakeCase } from "js-convert-case"; const commands = readdirSync("./src/commands") .filter((file) => file.endsWith(".ts")) .map((file) => file.replace(".ts", "")) .map((file) => ({ title: file, value: () => import(`./commands/${file}.ts`), })); const arg = toSnakeCase(process.argv[2]); const maybeCommand = commands.find((c) => c.title === arg); if (maybeCommand) { await maybeCommand.value(); } else { const command = await promptChoice("command", commands); await command(); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/utils/transaction_sender.ts
import type { Keypair, VersionedTransaction } from "@solana/web3.js"; import { ComputeBudgetProgram, LAMPORTS_PER_SOL } from "@solana/web3.js"; import { DecimalUtil, TransactionBuilder, estimateComputeBudgetLimit, } from "@orca-so/common-sdk"; import Decimal from "decimal.js"; import base58 from "bs58"; import { promptConfirm, promptText } from "./prompt"; export async function sendTransaction( builder: TransactionBuilder, ): Promise<boolean> { const instructions = builder.compressIx(true); // HACK: to clone TransactionBuilder const signers = builder["signers"] as Keypair[]; const estimatedComputeUnits = await estimateComputeBudgetLimit( builder.connection, [instructions], undefined, builder.wallet.publicKey, 0.1, // + 10% ); console.info("estimatedComputeUnits:", estimatedComputeUnits); let landed = false; let success = false; while (true) { let priorityFeeInLamports = 0; while (true) { const priorityFeeInSOL = await promptText("priorityFeeInSOL"); priorityFeeInLamports = DecimalUtil.toBN( new Decimal(priorityFeeInSOL), 9, ).toNumber(); if (priorityFeeInLamports > LAMPORTS_PER_SOL) { console.info("> 1 SOL is obviously too much for priority fee"); continue; } if (priorityFeeInLamports > 5_000_000) { console.info( `Is it okay to use ${priorityFeeInLamports / LAMPORTS_PER_SOL} SOL for priority fee ? (if it is OK, enter OK)`, ); const ok = await promptConfirm("OK"); if (!ok) continue; } console.info( "Priority fee:", priorityFeeInLamports / LAMPORTS_PER_SOL, "SOL", ); break; } const builderWithPriorityFee = new TransactionBuilder( builder.connection, builder.wallet, builder.opts, ); if (priorityFeeInLamports > 0) { const setComputeUnitPriceIx = ComputeBudgetProgram.setComputeUnitPrice({ microLamports: Math.floor( (priorityFeeInLamports * 1_000_000) / estimatedComputeUnits, ), }); const setComputeUnitLimitIx = ComputeBudgetProgram.setComputeUnitLimit({ units: estimatedComputeUnits, }); builderWithPriorityFee.addInstruction({ instructions: [setComputeUnitLimitIx, setComputeUnitPriceIx], cleanupInstructions: [], signers: [], }); } builderWithPriorityFee.addInstruction(instructions); signers.forEach((s) => builderWithPriorityFee.addSigner(s)); let withDifferentPriorityFee = false; while (true) { console.info("process transaction..."); const result = await send(builderWithPriorityFee); landed = result.landed; success = result.success; if (landed) break; console.info("\ntransaction have not landed. retry ?, enter OK"); const ok = await promptConfirm("OK"); if (!ok) break; console.info("\nchange priority fee setting?, enter YES"); const yesno = await promptConfirm("YES"); if (yesno) { withDifferentPriorityFee = true; break; } } if (landed) break; if (!withDifferentPriorityFee) break; } return landed && success; } async function send( builder: TransactionBuilder, ): Promise<{ landed: boolean; success: boolean }> { const connection = builder.connection; const wallet = builder.wallet; // manual build const built = await builder.build({ maxSupportedTransactionVersion: 0 }); const blockhash = await connection.getLatestBlockhashAndContext("confirmed"); const blockHeight = await connection.getBlockHeight({ commitment: "confirmed", minContextSlot: await blockhash.context.slot, }); // why 151: https://solana.com/docs/core/transactions/confirmation#how-does-transaction-expiration-work const transactionTTL = blockHeight + 151; const notSigned = built.transaction as VersionedTransaction; notSigned.message.recentBlockhash = blockhash.value.blockhash; if (built.signers.length > 0) notSigned.sign(built.signers); const signed = await wallet.signTransaction(notSigned); const signature = base58.encode(signed.signatures[0]); // manual send and confirm const waitToConfirm = () => new Promise((resolve) => setTimeout(resolve, 5000)); const waitToRetry = () => new Promise((resolve) => setTimeout(resolve, 3000)); const numTry = 100; // break by expiration let landed = false; let success = false; for (let i = 0; i < numTry; i++) { // check transaction TTL const blockHeight = await connection.getBlockHeight("confirmed"); if (blockHeight > transactionTTL) { // check signature status (to avoid false negative) const sigStatus = await connection.getSignatureStatus(signature); if (sigStatus.value?.confirmationStatus === "confirmed") { success = sigStatus.value.err === null; console.info( success ? "✅successfully landed" : `🚨landed BUT TRANSACTION FAILED`, ); landed = true; break; } console.info("transaction have been expired"); break; } console.info( "transaction is still valid,", transactionTTL - blockHeight, "blocks left (at most)", ); // send without retry on RPC server console.info("sending..."); await connection.sendRawTransaction(signed.serialize(), { skipPreflight: true, maxRetries: 0, }); console.info("confirming..."); await waitToConfirm(); // check signature status const sigStatus = await connection.getSignatureStatus(signature); if (sigStatus.value?.confirmationStatus === "confirmed") { success = sigStatus.value.err === null; console.info( success ? "✅successfully landed" : `🚨landed BUT TRANSACTION FAILED`, ); landed = true; break; } // todo: need to increase wait time, but TTL is not long... await waitToRetry(); } if (landed) { console.info("signature", signature); } return { landed, success }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/utils/prompt.ts
import prompt from "prompts"; export async function promptText( message: string, initial?: string, ): Promise<string> { const response = (await prompt({ type: "text", name: "text", message, initial, })) as { text: string }; if (Object.keys(response).length === 0) { throw new Error("Prompt cancelled"); } const result = response.text.trim(); if (result.length === 0) { throw new Error("Prompt empty"); } return result; } export async function promptNumber( message: string, initial?: number, ): Promise<number> { const response = (await prompt({ type: "number", name: "number", float: true, message, initial, })) as { number: number }; if (Object.keys(response).length === 0) { throw new Error("Prompt cancelled"); } return response.number; } export interface Choice<T> { readonly title: string; readonly description?: string; readonly value: T; } export async function promptChoice<T>( message: string, choices: Choice<T>[], ): Promise<T> { const response = (await prompt({ type: "select", name: "choice", message, choices, })) as { choice: T }; if (Object.keys(response).length === 0) { throw new Error("Prompt cancelled"); } return response.choice; } export async function promptConfirm(message: string): Promise<boolean> { const choices = [ { title: "Yes", value: true }, { title: "No", value: false }, ]; return promptChoice(message, choices); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/utils/deposit_ratio.ts
import { PriceMath } from "@orca-so/whirlpools-sdk"; import BN from "bn.js"; export function calcDepositRatio( currSqrtPriceX64: BN, lowerSqrtPriceX64: BN, upperSqrtPriceX64: BN, decimalsA: number, decimalsB: number, ): [number, number] { const clampedSqrtPriceX64 = BN.min( BN.max(currSqrtPriceX64, lowerSqrtPriceX64), upperSqrtPriceX64, ); const clampedSqrtPrice = PriceMath.sqrtPriceX64ToPrice( clampedSqrtPriceX64, decimalsA, decimalsB, ).sqrt(); const lowerSqrtPrice = PriceMath.sqrtPriceX64ToPrice( lowerSqrtPriceX64, decimalsA, decimalsB, ).sqrt(); const upperSqrtPrice = PriceMath.sqrtPriceX64ToPrice( upperSqrtPriceX64, decimalsA, decimalsB, ).sqrt(); const currPrice = PriceMath.sqrtPriceX64ToPrice( currSqrtPriceX64, decimalsA, decimalsB, ); // calc ratio (L: liquidity) // depositA = L/currSqrtPrice - L/upperSqrtPrice // depositB = L*currSqrtPrice - L*lowerSqrtPrice const depositA = upperSqrtPrice .sub(clampedSqrtPrice) .div(clampedSqrtPrice.mul(upperSqrtPrice)); const depositB = clampedSqrtPrice.sub(lowerSqrtPrice); const depositAValueInB = depositA.mul(currPrice); const depositBValueInB = depositB; const totalValueInB = depositAValueInB.add(depositBValueInB); const ratioA = depositAValueInB.div(totalValueInB).mul(100); const ratioB = depositBValueInB.div(totalValueInB).mul(100); return [ratioA.toNumber(), ratioB.toNumber()]; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/utils/provider.ts
import { AnchorProvider } from "@coral-xyz/anchor"; import { ORCA_WHIRLPOOL_PROGRAM_ID, WhirlpoolContext, } from "@orca-so/whirlpools-sdk"; // export ANCHOR_PROVIDER_URL=http://localhost:8899 // export ANCHOR_WALLET=~/.config/solana/id.json export const provider = AnchorProvider.env(); console.info("connection endpoint", provider.connection.rpcEndpoint); console.info("wallet", provider.wallet.publicKey.toBase58()); export const ctx = WhirlpoolContext.from( provider.connection, provider.wallet, ORCA_WHIRLPOOL_PROGRAM_ID, );
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_token_badge.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("initialize TokenBadge..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const tokenMintStr = await promptText("tokenMint"); const tokenMint = new PublicKey(tokenMintStr); const pda = PDAUtil.getTokenBadge( ctx.program.programId, whirlpoolsConfigPubkey, tokenMint, ); const configExtensionPda = PDAUtil.getConfigExtension( ctx.program.programId, whirlpoolsConfigPubkey, ); const configExtension = await ctx.fetcher.getConfigExtension( configExtensionPda.publicKey, ); if (!configExtension) { throw new Error("configExtension not found"); } if (!configExtension.tokenBadgeAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the token badge authority(${configExtension.tokenBadgeAuthority.toBase58()})`, ); } console.info( "setting...", "\n\twhirlpoolsConfig", whirlpoolsConfigPubkey.toBase58(), "\n\ttokenMint", tokenMint.toBase58(), ); const yesno = await promptConfirm("if the above is OK, enter YES"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializeTokenBadgeIx(ctx.program, { whirlpoolsConfigExtension: configExtensionPda.publicKey, whirlpoolsConfig: whirlpoolsConfigPubkey, tokenMint, tokenBadgePda: pda, tokenBadgeAuthority: configExtension.tokenBadgeAuthority, funder: ctx.wallet.publicKey, }), ); const landed = await sendTransaction(builder); if (landed) { console.info("tokenBadge address:", pda.publicKey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 initialize TokenBadge... prompt: whirlpoolsConfigPubkey: JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ prompt: tokenMint: FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu setting... whirlpoolsConfig JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ tokenMint FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu if the above is OK, enter YES prompt: yesno: YES tx: 5sQvVXTWHMdn9YVsWSqNCT2rCArMLz3Wazu67LETs2Hpfs4uHuWvBoKsz2RhaBwpc2DcE233DYQ4rs9PyzW88hj2 tokenBadge address: FZViZVK1ANAH9Ca3SfshZRpUdSfy1qpX3KGbDBCfCJNh */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/collect_rewards.ts
import { PublicKey } from "@solana/web3.js"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, TickArrayUtil, PoolUtil, collectRewardsQuote, } from "@orca-so/whirlpools-sdk"; import { DecimalUtil, TransactionBuilder } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import { TokenExtensionUtil } from "@orca-so/whirlpools-sdk/dist/utils/public/token-extension-util"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("collect Rewards..."); // prompt const positionPubkeyStr = await promptText("positionPubkey"); const positionPubkey = new PublicKey(positionPubkeyStr); const position = await ctx.fetcher.getPosition(positionPubkey); if (!position) { throw new Error("position not found"); } const positionMint = await ctx.fetcher.getMintInfo(position.positionMint); if (!positionMint) { throw new Error("positionMint not found"); } const whirlpoolPubkey = position.whirlpool; const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const rewardMintPubkeys = whirlpool.rewardInfos .filter((r) => PoolUtil.isRewardInitialized(r)) .map((r) => r.mint); const rewardMints = await Promise.all( rewardMintPubkeys.map((m) => ctx.fetcher.getMintInfo(m)), ); if (rewardMints.some((m) => !m)) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } if (rewardMints.length === 0) { throw new Error("no rewards"); } const lowerTickArrayPubkey = PDAUtil.getTickArrayFromTickIndex( position.tickLowerIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey; const upperTickArrayPubkey = PDAUtil.getTickArrayFromTickIndex( position.tickUpperIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey; const lowerTickArray = await ctx.fetcher.getTickArray(lowerTickArrayPubkey); const upperTickArray = await ctx.fetcher.getTickArray(upperTickArrayPubkey); if (!lowerTickArray || !upperTickArray) { throw new Error("tick array not found"); } const quote = collectRewardsQuote({ position, tickLower: TickArrayUtil.getTickFromArray( lowerTickArray, position.tickLowerIndex, tickSpacing, ), tickUpper: TickArrayUtil.getTickFromArray( upperTickArray, position.tickUpperIndex, tickSpacing, ), whirlpool, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, whirlpool, ), }); for (let i = 0; i < rewardMints.length; i++) { console.info( `collectable reward[${i}](${rewardMintPubkeys[i].toBase58()}): `, DecimalUtil.fromBN(quote.rewardOwed[i]!, rewardMints[i]!.decimals), ); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); if (position.liquidity.gtn(0)) { builder.addInstruction( WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { position: positionPubkey, tickArrayLower: lowerTickArrayPubkey, tickArrayUpper: upperTickArrayPubkey, whirlpool: whirlpoolPubkey, }), ); } for (let i = 0; i < rewardMints.length; i++) { // TODO: create if needed... const rewardOwnerAccount = getAssociatedTokenAddressSync( rewardMintPubkeys[i], ctx.wallet.publicKey, undefined, rewardMints[i]?.tokenProgram, ); builder.addInstruction( WhirlpoolIx.collectRewardV2Ix(ctx.program, { position: positionPubkey, positionAuthority: ctx.wallet.publicKey, rewardIndex: i, rewardMint: rewardMintPubkeys[i], rewardVault: whirlpool.rewardInfos[i].vault, rewardTokenProgram: rewardMints[i]!.tokenProgram, rewardOwnerAccount, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, undefined, positionMint.tokenProgram, ), whirlpool: whirlpoolPubkey, rewardTransferHookAccounts: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, rewardMints[i]!, rewardOwnerAccount, whirlpool.tokenVaultB, ctx.wallet.publicKey, ), }), ); } await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 collect Rewards... prompt: positionPubkey: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 collectable reward[0](Afn8YB1p4NsoZeS5XJBZ18LTfEy5NFPwN46wapZcBQr6): 0.004849 collectable reward[1](Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa): 0.000048513 estimatedComputeUnits: 154746 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature 4uRtXJHNQNhZC17Cryatk8ASbDABNqgskPcBouoRqUjA8P3YhbP1Z9Z25JAcJLP1wdxu9TsLwHiR7G2R3Z7oZss6 */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_config_extension.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("initialize WhirlpoolsConfigExtension..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const pda = PDAUtil.getConfigExtension( ctx.program.programId, whirlpoolsConfigPubkey, ); const whirlpoolsConfig = await ctx.fetcher.getConfig(whirlpoolsConfigPubkey); if (!whirlpoolsConfig) { throw new Error("whirlpoolsConfig not found"); } if (!whirlpoolsConfig.feeAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the fee authority(${whirlpoolsConfig.feeAuthority.toBase58()})`, ); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializeConfigExtensionIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigPubkey, whirlpoolsConfigExtensionPda: pda, feeAuthority: whirlpoolsConfig.feeAuthority, funder: ctx.wallet.publicKey, }), ); const landed = await sendTransaction(builder); if (landed) { console.info("whirlpoolsConfigExtension address:", pda.publicKey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 initialize WhirlpoolsConfigExtension... prompt: whirlpoolsConfigPubkey: JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ tx: 67TqdLX2BisDS6dAm3ofNzoFzoiC8Xu2ZH7Z3j6PSSNm2r8s3RVbBzZA64trn4D7EdZy3Rxgk4aVjKwDonDh8k3j whirlpoolsConfigExtension address: BbTBWGoiXTbekvLbK1bKzkZEPpTBCY3bXhyf5pCoX4V3 */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_default_protocol_fee_rate.ts
import { TransactionBuilder } from "@orca-so/common-sdk"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { PublicKey } from "@solana/web3.js"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const feeAuthorityPubkeyStr = await promptText("feeAuthorityPubkey"); const defaultProtocolFeeRatePer10000Str = await promptText( "defaultProtocolFeeRatePer10000", ); const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.setDefaultProtocolFeeRateIx(ctx.program, { whirlpoolsConfig: new PublicKey(whirlpoolsConfigPubkeyStr), feeAuthority: new PublicKey(feeAuthorityPubkeyStr), defaultProtocolFeeRate: Number.parseInt(defaultProtocolFeeRatePer10000Str), }), ); const landed = await sendTransaction(builder); if (landed) { console.info("tx landed"); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_reward_authority.ts
import { PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("set RewardAuthority..."); // prompt const whirlpoolPubkeyStr = await promptText("whirlpoolPubkey"); const whirlpoolPubkey = new PublicKey(whirlpoolPubkeyStr); const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const updatableRewardIndexes: number[] = []; whirlpool.rewardInfos.forEach((ri, i) => { const updatable = ri.authority.equals(ctx.wallet.publicKey); if (updatable) updatableRewardIndexes.push(i); console.info( `reward[${i}] authority: ${ri.authority.toBase58()} ${updatable ? " (Updatable)" : " (wallet is not authority)"}`, ); }); if (updatableRewardIndexes.length === 0) { throw new Error("This wallet is NOT reward authority for all reward indexes"); } console.info( "\nEnter new reward authority\n* If you don't want to update it, just type SKIP\n", ); const newRewardAuthorities: (PublicKey | undefined)[] = []; for (let i = 0; i < updatableRewardIndexes.length; i++) { const newRewardAuthority = await promptText( `newRewardAuthority for reward[${updatableRewardIndexes[i]}]`, ); try { const newAuthority = new PublicKey(newRewardAuthority); if (newAuthority.equals(ctx.wallet.publicKey)) { throw new Error("newAuthority is same to the current authority"); } newRewardAuthorities.push(newAuthority); } catch (_e) { newRewardAuthorities.push(undefined); } } if (newRewardAuthorities.every((a) => a === undefined)) { throw new Error("No new reward authority"); } console.info("setting..."); for (let i = 0; i < updatableRewardIndexes.length; i++) { if (newRewardAuthorities[i]) { console.info( `\treward[${updatableRewardIndexes[i]}] ${whirlpool.rewardInfos[updatableRewardIndexes[i]].authority.toBase58()} -> ${newRewardAuthorities[i]!.toBase58()}`, ); } else { console.info( `\treward[${updatableRewardIndexes[i]}] ${whirlpool.rewardInfos[updatableRewardIndexes[i]].authority.toBase58()} (unchanged)`, ); } } console.info("\nif the above is OK, enter YES"); const yesno = await promptConfirm("yesno"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); for (let i = 0; i < updatableRewardIndexes.length; i++) { const rewardIndex = updatableRewardIndexes[i]; const newRewardAuthority = newRewardAuthorities[i]; if (newRewardAuthority) { builder.addInstruction( WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: whirlpoolPubkey, rewardIndex, rewardAuthority: ctx.wallet.publicKey, newRewardAuthority, }), ); } } await sendTransaction(builder); /* SAMPLE EXECUTION LOG wallet 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo set RewardAuthority... ✔ whirlpoolPubkey … 3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt reward[0] authority: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo (Updatable) reward[1] authority: 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 (wallet is not authority) reward[2] authority: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo (Updatable) Enter new reward authority * If you don't want to update it, just type SKIP ✔ newRewardAuthority for reward[0] … SKIP ✔ newRewardAuthority for reward[2] … 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 setting... reward[0] 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo (unchanged) reward[2] 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo -> 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 if the above is OK, enter YES ✔ yesno › Yes estimatedComputeUnits: 103936 ✔ priorityFeeInSOL … 0.000001 Priority fee: 0.000001 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature 5iLophVC1xsk2MsCZQ5pW81Pa18ta7pe1FsNHQPUptdRh2kLDTHw54MQNwKd5HbVY9kzqNvEELrN4xB29gUhwAPx */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_fee_tier.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("initialize FeeTier..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const tickSpacingStr = await promptText("tickSpacing"); const defaultFeeRatePer1000000Str = await promptText( "defaultFeeRatePer1000000", ); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const tickSpacing = Number.parseInt(tickSpacingStr); const pda = PDAUtil.getFeeTier( ctx.program.programId, whirlpoolsConfigPubkey, tickSpacing, ); const whirlpoolsConfig = await ctx.fetcher.getConfig(whirlpoolsConfigPubkey); if (!whirlpoolsConfig) { throw new Error("whirlpoolsConfig not found"); } if (!whirlpoolsConfig.feeAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the fee authority(${whirlpoolsConfig.feeAuthority.toBase58()})`, ); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializeFeeTierIx(ctx.program, { feeTierPda: pda, funder: ctx.wallet.publicKey, whirlpoolsConfig: whirlpoolsConfigPubkey, feeAuthority: whirlpoolsConfig.feeAuthority, tickSpacing, defaultFeeRate: Number.parseInt(defaultFeeRatePer1000000Str), }), ); const landed = await sendTransaction(builder); if (landed) { console.info("feeTier address:", pda.publicKey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create FeeTier... prompt: whirlpoolsConfigPubkey: 8raEdn1tNEft7MnbMQJ1ktBqTKmHLZu7NJ7teoBkEPKm prompt: tickSpacing: 64 prompt: defaultFeeRatePer1000000: 3000 tx: gomSUyS88MbjVFTfTw2JPgQumVGttDYgm2Si7kqR5JYaqCgLA1fnSycRhjdAxXdfUWbpK1FZJQxKHgfNJrXgn2h feeTier address: BYUiw9LdPsn5n8qHQhL7SNphubKtLXKwQ4tsSioP6nTj */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/delete_token_badge.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("delete TokenBadge..."); const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const tokenMintStr = await promptText("tokenMint"); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const tokenMint = new PublicKey(tokenMintStr); const pda = PDAUtil.getTokenBadge( ctx.program.programId, whirlpoolsConfigPubkey, tokenMint, ); const configExtensionPda = PDAUtil.getConfigExtension( ctx.program.programId, whirlpoolsConfigPubkey, ); const configExtension = await ctx.fetcher.getConfigExtension( configExtensionPda.publicKey, ); if (!configExtension) { throw new Error("configExtension not found"); } if (!configExtension.tokenBadgeAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the token badge authority(${configExtension.tokenBadgeAuthority.toBase58()})`, ); } console.info( "setting...", "\n\twhirlpoolsConfig", whirlpoolsConfigPubkey.toBase58(), "\n\ttokenMint", tokenMint.toBase58(), "\n\ttokenBadge", pda.publicKey.toBase58(), ); const ok = await promptConfirm("If the above is OK, enter YES"); if (!ok) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.deleteTokenBadgeIx(ctx.program, { whirlpoolsConfigExtension: configExtensionPda.publicKey, whirlpoolsConfig: whirlpoolsConfigPubkey, tokenMint, tokenBadge: pda.publicKey, tokenBadgeAuthority: configExtension.tokenBadgeAuthority, receiver: ctx.wallet.publicKey, }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 delete TokenBadge... prompt: whirlpoolsConfigPubkey: JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ prompt: tokenMint: FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu setting... whirlpoolsConfig JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ tokenMint FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu tokenBadge FZViZVK1ANAH9Ca3SfshZRpUdSfy1qpX3KGbDBCfCJNh if the above is OK, enter YES prompt: yesno: YES tx: 1k7UNUdrVqbSbDG4XhWuLaKpxXZpGw9akz4q7iLF6ismWhtnSnJUK8san5voNCBYMFWCUyxUgYwWb3iTHBZe8Tf */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_collect_protocol_fees_authority.ts
import { PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("set CollectProtocolFeesAuthority..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const newCollectProtocolFeesAuthorityPubkeyStr = await promptText( "newCollectProtocolFeesAuthorityPubkey", ); const newCollectProtocolFeesAuthorityPubkeyAgainStr = await promptText( "newCollectProtocolFeesAuthorityPubkeyAgain", ); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const newCollectProtocolFeesAuthorityPubkey = new PublicKey( newCollectProtocolFeesAuthorityPubkeyStr, ); const newCollectProtocolFeesAuthorityPubkeyAgain = new PublicKey( newCollectProtocolFeesAuthorityPubkeyAgainStr, ); if ( !newCollectProtocolFeesAuthorityPubkey.equals( newCollectProtocolFeesAuthorityPubkeyAgain, ) ) { throw new Error( "newCollectProtocolFeesAuthorityPubkey and newCollectProtocolFeesAuthorityPubkeyAgain must be the same", ); } const whirlpoolsConfig = await ctx.fetcher.getConfig(whirlpoolsConfigPubkey); if (!whirlpoolsConfig) { throw new Error("whirlpoolsConfig not found"); } if ( !whirlpoolsConfig.collectProtocolFeesAuthority.equals(ctx.wallet.publicKey) ) { throw new Error( `the current wallet must be the collect protocol fees authority(${whirlpoolsConfig.collectProtocolFeesAuthority.toBase58()})`, ); } console.info( "setting...", "\n\tcollectProtocolFeesAuthority", whirlpoolsConfig.collectProtocolFeesAuthority.toBase58(), "\n\tnewCollectProtocolFeesAuthority", newCollectProtocolFeesAuthorityPubkey.toBase58(), ); console.info("\nif the above is OK, enter YES"); console.info( "\n>>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<<\n", ); const yesno = await promptConfirm("yesno"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.setCollectProtocolFeesAuthorityIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigPubkey, collectProtocolFeesAuthority: whirlpoolsConfig.collectProtocolFeesAuthority, newCollectProtocolFeesAuthority: newCollectProtocolFeesAuthorityPubkey, }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 set CollectProtocolFeesAuthority... prompt: whirlpoolsConfigPubkey: FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR prompt: newCollectProtocolFeesAuthorityPubkey: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo prompt: newCollectProtocolFeesAuthorityPubkeyAgain: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo setting... collectProtocolFeesAuthority 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 newCollectProtocolFeesAuthority 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo if the above is OK, enter YES >>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<< prompt: yesno: YES estimatedComputeUnits: 102679 prompt: priorityFeeInSOL: 0.000005 Priority fee: 0.000005 SOL process transaction... transaction is still valid, 151 blocks left (at most) sending... confirming... ✅successfully landed signature WNmYAhcYSoiJgJRveeKijsA77w1i68eD7iYjZzmEtwAf7VnzLqZYcFZk1acCzY5Qt3rMXNjnS6Xvd8mFNtyWmas */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_reward_emissions_super_authority.ts
import { PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("set RewardEmissionsSuperAuthority..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const newRewardEmissionsSuperAuthorityPubkeyStr = await promptText( "newRewardEmissionsSuperAuthorityPubkey", ); const newRewardEmissionsSuperAuthorityPubkeyAgainStr = await promptText( "newRewardEmissionsSuperAuthorityPubkeyAgain", ); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const newRewardEmissionsSuperAuthorityPubkey = new PublicKey( newRewardEmissionsSuperAuthorityPubkeyStr, ); const newRewardEmissionsSuperAuthorityPubkeyAgain = new PublicKey( newRewardEmissionsSuperAuthorityPubkeyAgainStr, ); if ( !newRewardEmissionsSuperAuthorityPubkey.equals( newRewardEmissionsSuperAuthorityPubkeyAgain, ) ) { throw new Error( "newRewardEmissionsSuperAuthorityPubkey and newRewardEmissionsSuperAuthorityPubkeyAgain must be the same", ); } const whirlpoolsConfig = await ctx.fetcher.getConfig(whirlpoolsConfigPubkey); if (!whirlpoolsConfig) { throw new Error("whirlpoolsConfig not found"); } if ( !whirlpoolsConfig.rewardEmissionsSuperAuthority.equals(ctx.wallet.publicKey) ) { throw new Error( `the current wallet must be the reward emissions super authority(${whirlpoolsConfig.rewardEmissionsSuperAuthority.toBase58()})`, ); } console.info( "setting...", "\n\trewardEmissionsSuperAuthority", whirlpoolsConfig.rewardEmissionsSuperAuthority.toBase58(), "\n\tnewRewardEmissionsSuperAuthority", newRewardEmissionsSuperAuthorityPubkey.toBase58(), ); console.info("\nif the above is OK, enter YES"); console.info( "\n>>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<<\n", ); const yesno = await promptConfirm("yesno"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.setRewardEmissionsSuperAuthorityIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigPubkey, rewardEmissionsSuperAuthority: whirlpoolsConfig.rewardEmissionsSuperAuthority, newRewardEmissionsSuperAuthority: newRewardEmissionsSuperAuthorityPubkey, }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 set RewardEmissionsSuperAuthority... ✔ whirlpoolsConfigPubkey … FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR ✔ newRewardEmissionsSuperAuthorityPubkey … 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo ✔ newRewardEmissionsSuperAuthorityPubkeyAgain … 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo setting... rewardEmissionsSuperAuthority 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 newRewardEmissionsSuperAuthority 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo if the above is OK, enter YES >>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<< ✔ yesno › Yes estimatedComputeUnits: 102385 ✔ priorityFeeInSOL … 0.000002 Priority fee: 0.000002 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature 432eMv1tPRN6JU7b7ezFCSU1npEVudkmfXcVsUYEnyGep988oLraMP9cz7nMEcwzhh8xW3YfnHZa4eReHU5tfzfC */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_config.ts
import { Keypair, PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("initialize WhirlpoolsConfig..."); // prompt const feeAuthorityPubkeyStr = await promptText("feeAuthorityPubkey"); const collectProtocolFeesAuthorityPubkeyStr = await promptText( "collectProtocolFeesAuthorityPubkey", ); const rewardEmissionsSuperAuthorityPubkeyStr = await promptText( "rewardEmissionsSuperAuthorityPubkey", ); const defaultProtocolFeeRatePer10000Str = await promptText( "defaultProtocolFeeRatePer10000", ); const configKeypair = Keypair.generate(); const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializeConfigIx(ctx.program, { whirlpoolsConfigKeypair: configKeypair, funder: ctx.wallet.publicKey, feeAuthority: new PublicKey(feeAuthorityPubkeyStr), collectProtocolFeesAuthority: new PublicKey( collectProtocolFeesAuthorityPubkeyStr, ), rewardEmissionsSuperAuthority: new PublicKey( rewardEmissionsSuperAuthorityPubkeyStr, ), defaultProtocolFeeRate: Number.parseInt(defaultProtocolFeeRatePer10000Str), }), ); const landed = await sendTransaction(builder); if (landed) { console.info("whirlpoolsConfig address:", configKeypair.publicKey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create WhirlpoolsConfig... prompt: feeAuthorityPubkey: r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 prompt: collectProtocolFeesAuthorityPubkey: r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 prompt: rewardEmissionsSuperAuthorityPubkey: r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 prompt: defaultProtocolFeeRatePer10000: 300 tx: 5k733gttt65s2vAuABVhVcyGMkFDKRU3MQLhmxZ1crxCaxxXn2PsucntLN6rxqz3VeAv1jPTxfZoxUbkChbDngzT whirlpoolsConfig address: 8raEdn1tNEft7MnbMQJ1ktBqTKmHLZu7NJ7teoBkEPKm */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_tick_array.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx, PriceMath, TickUtil, TICK_ARRAY_SIZE, IGNORE_CACHE, } from "@orca-so/whirlpools-sdk"; import type { PDA } from "@orca-so/common-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import type Decimal from "decimal.js"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("initialize TickArray..."); // prompt const whirlpoolPubkeyStr = await promptText("whirlpoolPubkey"); const whirlpoolPubkey = new PublicKey(whirlpoolPubkeyStr); const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const mintA = await ctx.fetcher.getMintInfo(whirlpool.tokenMintA); const mintB = await ctx.fetcher.getMintInfo(whirlpool.tokenMintB); const tickSpacing = whirlpool.tickSpacing; if (!mintA || !mintB) { throw new Error("mintA or mintB not found"); } type TickArrayInfo = { pda: PDA; startTickIndex: number; startPrice: Decimal; endPrice: Decimal; isCurrent: boolean; isFullRange: boolean; isInitialized?: boolean; }; const tickArrayInfos: TickArrayInfo[] = []; const [minTickIndex, maxTickIndex] = TickUtil.getFullRangeTickIndex(tickSpacing); tickArrayInfos.push({ pda: PDAUtil.getTickArrayFromTickIndex( minTickIndex, tickSpacing, whirlpoolPubkey, ctx.program.programId, ), startTickIndex: TickUtil.getStartTickIndex(minTickIndex, tickSpacing), startPrice: PriceMath.tickIndexToPrice( minTickIndex, mintA.decimals, mintB.decimals, ), endPrice: PriceMath.tickIndexToPrice( Math.ceil(minTickIndex / (tickSpacing * TICK_ARRAY_SIZE)) * (tickSpacing * TICK_ARRAY_SIZE), mintA.decimals, mintB.decimals, ), isCurrent: false, isFullRange: true, }); for (let offset = -6; offset <= +6; offset++) { const startTickIndex = TickUtil.getStartTickIndex( whirlpool.tickCurrentIndex, tickSpacing, offset, ); const pda = PDAUtil.getTickArray( ctx.program.programId, whirlpoolPubkey, startTickIndex, ); const endTickIndex = startTickIndex + tickSpacing * TICK_ARRAY_SIZE; const startPrice = PriceMath.tickIndexToPrice( startTickIndex, mintA.decimals, mintB.decimals, ); const endPrice = PriceMath.tickIndexToPrice( endTickIndex, mintA.decimals, mintB.decimals, ); tickArrayInfos.push({ pda, startTickIndex, startPrice, endPrice, isCurrent: offset == 0, isFullRange: false, }); } tickArrayInfos.push({ pda: PDAUtil.getTickArrayFromTickIndex( maxTickIndex, tickSpacing, whirlpoolPubkey, ctx.program.programId, ), startTickIndex: TickUtil.getStartTickIndex(maxTickIndex, tickSpacing), startPrice: PriceMath.tickIndexToPrice( Math.floor(maxTickIndex / (tickSpacing * TICK_ARRAY_SIZE)) * (tickSpacing * TICK_ARRAY_SIZE), mintA.decimals, mintB.decimals, ), endPrice: PriceMath.tickIndexToPrice( maxTickIndex, mintA.decimals, mintB.decimals, ), isCurrent: false, isFullRange: true, }); const checkInitialized = await ctx.fetcher.getTickArrays( tickArrayInfos.map((info) => info.pda.publicKey), IGNORE_CACHE, ); checkInitialized.forEach((ta, i) => (tickArrayInfos[i].isInitialized = !!ta)); console.info("neighring tickarrays & fullrange tickarrays..."); tickArrayInfos.forEach((ta) => console.info( ta.isCurrent ? ">>" : " ", ta.pda.publicKey.toBase58().padEnd(45, " "), ta.isInitialized ? " initialized" : "NOT INITIALIZED", "start", ta.startTickIndex.toString().padStart(10, " "), "covered range", ta.startPrice.toSignificantDigits(6), "-", ta.endPrice.toSignificantDigits(6), ta.isFullRange ? "(FULL)" : "", ), ); const tickArrayPubkeyStr = await promptText("tickArrayPubkey"); const tickArrayPubkey = new PublicKey(tickArrayPubkeyStr); const which = tickArrayInfos.filter((ta) => ta.pda.publicKey.equals(tickArrayPubkey), )[0]; const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initTickArrayIx(ctx.program, { funder: ctx.wallet.publicKey, whirlpool: whirlpoolPubkey, startTick: which.startTickIndex, tickArrayPda: which.pda, }), ); const landed = await sendTransaction(builder); if (landed) { console.info("initialized tickArray address:", tickArrayPubkey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create TickArray... prompt: whirlpoolPubkey: CJBunHdcRxtYSWGxkw8KarDpoz78KtNeMni2yU51TbPq neighring tickarrays... DUeNdqcFMo573Wg58GmRvYYhw3m9p5cZmzeg7kTxxLuy NOT INITIALIZED start -73216 covered range 0.661345 - 1.161477 dufQnkLbrHTWZmbmuZGwxQgBCebKLVi2peTrdgmsq3S NOT INITIALIZED start -67584 covered range 1.161477 - 2.039827 9Fj1szNFbzc7hwJxuGkHmjBreAGR7Yvqnt6FCwuyTd3w NOT INITIALIZED start -61952 covered range 2.039827 - 3.582413 7tQ6FvFkm2PwbbyZ3tBnHyE5bqq8dw8ucnfLGBjHPbtD NOT INITIALIZED start -56320 covered range 3.582413 - 6.291557 6f2k4NkMBR6jhy52QTqrMca7Hb7a7ArWdP1bWgtuxYij NOT INITIALIZED start -50688 covered range 6.291557 - 11.049448 DpNHXExUnksYhmD1tQLr25W4BJSz3Ykk4a8DN7YtYgBG NOT INITIALIZED start -45056 covered range 11.049448 - 19.405419 >> 48W97WVPhfbLWHBP4Z5828GAWzgvmbr9YngkNbGmR7zr NOT INITIALIZED start -39424 covered range 19.405419 - 34.080460 ck7UA3Hb68mC33hftDY5aGpyNzrTHaTu4ZShBV5yzqY NOT INITIALIZED start -33792 covered range 34.080460 - 59.853270 BTHpoHPNh8TQq4HSoKAvxKBxee1BffyFAbxEZcxr4BYU NOT INITIALIZED start -28160 covered range 59.853270 - 105.116358 3CMuyPQatYQQmyXsrUMQTDAghzcecpw1qXyiR1uczFe6 NOT INITIALIZED start -22528 covered range 105.116358 - 184.608940 By4Avt7jgymhiK5EaTzQnrDMMdzDWguEuuPLwJ1jazcS NOT INITIALIZED start -16896 covered range 184.608940 - 324.216530 9qKqNjLf61YfyhnDBK5Nf35e1PCxkQqRnCiApqs9uJSo NOT INITIALIZED start -11264 covered range 324.216530 - 569.400149 EzHNpv1X8KDwugXi1ALnkzV9wpJdsShXY5DdNcgCXoc4 NOT INITIALIZED start -5632 covered range 569.400149 - 999.999999 prompt: tickArrayPubkey: 48W97WVPhfbLWHBP4Z5828GAWzgvmbr9YngkNbGmR7zr tx: 5cxpJC4MDxiHxh1hSjKPtVxKjLR1CzNA3As3scBZu7vLYEmc6PPgUACG5tnnh2QYSFhM2h1nCkt6Ao5PRhq5G6b1 initialized tickArray address: 48W97WVPhfbLWHBP4Z5828GAWzgvmbr9YngkNbGmR7zr connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create TickArray... prompt: whirlpoolPubkey: CJBunHdcRxtYSWGxkw8KarDpoz78KtNeMni2yU51TbPq neighring tickarrays... DUeNdqcFMo573Wg58GmRvYYhw3m9p5cZmzeg7kTxxLuy NOT INITIALIZED start -73216 covered range 0.661345 - 1.161477 dufQnkLbrHTWZmbmuZGwxQgBCebKLVi2peTrdgmsq3S NOT INITIALIZED start -67584 covered range 1.161477 - 2.039827 9Fj1szNFbzc7hwJxuGkHmjBreAGR7Yvqnt6FCwuyTd3w NOT INITIALIZED start -61952 covered range 2.039827 - 3.582413 7tQ6FvFkm2PwbbyZ3tBnHyE5bqq8dw8ucnfLGBjHPbtD NOT INITIALIZED start -56320 covered range 3.582413 - 6.291557 6f2k4NkMBR6jhy52QTqrMca7Hb7a7ArWdP1bWgtuxYij NOT INITIALIZED start -50688 covered range 6.291557 - 11.049448 DpNHXExUnksYhmD1tQLr25W4BJSz3Ykk4a8DN7YtYgBG NOT INITIALIZED start -45056 covered range 11.049448 - 19.405419 >> 48W97WVPhfbLWHBP4Z5828GAWzgvmbr9YngkNbGmR7zr initialized start -39424 covered range 19.405419 - 34.080460 ck7UA3Hb68mC33hftDY5aGpyNzrTHaTu4ZShBV5yzqY NOT INITIALIZED start -33792 covered range 34.080460 - 59.853270 BTHpoHPNh8TQq4HSoKAvxKBxee1BffyFAbxEZcxr4BYU NOT INITIALIZED start -28160 covered range 59.853270 - 105.116358 3CMuyPQatYQQmyXsrUMQTDAghzcecpw1qXyiR1uczFe6 NOT INITIALIZED start -22528 covered range 105.116358 - 184.608940 By4Avt7jgymhiK5EaTzQnrDMMdzDWguEuuPLwJ1jazcS NOT INITIALIZED start -16896 covered range 184.608940 - 324.216530 9qKqNjLf61YfyhnDBK5Nf35e1PCxkQqRnCiApqs9uJSo NOT INITIALIZED start -11264 covered range 324.216530 - 569.400149 EzHNpv1X8KDwugXi1ALnkzV9wpJdsShXY5DdNcgCXoc4 NOT INITIALIZED start -5632 covered range 569.400149 - 999.999999 prompt: tickArrayPubkey: ck7UA3Hb68mC33hftDY5aGpyNzrTHaTu4ZShBV5yzqY tx: 34hg8C72sXYYdHdy47u3r57AKJNCyDySCzbijjcfw6kVwrSDjdFnMY743tAiMxnyp4pUByZYgxHu6a1GQR4JRjgN initialized tickArray address: ck7UA3Hb68mC33hftDY5aGpyNzrTHaTu4ZShBV5yzqY connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create TickArray... prompt: whirlpoolPubkey: CJBunHdcRxtYSWGxkw8KarDpoz78KtNeMni2yU51TbPq neighring tickarrays... DUeNdqcFMo573Wg58GmRvYYhw3m9p5cZmzeg7kTxxLuy NOT INITIALIZED start -73216 covered range 0.661345 - 1.161477 dufQnkLbrHTWZmbmuZGwxQgBCebKLVi2peTrdgmsq3S NOT INITIALIZED start -67584 covered range 1.161477 - 2.039827 9Fj1szNFbzc7hwJxuGkHmjBreAGR7Yvqnt6FCwuyTd3w NOT INITIALIZED start -61952 covered range 2.039827 - 3.582413 7tQ6FvFkm2PwbbyZ3tBnHyE5bqq8dw8ucnfLGBjHPbtD NOT INITIALIZED start -56320 covered range 3.582413 - 6.291557 6f2k4NkMBR6jhy52QTqrMca7Hb7a7ArWdP1bWgtuxYij NOT INITIALIZED start -50688 covered range 6.291557 - 11.049448 DpNHXExUnksYhmD1tQLr25W4BJSz3Ykk4a8DN7YtYgBG NOT INITIALIZED start -45056 covered range 11.049448 - 19.405419 >> 48W97WVPhfbLWHBP4Z5828GAWzgvmbr9YngkNbGmR7zr initialized start -39424 covered range 19.405419 - 34.080460 ck7UA3Hb68mC33hftDY5aGpyNzrTHaTu4ZShBV5yzqY initialized start -33792 covered range 34.080460 - 59.853270 BTHpoHPNh8TQq4HSoKAvxKBxee1BffyFAbxEZcxr4BYU NOT INITIALIZED start -28160 covered range 59.853270 - 105.116358 3CMuyPQatYQQmyXsrUMQTDAghzcecpw1qXyiR1uczFe6 NOT INITIALIZED start -22528 covered range 105.116358 - 184.608940 By4Avt7jgymhiK5EaTzQnrDMMdzDWguEuuPLwJ1jazcS NOT INITIALIZED start -16896 covered range 184.608940 - 324.216530 9qKqNjLf61YfyhnDBK5Nf35e1PCxkQqRnCiApqs9uJSo NOT INITIALIZED start -11264 covered range 324.216530 - 569.400149 EzHNpv1X8KDwugXi1ALnkzV9wpJdsShXY5DdNcgCXoc4 NOT INITIALIZED start -5632 covered range 569.400149 - 999.999999 prompt: tickArrayPubkey: DpNHXExUnksYhmD1tQLr25W4BJSz3Ykk4a8DN7YtYgBG tx: 4xLJmdjV9UvUxotH3iE4oqXXZj2MAthP27iFN9iGSRT8CYtzKj1vK3y6sa3DtyxUqZ3JPLziKTpKvWXHQPBggStv initialized tickArray address: DpNHXExUnksYhmD1tQLr25W4BJSz3Ykk4a8DN7YtYgBG */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/push_price.ts
import { PublicKey } from "@solana/web3.js"; import type { SwapV2Params } from "@orca-so/whirlpools-sdk"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, PriceMath, TICK_ARRAY_SIZE, MAX_TICK_INDEX, MIN_TICK_INDEX, SwapUtils, IGNORE_CACHE, swapQuoteWithParams, TokenExtensionUtil, PREFER_CACHE, } from "@orca-so/whirlpools-sdk"; import { DecimalUtil, Percentage, TransactionBuilder, U64_MAX, } from "@orca-so/common-sdk"; import BN from "bn.js"; import { getAssociatedTokenAddressSync } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import Decimal from "decimal.js"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; const SIGNIFICANT_DIGITS = 9; console.info("try to push pool price..."); // prompt const whirlpoolPubkeyStr = await promptText("whirlpoolPubkey"); const whirlpoolPubkey = new PublicKey(whirlpoolPubkeyStr); const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const tokenMintAPubkey = whirlpool.tokenMintA; const tokenMintBPubkey = whirlpool.tokenMintB; const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } const decimalsA = mintA.decimals; const decimalsB = mintB.decimals; const currentPrice = PriceMath.sqrtPriceX64ToPrice( whirlpool.sqrtPrice, decimalsA, decimalsB, ); console.info( "tokenMintA", tokenMintAPubkey.toBase58(), `(${mintA.tokenProgram})`, ); console.info( "tokenMintB", tokenMintBPubkey.toBase58(), `(${mintB.tokenProgram})`, ); const currentTickIndex = whirlpool.tickCurrentIndex; // yeah, there is obviously edge-case, but it is okay because this is just a dev tool const ticksInArray = tickSpacing * TICK_ARRAY_SIZE; const targetTickIndexMax = Math.min( Math.ceil(currentTickIndex / ticksInArray) * ticksInArray + 2 * ticksInArray - 1, MAX_TICK_INDEX, ); const targetTickIndexMin = Math.max( Math.floor(currentTickIndex / ticksInArray) * ticksInArray - 2 * ticksInArray, MIN_TICK_INDEX, ); const targetPriceMax = PriceMath.tickIndexToPrice( targetTickIndexMax, decimalsA, decimalsB, ); const targetPriceMin = PriceMath.tickIndexToPrice( targetTickIndexMin, decimalsA, decimalsB, ); const targetSqrtPriceMax = PriceMath.priceToSqrtPriceX64( targetPriceMax, decimalsA, decimalsB, ); const targetSqrtPriceMin = PriceMath.priceToSqrtPriceX64( targetPriceMin, decimalsA, decimalsB, ); let targetSqrtPrice: BN; while (true) { console.info(`current price: ${currentPrice.toSD(SIGNIFICANT_DIGITS)} B/A`); console.info( `available target price range: ${targetPriceMin.toSD(SIGNIFICANT_DIGITS)} B/A ~ ${targetPriceMax.toSD(SIGNIFICANT_DIGITS)} B/A`, ); const targetPriceStr = await promptText("targetPrice"); const targetPrice = new Decimal(targetPriceStr); targetSqrtPrice = PriceMath.priceToSqrtPriceX64( targetPrice, decimalsA, decimalsB, ); if ( targetSqrtPrice.lt(targetSqrtPriceMin) || targetSqrtPrice.gt(targetSqrtPriceMax) ) { console.info("invalid target price"); continue; } console.info(`target price: ${targetPrice.toSD(SIGNIFICANT_DIGITS)} B/A`); console.info(`is target price OK ? (if it is OK, enter OK)`); const ok = await promptConfirm("OK"); if (ok) { break; } } // get swap quote const aToB = targetSqrtPrice.lt(whirlpool.sqrtPrice); const inputToken = aToB ? mintA : mintB; const outputToken = aToB ? mintB : mintA; const tickArrays = await SwapUtils.getTickArrays( whirlpool.tickCurrentIndex, tickSpacing, aToB, ORCA_WHIRLPOOL_PROGRAM_ID, whirlpoolPubkey, ctx.fetcher, IGNORE_CACHE, ); const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContextForPool( ctx.fetcher, tokenMintAPubkey, tokenMintBPubkey, PREFER_CACHE, ); const quote = swapQuoteWithParams( { aToB, amountSpecifiedIsInput: true, otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true), tickArrays, whirlpoolData: whirlpool, tokenExtensionCtx, // use too much input to estimate required input amount tokenAmount: U64_MAX, sqrtPriceLimit: targetSqrtPrice, }, Percentage.fromFraction(1, 1000), ); // 0.1% slippage console.info("aToB", quote.aToB); console.info( "estimatedAmountIn", DecimalUtil.fromBN(quote.estimatedAmountIn, inputToken.decimals).toString(), aToB ? "A" : "B", ); console.info( "estimatedAmountOut", DecimalUtil.fromBN(quote.estimatedAmountOut, outputToken.decimals).toString(), aToB ? "B" : "A", ); // ok prompt console.info(`OK ? (if it is OK, enter OK)`); const ok = await promptConfirm("OK"); if (!ok) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); const tokenOwnerAccountA = getAssociatedTokenAddressSync( tokenMintAPubkey, ctx.wallet.publicKey, undefined, mintA.tokenProgram, ); const tokenOwnerAccountB = getAssociatedTokenAddressSync( tokenMintBPubkey, ctx.wallet.publicKey, undefined, mintB.tokenProgram, ); const swapV2Params: SwapV2Params = { amount: quote.amount, amountSpecifiedIsInput: quote.amountSpecifiedIsInput, aToB: quote.aToB, sqrtPriceLimit: targetSqrtPrice, otherAmountThreshold: quote.otherAmountThreshold, tokenAuthority: ctx.wallet.publicKey, tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, whirlpool: whirlpoolPubkey, tokenProgramA: mintA.tokenProgram, tokenProgramB: mintB.tokenProgram, oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey).publicKey, tickArray0: quote.tickArray0, tickArray1: quote.tickArray1, tickArray2: quote.tickArray2, ...TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool( ctx.connection, tokenExtensionCtx, // hmm, why I didn't make Utility class more convenient ... ? aToB ? tokenOwnerAccountA : whirlpool.tokenVaultA, aToB ? whirlpool.tokenVaultA : tokenOwnerAccountA, aToB ? ctx.wallet.publicKey : whirlpoolPubkey, aToB ? whirlpool.tokenVaultB : tokenOwnerAccountB, aToB ? tokenOwnerAccountB : whirlpool.tokenVaultB, aToB ? whirlpoolPubkey : ctx.wallet.publicKey, ), }; if (quote.estimatedAmountIn.isZero() && quote.estimatedAmountOut.isZero()) { // push empty pool price builder.addInstruction( WhirlpoolIx.swapV2Ix(ctx.program, { ...swapV2Params, // partial fill (intentional) amount: new BN(1), amountSpecifiedIsInput: false, sqrtPriceLimit: targetSqrtPrice, otherAmountThreshold: new BN(1), }), ); } else { builder.addInstruction(WhirlpoolIx.swapV2Ix(ctx.program, swapV2Params)); } const landed = await sendTransaction(builder); if (landed) { const postWhirlpool = await ctx.fetcher.getPool( whirlpoolPubkey, IGNORE_CACHE, ); if (!postWhirlpool) { throw new Error("whirlpool not found"); } const updatedPrice = PriceMath.sqrtPriceX64ToPrice( postWhirlpool.sqrtPrice, decimalsA, decimalsB, ); // if arb bot executed opposite trade, the price will be reverted console.info( "updated current price", updatedPrice.toSD(SIGNIFICANT_DIGITS), "B/A", ); } /* SAMPLE EXECUTION LOG $ yarn run pushPrice yarn run v1.22.22 $ npx ts-node src/push_price.ts connection endpoint https://orca.mainnet.eclipse.rpcpool.com/xxxxxxxxxxxxxx wallet EvQdhqCLKc6Sh6mxvzF7pMrCjhnMzsJCvXEmYfu18Boj try to push pool price... prompt: whirlpoolPubkey: 44w4HrojzxKwxEb3bmjRNcJ4irFhUGBUjrCYecYhPvqq tokenMintA So11111111111111111111111111111111111111112 (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) tokenMintB AKEWE7Bgh87GPp171b4cJPSSZfmZwQ3KaqYqXoKLNAEE (TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb) current price: 1054.7755 B/A available target price range: 868.669141 B/A ~ 1235.02281 B/A prompt: targetPrice: 1080 target price: 1080 B/A is target price OK ? (if it is OK, enter OK) prompt: OK: OK aToB false estimatedAmountIn 0.333295 B estimatedAmountOut 0.00031196 A OK ? (if it is OK, enter OK) prompt: OK: OK estimatedComputeUnits: 176958 prompt: priorityFeeInSOL: 0.0000001 Priority fee: 1e-7 SOL process transaction... transaction is still valid, 151 blocks left (at most) sending... confirming... ✅successfully landed signature 23KANyU2dQCowps4HEstxHsqZMJS8GYJV7hb6NZhrVPQfmk1aRHFHMVMdxY1sVcEsbTe37ozqd513orzH7fZHnJP updated current price 1079.99999 B/A ✨ Done in 49.55s. */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/open_position.ts
import { Keypair, PublicKey } from "@solana/web3.js"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, PriceMath, TickUtil, } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import Decimal from "decimal.js"; import { calcDepositRatio } from "../utils/deposit_ratio"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("open Position..."); // prompt const whirlpoolPubkeyStr = await promptText("whirlpoolPubkey"); const whirlpoolPubkey = new PublicKey(whirlpoolPubkeyStr); const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const tokenMintAPubkey = whirlpool.tokenMintA; const tokenMintBPubkey = whirlpool.tokenMintB; const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } const decimalsA = mintA.decimals; const decimalsB = mintB.decimals; const currentPrice = PriceMath.sqrtPriceX64ToPrice( whirlpool.sqrtPrice, decimalsA, decimalsB, ); console.info( "tokenMintA", tokenMintAPubkey.toBase58(), `(${mintA.tokenProgram})`, ); console.info( "tokenMintB", tokenMintBPubkey.toBase58(), `(${mintB.tokenProgram})`, ); let lowerTickIndex: number; let upperTickIndex: number; console.info(`if you want to create FULL RANGE position, enter YES`); const fullrangeYesno = await promptConfirm("YES"); if (fullrangeYesno) { // RULL RANGE const fullrange = TickUtil.getFullRangeTickIndex(tickSpacing); lowerTickIndex = fullrange[0]; upperTickIndex = fullrange[1]; console.info("using full range"); } else { // CONCENTRATED while (true) { console.info(`current price: ${currentPrice.toSD(6)} B/A`); const lowerPriceStr = await promptText("lowerPrice"); const upperPriceStr = await promptText("upperPrice"); const lowerPrice = new Decimal(lowerPriceStr); const upperPrice = new Decimal(upperPriceStr); const initializableLowerTickIndex = PriceMath.priceToInitializableTickIndex( lowerPrice, decimalsA, decimalsB, tickSpacing, ); const initializableUpperTickIndex = PriceMath.priceToInitializableTickIndex( upperPrice, decimalsA, decimalsB, tickSpacing, ); const initializableLowerPrice = PriceMath.tickIndexToPrice( initializableLowerTickIndex, decimalsA, decimalsB, ); const initializableUpperPrice = PriceMath.tickIndexToPrice( initializableUpperTickIndex, decimalsA, decimalsB, ); const [ratioA, ratioB] = calcDepositRatio( whirlpool.sqrtPrice, PriceMath.tickIndexToSqrtPriceX64(initializableLowerTickIndex), PriceMath.tickIndexToSqrtPriceX64(initializableUpperTickIndex), decimalsA, decimalsB, ); console.info( `deposit ratio A:B ${ratioA.toFixed(2)}% : ${ratioB.toFixed(2)}%`, ); console.info( `is range [${initializableLowerPrice.toSD(6)}, ${initializableUpperPrice.toSD(6)}] OK ? (if it is OK, enter OK)`, ); const ok = await promptConfirm("OK"); if (ok) { lowerTickIndex = initializableLowerTickIndex; upperTickIndex = initializableUpperTickIndex; break; } } } const lowerTickArrayPda = PDAUtil.getTickArrayFromTickIndex( lowerTickIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ); const upperTickArrayPda = PDAUtil.getTickArrayFromTickIndex( upperTickIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ); const lowerTickArray = await ctx.fetcher.getTickArray( lowerTickArrayPda.publicKey, ); const upperTickArray = await ctx.fetcher.getTickArray( upperTickArrayPda.publicKey, ); const initLowerTickArray = !lowerTickArray; const initUpperTickArray = !upperTickArray; console.info(`if you want to create position with Metadata, enter YES`); const withMetadataYesno = await promptConfirm("YES"); console.info( `if you want to create position WITHOUT TokenExtensions, enter YES`, ); const withoutTokenExtensions = await promptConfirm("YES"); console.info( "setting...", "\n\twhirlpool", whirlpoolPubkey.toBase58(), "\n\ttokenMintA", tokenMintAPubkey.toBase58(), "\n\ttokenMintB", tokenMintBPubkey.toBase58(), "\n\ttickSpacing", tickSpacing, "\n\tcurrentPrice", currentPrice.toSD(6), "B/A", "\n\tlowerPrice(Index)", PriceMath.tickIndexToPrice(lowerTickIndex, decimalsA, decimalsB).toSD(6), `(${lowerTickIndex})`, "\n\tupperPrice(Index)", PriceMath.tickIndexToPrice(upperTickIndex, decimalsA, decimalsB).toSD(6), `(${upperTickIndex})`, "\n\tlowerTickArray", lowerTickArrayPda.publicKey.toBase58(), initLowerTickArray ? "(TO BE INITIALIZED)" : "(initialized)", "\n\tupperTickArray", upperTickArrayPda.publicKey.toBase58(), initUpperTickArray ? "(TO BE INITIALIZED)" : "(initialized)", "\n\twithMetadata", withMetadataYesno ? "WITH metadata" : "WITHOUT metadata", "\n\twithTokenExtensions", !withoutTokenExtensions ? "WITH TokenExtensions" : "WITHOUT TokenExtensions", ); const yesno = await promptConfirm("if the above is OK, enter YES"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); if (initLowerTickArray) { builder.addInstruction( WhirlpoolIx.initTickArrayIx(ctx.program, { whirlpool: whirlpoolPubkey, funder: ctx.wallet.publicKey, startTick: TickUtil.getStartTickIndex(lowerTickIndex, tickSpacing), tickArrayPda: lowerTickArrayPda, }), ); } if (initUpperTickArray) { builder.addInstruction( WhirlpoolIx.initTickArrayIx(ctx.program, { whirlpool: whirlpoolPubkey, funder: ctx.wallet.publicKey, startTick: TickUtil.getStartTickIndex(upperTickIndex, tickSpacing), tickArrayPda: upperTickArrayPda, }), ); } const positionMintKeypair = Keypair.generate(); const positionPda = PDAUtil.getPosition( ORCA_WHIRLPOOL_PROGRAM_ID, positionMintKeypair.publicKey, ); if (!withoutTokenExtensions) { // TokenExtensions based Position NFT builder.addInstruction( WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { funder: ctx.wallet.publicKey, whirlpool: whirlpoolPubkey, tickLowerIndex: lowerTickIndex, tickUpperIndex: upperTickIndex, withTokenMetadataExtension: withMetadataYesno, owner: ctx.wallet.publicKey, positionMint: positionMintKeypair.publicKey, positionPda, positionTokenAccount: getAssociatedTokenAddressSync( positionMintKeypair.publicKey, ctx.wallet.publicKey, undefined, TOKEN_2022_PROGRAM_ID, ), }), ); } else { // TokenProgram based Position NFT const metadataPda = PDAUtil.getPositionMetadata( positionMintKeypair.publicKey, ); const params = { funder: ctx.wallet.publicKey, whirlpool: whirlpoolPubkey, tickLowerIndex: lowerTickIndex, tickUpperIndex: upperTickIndex, owner: ctx.wallet.publicKey, positionMintAddress: positionMintKeypair.publicKey, positionPda, positionTokenAccount: getAssociatedTokenAddressSync( positionMintKeypair.publicKey, ctx.wallet.publicKey, ), metadataPda, }; if (withMetadataYesno) { builder.addInstruction( WhirlpoolIx.openPositionWithMetadataIx(ctx.program, params), ); } else { builder.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, params)); } } builder.addSigner(positionMintKeypair); const landed = await sendTransaction(builder); if (landed) { console.info( "position mint address:", positionMintKeypair.publicKey.toBase58(), ); console.info("position address:", positionPda.publicKey.toBase58()); console.info( "📝position liquidity is empty, please use yarn run increaseLiquidity to deposit", ); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 open Position... prompt: whirlpoolPubkey: EgxU92G34jw6QDG9RuTX9StFg1PmHuDqkRKAE5kVEiZ4 tokenMintA Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) tokenMintB BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) if you want to create FULL RANGE position, enter YES prompt: yesno: YES using full range if you want to create position with Metadata, enter YES prompt: yesno: no setting... whirlpool EgxU92G34jw6QDG9RuTX9StFg1PmHuDqkRKAE5kVEiZ4 tokenMintA Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa tokenMintB BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k tickSpacing 64 currentPrice 0.0100099 B/A lowerPrice(Index) 0.0000000000000000544947 (-443584) upperPrice(Index) 18350300000000000000000 (443584) lowerTickArray AihMywzP74pU2riq1ihFW2YSVcc1itT3yiP7minvkxDs (initialized) upperTickArray F4h3qr6uBgdLDJyTms4YiebiaiuCEvC5C9LJE8scA1LV (initialized) withMetadata WITHOUT metadata if the above is OK, enter YES prompt: yesno: YES estimatedComputeUnits: 163606 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature CAY5wBXVhbHRVjJYgi8c1KS5XczLDwZB1S7sf5fwkCakXo8SQBtasvjBvtjwpdZUoQnwJoPmhG2ZrPGX3PRQ8ax position mint address: 8nBbX74FraqPuoL8AwXxPiPaULg8CP8hUJ41hJGAx4nb position address: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 📝position liquidity is empty, please use yarn run increaseLiquidity to deposit */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_reward.ts
import { PublicKey, Keypair } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx, PoolUtil } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("initialize Reward..."); // prompt const whirlpoolPubkeyStr = await promptText("whirlpoolPubkey"); const rewardTokenMintStr = await promptText("rewardTokenMint"); const whirlpoolPubkey = new PublicKey(whirlpoolPubkeyStr); const rewardTokenMintPubkey = new PublicKey(rewardTokenMintStr); const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const rewardToken = await ctx.fetcher.getMintInfo(rewardTokenMintPubkey); if (!rewardToken) { throw new Error("reward token not found"); } const rewardTokenProgram = rewardToken.tokenProgram.equals( TOKEN_2022_PROGRAM_ID, ) ? "Token-2022" : "Token"; const alreadyInitialized = whirlpool.rewardInfos.some((r) => r.mint.equals(rewardTokenMintPubkey), ); if (alreadyInitialized) { throw new Error("reward for the token already initialized"); } const allInitialized = whirlpool.rewardInfos.every((r) => PoolUtil.isRewardInitialized(r), ); if (allInitialized) { throw new Error( "all rewards already initialized, no more reward can be initialized", ); } const rewardIndex = whirlpool.rewardInfos.findIndex( (r) => !PoolUtil.isRewardInitialized(r), ); const rewardAuthority = whirlpool.rewardInfos[rewardIndex].authority; if (!rewardAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the reward authority(${rewardAuthority.toBase58()})`, ); } const rewardTokenBadgePubkey = PDAUtil.getTokenBadge( ctx.program.programId, whirlpool.whirlpoolsConfig, rewardTokenMintPubkey, ).publicKey; const rewardTokenBadge = await ctx.fetcher.getTokenBadge( rewardTokenBadgePubkey, ); const rewardTokenBadgeInialized = !!rewardTokenBadge; const rewardVaultKeypair = Keypair.generate(); console.info( "setting...", "\n\twhirlpool", whirlpoolPubkey.toBase58(), "\n\trewardIndex", rewardIndex, "\n\trewardToken", rewardTokenMintPubkey.toBase58(), `(${rewardTokenProgram})`, rewardTokenBadgeInialized ? "with badge" : "without badge", "\n\trewardVault(gen)", rewardVaultKeypair.publicKey.toBase58(), ); const yesno = await promptConfirm("if the above is OK, enter YES"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializeRewardV2Ix(ctx.program, { funder: ctx.wallet.publicKey, rewardAuthority: ctx.wallet.publicKey, rewardIndex, rewardMint: rewardTokenMintPubkey, rewardTokenBadge: rewardTokenBadgePubkey, rewardTokenProgram: rewardToken.tokenProgram, rewardVaultKeypair, whirlpool: whirlpoolPubkey, }), ); const landed = await sendTransaction(builder); if (landed) { console.info( "initialized reward vault address:", rewardVaultKeypair.publicKey.toBase58(), ); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 initialize Reward... prompt: whirlpoolPubkey: 9dXKLjL2137ojWsQZALxV9mzQAb3ovwzHn6DbiV1NHZf prompt: rewardTokenMint: FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu setting... whirlpool 9dXKLjL2137ojWsQZALxV9mzQAb3ovwzHn6DbiV1NHZf rewardIndex 1 rewardToken FfprBPB2ULqp4tyBfzrzwxNvpGYoh8hidzSmiA5oDtmu (Token) with badge rewardVault(gen) DKaGdKFMLpY3Pj4crPW2tJNVuoQLA1tarLaTDCn2ZWox if the above is OK, enter YES prompt: yesno: YES tx: 47bP5aPKGBMift8xJYK3oCnDog45UNYAcr4yJsjYKsatkb7RhNFyBshaAECM3CVpvXZNC2JkLD7rcoYSaKviz2ZD initialized reward vault address: DKaGdKFMLpY3Pj4crPW2tJNVuoQLA1tarLaTDCn2ZWox */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/initialize_whirlpool.ts
import { Keypair, PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx, PoolUtil, PriceMath, } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText, promptConfirm } from "../utils/prompt"; console.info("initialize Whirlpool..."); // prompt const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const tokenMint0PubkeyStr = await promptText("tokenMint0Pubkey"); const tokenMint1PubkeyStr = await promptText("tokenMint1Pubkey"); const tickSpacingStr = await promptText("tickSpacing"); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const tokenMint0Pubkey = new PublicKey(tokenMint0PubkeyStr); const tokenMint1Pubkey = new PublicKey(tokenMint1PubkeyStr); const tickSpacing = Number.parseInt(tickSpacingStr); const [tokenMintAAddress, tokenMintBAddress] = PoolUtil.orderMints( tokenMint0Pubkey, tokenMint1Pubkey, ); if (tokenMintAAddress.toString() !== tokenMint0Pubkey.toBase58()) { console.info("token order is inverted due to order restriction"); } const tokenMintAPubkey = new PublicKey(tokenMintAAddress); const tokenMintBPubkey = new PublicKey(tokenMintBAddress); const feeTierPubkey = PDAUtil.getFeeTier( ctx.program.programId, whirlpoolsConfigPubkey, tickSpacing, ).publicKey; const pda = PDAUtil.getWhirlpool( ctx.program.programId, whirlpoolsConfigPubkey, tokenMintAPubkey, tokenMintBPubkey, tickSpacing, ); const tokenVaultAKeypair = Keypair.generate(); const tokenVaultBKeypair = Keypair.generate(); const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { throw new Error("mint not found"); } const tokenProgramA = mintA.tokenProgram.equals(TOKEN_2022_PROGRAM_ID) ? "Token-2022" : "Token"; const tokenProgramB = mintB.tokenProgram.equals(TOKEN_2022_PROGRAM_ID) ? "Token-2022" : "Token"; const tokenBadgeAPubkey = PDAUtil.getTokenBadge( ctx.program.programId, whirlpoolsConfigPubkey, tokenMintAPubkey, ).publicKey; const tokenBadgeBPubkey = PDAUtil.getTokenBadge( ctx.program.programId, whirlpoolsConfigPubkey, tokenMintBPubkey, ).publicKey; const tokenBadge = await ctx.fetcher.getTokenBadges([ tokenBadgeAPubkey, tokenBadgeBPubkey, ]); const tokenBadgeAInitialized = !!tokenBadge.get(tokenBadgeAPubkey.toBase58()); const tokenBadgeBInitialized = !!tokenBadge.get(tokenBadgeBPubkey.toBase58()); let initTickIndex, initPrice; while (true) { initTickIndex = Number.parseInt(await promptText("initTickIndex")); initPrice = PriceMath.tickIndexToPrice( initTickIndex, mintA.decimals, mintB.decimals, ); const ok = await promptConfirm( `is InitPrice ${initPrice.toFixed(6)} OK ? (if it is OK, enter OK)`, ); if (ok) break; } const initSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(initTickIndex); console.info( "setting...", "\n\twhirlpoolsConfig", whirlpoolsConfigPubkey.toBase58(), "\n\ttokenMintA", tokenMintAPubkey.toBase58(), `(${tokenProgramA})`, tokenBadgeAInitialized ? "with badge" : "without badge", "\n\ttokenMintB", tokenMintBPubkey.toBase58(), `(${tokenProgramB})`, tokenBadgeBInitialized ? "with badge" : "without badge", "\n\ttickSpacing", tickSpacing, "\n\tinitPrice", initPrice.toFixed(mintB.decimals), "B/A", "\n\ttokenVaultA(gen)", tokenVaultAKeypair.publicKey.toBase58(), "\n\ttokenVaultB(gen)", tokenVaultBKeypair.publicKey.toBase58(), ); const yesno = await promptConfirm("if the above is OK, enter YES"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.initializePoolV2Ix(ctx.program, { whirlpoolPda: pda, funder: ctx.wallet.publicKey, whirlpoolsConfig: whirlpoolsConfigPubkey, tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, tokenProgramA: mintA.tokenProgram, tokenProgramB: mintB.tokenProgram, tokenBadgeA: tokenBadgeAPubkey, tokenBadgeB: tokenBadgeBPubkey, tickSpacing, feeTierKey: feeTierPubkey, tokenVaultAKeypair, tokenVaultBKeypair, initSqrtPrice, }), ); const landed = await sendTransaction(builder); if (landed) { console.info("whirlpool address:", pda.publicKey.toBase58()); } /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 create Whirlpool... prompt: whirlpoolsConfigPubkey: 8raEdn1tNEft7MnbMQJ1ktBqTKmHLZu7NJ7teoBkEPKm prompt: tokenMintAPubkey: So11111111111111111111111111111111111111112 prompt: tokenMintBPubkey: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v prompt: feeTierPubkey: BYUiw9LdPsn5n8qHQhL7SNphubKtLXKwQ4tsSioP6nTj prompt: initTickIndex: 0 is InitPrice 999.999999 OK ? (if it is OK, enter OK) prompt: OK: prompt: initTickIndex: -1000 is InitPrice 904.841941 OK ? (if it is OK, enter OK) prompt: OK: prompt: initTickIndex: -10000 is InitPrice 367.897834 OK ? (if it is OK, enter OK) prompt: OK: prompt: initTickIndex: -50000 is InitPrice 6.739631 OK ? (if it is OK, enter OK) prompt: OK: prompt: initTickIndex: -40000 is InitPrice 18.319302 OK ? (if it is OK, enter OK) prompt: OK: prompt: initTickIndex: -38000 is InitPrice 22.375022 OK ? (if it is OK, enter OK) prompt: OK: OK setting... whirlpoolsConfig 8raEdn1tNEft7MnbMQJ1ktBqTKmHLZu7NJ7teoBkEPKm tokenMintA So11111111111111111111111111111111111111112 tokenMintB EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v tickSpacing 64 initPrice 22.375022 B/A tokenVaultA(gen) G5JMrgXxUdjjGXPVMezddTZAr5x7L9N4Nix6ZBS1FAwB tokenVaultB(gen) 3wwdjzY7mAsoG5yYN3Ebo58p1HdihCCSeo8Qbwx8Yg5r if the above is OK, enter YES prompt: yesno: YES tx: X7pyW22o6fi5x1YmjDEacabvbtPYrqLyXaJpv88JJ6xLBi9eXra9QhuqeYuRmLGh72NsmQ11Kf8YCe3rPzqcc9r whirlpool address: CJBunHdcRxtYSWGxkw8KarDpoz78KtNeMni2yU51TbPq */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_token_badge_authority.ts
import { PublicKey } from "@solana/web3.js"; import { PDAUtil, WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("set TokenBadgeAuthority..."); const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const newTokenBadgeAuthorityPubkeyStr = await promptText( "newTokenBadgeAuthorityPubkey", ); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const newTokenBadgeAuthorityPubkey = new PublicKey( newTokenBadgeAuthorityPubkeyStr, ); const pda = PDAUtil.getConfigExtension( ctx.program.programId, whirlpoolsConfigPubkey, ); const whirlpoolsConfigExtension = await ctx.fetcher.getConfigExtension( pda.publicKey, ); if (!whirlpoolsConfigExtension) { throw new Error("whirlpoolsConfigExtension not found"); } if ( !whirlpoolsConfigExtension.configExtensionAuthority.equals( ctx.wallet.publicKey, ) ) { throw new Error( `the current wallet must be the config extension authority(${whirlpoolsConfigExtension.configExtensionAuthority.toBase58()})`, ); } console.info( "setting...", "\n\ttokenBadgeAuthority", whirlpoolsConfigExtension.tokenBadgeAuthority.toBase58(), "\n\tnewTokenBadgeAuthority", newTokenBadgeAuthorityPubkey.toBase58(), ); console.info("\nif the above is OK, enter YES"); const yesno = await promptConfirm("yesno"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigPubkey, whirlpoolsConfigExtension: pda.publicKey, configExtensionAuthority: whirlpoolsConfigExtension.configExtensionAuthority, newTokenBadgeAuthority: newTokenBadgeAuthorityPubkey, }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 set TokenBadgeAuthority... prompt: whirlpoolsConfigPubkey: JChtLEVR9E6B5jiHTZS1Nd9WgMULMHv2UcVryYACAFYQ prompt: newTokenBadgeAuthorityPubkey: 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 setting... tokenBadgeAuthority r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 newTokenBadgeAuthority 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 if the above is OK, enter YES prompt: yesno: YES tx: 2g8gsZFYyNcp4oQU6s9ZM5ZcyH4sye3KbNVTdTyt9KZzPrwP2tqK3Hxrc8LEXiTHGUSiyw228QWsYBdJMdPNqib5 */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/collect_fees.ts
import { PublicKey } from "@solana/web3.js"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, collectFeesQuote, TickArrayUtil, } from "@orca-so/whirlpools-sdk"; import { DecimalUtil, TransactionBuilder } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import { TokenExtensionUtil } from "@orca-so/whirlpools-sdk/dist/utils/public/token-extension-util"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("collect Fees..."); // prompt const positionPubkeyStr = await promptText("positionPubkey"); const positionPubkey = new PublicKey(positionPubkeyStr); const position = await ctx.fetcher.getPosition(positionPubkey); if (!position) { throw new Error("position not found"); } const positionMint = await ctx.fetcher.getMintInfo(position.positionMint); if (!positionMint) { throw new Error("positionMint not found"); } const whirlpoolPubkey = position.whirlpool; const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const tokenMintAPubkey = whirlpool.tokenMintA; const tokenMintBPubkey = whirlpool.tokenMintB; const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } const decimalsA = mintA.decimals; const decimalsB = mintB.decimals; const lowerTickArrayPubkey = PDAUtil.getTickArrayFromTickIndex( position.tickLowerIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey; const upperTickArrayPubkey = PDAUtil.getTickArrayFromTickIndex( position.tickUpperIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey; const lowerTickArray = await ctx.fetcher.getTickArray(lowerTickArrayPubkey); const upperTickArray = await ctx.fetcher.getTickArray(upperTickArrayPubkey); if (!lowerTickArray || !upperTickArray) { throw new Error("tick array not found"); } const quote = collectFeesQuote({ position, tickLower: TickArrayUtil.getTickFromArray( lowerTickArray, position.tickLowerIndex, tickSpacing, ), tickUpper: TickArrayUtil.getTickFromArray( upperTickArray, position.tickUpperIndex, tickSpacing, ), whirlpool, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, whirlpool, ), }); console.info( "collectable feeA: ", DecimalUtil.fromBN(quote.feeOwedA, decimalsA), ); console.info( "collectable feeB: ", DecimalUtil.fromBN(quote.feeOwedB, decimalsB), ); const builder = new TransactionBuilder(ctx.connection, ctx.wallet); const tokenOwnerAccountA = getAssociatedTokenAddressSync( tokenMintAPubkey, ctx.wallet.publicKey, undefined, mintA.tokenProgram, ); const tokenOwnerAccountB = getAssociatedTokenAddressSync( tokenMintBPubkey, ctx.wallet.publicKey, undefined, mintB.tokenProgram, ); if (position.liquidity.gtn(0)) { builder.addInstruction( WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { position: positionPubkey, tickArrayLower: lowerTickArrayPubkey, tickArrayUpper: upperTickArrayPubkey, whirlpool: whirlpoolPubkey, }), ); } builder.addInstruction( WhirlpoolIx.collectFeesV2Ix(ctx.program, { position: positionPubkey, positionAuthority: ctx.wallet.publicKey, tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, undefined, positionMint.tokenProgram, ), tokenOwnerAccountA, tokenOwnerAccountB, tokenProgramA: mintA.tokenProgram, tokenProgramB: mintB.tokenProgram, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, whirlpool: whirlpoolPubkey, tokenTransferHookAccountsA: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintA, tokenOwnerAccountA, whirlpool.tokenVaultA, ctx.wallet.publicKey, ), tokenTransferHookAccountsB: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintB, tokenOwnerAccountB, whirlpool.tokenVaultB, ctx.wallet.publicKey, ), }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 collect Fees... prompt: positionPubkey: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 collectable feeA: 0 collectable feeB: 0 estimatedComputeUnits: 149469 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature 3VfNAQJ8nxTStU9fjkhg5sNRPpBrAMYx5Vyp92aDS5FsWpEqgLw5Ckzzw5hJ1rsNEh6VGLaf9TZWWcLCRWzvhNjX */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/decrease_liquidity.ts
import { PublicKey } from "@solana/web3.js"; import type { DecreaseLiquidityQuote } from "@orca-so/whirlpools-sdk"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, PoolUtil, PriceMath, IGNORE_CACHE, decreaseLiquidityQuoteByLiquidityWithParams, } from "@orca-so/whirlpools-sdk"; import { DecimalUtil, Percentage, TransactionBuilder, } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import Decimal from "decimal.js"; import { calcDepositRatio } from "../utils/deposit_ratio"; import BN from "bn.js"; import { TokenExtensionUtil } from "@orca-so/whirlpools-sdk/dist/utils/public/token-extension-util"; import { ctx } from "../utils/provider"; import { promptConfirm, promptNumber, promptText } from "../utils/prompt"; console.info("decrease Liquidity..."); // prompt const positionPubkeyStr = await promptText("positionPubkey"); const positionPubkey = new PublicKey(positionPubkeyStr); const position = await ctx.fetcher.getPosition(positionPubkey); if (!position) { throw new Error("position not found"); } const positionMint = await ctx.fetcher.getMintInfo(position.positionMint); if (!positionMint) { throw new Error("positionMint not found"); } const whirlpoolPubkey = position.whirlpool; const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const tokenMintAPubkey = whirlpool.tokenMintA; const tokenMintBPubkey = whirlpool.tokenMintB; const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } const decimalsA = mintA.decimals; const decimalsB = mintB.decimals; const currentPrice = PriceMath.sqrtPriceX64ToPrice( whirlpool.sqrtPrice, decimalsA, decimalsB, ); console.info( "tokenMintA", tokenMintAPubkey.toBase58(), `(${mintA.tokenProgram})`, ); console.info( "tokenMintB", tokenMintBPubkey.toBase58(), `(${mintB.tokenProgram})`, ); const currentBalance = PoolUtil.getTokenAmountsFromLiquidity( position.liquidity, whirlpool.sqrtPrice, PriceMath.tickIndexToSqrtPriceX64(position.tickLowerIndex), PriceMath.tickIndexToSqrtPriceX64(position.tickUpperIndex), false, ); console.info( `current liquidity: ${position.liquidity} (${DecimalUtil.fromBN(currentBalance.tokenA, decimalsA).toSD(6)} A, ${DecimalUtil.fromBN(currentBalance.tokenB, decimalsB).toSD(6)} B)`, ); console.info( "lowerPrice(Index):", PriceMath.tickIndexToPrice( position.tickLowerIndex, decimalsA, decimalsB, ).toSD(6), `(${position.tickLowerIndex})`, ); console.info( "upperPrice(Index):", PriceMath.tickIndexToPrice( position.tickUpperIndex, decimalsA, decimalsB, ).toSD(6), `(${position.tickUpperIndex})`, ); const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64( position.tickLowerIndex, ); const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64( position.tickUpperIndex, ); const depositRatio = calcDepositRatio( whirlpool.sqrtPrice, lowerSqrtPrice, upperSqrtPrice, decimalsA, decimalsB, ); console.info(`current price: ${currentPrice.toSD(6)} B/A`); console.info( `deposit ratio A:B ${depositRatio[0].toFixed(2)}% : ${depositRatio[1].toFixed(2)}%`, ); let decreaseLiquidityQuote: DecreaseLiquidityQuote; while (true) { console.info(); const decreaseLiquidityAmountOrPercentage = await promptText( "Please enter liquidity amount to decrease or enter percentage to decrease with % (e.g. 10%)", ); let liquidityAmount: BN; if (decreaseLiquidityAmountOrPercentage.trim().endsWith("%")) { const percentage = new Decimal( decreaseLiquidityAmountOrPercentage.trim().slice(0, -1), ); if (percentage.gt(100) || percentage.lessThanOrEqualTo(0)) { console.info("invalid percentage"); continue; } const liquidity = new Decimal(position.liquidity.toString()); liquidityAmount = new BN( liquidity.mul(percentage).div(100).floor().toString(), ); } else { liquidityAmount = new BN(decreaseLiquidityAmountOrPercentage); if (liquidityAmount.gt(position.liquidity)) { console.info("too large liquidity amount"); continue; } } const decimalSlippagePercentNum = await promptNumber( "decimalSlippagePercent", ); const decimalSlippagePercent = new Decimal(decimalSlippagePercentNum); const slippage = Percentage.fromDecimal(decimalSlippagePercent); const quote = await decreaseLiquidityQuoteByLiquidityWithParams({ liquidity: liquidityAmount, sqrtPrice: whirlpool.sqrtPrice, tickCurrentIndex: whirlpool.tickCurrentIndex, tickLowerIndex: position.tickLowerIndex, tickUpperIndex: position.tickUpperIndex, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, whirlpool, IGNORE_CACHE, ), slippageTolerance: slippage, }); console.info(`liquidity DELTA: ${quote.liquidityAmount.toString()}`); console.info( `estimated tokenA: ${DecimalUtil.fromBN(quote.tokenEstA, decimalsA).toSD(6)} at least ${DecimalUtil.fromBN(quote.tokenMinA, decimalsA).toSD(6)}`, ); console.info( `estimated tokenB: ${DecimalUtil.fromBN(quote.tokenEstB, decimalsB).toSD(6)} at least ${DecimalUtil.fromBN(quote.tokenMinB, decimalsB).toSD(6)}`, ); const ok = await promptConfirm("If the above is OK, enter YES"); if (ok) { decreaseLiquidityQuote = quote; break; } } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); const tokenOwnerAccountA = getAssociatedTokenAddressSync( tokenMintAPubkey, ctx.wallet.publicKey, undefined, mintA.tokenProgram, ); const tokenOwnerAccountB = getAssociatedTokenAddressSync( tokenMintBPubkey, ctx.wallet.publicKey, undefined, mintB.tokenProgram, ); builder.addInstruction( WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, { liquidityAmount: decreaseLiquidityQuote.liquidityAmount, tokenMinA: decreaseLiquidityQuote.tokenMinA, tokenMinB: decreaseLiquidityQuote.tokenMinB, position: positionPubkey, positionAuthority: ctx.wallet.publicKey, tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, undefined, positionMint.tokenProgram, ), tickArrayLower: PDAUtil.getTickArrayFromTickIndex( position.tickLowerIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey, tickArrayUpper: PDAUtil.getTickArrayFromTickIndex( position.tickUpperIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey, tokenOwnerAccountA, tokenOwnerAccountB, tokenProgramA: mintA.tokenProgram, tokenProgramB: mintB.tokenProgram, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, whirlpool: whirlpoolPubkey, tokenTransferHookAccountsA: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintA, tokenOwnerAccountA, whirlpool.tokenVaultA, ctx.wallet.publicKey, ), tokenTransferHookAccountsB: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintB, tokenOwnerAccountB, whirlpool.tokenVaultB, ctx.wallet.publicKey, ), }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 decrease Liquidity... prompt: positionPubkey: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 tokenMintA Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) tokenMintB BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) current liquidity: 31538582 (9.96839 A, 0.099783 B) lowerPrice(Index): 0.0000000000000000544947 (-443584) upperPrice(Index): 18350300000000000000000 (443584) current price: 0.0100099 B/A deposit ratio A:B 50.00% : 50.00% Please enter liquidity amount to decrease or enter percentage to decrease with % (e.g. 10%) prompt: decreaseLiquidityAmountOrPercentage: 50% prompt: decimalSlippagePercent: 10 liquidity DELTA: 15769291 estimated tokenA: 4.98419 at least 4.53108 estimated tokenB: 0.049891 at least 0.045355 if the above is OK, enter OK prompt: OK: OK estimatedComputeUnits: 153091 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature 2XPsDXqcX936gD46MM4MsyigaFcP7u2vxFCErYTKUMUXGVHphMFdx9P6ckoVnNeVDS1TxK1C5qn4LKg4ivz9c6um */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/increase_liquidity.ts
import { PublicKey } from "@solana/web3.js"; import type { IncreaseLiquidityQuote } from "@orca-so/whirlpools-sdk"; import { ORCA_WHIRLPOOL_PROGRAM_ID, PDAUtil, WhirlpoolIx, PoolUtil, PriceMath, increaseLiquidityQuoteByInputTokenWithParams, IGNORE_CACHE, } from "@orca-so/whirlpools-sdk"; import { DecimalUtil, Percentage, TransactionBuilder, } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import Decimal from "decimal.js"; import { calcDepositRatio } from "../utils/deposit_ratio"; import BN from "bn.js"; import { TokenExtensionUtil } from "@orca-so/whirlpools-sdk/dist/utils/public/token-extension-util"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("increase Liquidity..."); // prompt const positionPubkeyStr = await promptText("positionPubkey"); const positionPubkey = new PublicKey(positionPubkeyStr); const position = await ctx.fetcher.getPosition(positionPubkey); if (!position) { throw new Error("position not found"); } const positionMint = await ctx.fetcher.getMintInfo(position.positionMint); if (!positionMint) { throw new Error("positionMint not found"); } const whirlpoolPubkey = position.whirlpool; const whirlpool = await ctx.fetcher.getPool(whirlpoolPubkey); if (!whirlpool) { throw new Error("whirlpool not found"); } const tickSpacing = whirlpool.tickSpacing; const tokenMintAPubkey = whirlpool.tokenMintA; const tokenMintBPubkey = whirlpool.tokenMintB; const mintA = await ctx.fetcher.getMintInfo(tokenMintAPubkey); const mintB = await ctx.fetcher.getMintInfo(tokenMintBPubkey); if (!mintA || !mintB) { // extremely rare case (CloseMint extension on Token-2022 is used) throw new Error("token mint not found"); } const decimalsA = mintA.decimals; const decimalsB = mintB.decimals; const currentPrice = PriceMath.sqrtPriceX64ToPrice( whirlpool.sqrtPrice, decimalsA, decimalsB, ); console.info( "tokenMintA", tokenMintAPubkey.toBase58(), `(${mintA.tokenProgram})`, ); console.info( "tokenMintB", tokenMintBPubkey.toBase58(), `(${mintB.tokenProgram})`, ); const currentBalance = PoolUtil.getTokenAmountsFromLiquidity( position.liquidity, whirlpool.sqrtPrice, PriceMath.tickIndexToSqrtPriceX64(position.tickLowerIndex), PriceMath.tickIndexToSqrtPriceX64(position.tickUpperIndex), false, ); console.info( `current liquidity: ${position.liquidity} (${DecimalUtil.fromBN(currentBalance.tokenA, decimalsA).toSD(6)} A, ${DecimalUtil.fromBN(currentBalance.tokenB, decimalsB).toSD(6)} B)`, ); console.info( "lowerPrice(Index):", PriceMath.tickIndexToPrice( position.tickLowerIndex, decimalsA, decimalsB, ).toSD(6), `(${position.tickLowerIndex})`, ); console.info( "upperPrice(Index):", PriceMath.tickIndexToPrice( position.tickUpperIndex, decimalsA, decimalsB, ).toSD(6), `(${position.tickUpperIndex})`, ); const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64( position.tickLowerIndex, ); const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64( position.tickUpperIndex, ); const depositRatio = calcDepositRatio( whirlpool.sqrtPrice, lowerSqrtPrice, upperSqrtPrice, decimalsA, decimalsB, ); console.info(`current price: ${currentPrice.toSD(6)} B/A`); console.info( `deposit ratio A:B ${depositRatio[0].toFixed(2)}% : ${depositRatio[1].toFixed(2)}%`, ); const balanceA = await ctx.fetcher.getTokenInfo( getAssociatedTokenAddressSync( tokenMintAPubkey, ctx.wallet.publicKey, undefined, mintA.tokenProgram, ), ); const balanceB = await ctx.fetcher.getTokenInfo( getAssociatedTokenAddressSync( tokenMintBPubkey, ctx.wallet.publicKey, undefined, mintB.tokenProgram, ), ); let increaseLiquidityQuote: IncreaseLiquidityQuote; while (true) { let depositByA: boolean; if (whirlpool.sqrtPrice.lte(lowerSqrtPrice)) { depositByA = true; } else if (whirlpool.sqrtPrice.gte(upperSqrtPrice)) { depositByA = false; } else { console.info( "current price is in the range, please specify the token to deposit (A or B)", ); while (true) { const tokenAorB = await promptText("AorB"); if (tokenAorB === "A" || tokenAorB === "B") { depositByA = tokenAorB === "A"; break; } } } console.info( `balance A: ${DecimalUtil.fromBN(new BN(balanceA!.amount.toString()), decimalsA).toSD(6)}`, ); console.info( `balance B: ${DecimalUtil.fromBN(new BN(balanceB!.amount.toString()), decimalsB).toSD(6)}`, ); console.info( `Please enter the decimal amount of token ${depositByA ? "A" : "B"} to deposit`, ); const decimalAmountStr = await promptText("decimalAmount"); const decimalAmount = new Decimal(decimalAmountStr); const amount = DecimalUtil.toBN( decimalAmount, depositByA ? decimalsA : decimalsB, ); const decimalSlippagePercentStr = await promptText("decimalSlippagePercent"); const decimalSlippagePercent = new Decimal(decimalSlippagePercentStr); const slippage = Percentage.fromDecimal(decimalSlippagePercent); const quote = await increaseLiquidityQuoteByInputTokenWithParams({ inputTokenAmount: amount, inputTokenMint: depositByA ? tokenMintAPubkey : tokenMintBPubkey, sqrtPrice: whirlpool.sqrtPrice, tickCurrentIndex: whirlpool.tickCurrentIndex, tickLowerIndex: position.tickLowerIndex, tickUpperIndex: position.tickUpperIndex, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, whirlpool, IGNORE_CACHE, ), tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, slippageTolerance: slippage, }); console.info(`estimated liquidity: ${quote.liquidityAmount.toString()}`); console.info( `estimated tokenA: ${DecimalUtil.fromBN(quote.tokenEstA, decimalsA).toSD(6)} at most ${DecimalUtil.fromBN(quote.tokenMaxA, decimalsA).toSD(6)}`, ); console.info( `estimated tokenB: ${DecimalUtil.fromBN(quote.tokenEstB, decimalsB).toSD(6)} at most ${DecimalUtil.fromBN(quote.tokenMaxB, decimalsB).toSD(6)}`, ); if ( quote.tokenMaxA.gt(new BN(balanceA!.amount.toString())) || quote.tokenMaxB.gt(new BN(balanceB!.amount.toString())) ) { throw new Error("insufficient balance"); } const ok = await promptConfirm("if the above is OK, enter YES"); if (ok) { increaseLiquidityQuote = quote; break; } } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); const tokenOwnerAccountA = getAssociatedTokenAddressSync( tokenMintAPubkey, ctx.wallet.publicKey, undefined, mintA.tokenProgram, ); const tokenOwnerAccountB = getAssociatedTokenAddressSync( tokenMintBPubkey, ctx.wallet.publicKey, undefined, mintB.tokenProgram, ); builder.addInstruction( WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, { liquidityAmount: increaseLiquidityQuote.liquidityAmount, tokenMaxA: increaseLiquidityQuote.tokenMaxA, tokenMaxB: increaseLiquidityQuote.tokenMaxB, position: positionPubkey, positionAuthority: ctx.wallet.publicKey, tokenMintA: tokenMintAPubkey, tokenMintB: tokenMintBPubkey, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, undefined, positionMint.tokenProgram, ), tickArrayLower: PDAUtil.getTickArrayFromTickIndex( position.tickLowerIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey, tickArrayUpper: PDAUtil.getTickArrayFromTickIndex( position.tickUpperIndex, tickSpacing, whirlpoolPubkey, ORCA_WHIRLPOOL_PROGRAM_ID, ).publicKey, tokenOwnerAccountA, tokenOwnerAccountB, tokenProgramA: mintA.tokenProgram, tokenProgramB: mintB.tokenProgram, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, whirlpool: whirlpoolPubkey, tokenTransferHookAccountsA: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintA, tokenOwnerAccountA, whirlpool.tokenVaultA, ctx.wallet.publicKey, ), tokenTransferHookAccountsB: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.provider.connection, mintB, tokenOwnerAccountB, whirlpool.tokenVaultB, ctx.wallet.publicKey, ), }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 increase Liquidity... prompt: positionPubkey: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 tokenMintA Jd4M8bfJG3sAkd82RsGWyEXoaBXQP7njFzBwEaCTuDa (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) tokenMintB BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) current liquidity: 0 (0 A, 0 B) lowerPrice(Index): 0.0000000000000000544947 (-443584) upperPrice(Index): 18350300000000000000000 (443584) deposit ratio A:B 50.00% : 50.00% current price is in the range, please specify the token to deposit (A or B) prompt: AorB: A balance A: 7708.07 balance B: 10189.3 Please enter the decimal amount of token A to deposit prompt: decimalAmount: 10 prompt: decimalSlippagePercent: 1 estimated liquidity: 31638582 estimated tokenA: 9.99999 at most 10.0999 estimated tokenB: 0.1001 at most 0.101101 prompt: OK: OK estimatedComputeUnits: 152435 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature UdEZa3GWncberjduAxCLiiQH5MTMdLuzCycN6jceXo9bUefKPGuaqnvYJc1EiAeh4VDgvfUCEKB8L5UHnJr6ZXA */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/close_position.ts
import { PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptText } from "../utils/prompt"; console.info("close Position..."); // prompt const positionPubkeyStr = await promptText("positionPubkey"); const positionPubkey = new PublicKey(positionPubkeyStr); const position = await ctx.fetcher.getPosition(positionPubkey); if (!position) { throw new Error("position not found"); } const positionMint = await ctx.fetcher.getMintInfo(position.positionMint); if (!positionMint) { throw new Error("positionMint not found"); } if (!position.liquidity.isZero()) { throw new Error("position is not empty (liquidity is not zero)"); } if (!position.feeOwedA.isZero() || !position.feeOwedB.isZero()) { throw new Error("position has collectable fees"); } if (!position.rewardInfos.every((r) => r.amountOwed.isZero())) { throw new Error("position has collectable rewards"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); if (positionMint.tokenProgram.equals(TOKEN_PROGRAM_ID)) { builder.addInstruction( WhirlpoolIx.closePositionIx(ctx.program, { position: positionPubkey, positionAuthority: ctx.wallet.publicKey, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, ), positionMint: position.positionMint, receiver: ctx.wallet.publicKey, }), ); } else { builder.addInstruction( WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { position: positionPubkey, positionAuthority: ctx.wallet.publicKey, positionTokenAccount: getAssociatedTokenAddressSync( position.positionMint, ctx.wallet.publicKey, undefined, TOKEN_2022_PROGRAM_ID, ), positionMint: position.positionMint, receiver: ctx.wallet.publicKey, }), ); } await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet r21Gamwd9DtyjHeGywsneoQYR39C1VDwrw7tWxHAwh6 close Position... prompt: positionPubkey: H4WEb57EYh5AhorHArjgRXVgSBJRMZi3DvsLb3J1XNj6 estimatedComputeUnits: 120649 prompt: priorityFeeInSOL: 0 Priority fee: 0 SOL process transaction... transaction is still valid, 150 blocks left (at most) sending... confirming... ✅successfully landed signature dQwedycTbM9UTYwQiiUE5Q7ydZRzL3zywaQ3xEo3RhHxDvfsY8wkAakSXQRdXswxdQCLLMwwDJVSNHYcTCDDcf3 */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/set_fee_authority.ts
import { PublicKey } from "@solana/web3.js"; import { WhirlpoolIx } from "@orca-so/whirlpools-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { sendTransaction } from "../utils/transaction_sender"; import { ctx } from "../utils/provider"; import { promptConfirm, promptText } from "../utils/prompt"; console.info("set FeeAuthority..."); const whirlpoolsConfigPubkeyStr = await promptText("whirlpoolsConfigPubkey"); const newFeeAuthorityPubkeyStr = await promptText("newFeeAuthorityPubkey"); const newFeeAuthorityPubkeyAgainStr = await promptText( "newFeeAuthorityPubkeyAgain", ); const whirlpoolsConfigPubkey = new PublicKey(whirlpoolsConfigPubkeyStr); const newFeeAuthorityPubkey = new PublicKey(newFeeAuthorityPubkeyStr); const newFeeAuthorityPubkeyAgain = new PublicKey(newFeeAuthorityPubkeyAgainStr); if (!newFeeAuthorityPubkey.equals(newFeeAuthorityPubkeyAgain)) { throw new Error( "newFeeAuthorityPubkey and newFeeAuthorityPubkeyAgain must be the same", ); } const whirlpoolsConfig = await ctx.fetcher.getConfig(whirlpoolsConfigPubkey); if (!whirlpoolsConfig) { throw new Error("whirlpoolsConfig not found"); } if (!whirlpoolsConfig.feeAuthority.equals(ctx.wallet.publicKey)) { throw new Error( `the current wallet must be the fee authority(${whirlpoolsConfig.feeAuthority.toBase58()})`, ); } console.info( "setting...", "\n\tfeeAuthority", whirlpoolsConfig.feeAuthority.toBase58(), "\n\tnewFeeAuthority", newFeeAuthorityPubkey.toBase58(), ); console.info("\nif the above is OK, enter YES"); console.info( "\n>>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<<\n", ); const yesno = await promptConfirm("yesno"); if (!yesno) { throw new Error("stopped"); } const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction( WhirlpoolIx.setFeeAuthorityIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigPubkey, feeAuthority: whirlpoolsConfig.feeAuthority, newFeeAuthority: newFeeAuthorityPubkey, }), ); await sendTransaction(builder); /* SAMPLE EXECUTION LOG connection endpoint http://localhost:8899 wallet 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 set FeeAuthority... prompt: whirlpoolsConfigPubkey: FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR prompt: newFeeAuthorityPubkey: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo prompt: newFeeAuthorityPubkeyAgain: 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo setting... feeAuthority 2v112XbwQXFrdqX438HUrfZF91qCZb7QRP4bwUiN7JF5 newFeeAuthority 3otH3AHWqkqgSVfKFkrxyDqd2vK6LcaqigHrFEmWcGuo if the above is OK, enter YES >>>>> WARNING: authority transfer is highly sensitive operation, please double check new authority address <<<<< prompt: yesno: YES estimatedComputeUnits: 102611 prompt: priorityFeeInSOL: 0.000005 Priority fee: 0.000005 SOL process transaction... transaction is still valid, 151 blocks left (at most) sending... confirming... ✅successfully landed signature 5Z75rUDcMkXS5sUz45rKNLVMbniBtEzLdU3LC1mHmQymSUBYEzZTHAmmeE6gxzRTHtmmp9AWVWvM9MPYYNsGWTyq */
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/todo/initializeTickArrayRange
import type { PDA} from "@orca-so/common-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import type { AccountFetcher, WhirlpoolData} from "@orca-so/whirlpools-sdk"; import { MAX_TICK_INDEX, MIN_TICK_INDEX, ORCA_WHIRLPOOL_PROGRAM_ID, PriceMath, TickArrayUtil, TickUtil, TICK_ARRAY_SIZE, WhirlpoolContext, WhirlpoolIx, } from "@orca-so/whirlpools-sdk"; import NodeWallet from "@project-serum/anchor/dist/cjs/nodewallet"; import type { MintInfo } from "@solana/spl-token"; import type { Connection, PublicKey } from "@solana/web3.js"; import Decimal from "decimal.js"; import prompts from "prompts"; import { getConnectionFromEnv } from "../connection"; import { getOwnerKeypair } from "../loadAccounts"; import { promptForNetwork, promptForWhirlpool } from "./whirlpool-script-utils"; const SOL_9_DEC = new Decimal(10).pow(9); const TICK_ARRAYS_TO_FETCH_PER_TX = 5; async function run() { const owner = await getOwnerKeypair(); const network = await promptForNetwork(); const connection = await getConnectionFromEnv(network); console.log(`Connected to RPC - ${connection.rpcEndpoint}`); const ctx = WhirlpoolContext.from( connection, new NodeWallet(owner), ORCA_WHIRLPOOL_PROGRAM_ID, ); const fetcher = ctx.fetcher; // Derive Whirlpool address const { key: whirlpoolAddr, tokenKeyInverted } = await promptForWhirlpool(); if (tokenKeyInverted) { console.log(`NOTE: tokenMintA & B order had been inverted.`); } console.log(`Fetching Whirlpool at address - ${whirlpoolAddr.toBase58()}`); console.log(`...`); const acct = await fetchWhirlpoolAccounts(fetcher, whirlpoolAddr); const { lowerTick, upperTick } = await promptForTickRange(acct); console.log( `Script will initialize arrays range [${lowerTick} -> ${upperTick}] (start-indices). Current tick is at ${ acct.data.tickCurrentIndex } / price - $${PriceMath.sqrtPriceX64ToPrice( acct.data.sqrtPrice, acct.tokenA.decimals, acct.tokenB.decimals, ).toDecimalPlaces(5)}`, ); console.log(`Fetching tick-array data...`); const tickArrayInfo = await getTickArrays( fetcher, connection, whirlpoolAddr, acct, lowerTick, upperTick, ); console.log(``); console.log( `There are ${tickArrayInfo.numTickArraysInRange} arrays in range, with ${tickArrayInfo.numTickArraysToInit} arrays that needs to be initialized.`, ); if (tickArrayInfo.numTickArraysToInit > 0) { await checkWalletBalance( connection, owner.publicKey, tickArrayInfo.costToInit, ); await executeInitialization(ctx, whirlpoolAddr, tickArrayInfo.pdasToInit); } console.log("Complete."); } async function executeInitialization( ctx: WhirlpoolContext, addr: PublicKey, arraysToInit: { startIndex: number; pda: PDA }[], ) { const response = await prompts([ { type: "select", name: "execute", message: "Execute?", choices: [ { title: "yes", value: "yes" }, { title: "no", value: "no" }, ], }, ]); if (response.execute === "no") { return; } let start = 0; let end = TICK_ARRAYS_TO_FETCH_PER_TX; do { const chunk = arraysToInit.slice(start, end); const startIndicies = chunk.map((val) => val.startIndex); console.log( `Executing initializations for array w/ start indices [${startIndicies}]...`, ); const txBuilder = new TransactionBuilder(ctx.connection, ctx.wallet); for (const tickArray of chunk) { txBuilder.addInstruction( WhirlpoolIx.initTickArrayIx(ctx.program, { startTick: tickArray.startIndex, tickArrayPda: tickArray.pda, whirlpool: addr, funder: ctx.wallet.publicKey, }), ); } const txId = await txBuilder.buildAndExecute(); console.log(`Tx executed at ${txId}`); start = end; end = end + TICK_ARRAYS_TO_FETCH_PER_TX; } while (start < arraysToInit.length); } async function checkWalletBalance( connection: Connection, ownerKey: PublicKey, costToInit: Decimal, ) { const walletBalance = new Decimal(await connection.getBalance(ownerKey)).div( SOL_9_DEC, ); console.log( `Wallet balance (${ownerKey.toBase58()}) - ${walletBalance} SOL. Est. cost - ${costToInit} SOL`, ); if (walletBalance.lessThan(costToInit)) { throw new Error("Wallet has insufficent SOL to complete this operation."); } } async function getTickArrays( fetcher: AccountFetcher, connection: Connection, whirlpool: PublicKey, acct: WhirlpoolAccounts, lowerTick: number, upperTick: number, ) { const lowerStartTick = TickUtil.getStartTickIndex( lowerTick, acct.data.tickSpacing, ); const upperStartTick = TickUtil.getStartTickIndex( upperTick, acct.data.tickSpacing, ); const numTickArraysInRange = Math.ceil( (upperStartTick - lowerStartTick) / acct.data.tickSpacing / TICK_ARRAY_SIZE, ) + 1; const arrayStartIndicies = [...Array(numTickArraysInRange).keys()].map( (index) => lowerStartTick + index * acct.data.tickSpacing * TICK_ARRAY_SIZE, ); const initArrayKeys = await TickArrayUtil.getUninitializedArraysPDAs( arrayStartIndicies, ORCA_WHIRLPOOL_PROGRAM_ID, whirlpool, acct.data.tickSpacing, fetcher, true, ); // TickArray = Tick.LEN(113) * Array_SIZE (88) + 36 + 8 = 9988 const rentExemptPerAcct = await connection.getMinimumBalanceForRentExemption(9988); const costToInit = new Decimal(initArrayKeys.length * rentExemptPerAcct).div( SOL_9_DEC, ); return { numTickArraysInRange, numTickArraysToInit: initArrayKeys.length, pdasToInit: initArrayKeys, costToInit, }; } type WhirlpoolAccounts = { tokenMintA: PublicKey; tokenMintB: PublicKey; tokenA: MintInfo; tokenB: MintInfo; data: WhirlpoolData; }; async function fetchWhirlpoolAccounts( fetcher: AccountFetcher, whirlpoolAddr: PublicKey, ): Promise<WhirlpoolAccounts> { const pool = await fetcher.getPool(whirlpoolAddr, true); if (!pool) { throw new Error( `Unable to fetch Whirlpool at addr - ${whirlpoolAddr.toBase58()}`, ); } const { tokenMintA, tokenMintB } = pool; const [tokenA, tokenB] = await fetcher.listMintInfos( [tokenMintA, tokenMintB], true, ); if (!tokenA) { throw new Error(`Unable to fetch token - ${tokenMintA.toBase58()}`); } if (!tokenB) { throw new Error(`Unable to fetch token - ${tokenMintB.toBase58()}`); } return { tokenMintA, tokenMintB, tokenA, tokenB, data: pool, }; } type PriceRangeResponse = { lowerTick: number; upperTick: number; }; async function promptForTickRange( acct: WhirlpoolAccounts, ): Promise<PriceRangeResponse> { const provideTypeResponse = await prompts([ { type: "select", name: "provideType", message: "How would you like to provide the price range?", choices: [ { title: "Full Range", value: "fullRange" }, { title: "By Price", value: "price" }, { title: "By tick", value: "tick" }, { title: "Current Price", value: "currentPrice" }, ], }, ]); let lowerTick = 0, upperTick = 0; switch (provideTypeResponse.provideType) { case "fullRange": { lowerTick = MIN_TICK_INDEX; upperTick = MAX_TICK_INDEX; break; } case "price": { const priceResponse = await prompts([ { type: "number", name: "lowerPrice", message: `Lower Price for ${acct.tokenMintB.toBase58()}/${acct.tokenMintB.toBase58()}`, }, { type: "number", name: "upperPrice", message: `Upper Price for ${acct.tokenMintB.toBase58()}/${acct.tokenMintB.toBase58()}`, }, ]); lowerTick = PriceMath.priceToTickIndex( new Decimal(priceResponse.lowerPrice), acct.tokenA.decimals, acct.tokenB.decimals, ); upperTick = PriceMath.priceToTickIndex( new Decimal(priceResponse.upperPrice), acct.tokenA.decimals, acct.tokenB.decimals, ); break; } case "tick": { const tickResponse = await prompts([ { type: "text", name: "lowerTick", message: `Lower Tick for ${acct.tokenMintB.toBase58()}/${acct.tokenMintB.toBase58()}`, }, { type: "text", name: "upperTick", message: `Upper Tick for ${acct.tokenMintB.toBase58()}/${acct.tokenMintB.toBase58()}`, }, ]); lowerTick = new Decimal(tickResponse.lowerTick) .toDecimalPlaces(0) .toNumber(); upperTick = new Decimal(tickResponse.upperTick) .toDecimalPlaces(0) .toNumber(); break; } case "currentPrice": { const currPriceResponse = await prompts([ { type: "number", name: "expandBy", message: `Current price is ${PriceMath.sqrtPriceX64ToPrice( acct.data.sqrtPrice, acct.tokenA.decimals, acct.tokenB.decimals, ).toDecimalPlaces(9)} / tick - ${ acct.data.tickCurrentIndex }. How many tick arrays on each direction would you like to initialize?`, }, ]); const currTick = TickUtil.getInitializableTickIndex( acct.data.tickCurrentIndex, acct.data.tickSpacing, ); const expandByTick = currPriceResponse.expandBy * acct.data.tickSpacing * TICK_ARRAY_SIZE; lowerTick = currTick - expandByTick; upperTick = currTick + expandByTick; break; } } if (lowerTick < MIN_TICK_INDEX || lowerTick > MAX_TICK_INDEX) { throw new Error( `Lower tick - ${lowerTick} is lower than MIN allowed [(${MIN_TICK_INDEX}, ${MAX_TICK_INDEX}]`, ); } if (upperTick < MIN_TICK_INDEX || upperTick > MAX_TICK_INDEX) { throw new Error( `Upper tick - ${lowerTick} is not within bounds [${MIN_TICK_INDEX}, ${MAX_TICK_INDEX}]`, ); } if (lowerTick >= upperTick) { throw new Error( `Upper tick ${upperTick} must be higher than lower tick - ${lowerTick}`, ); } return { lowerTick: TickUtil.getInitializableTickIndex( lowerTick, acct.data.tickSpacing, ), upperTick: TickUtil.getInitializableTickIndex( upperTick, acct.data.tickSpacing, ), }; } run();
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands
solana_public_repos/orca-so/whirlpools/legacy-sdk/cli/src/commands/todo/initializeWhirlpoolReward
import { Provider } from "@project-serum/anchor"; import { OrcaNetwork, OrcaWhirlpoolClient } from "@orca-so/whirlpool-sdk"; const SOLANA_NETWORK_URL = "https://api.devnet.solana.com"; async function run() { // @ts-expect-error this script doesn't work with latest anchor version const provider = Provider.local(SOLANA_NETWORK_URL); const rewardAuthority = "81dVYq6RgX6Jt1TEDWpLkYUMWesNq3GMSYLKaKsopUqi"; const poolAddress = "75dykYVKVj15kHEYiK4p9XEy8XpkrnfWMR8q3pbiC9Uo"; const rewardMint = "orcarKHSqC5CDDsGbho8GKvwExejWHxTqGzXgcewB9L"; const client = new OrcaWhirlpoolClient({ network: OrcaNetwork.DEVNET, }); const { tx, rewardVault } = client.admin.getInitRewardTx({ provider, rewardAuthority, poolAddress, rewardMint, rewardIndex: 0, }); const txId = await tx.buildAndExecute(); console.log("txId", txId); console.log("rewardVault", rewardVault.toBase58()); } run() .then(() => { console.log("Success"); }) .catch((e) => { console.error(e); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/README.md
# Legacy Whirlpools SDK Whirpools is an open-source concentrated liquidity AMM contract on the Solana blockchain. 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. The contract has been audited by Kudelski and Neodyme. ## Installation 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" ``` ## Usage Visit our [documentation site on GitHub](https://orca-so.github.io/whirlpools/) to to learn more about how to use this SDK. ## Tests To run tests for the SDK, setup your anchor environment and run: ``` anchor test ``` # License [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/)
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/package.json
{ "name": "@orca-so/whirlpools-sdk", "version": "0.13.9", "description": "Typescript SDK to interact with Orca's Whirlpool program.", "license": "Apache-2.0", "main": "dist/index.js", "types": "dist/index.d.ts", "peerDependencies": { "@coral-xyz/anchor": "~0.29.0", "@orca-so/common-sdk": "0.6.4", "@solana/spl-token": "^0.4.8", "@solana/web3.js": "^1.90.0", "decimal.js": "^10.4.3" }, "dependencies": { "tiny-invariant": "^1.3.1" }, "devDependencies": { "@coral-xyz/anchor": "~0.29.0", "@orca-so/common-sdk": "0.6.4", "@orca-so/whirlpools-program": "*", "@solana/spl-token": "^0.4.8", "@solana/web3.js": "^1.90.0", "@types/bn.js": "~5.1.6", "@types/jest": "^29.5.14", "decimal.js": "^10.4.3", "typescript": "^5.7.2" }, "scripts": { "build": "mkdir -p ./src/artifacts && cp -f ../../target/idl/whirlpool.json ./src/artifacts/whirlpool.json && cp -f ../../target/types/whirlpool.ts ./src/artifacts/whirlpool.ts && tsc", "clean": "rimraf dist", "test": "anchor test --skip-build" }, "files": [ "dist", "README.md" ], "repository": { "type": "git", "url": "git+https://github.com/orca-so/whirlpools.git" }, "keywords": [ "solana", "crypto", "defi", "dex", "amm" ], "author": "team@orca.so", "bugs": { "url": "https://github.com/orca-so/whirlpools/issues" }, "homepage": "https://orca.so" }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tsconfig.json
{ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "./dist" }, "include": ["./src/**/*.ts", "./src/artifacts/whirlpool.json"] }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/open_position_with_token_extensions.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { ExtensionType, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, createMintToInstruction, getAssociatedTokenAddressSync, getExtensionData, getExtensionTypes, getMetadataPointerState, getMintCloseAuthority, createMint, ASSOCIATED_TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import { unpack as unpackTokenMetadata } from "@solana/spl-token-metadata"; import type { TokenMetadata } from "@solana/spl-token-metadata"; import { Keypair, SystemProgram } from "@solana/web3.js"; import type { PublicKey } from "@solana/web3.js"; import * as assert from "assert"; import type { InitPoolParams, PositionData } from "../../src"; import { IGNORE_CACHE, MAX_TICK_INDEX, MIN_TICK_INDEX, PDAUtil, WHIRLPOOL_NFT_UPDATE_AUTH, WhirlpoolContext, WhirlpoolIx, toTx, } from "../../src"; import { ONE_SOL, TickSpacing, ZERO_BN, systemTransferTx } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; import { generateDefaultOpenPositionWithTokenExtensionsParams } from "../utils/test-builders"; import type { OpenPositionWithTokenExtensionsParams } from "../../src/instructions"; import { useMaxCU } from "../utils/v2/init-utils-v2"; describe("open_position_with_token_extensions", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const tickLowerIndex = 0; const tickUpperIndex = 11392; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); function checkMetadata( tokenMetadata: TokenMetadata, positionMint: PublicKey, poolAddress: PublicKey, positionAddress: PublicKey, ) { const WP_2022_METADATA_NAME_PREFIX = "OWP"; const WP_2022_METADATA_SYMBOL = "OWP"; const WP_2022_METADATA_URI_BASE = "https://position-nft.orca.so/meta"; const mintAddress = positionMint.toBase58(); const name = WP_2022_METADATA_NAME_PREFIX + " " + mintAddress.slice(0, 4) + "..." + mintAddress.slice(-4); const uri = WP_2022_METADATA_URI_BASE + "/" + poolAddress.toBase58() + "/" + positionAddress.toBase58(); assert.ok(tokenMetadata.mint.equals(positionMint)); assert.ok(tokenMetadata.name === name); assert.ok(tokenMetadata.symbol === WP_2022_METADATA_SYMBOL); assert.ok(tokenMetadata.uri === uri); assert.ok(!!tokenMetadata.updateAuthority); assert.ok(tokenMetadata.updateAuthority.equals(WHIRLPOOL_NFT_UPDATE_AUTH)); assert.ok(tokenMetadata.additionalMetadata.length === 0); // no additional metadata } async function checkMintState( positionMint: PublicKey, withTokenMetadataExtension: boolean, poolAddress: PublicKey, ) { const positionPda = PDAUtil.getPosition( ctx.program.programId, positionMint, ); const mint = await fetcher.getMintInfo(positionMint, IGNORE_CACHE); assert.ok(mint !== null); assert.ok(mint.tokenProgram.equals(TOKEN_2022_PROGRAM_ID)); // freeze authority: reserved for future improvements assert.ok(mint.freezeAuthority !== null); assert.ok(mint.freezeAuthority.equals(positionPda.publicKey)); // mint authority: should be removed assert.ok(mint.mintAuthority === null); assert.ok(mint.decimals === 0); // NFT assert.ok(mint.supply === 1n); // NFT // rent should be necessary and sufficient const mintAccount = await ctx.connection.getAccountInfo(positionMint); assert.ok(mintAccount !== null); const dataLength = mintAccount.data.length; const rentRequired = await ctx.connection.getMinimumBalanceForRentExemption(dataLength); assert.ok(mintAccount.lamports === rentRequired); // check initialized extensions const initializedExtensions = getExtensionTypes(mint.tlvData); assert.ok(initializedExtensions.length >= 1); // check MintCloseAuthority extension // - closeAuthority = position (PDA) assert.ok(initializedExtensions.includes(ExtensionType.MintCloseAuthority)); const mintCloseAuthority = getMintCloseAuthority(mint); assert.ok(mintCloseAuthority !== null); assert.ok(mintCloseAuthority.closeAuthority.equals(positionPda.publicKey)); if (!withTokenMetadataExtension) { // no more extension assert.ok(initializedExtensions.length === 1); } else { // additional 2 extensions assert.ok(initializedExtensions.includes(ExtensionType.MetadataPointer)); assert.ok(initializedExtensions.includes(ExtensionType.TokenMetadata)); assert.ok(initializedExtensions.length === 3); // check MetadataPointer extension // - metadataAddress = mint itself // - authority = null const metadataPointer = getMetadataPointerState(mint); assert.ok(metadataPointer !== null); assert.ok(!!metadataPointer.metadataAddress); assert.ok(metadataPointer.metadataAddress.equals(positionMint)); assert.ok(!metadataPointer.authority); // check TokenMetadata extension const tokenMetadata = (() => { const data = getExtensionData( ExtensionType.TokenMetadata, mint.tlvData, ); if (data === null) return null; return unpackTokenMetadata(data); })(); assert.ok(tokenMetadata !== null); checkMetadata( tokenMetadata, positionMint, poolAddress, positionPda.publicKey, ); } } async function checkTokenAccountState( positionTokenAccount: PublicKey, positionMint: PublicKey, owner: PublicKey, ) { const tokenAccount = await fetcher.getTokenInfo( positionTokenAccount, IGNORE_CACHE, ); assert.ok(tokenAccount !== null); assert.ok(tokenAccount.tokenProgram.equals(TOKEN_2022_PROGRAM_ID)); assert.ok(tokenAccount.isInitialized); assert.ok(!tokenAccount.isFrozen); assert.ok(tokenAccount.mint.equals(positionMint)); assert.ok(tokenAccount.owner.equals(owner)); assert.ok(tokenAccount.amount === 1n); assert.ok(tokenAccount.delegate === null); // ATA requires ImmutableOwner extension const initializedExtensions = getExtensionTypes(tokenAccount.tlvData); assert.ok(initializedExtensions.length === 1); assert.ok(initializedExtensions.includes(ExtensionType.ImmutableOwner)); } async function checkInitialPositionState( params: OpenPositionWithTokenExtensionsParams, ) { const position = (await fetcher.getPosition( params.positionPda.publicKey, )) as PositionData; assert.strictEqual(position.tickLowerIndex, params.tickLowerIndex); assert.strictEqual(position.tickUpperIndex, params.tickUpperIndex); assert.ok(position.whirlpool.equals(params.whirlpool)); assert.ok(position.positionMint.equals(params.positionMint)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); } it("successfully opens position with metadata and verify position address contents", async () => { const withTokenMetadataExtension = true; // open position const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, withTokenMetadataExtension, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .prependInstruction(useMaxCU()) .buildAndExecute(); // check Mint state (with metadata) await checkMintState( params.positionMint, withTokenMetadataExtension, whirlpoolPda.publicKey, ); // check TokenAccount state await checkTokenAccountState( params.positionTokenAccount, params.positionMint, params.owner, ); // check Position state await checkInitialPositionState(params); }); it("successfully opens position without metadata and verify position address contents", async () => { const withTokenMetadataExtension = false; // open position const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, withTokenMetadataExtension, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); // check Mint state (with metadata) await checkMintState( params.positionMint, withTokenMetadataExtension, whirlpoolPda.publicKey, ); // check TokenAccount state await checkTokenAccountState( params.positionTokenAccount, params.positionMint, params.owner, ); // check Position state await checkInitialPositionState(params); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, // owner funderKeypair.publicKey, // funder ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .addSigner(funderKeypair) .buildAndExecute(); await checkInitialPositionState(params); }); it("succeeds when owner is different than account paying for transaction fee", async () => { const ownerKeypair = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ownerKeypair.publicKey, // owner ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await checkInitialPositionState(params); const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(tokenAccount !== null); assert.ok(tokenAccount.owner.equals(ownerKeypair.publicKey)); }); it("should be failed: mint one more position token", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await checkInitialPositionState(params); const builder = new TransactionBuilder(ctx.connection, ctx.wallet); builder.addInstruction({ instructions: [ createMintToInstruction( params.positionMint, params.positionTokenAccount, provider.wallet.publicKey, 1n, undefined, TOKEN_2022_PROGRAM_ID, ), ], cleanupInstructions: [], signers: [], }); await assert.rejects( builder.buildAndExecute(), /0x5/, // the total supply of this token is fixed ); }); describe("should be failed: invalid ticks", () => { async function assertTicksFail(lowerTick: number, upperTick: number) { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, lowerTick, upperTick, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(), /0x177a/, // InvalidTickIndex ); } it("fail when user pass in an out of bound tick index for upper-index", async () => { await assertTicksFail(0, MAX_TICK_INDEX + 1); }); it("fail when user pass in a lower tick index that is higher than the upper-index", async () => { await assertTicksFail(-22534, -22534 - 1); }); it("fail when user pass in a lower tick index that equals the upper-index", async () => { await assertTicksFail(22365, 22365); }); it("fail when user pass in an out of bound tick index for lower-index", async () => { await assertTicksFail(MIN_TICK_INDEX - 1, 0); }); it("fail when user pass in a non-initializable tick index for upper-index", async () => { await assertTicksFail(0, 1); }); it("fail when user pass in a non-initializable tick index for lower-index", async () => { await assertTicksFail(1, 2); }); }); describe("should be failed: invalid account constraints", () => { let defaultParams: OpenPositionWithTokenExtensionsParams; let defaultMint: Keypair; beforeAll(async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, // owner ); defaultParams = params; defaultMint = mint; }); it("no signature of funder", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, // owner funderKeypair.publicKey, // funder ); const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, params, ).instructions[0]; // drop isSigner flag const keysWithoutSign = ix.keys.map((key) => { if (key.pubkey.equals(funderKeypair.publicKey)) { return { pubkey: key.pubkey, isSigner: false, isWritable: key.isWritable, }; } return key; }); const ixWithoutSign = { ...ix, keys: keysWithoutSign, }; await assert.rejects( toTx(ctx, { instructions: [ixWithoutSign], cleanupInstructions: [], signers: [], }) .addSigner(mint) // no signature of funder .buildAndExecute(), /0xbc2/, // AccountNotSigner ); }); it("invalid position address (invalid PDA)", async () => { await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { ...defaultParams, positionPda: PDAUtil.getPosition( ctx.program.programId, Keypair.generate().publicKey, ), }), ) .addSigner(defaultMint) .buildAndExecute(), /0x7d6/, // ConstraintSeeds ); }); it("no signature of position mint", async () => { const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, defaultParams, ).instructions[0]; // drop isSigner flag const keysWithoutSign = ix.keys.map((key) => { if (key.pubkey.equals(defaultParams.positionMint)) { return { pubkey: key.pubkey, isSigner: false, isWritable: key.isWritable, }; } return key; }); const ixWithoutSign = { ...ix, keys: keysWithoutSign, }; await assert.rejects( toTx(ctx, { instructions: [ixWithoutSign], cleanupInstructions: [], signers: [], }) // no signature of position mint .buildAndExecute(), /0xbc2/, // AccountNotSigner ); }); it("position mint already initialized", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); await createMint( ctx.connection, funderKeypair, ctx.wallet.publicKey, null, 6, mint, { commitment: "confirmed" }, TOKEN_2022_PROGRAM_ID, ); const created = await fetcher.getMintInfo( params.positionMint, IGNORE_CACHE, ); assert.ok(created !== null); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(), /already in use/, ); }); it("invalid position token account (ATA for different mint)", async () => { const anotherMint = Keypair.generate(); const ataForAnotherMint = getAssociatedTokenAddressSync( anotherMint.publicKey, defaultParams.owner, true, TOKEN_2022_PROGRAM_ID, ); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { ...defaultParams, positionTokenAccount: ataForAnotherMint, }), ) .addSigner(defaultMint) .buildAndExecute(), /An account required by the instruction is missing/, // missing valid ATA address ); }); it("invalid position token account (ATA with TokenProgram (not Token-2022 program))", async () => { const ataWithTokenProgram = getAssociatedTokenAddressSync( defaultParams.positionMint, defaultParams.owner, true, TOKEN_PROGRAM_ID, ); assert.ok( !defaultParams.positionTokenAccount.equals(ataWithTokenProgram), ); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { ...defaultParams, positionTokenAccount: ataWithTokenProgram, }), ) .addSigner(defaultMint) .buildAndExecute(), /An account required by the instruction is missing/, // missing valid ATA address ); }); it("invalid whirlpool address", async () => { // uninitialized address await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { ...defaultParams, whirlpool: Keypair.generate().publicKey, }), ) .addSigner(defaultMint) .buildAndExecute(), /0xbc4/, // AccountNotInitialized ); // not Whirlpool account await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, { ...defaultParams, whirlpool: poolInitInfo.whirlpoolsConfig, }), ) .addSigner(defaultMint) .buildAndExecute(), /0xbba/, // AccountDiscriminatorMismatch ); }); it("invalid token 2022 program", async () => { const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, defaultParams, ).instructions[0]; const ixWithWrongAccount = { ...ix, keys: ix.keys.map((key) => { if (key.pubkey.equals(TOKEN_2022_PROGRAM_ID)) { return { ...key, pubkey: TOKEN_PROGRAM_ID }; } return key; }), }; await assert.rejects( toTx(ctx, { instructions: [ixWithWrongAccount], cleanupInstructions: [], signers: [], }) .addSigner(defaultMint) .buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("invalid system program", async () => { const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, defaultParams, ).instructions[0]; const ixWithWrongAccount = { ...ix, keys: ix.keys.map((key) => { if (key.pubkey.equals(SystemProgram.programId)) { return { ...key, pubkey: TOKEN_PROGRAM_ID }; } return key; }), }; await assert.rejects( toTx(ctx, { instructions: [ixWithWrongAccount], cleanupInstructions: [], signers: [], }) .addSigner(defaultMint) .buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("invalid associated token program", async () => { const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, defaultParams, ).instructions[0]; const ixWithWrongAccount = { ...ix, keys: ix.keys.map((key) => { if (key.pubkey.equals(ASSOCIATED_TOKEN_PROGRAM_ID)) { return { ...key, pubkey: TOKEN_PROGRAM_ID }; } return key; }), }; await assert.rejects( toTx(ctx, { instructions: [ixWithWrongAccount], cleanupInstructions: [], signers: [], }) .addSigner(defaultMint) .buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("invalid metadata update auth", async () => { const ix = WhirlpoolIx.openPositionWithTokenExtensionsIx( ctx.program, defaultParams, ).instructions[0]; const ixWithWrongAccount = { ...ix, keys: ix.keys.map((key) => { if (key.pubkey.equals(WHIRLPOOL_NFT_UPDATE_AUTH)) { return { ...key, pubkey: Keypair.generate().publicKey }; } return key; }), }; await assert.rejects( toTx(ctx, { instructions: [ixWithWrongAccount], cleanupInstructions: [], signers: [], }) .addSigner(defaultMint) .buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_fee_rate.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("set_fee_rate", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully sets_fee_rate", async () => { const { poolInitInfo, configInitInfo, configKeypairs, feeTierParams } = await initTestPool(ctx, TickSpacing.Standard); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newFeeRate = 50; let whirlpool = (await fetcher.getPool( whirlpoolKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate); const setFeeRateTx = toTx( ctx, WhirlpoolIx.setFeeRateIx(program, { whirlpool: whirlpoolKey, whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, feeRate: newFeeRate, }), ).addSigner(feeAuthorityKeypair); await setFeeRateTx.buildAndExecute(); whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal(whirlpool.feeRate, newFeeRate); }); it("successfully sets_fee_rate max", async () => { const { poolInitInfo, configInitInfo, configKeypairs, feeTierParams } = await initTestPool(ctx, TickSpacing.Standard); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newFeeRate = 30_000; let whirlpool = (await fetcher.getPool( whirlpoolKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate); const setFeeRateTx = toTx( ctx, WhirlpoolIx.setFeeRateIx(program, { whirlpool: whirlpoolKey, whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, feeRate: newFeeRate, }), ).addSigner(feeAuthorityKeypair); await setFeeRateTx.buildAndExecute(); whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal(whirlpool.feeRate, newFeeRate); }); it("fails when fee rate exceeds max", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newFeeRate = 30_000 + 1; await assert.rejects( toTx( ctx, WhirlpoolIx.setFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, feeRate: newFeeRate, }), ) .addSigner(configKeypairs.feeAuthorityKeypair) .buildAndExecute(), /0x178c/, // FeeRateMaxExceeded ); }); it("fails when fee authority is not signer", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newFeeRate = 1000; await assert.rejects( toTx( ctx, WhirlpoolIx.setFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, feeRate: newFeeRate, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when whirlpool and whirlpools config don't match", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const { configInitInfo: otherConfigInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, otherConfigInitInfo), ).buildAndExecute(); const newFeeRate = 1000; await assert.rejects( ctx.program.rpc.setFeeRate(newFeeRate, { accounts: { whirlpoolsConfig: otherConfigInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, }, signers: [configKeypairs.feeAuthorityKeypair], }), // message have been changed // https://github.com/coral-xyz/anchor/pull/2101/files#diff-e564d6832afe5358ef129e96970ba1e5180b5e74aba761831e1923c06d7b839fR412 /A has[_ ]one constraint was violated/, // ConstraintHasOne ); }); it("fails when fee authority is invalid", async () => { const { poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const fakeAuthorityKeypair = anchor.web3.Keypair.generate(); const newFeeRate = 1000; await assert.rejects( ctx.program.rpc.setFeeRate(newFeeRate, { accounts: { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolKey, feeAuthority: fakeAuthorityKeypair.publicKey, }, signers: [fakeAuthorityKeypair], }), /An address constraint was violated/, // ConstraintAddress ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/get_pool_prices.test.ts
import * as anchor from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import * as assert from "assert"; import BN from "bn.js"; import Decimal from "decimal.js"; import type { GetPricesConfig, GetPricesThresholdConfig } from "../../src"; import { PriceModule, PriceModuleUtils, WhirlpoolContext } from "../../src"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import type { FundedPositionParams } from "../utils/init-utils"; import { buildTestAquariums, getDefaultAquarium, initTestPoolWithLiquidity, } from "../utils/init-utils"; // TODO: Move these tests to use mock data instead of relying on solana localnet. It's very slow. describe("get_pool_prices", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const context = WhirlpoolContext.fromWorkspace(provider, program); async function fetchMaps( context: WhirlpoolContext, mints: PublicKey[], config: GetPricesConfig, ) { const poolMap = await PriceModuleUtils.fetchPoolDataFromMints( context.fetcher, mints, config, ); const tickArrayMap = await PriceModuleUtils.fetchTickArraysForPools( context.fetcher, poolMap, config, ); const decimalsMap = await PriceModuleUtils.fetchDecimalsForMints( context.fetcher, mints, ); return { poolMap, tickArrayMap, decimalsMap }; } async function fetchAndCalculate( context: WhirlpoolContext, mints: PublicKey[], config: GetPricesConfig, thresholdConfig: GetPricesThresholdConfig, ) { const { poolMap, tickArrayMap, decimalsMap } = await fetchMaps( context, mints, config, ); const priceMap = PriceModule.calculateTokenPrices( mints, { poolMap, tickArrayMap, decimalsMap, }, config, thresholdConfig, ); return { poolMap, tickArrayMap, decimalsMap, priceMap, }; } function getDefaultThresholdConfig(): GetPricesThresholdConfig { return { amountOut: new BN(1_000_000), priceImpactThreshold: 1.05, }; } it("successfully calculates the price for one token with a single pool", async () => { const { poolInitInfo, configInitInfo } = await initTestPoolWithLiquidity(context); const config: GetPricesConfig = { quoteTokens: [poolInitInfo.tokenMintB], tickSpacings: [TickSpacing.Standard], programId: program.programId, whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, }; const thresholdConfig = getDefaultThresholdConfig(); const mints = [poolInitInfo.tokenMintA, poolInitInfo.tokenMintB]; const { poolMap, tickArrayMap, priceMap } = await fetchAndCalculate( context, mints, config, thresholdConfig, ); assert.equal(Object.keys(poolMap).length, 1); assert.equal(Object.keys(tickArrayMap).length, 1); // mintA to mintB direction assert.equal(Object.keys(priceMap).length, 2); }); it("successfully calculates the price for two tokens against a third quote token", async () => { const aqConfig = getDefaultAquarium(); // Add a third token and account and a second pool aqConfig.initMintParams.push({}); aqConfig.initTokenAccParams.push({ mintIndex: 2 }); aqConfig.initPoolParams.push({ mintIndices: [1, 2], tickSpacing: TickSpacing.Standard, }); // Add tick arrays and positions const aToB = false; aqConfig.initTickArrayRangeParams.push({ poolIndex: 0, startTickIndex: 22528, arrayCount: 3, aToB, }); aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 3, aToB, }); const fundParams: FundedPositionParams[] = [ { liquidityAmount: new anchor.BN(10_000_000), tickLowerIndex: 29440, tickUpperIndex: 33536, }, ]; aqConfig.initPositionParams.push({ poolIndex: 0, fundParams }); aqConfig.initPositionParams.push({ poolIndex: 1, fundParams }); const aquarium = (await buildTestAquariums(context, [aqConfig]))[0]; const { mintKeys, configParams } = aquarium; const config: GetPricesConfig = { quoteTokens: [mintKeys[1]], tickSpacings: [TickSpacing.Standard], programId: program.programId, whirlpoolsConfig: configParams.configInitInfo.whirlpoolsConfigKeypair.publicKey, }; const thresholdConfig = getDefaultThresholdConfig(); const mints = [mintKeys[0], mintKeys[1], mintKeys[2]]; const { poolMap, tickArrayMap, priceMap } = await fetchAndCalculate( context, mints, config, thresholdConfig, ); // mints are sorted (mintKeys[0] < mintKeys[1] < mintKeys[2]) const fetchedTickArrayForPool0 = 1; // A to B direction (mintKeys[0] to mintKeys[1]) const fetchedTickArrayForPool1 = 3; // B to A direction (mintKeys[2] to mintKeys[1]) assert.equal(Object.keys(poolMap).length, 2); assert.equal( Object.keys(tickArrayMap).length, fetchedTickArrayForPool0 + fetchedTickArrayForPool1, ); assert.equal(Object.keys(priceMap).length, 3); }); it("successfully calculates the price for one token with multiple pools against a quote token", async () => { const aqConfig = getDefaultAquarium(); // Add a third token and account and a second pool aqConfig.initFeeTierParams.push({ tickSpacing: TickSpacing.SixtyFour, }); aqConfig.initPoolParams.push({ mintIndices: [0, 1], tickSpacing: TickSpacing.SixtyFour, feeTierIndex: 1, initSqrtPrice: MathUtil.toX64(new Decimal(5.2)), }); // Add tick arrays and positions const aToB = false; aqConfig.initTickArrayRangeParams.push({ poolIndex: 0, startTickIndex: 22528, arrayCount: 3, aToB, }); aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 3, aToB, }); const fundParams0: FundedPositionParams[] = [ { liquidityAmount: new anchor.BN(10_000_000), tickLowerIndex: 29440, tickUpperIndex: 33536, }, ]; const fundParams1: FundedPositionParams[] = [ { liquidityAmount: new anchor.BN(50_000_000), tickLowerIndex: 29440, tickUpperIndex: 33536, }, ]; aqConfig.initPositionParams.push({ poolIndex: 0, fundParams: fundParams0 }); aqConfig.initPositionParams.push({ poolIndex: 1, fundParams: fundParams1 }); const aquarium = (await buildTestAquariums(context, [aqConfig]))[0]; const { mintKeys, configParams } = aquarium; const config: GetPricesConfig = { quoteTokens: [mintKeys[1]], tickSpacings: [TickSpacing.Standard, TickSpacing.SixtyFour], programId: program.programId, whirlpoolsConfig: configParams.configInitInfo.whirlpoolsConfigKeypair.publicKey, }; const thresholdConfig = getDefaultThresholdConfig(); const mints = [mintKeys[0], mintKeys[1]]; const { poolMap, priceMap } = await fetchAndCalculate( context, mints, config, thresholdConfig, ); assert.equal(Object.keys(poolMap).length, 2); assert.equal(Object.keys(priceMap).length, 2); }); it("successfully calculates the price for one token which requires an indirect pool to calculate price", async () => { const aqConfig = getDefaultAquarium(); // Add a third token and account and a second pool aqConfig.initMintParams.push({}); aqConfig.initTokenAccParams.push({ mintIndex: 2 }); aqConfig.initPoolParams.push({ mintIndices: [1, 2], tickSpacing: TickSpacing.Standard, }); // Add tick arrays and positions const aToB = false; aqConfig.initTickArrayRangeParams.push({ poolIndex: 0, startTickIndex: 22528, arrayCount: 3, aToB, }); aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 3, aToB, }); const fundParams: FundedPositionParams[] = [ { liquidityAmount: new anchor.BN(10_000_000_000), tickLowerIndex: 29440, tickUpperIndex: 33536, }, ]; aqConfig.initPositionParams.push({ poolIndex: 0, fundParams }); aqConfig.initPositionParams.push({ poolIndex: 1, fundParams }); const aquarium = (await buildTestAquariums(context, [aqConfig]))[0]; const { mintKeys, configParams } = aquarium; const config: GetPricesConfig = { quoteTokens: [mintKeys[2], mintKeys[1]], tickSpacings: [TickSpacing.Standard], programId: program.programId, whirlpoolsConfig: configParams.configInitInfo.whirlpoolsConfigKeypair.publicKey, }; const thresholdConfig = getDefaultThresholdConfig(); const mints = [mintKeys[0], mintKeys[1], mintKeys[2]]; const { poolMap, tickArrayMap, priceMap } = await fetchAndCalculate( context, mints, config, thresholdConfig, ); // mints are sorted (mintKeys[0] < mintKeys[1] < mintKeys[2]) const fetchedTickArrayForPool0 = 1; // A to B direction (mintKeys[0] to mintKeys[1]) const fetchedTickArrayForPool1 = 1; // A to B direction (mintKeys[1] to mintKeys[2]) assert.equal(Object.keys(poolMap).length, 2); assert.equal( Object.keys(tickArrayMap).length, fetchedTickArrayForPool0 + fetchedTickArrayForPool1, ); assert.equal(Object.keys(priceMap).length, 3); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/collect_reward.test.ts
import * as anchor from "@coral-xyz/anchor"; import { BN } from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import * as assert from "assert"; import Decimal from "decimal.js"; import { buildWhirlpoolClient, collectRewardsQuote, NUM_REWARDS, toTx, WhirlpoolContext, WhirlpoolIx, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { approveToken, createAndMintToTokenAccount, createMint, createTokenAccount, getTokenBalance, sleep, TickSpacing, transferToken, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initTestPool } from "../utils/init-utils"; import { TokenExtensionUtil } from "../../src/utils/public/token-extension-util"; describe("collect_reward", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const client = buildWhirlpoolClient(ctx); it("successfully collect rewards", async () => { const vaultStartBalance = 1_000_000; const lowerTickIndex = -1280, upperTickIndex = 1280, tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: tickSpacing, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: lowerTickIndex, tickUpperIndex: upperTickIndex, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)), vaultAmount: new BN(vaultStartBalance), }, { emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)), vaultAmount: new BN(vaultStartBalance), }, { emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)), vaultAmount: new BN(vaultStartBalance), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[0].publicKey, tickArrayLower: positions[0].tickArrayLower, tickArrayUpper: positions[0].tickArrayUpper, }), ).buildAndExecute(); // Generate collect reward expectation const pool = await client.getPool(whirlpoolPda.publicKey, IGNORE_CACHE); const positionPreCollect = await client.getPosition( positions[0].publicKey, IGNORE_CACHE, ); // Lock the collectRewards quote to the last time we called updateFeesAndRewards const expectation = collectRewardsQuote({ whirlpool: pool.getData(), position: positionPreCollect.getData(), tickLower: positionPreCollect.getLowerTickData(), tickUpper: positionPreCollect.getUpperTickData(), timeStampInSeconds: pool.getData().rewardLastUpdatedTimestamp, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( fetcher, pool.getData(), IGNORE_CACHE, ), }); // Check that the expectation is not zero for (let i = 0; i < NUM_REWARDS; i++) { assert.ok(!expectation.rewardOwed[i]!.isZero()); } // Perform collect rewards tx for (let i = 0; i < NUM_REWARDS; i++) { const rewardOwnerAccount = await createTokenAccount( provider, rewards[i].rewardMint, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount: rewardOwnerAccount, rewardVault: rewards[i].rewardVaultKeypair.publicKey, rewardIndex: i, }), ).buildAndExecute(); const collectedBalance = parseInt( await getTokenBalance(provider, rewardOwnerAccount), ); assert.equal(collectedBalance, expectation.rewardOwed[i]?.toNumber()); const vaultBalance = parseInt( await getTokenBalance( provider, rewards[i].rewardVaultKeypair.publicKey, ), ); assert.equal(vaultStartBalance - collectedBalance, vaultBalance); const position = await fetcher.getPosition( positions[0].publicKey, IGNORE_CACHE, ); assert.equal(position?.rewardInfos[i].amountOwed, 0); assert.ok(position?.rewardInfos[i].growthInsideCheckpoint.gte(ZERO_BN)); } }); it("successfully collect reward with a position authority delegate", async () => { const vaultStartBalance = 1_000_000; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(vaultStartBalance), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[0].publicKey, tickArrayLower: positions[0].tickArrayLower, tickArrayUpper: positions[0].tickArrayUpper, }), ).buildAndExecute(); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ) .addSigner(delegate) .buildAndExecute(); }); it("successfully collect reward with transferred position token", async () => { const vaultStartBalance = 1_000_000; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(vaultStartBalance), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const delegate = anchor.web3.Keypair.generate(); const delegatePositionAccount = await createTokenAccount( provider, positions[0].mintKeypair.publicKey, delegate.publicKey, ); await transferToken( provider, positions[0].tokenAccount, delegatePositionAccount, 1, ); await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[0].publicKey, tickArrayLower: positions[0].tickArrayLower, tickArrayUpper: positions[0].tickArrayUpper, }), ).buildAndExecute(); await toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: delegatePositionAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ) .addSigner(delegate) .buildAndExecute(); }); it("successfully collect reward with owner even when there is a delegate", async () => { const vaultStartBalance = 1_000_000; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(vaultStartBalance), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[0].publicKey, tickArrayLower: positions[0].tickArrayLower, tickArrayUpper: positions[0].tickArrayUpper, }), ).buildAndExecute(); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(); }); it("fails when reward index references an uninitialized reward", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, } = fixture.getInfos(); // accrue rewards await sleep(1200); const fakeRewardMint = await createMint(provider); const rewardOwnerAccount = await createTokenAccount( provider, fakeRewardMint, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: anchor.web3.PublicKey.default, rewardIndex: 0, }), ).buildAndExecute(), /0xbbf/, // AccountNotInitialized ); }); it("fails when position does not match whirlpool", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { positions, rewards } = fixture.getInfos(); // accrue rewards await sleep(1200); const { poolInitInfo: { whirlpoolPda }, } = await initTestPool(ctx, TickSpacing.Standard); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /0x7d1/, // ConstraintHasOne ); }); it("fails when position token account does not have exactly one token", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const otherPositionAcount = await createTokenAccount( provider, positions[0].mintKeypair.publicKey, provider.wallet.publicKey, ); await transferToken( provider, positions[0].tokenAccount, otherPositionAcount, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when position token account mint does not match position mint", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenMintA }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const fakePositionTokenAccount = await createAndMintToTokenAccount( provider, tokenMintA, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: fakePositionTokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when position authority is not approved delegate for position token account", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const delegate = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ) .addSigner(delegate) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails when position authority is not authorized for exactly one token", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 2, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ) .addSigner(delegate) .buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); it("fails when position authority was not a signer", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when reward vault does not match whirlpool reward vault", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, rewards[0].rewardMint, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewardOwnerAccount, rewardIndex: 0, }), ).buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("fails when reward owner account mint does not match whirlpool reward mint", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenMintA }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when reward index is out of bounds", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: new anchor.BN(1_000_000), }, ], rewards: [ { emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)), vaultAmount: new BN(1_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenMintA }, positions, rewards, } = fixture.getInfos(); // accrue rewards await sleep(1200); const rewardOwnerAccount = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectRewardIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, rewardOwnerAccount, rewardVault: rewards[0].rewardVaultKeypair.publicKey, rewardIndex: 4, }), ).buildAndExecute(), /Program failed to complete/, // index out of bounds ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_fee_authority.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolsConfigData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { defaultConfirmOptions } from "../utils/const"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("set_fee_authority", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_fee_authority", async () => { const { configInitInfo, configKeypairs: { feeAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const newAuthorityKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.setFeeAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, feeAuthority: feeAuthorityKeypair.publicKey, newFeeAuthority: newAuthorityKeypair.publicKey, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(); const config = (await fetcher.getConfig( configInitInfo.whirlpoolsConfigKeypair.publicKey, )) as WhirlpoolsConfigData; assert.ok(config.feeAuthority.equals(newAuthorityKeypair.publicKey)); }); it("fails if current fee_authority is not a signer", async () => { const { configInitInfo, configKeypairs: { feeAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.setFeeAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, feeAuthority: feeAuthorityKeypair.publicKey, newFeeAuthority: provider.wallet.publicKey, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails if invalid fee_authority provided", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.setFeeAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, feeAuthority: provider.wallet.publicKey, newFeeAuthority: provider.wallet.publicKey, }), ).buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/close_bundled_position.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { Percentage } from "@orca-so/common-sdk"; import * as assert from "assert"; import BN from "bn.js"; import type { InitPoolParams, PositionBundleData } from "../../src"; import { POSITION_BUNDLE_SIZE, WhirlpoolContext, WhirlpoolIx, buildWhirlpoolClient, increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage, toTx, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { ONE_SOL, TickSpacing, approveToken, createAssociatedTokenAccount, systemTransferTx, transferToken, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool, initializePositionBundle, openBundledPosition, openPosition, } from "../utils/init-utils"; import { generateDefaultOpenPositionWithTokenExtensionsParams, mintTokensToTestAccount, } from "../utils/test-builders"; import { TokenExtensionUtil } from "../../src/utils/public/token-extension-util"; describe("close_bundled_position", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const client = buildWhirlpoolClient(ctx); const fetcher = ctx.fetcher; const tickLowerIndex = 0; const tickUpperIndex = 128; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); const pool = await client.getPool(whirlpoolPda.publicKey); await (await pool.initTickArrayForTicks([0]))?.buildAndExecute(); }); function checkBitmapIsOpened( account: PositionBundleData, bundleIndex: number, ): boolean { if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE) throw Error("bundleIndex is out of bounds"); const bitmapIndex = Math.floor(bundleIndex / 8); const bitmapOffset = bundleIndex % 8; return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) > 0; } function checkBitmapIsClosed( account: PositionBundleData, bundleIndex: number, ): boolean { if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE) throw Error("bundleIndex is out of bounds"); const bitmapIndex = Math.floor(bundleIndex / 8); const bitmapOffset = bundleIndex % 8; return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) === 0; } function checkBitmap( account: PositionBundleData, openedBundleIndexes: number[], ) { for (let i = 0; i < POSITION_BUNDLE_SIZE; i++) { if (openedBundleIndexes.includes(i)) { assert.ok(checkBitmapIsOpened(account, i)); } else { assert.ok(checkBitmapIsClosed(account, i)); } } } it("successfully closes an opened bundled position", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const preAccount = await fetcher.getPosition( bundledPositionPda.publicKey, IGNORE_CACHE, ); const prePositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmap(prePositionBundle!, [bundleIndex]); assert.ok(preAccount !== null); const receiverKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: receiverKeypair.publicKey, }), ).buildAndExecute(); const postAccount = await fetcher.getPosition( bundledPositionPda.publicKey, IGNORE_CACHE, ); const postPositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmap(postPositionBundle!, []); assert.ok(postAccount === null); const receiverAccount = await provider.connection.getAccountInfo( receiverKeypair.publicKey, ); const lamports = receiverAccount?.lamports; assert.ok(lamports != undefined && lamports > 0); }); it("should be failed: invalid bundle index", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const tx = await toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex: 1, // invalid positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("should be failed: user closes bundled position already closed", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); // close... await tx.buildAndExecute(); // re-close... await assert.rejects( tx.buildAndExecute(), /0xbc4/, // AccountNotInitialized ); }); it("should be failed: bundled position is not empty", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; // deposit const pool = await client.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, ); const quote = increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage({ tokenMintA: poolInitInfo.tokenMintA, tokenMintB: poolInitInfo.tokenMintB, sqrtPrice: pool.getData().sqrtPrice, slippageTolerance: Percentage.fromFraction(0, 100), tickLowerIndex, tickUpperIndex, tickCurrentIndex: pool.getData().tickCurrentIndex, inputTokenMint: poolInitInfo.tokenMintB, inputTokenAmount: new BN(1_000_000), tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( fetcher, pool.getData(), IGNORE_CACHE, ), }); await mintTokensToTestAccount( provider, poolInitInfo.tokenMintA, quote.tokenMaxA.toNumber(), poolInitInfo.tokenMintB, quote.tokenMaxB.toNumber(), ctx.wallet.publicKey, ); const position = await client.getPosition( bundledPositionPda.publicKey, IGNORE_CACHE, ); await (await position.increaseLiquidity(quote)).buildAndExecute(); assert.ok((await position.refreshData()).liquidity.gtn(0)); // try to close... const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x1775/, // ClosePositionNotEmpty ); }); describe("invalid input account", () => { it("should be failed: invalid bundled position", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, tickLowerIndex, tickUpperIndex, ); const positionInitInfo1 = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, 1, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo1.params.bundledPositionPda.publicKey, // invalid bundleIndex: 0, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("should be failed: invalid position bundle", async () => { const positionBundleInfo0 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const positionBundleInfo1 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo0.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo1.positionBundlePda.publicKey, // invalid positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo0.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("should be failed: invalid ATA (amount is zero)", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const ata = await createAssociatedTokenAccount( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, funderKeypair.publicKey, ctx.wallet.publicKey, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: ata, // invalid receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw (amount == 1) ); }); it("should be failed: invalid ATA (invalid mint)", async () => { const positionBundleInfo0 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const positionBundleInfo1 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo0.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo0.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo1.positionBundleTokenAccount, // invalid receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw (mint == position_bundle.position_bundle_mint) ); }); it("should be failed: invalid position bundle authority", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: funderKeypair.publicKey, // invalid positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); tx.addSigner(funderKeypair); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); }); describe("authority delegation", () => { it("successfully closes bundled position with delegated authority", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: funderKeypair.publicKey, // should be delegated positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); tx.addSigner(funderKeypair); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); // delegate 1 token from ctx.wallet to funder await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, funderKeypair.publicKey, 1, ); await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsClosed(positionBundle!, 0); }); it("successfully closes bundled position even if delegation exists", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); // delegate 1 token from ctx.wallet to funder await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, funderKeypair.publicKey, 1, ); // owner can close even if delegation exists await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsClosed(positionBundle!, 0); }); it("should be faild: delegated amount is zero", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: funderKeypair.publicKey, // should be delegated positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); tx.addSigner(funderKeypair); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); // delegate ZERO token from ctx.wallet to funder await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, funderKeypair.publicKey, 0, ); await assert.rejects( tx.buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); }); describe("transfer position bundle", () => { it("successfully closes bundled position after position bundle token transfer", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const funderATA = await createAssociatedTokenAccount( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, funderKeypair.publicKey, ctx.wallet.publicKey, ); await transferToken( provider, positionBundleInfo.positionBundleTokenAccount, funderATA, 1, ); const tokenInfo = await fetcher.getTokenInfo(funderATA, IGNORE_CACHE); assert.ok(tokenInfo?.amount === 1n); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: positionInitInfo.params.bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: funderKeypair.publicKey, // new owner positionBundleTokenAccount: funderATA, receiver: funderKeypair.publicKey, }), ); tx.addSigner(funderKeypair); await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsClosed(positionBundle!, 0); }); }); describe("non-bundled position", () => { it("should be failed: try to close NON-bundled position (TokenProgram based)", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); // open NON-bundled position const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, ); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: params.positionPda.publicKey, // NON-bundled position bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("should be failed: try to close NON-bundled position (TokenExtensions based)", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); // open position with TokenExtensions const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, poolInitInfo.whirlpoolPda.publicKey, true, 0, poolInitInfo.tickSpacing, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); const tx = toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: params.positionPda.publicKey, // NON-bundled position bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_config.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { InitConfigParams, WhirlpoolsConfigData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { ONE_SOL, systemTransferTx } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("initialize_config", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; let initializedConfigInfo: InitConfigParams; it("successfully init a WhirlpoolsConfig account", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const configAccount = (await fetcher.getConfig( configInitInfo.whirlpoolsConfigKeypair.publicKey, )) as WhirlpoolsConfigData; assert.ok( configAccount.collectProtocolFeesAuthority.equals( configInitInfo.collectProtocolFeesAuthority, ), ); assert.ok(configAccount.feeAuthority.equals(configInitInfo.feeAuthority)); assert.ok( configAccount.rewardEmissionsSuperAuthority.equals( configInitInfo.rewardEmissionsSuperAuthority, ), ); assert.equal( configAccount.defaultProtocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); initializedConfigInfo = configInitInfo; }); it("fail on passing in already initialized whirlpool account", async () => { let infoWithDupeConfigKey = { ...generateDefaultConfigParams(ctx).configInitInfo, whirlpoolsConfigKeypair: initializedConfigInfo.whirlpoolsConfigKeypair, }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, infoWithDupeConfigKey), ).buildAndExecute(), /0x0/, ); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const funderKeypair = anchor.web3.Keypair.generate(); await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); const { configInitInfo } = generateDefaultConfigParams( ctx, funderKeypair.publicKey, ); await toTx(ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo)) .addSigner(funderKeypair) .buildAndExecute(); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/two_hop_swap.test.ts
import * as anchor from "@coral-xyz/anchor"; import { Percentage, U64_MAX } from "@orca-so/common-sdk"; import { PublicKey } from "@solana/web3.js"; import * as assert from "assert"; import BN from "bn.js"; import type { InitPoolParams } from "../../src"; import { buildWhirlpoolClient, MIN_SQRT_PRICE_BN, NO_TOKEN_EXTENSION_CONTEXT, PDAUtil, PriceMath, swapQuoteByInputToken, swapQuoteByOutputToken, swapQuoteWithParams, SwapUtils, toTx, twoHopSwapQuoteFromSwapQuotes, WhirlpoolContext, WhirlpoolIx, } from "../../src"; import type { TwoHopSwapParams } from "../../src/instructions"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { getTokenBalance, TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import type { FundedPositionParams, InitAquariumParams, } from "../utils/init-utils"; import { buildTestAquariums, getDefaultAquarium, getTokenAccsForPools, } from "../utils/init-utils"; describe("two-hop swap", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const client = buildWhirlpoolClient(ctx); let aqConfig: InitAquariumParams; beforeEach(async () => { aqConfig = getDefaultAquarium(); // Add a third token and account and a second pool aqConfig.initMintParams.push({}); aqConfig.initTokenAccParams.push({ mintIndex: 2 }); aqConfig.initPoolParams.push({ mintIndices: [1, 2], tickSpacing: TickSpacing.Standard, }); // Add tick arrays and positions const aToB = false; aqConfig.initTickArrayRangeParams.push({ poolIndex: 0, startTickIndex: 22528, arrayCount: 3, aToB, }); aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 3, aToB, }); const fundParams: FundedPositionParams[] = [ { liquidityAmount: new anchor.BN(10_000_000), tickLowerIndex: 29440, tickUpperIndex: 33536, }, ]; aqConfig.initPositionParams.push({ poolIndex: 0, fundParams }); aqConfig.initPositionParams.push({ poolIndex: 1, fundParams }); }); describe("fails [2] with two-hop swap, invalid accounts", () => { let baseIxParams: TwoHopSwapParams; beforeEach(async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); baseIxParams = { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }; }); it("fails invalid whirlpool", async () => { await rejectParams( { ...baseIxParams, whirlpoolOne: baseIxParams.whirlpoolTwo, }, /0x7d3/, // ConstraintRaw ); }); it("fails invalid token account", async () => { await rejectParams( { ...baseIxParams, tokenOwnerAccountOneA: baseIxParams.tokenOwnerAccountOneB, }, /0x7d3/, // ConstraintRaw ); }); it("fails invalid token vault", async () => { await rejectParams( { ...baseIxParams, tokenVaultOneA: baseIxParams.tokenVaultOneB, }, /0x7dc/, // ConstraintAddress ); }); it("fails invalid oracle one address", async () => { await rejectParams( { ...baseIxParams, oracleOne: PublicKey.unique(), }, /0x7d6/, // Constraint Seeds ); }); it("fails invalid oracle two address", async () => { await rejectParams( { ...baseIxParams, oracleTwo: PublicKey.unique(), }, /0x7d6/, // Constraint Seeds ); }); it("fails invalid tick array one", async () => { await rejectParams( { ...baseIxParams, // sparse-swap can accept completely uninitialized account as candidate for uninitialized tick arrays. // so now we use token account as clearly invalid account. tickArrayOne0: baseIxParams.tokenVaultOneA, }, /0xbbf/, // AccountOwnedByWrongProgram ); await rejectParams( { ...baseIxParams, tickArrayOne1: baseIxParams.tokenVaultOneA, }, /0xbbf/, // AccountOwnedByWrongProgram ); await rejectParams( { ...baseIxParams, tickArrayOne2: baseIxParams.tokenVaultOneA, }, /0xbbf/, // AccountOwnedByWrongProgram ); }); it("fails invalid tick array two", async () => { await rejectParams( { ...baseIxParams, // sparse-swap can accept completely uninitialized account as candidate for uninitialized tick arrays. // so now we use token account as clearly invalid account. tickArrayTwo0: baseIxParams.tokenVaultTwoA, }, /0xbbf/, // AccountOwnedByWrongProgram ); await rejectParams( { ...baseIxParams, tickArrayTwo1: baseIxParams.tokenVaultTwoA, }, /0xbbf/, // AccountOwnedByWrongProgram ); await rejectParams( { ...baseIxParams, tickArrayTwo2: baseIxParams.tokenVaultTwoA, }, /0xbbf/, // AccountOwnedByWrongProgram ); }); async function rejectParams( params: TwoHopSwapParams, error: assert.AssertPredicate, ) { await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, params), ).buildAndExecute(), error, ); } }); it("swaps [2] with two-hop swap, amountSpecifiedIsInput=true", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; let tokenBalances = await getTokenBalances( tokenAccounts.map((acc) => acc.account), ); const tokenVaultBalances = await getTokenBalancesForVaults(pools); const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); assert.deepEqual(await getTokenBalancesForVaults(pools), [ tokenVaultBalances[0].add(quote.estimatedAmountIn), tokenVaultBalances[1].sub(quote.estimatedAmountOut), tokenVaultBalances[2].add(quote2.estimatedAmountIn), tokenVaultBalances[3].sub(quote2.estimatedAmountOut), ]); const prevTbs = [...tokenBalances]; tokenBalances = await getTokenBalances( tokenAccounts.map((acc) => acc.account), ); assert.deepEqual(tokenBalances, [ prevTbs[0].sub(quote.estimatedAmountIn), prevTbs[1], prevTbs[2].add(quote2.estimatedAmountOut), ]); whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); }); it("swaps [2] with two-hop swap, amountSpecifiedIsInput=true, A->B->A", async () => { // Add another mint and update pool so there is no overlapping mint aqConfig.initFeeTierParams.push({ tickSpacing: TickSpacing.ThirtyTwo }); aqConfig.initPoolParams[1] = { mintIndices: [0, 1], tickSpacing: TickSpacing.ThirtyTwo, feeTierIndex: 1, }; aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 12, aToB: true, }); aqConfig.initTickArrayRangeParams.push({ poolIndex: 1, startTickIndex: 22528, arrayCount: 12, aToB: false, }); const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; let tokenBalances = await getTokenBalances( tokenAccounts.map((acc) => acc.account), ); const tokenVaultBalances = await getTokenBalancesForVaults(pools); const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [tokenA, tokenB, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, tokenA, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, tokenB, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); assert.deepEqual(await getTokenBalancesForVaults(pools), [ tokenVaultBalances[0].add(quote.estimatedAmountIn), tokenVaultBalances[1].sub(quote.estimatedAmountOut), tokenVaultBalances[2].sub(quote2.estimatedAmountOut), tokenVaultBalances[3].add(quote2.estimatedAmountIn), ]); const prevTbs = [...tokenBalances]; tokenBalances = await getTokenBalances( tokenAccounts.map((acc) => acc.account), ); assert.deepEqual(tokenBalances, [ prevTbs[0].sub(quote.estimatedAmountIn).add(quote2.estimatedAmountOut), prevTbs[1].add(quote.estimatedAmountOut).sub(quote2.estimatedAmountIn), prevTbs[2], ]); }); it("fails swaps [2] with top-hop swap, amountSpecifiedIsInput=true, slippage", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), otherAmountThreshold: new BN(613309), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x1794/, // Above Out Below Minimum ); }); it("swaps [2] with two-hop swap, amountSpecifiedIsInput=false", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const preSwapBalances = await getTokenBalances( tokenAccounts.map((acc) => acc.account), ); const tokenVaultBalances = await getTokenBalancesForVaults(pools); const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; const quote2 = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quote2.estimatedAmountIn, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); assert.deepEqual(await getTokenBalancesForVaults(pools), [ tokenVaultBalances[0].add(quote.estimatedAmountIn), tokenVaultBalances[1].sub(quote.estimatedAmountOut), tokenVaultBalances[2].add(quote2.estimatedAmountIn), tokenVaultBalances[3].sub(quote2.estimatedAmountOut), ]); assert.deepEqual( await getTokenBalances(tokenAccounts.map((acc) => acc.account)), [ preSwapBalances[0].sub(quote.estimatedAmountIn), preSwapBalances[1], preSwapBalances[2].add(quote2.estimatedAmountOut), ], ); }); it("fails swaps [2] with two-hop swap, amountSpecifiedIsInput=false slippage", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; const quote2 = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quote2.estimatedAmountIn, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), otherAmountThreshold: new BN(2), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x1795/, // Above In Above Maximum ); }); it("fails swaps [2] with two-hop swap, no overlapping mints", async () => { // Add another mint and update pool so there is no overlapping mint aqConfig.initMintParams.push({}); aqConfig.initTokenAccParams.push({ mintIndex: 3 }); aqConfig.initPoolParams[1].mintIndices = [2, 3]; const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; const quote2 = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1000), Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quote2.estimatedAmountIn, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x1799/, // Invalid intermediary mint ); }); it("swaps [2] with two-hop swap, amount_specified_is_input=true, first swap price limit", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // Set a price limit that is less than the 1% slippage threshold, // which will allow the swap to go through quote.sqrtPriceLimit = quote.estimatedEndSqrtPrice.add( whirlpoolOne .getData() .sqrtPrice.sub(quote.estimatedEndSqrtPrice) .mul(new anchor.BN("5")) .div(new anchor.BN("1000")), ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); assert.equal( whirlpoolOne.getData().sqrtPrice.eq(quote.sqrtPriceLimit), true, ); }); it("fails swaps [2] with two-hop swap, amount_specified_is_input=true, second swap price limit", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // Set a price limit that is less than the 1% slippage threshold, // which will allow the swap to go through quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add( whirlpoolTwo .getData() .sqrtPrice.sub(quote2.estimatedEndSqrtPrice) .mul(new anchor.BN("5")) .div(new anchor.BN("1000")), ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); // output amount of swapOne must be equal to input amount of swapTwo await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x17a3/, // IntermediateTokenAmountMismatch ); }); it("fails swaps [2] with two-hop swap, amount_specified_is_input=true, first swap price limit", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // Set a price limit that is less than the 1% slippage threshold, // which will allow the swap to go through quote.sqrtPriceLimit = quote.estimatedEndSqrtPrice.add( whirlpoolOne .getData() .sqrtPrice.sub(quote.estimatedEndSqrtPrice) .mul(new anchor.BN("15")) .div(new anchor.BN("1000")), ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), ); }); it("fails swaps [2] with two-hop swap, amount_specified_is_input=true, second swap price limit", async () => { const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; const quote = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1000), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quote2 = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quote.estimatedAmountOut, Percentage.fromFraction(1, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // Set a price limit that is greater than the 1% slippage threshold, // which will cause the swap to fail quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add( whirlpoolTwo .getData() .sqrtPrice.sub(quote2.estimatedEndSqrtPrice) .mul(new anchor.BN("15")) .div(new anchor.BN("1000")), ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), ); }); describe("partial fill", () => { // Partial fill on second swap in ExactOut is allowed // |--***T**-S-| --> |--***T,limit**-S-| (where *: liquidity, S: start, T: end) it("ExactOut, partial fill on second swap", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: aqConfig.initFeeTierParams, initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: 0, arrayCount: 3, aToB: true, }, { poolIndex: 1, startTickIndex: 0, arrayCount: 3, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, _outputToken] = mintKeys; const quoteParams = { amountSpecifiedIsInput: false, aToB: true, otherAmountThreshold: U64_MAX, tickArrays: await SwapUtils.getTickArrays( whirlpoolTwo.getData().tickCurrentIndex, whirlpoolTwo.getData().tickSpacing, true, ctx.program.programId, whirlpoolTwoKey, ctx.fetcher, IGNORE_CACHE, ), tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, whirlpoolData: whirlpoolOne.getData(), tokenAmount: new BN(1_000_000), }; // 906251 --> 1000000 (end tick: 1004) const quoteSecondWithoutLimit = swapQuoteWithParams( { ...quoteParams, sqrtPriceLimit: MIN_SQRT_PRICE_BN, }, Percentage.fromFraction(0, 100), ); assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex < 1008); // 762627 --> 841645 (end tick: 1008) const quoteSecondWithLimit = swapQuoteWithParams( { ...quoteParams, sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(1008), }, Percentage.fromFraction(0, 100), ); assert.ok(quoteSecondWithLimit.estimatedEndTickIndex == 1008); assert.ok( quoteSecondWithLimit.estimatedAmountOut.lt( quoteSecondWithoutLimit.estimatedAmountOut, ), ); assert.ok( quoteSecondWithLimit.estimatedAmountIn.lt( quoteSecondWithoutLimit.estimatedAmountIn, ), ); // 821218 --> 906251 const quoteFirstWithoutLimit = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quoteSecondWithoutLimit.estimatedAmountIn, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // 690975 --> 762627 const quoteFirstWithLimit = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quoteSecondWithLimit.estimatedAmountIn, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // build without limit const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirstWithoutLimit, quoteSecondWithoutLimit, ); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, amount: quoteSecondWithoutLimit.estimatedAmountOut, sqrtPriceLimitOne: new BN(0), // partial fill on second swap is NOT allowd sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1008), // partial fill is allowed // -1 to check input amount otherAmountThreshold: quoteFirstWithLimit.estimatedAmountIn.subn(1), ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x1795/, // AmountInAboveMaximum. ); assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, amount: quoteSecondWithoutLimit.estimatedAmountOut, sqrtPriceLimitOne: new BN(0), // partial fill on second swap is NOT allowd sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1008), // partial fill is allowed otherAmountThreshold: quoteFirstWithLimit.estimatedAmountIn, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); }); // Reject partial fill result // |--***T**-S-| --> |-min,T----**-S-| (where *: liquidity, S: start, T: end) it("fails ExactOut, partial fill on second swap, sqrt_price_limit_two == 0", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: aqConfig.initFeeTierParams, initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: 0, arrayCount: 3, aToB: true, }, { poolIndex: 1, startTickIndex: -450560, arrayCount: 1, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: -512, tickUpperIndex: -128, liquidityAmount: new BN(5_000_000_000_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: -439296 - 256, tickUpperIndex: -439296 - 128, liquidityAmount: new BN(1_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; const quoteSecond = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const quoteFirst = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quoteSecond.estimatedAmountIn, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirst, quoteSecond, ); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed sqrtPriceLimitTwo: new BN(0), // Partial fill is NOT allowed ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x17a9/, // PartialFillError ); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); }); // Reject partial fill on the first swap by sqrt_price_limit_one = 0 // |-min,T----**-S-| --> |--***T**-S-| (where *: liquidity, S: start, T: end) it("fails ExactOut, partial fill on first swap, sqrt_price_limit_one == 0", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: [{ tickSpacing: 128, feeRate: 0 }], // to realize input = 1 on second swap initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: -450560, arrayCount: 1, aToB: true, }, { poolIndex: 1, startTickIndex: 0, arrayCount: 3, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: -439296 - 256, tickUpperIndex: -439296 - 128, liquidityAmount: new BN(1_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(5_000_000_000_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; // 1 --> 1 const quoteSecond = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // 22337909818 --> 0 (not round up) const quoteFirst = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quoteSecond.estimatedAmountIn, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirst, quoteSecond, ); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitOne: new BN(0), // Partial fill is NOT allowed sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x17a9/, // PartialFillError ); }); // Reject partial fill on the first swap by the constraint that first output must be equal to the second input // Pools are safe, but owner consume intermediate tokens unproportionally // |-min,T----**-S-| --> |--***T**-S-| (where *: liquidity, S: start, T: end) it("fails ExactOut, partial fill on first swap, sqrt_price_limit_one != 0", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: [{ tickSpacing: 128, feeRate: 0 }], // to realize input = 1 on second swap initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: -450560, arrayCount: 1, aToB: true, }, { poolIndex: 1, startTickIndex: 0, arrayCount: 3, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: -439296 - 256, tickUpperIndex: -439296 - 128, liquidityAmount: new BN(1_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(5_000_000_000_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, outputToken] = mintKeys; // 1 --> 1 const quoteSecond = await swapQuoteByOutputToken( whirlpoolTwo, outputToken, new BN(1), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // 22337909818 --> 0 (not round up) const quoteFirst = await swapQuoteByOutputToken( whirlpoolOne, intermediaryToken, quoteSecond.estimatedAmountIn, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirst, quoteSecond, ); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x17a3/, // IntermediateTokenAmountMismatch ); }); // Partial fill on the first swap in ExactIn is allowed. // |--***T,limit**-S-| -> |--***T**-S--| (where *: liquidity, S: start, T: end) it("ExactIn, partial fill on first swap", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: aqConfig.initFeeTierParams, initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: 0, arrayCount: 3, aToB: true, }, { poolIndex: 1, startTickIndex: 0, arrayCount: 3, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [_inputToken, intermediaryToken, _outputToken] = mintKeys; const quoteParams = { amountSpecifiedIsInput: true, aToB: true, otherAmountThreshold: new BN(0), tickArrays: await SwapUtils.getTickArrays( whirlpoolOne.getData().tickCurrentIndex, whirlpoolOne.getData().tickSpacing, true, ctx.program.programId, whirlpoolOneKey, ctx.fetcher, IGNORE_CACHE, ), tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, whirlpoolData: whirlpoolOne.getData(), tokenAmount: new BN(1_000_000), }; // 1000000 --> 1103339 const quoteFirstWithoutLimit = swapQuoteWithParams( { ...quoteParams, sqrtPriceLimit: MIN_SQRT_PRICE_BN, }, Percentage.fromFraction(0, 100), ); assert.ok(quoteFirstWithoutLimit.estimatedEndTickIndex < 1010); // 667266 --> 736476 const quoteFirstWithLimit = swapQuoteWithParams( { ...quoteParams, sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(1010), }, Percentage.fromFraction(0, 100), ); assert.ok(quoteFirstWithLimit.estimatedEndTickIndex == 1010); assert.ok( quoteFirstWithLimit.estimatedAmountIn.lt( quoteFirstWithoutLimit.estimatedAmountIn, ), ); assert.ok( quoteFirstWithLimit.estimatedAmountOut.lt( quoteFirstWithoutLimit.estimatedAmountOut, ), ); // 1103339 --> 1217224 const quoteSecondWithoutLimit = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quoteFirstWithoutLimit.estimatedAmountOut, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // 736476 --> 812807 const quoteSecondWithLimit = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quoteFirstWithLimit.estimatedAmountOut, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // build without limit const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirstWithoutLimit, quoteSecondWithoutLimit, ); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, amount: quoteFirstWithoutLimit.estimatedAmountIn, sqrtPriceLimitOne: PriceMath.tickIndexToSqrtPriceX64(1010), // partial fill is allowed sqrtPriceLimitTwo: new BN(0), // partial fill on second swap is NOT allowd // +1 to check output amount otherAmountThreshold: quoteSecondWithLimit.estimatedAmountOut.addn(1), ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x1794/, // AmountOutBelowMinimum ); assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, amount: quoteFirstWithoutLimit.estimatedAmountIn, sqrtPriceLimitOne: PriceMath.tickIndexToSqrtPriceX64(1010), // partial fill is allowed sqrtPriceLimitTwo: new BN(0), // partial fill on second swap is NOT allowd otherAmountThreshold: quoteSecondWithLimit.estimatedAmountOut, ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); }); // Reject partial fill on the second swap by the constraint that second output must be equal to the first input // Pools and owner are safe, but owner will receive unconsumed intermediate tokens // |--***T**-S-| -> |--***T,limit**-S--| (where *: liquidity, S: start, T: end) it("fails ExactIn, partial fill on second swap", async () => { const aquarium = ( await buildTestAquariums(ctx, [ { configParams: aqConfig.configParams, initFeeTierParams: aqConfig.initFeeTierParams, initMintParams: aqConfig.initMintParams, initTokenAccParams: [ { mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) }, { mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) }, ], initPoolParams: [ { ...aqConfig.initPoolParams[0], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, { ...aqConfig.initPoolParams[1], tickSpacing: 128, initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1), }, ], initTickArrayRangeParams: [ { poolIndex: 0, startTickIndex: 0, arrayCount: 3, aToB: true, }, { poolIndex: 1, startTickIndex: 0, arrayCount: 3, aToB: true, }, ], initPositionParams: [ { poolIndex: 0, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, { poolIndex: 1, fundParams: [ { tickLowerIndex: 512, tickUpperIndex: 1024, liquidityAmount: new BN(1_000_000_000), }, ], }, ], }, ]) )[0]; const { tokenAccounts, mintKeys, pools } = aquarium; const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey; const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey; let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE); let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE); const [inputToken, intermediaryToken, _outputToken] = mintKeys; // 1000000 --> 1103339 const quoteFirst = await swapQuoteByInputToken( whirlpoolOne, inputToken, new BN(1_000_000), Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); // 1103339 --> 1217224 const quoteSecond = await swapQuoteByInputToken( whirlpoolTwo, intermediaryToken, quoteFirst.estimatedAmountOut, Percentage.fromFraction(0, 100), ctx.program.programId, fetcher, IGNORE_CACHE, ); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes( quoteFirst, quoteSecond, ); assert.ok(quoteSecond.estimatedEndTickIndex < 1002); await assert.rejects( toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1002), // Partial fill ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(), /0x17a3/, // IntermediateTokenAmountMismatch ); assert.ok(quoteSecond.estimatedEndTickIndex > 999); await toTx( ctx, WhirlpoolIx.twoHopSwapIx(ctx.program, { ...twoHopQuote, sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(999), ...getParamsFromPools([pools[0], pools[1]], tokenAccounts), tokenAuthority: ctx.wallet.publicKey, }), ).buildAndExecute(); }); }); function getParamsFromPools( pools: [InitPoolParams, InitPoolParams], tokenAccounts: { mint: PublicKey; account: PublicKey }[], ) { const tokenAccKeys = getTokenAccsForPools(pools, tokenAccounts); const whirlpoolOne = pools[0].whirlpoolPda.publicKey; const whirlpoolTwo = pools[1].whirlpoolPda.publicKey; const oracleOne = PDAUtil.getOracle( ctx.program.programId, whirlpoolOne, ).publicKey; const oracleTwo = PDAUtil.getOracle( ctx.program.programId, whirlpoolTwo, ).publicKey; return { whirlpoolOne: pools[0].whirlpoolPda.publicKey, whirlpoolTwo: pools[1].whirlpoolPda.publicKey, tokenOwnerAccountOneA: tokenAccKeys[0], tokenVaultOneA: pools[0].tokenVaultAKeypair.publicKey, tokenOwnerAccountOneB: tokenAccKeys[1], tokenVaultOneB: pools[0].tokenVaultBKeypair.publicKey, tokenOwnerAccountTwoA: tokenAccKeys[2], tokenVaultTwoA: pools[1].tokenVaultAKeypair.publicKey, tokenOwnerAccountTwoB: tokenAccKeys[3], tokenVaultTwoB: pools[1].tokenVaultBKeypair.publicKey, oracleOne, oracleTwo, }; } async function getTokenBalancesForVaults(pools: InitPoolParams[]) { const accs: PublicKey[] = []; for (const pool of pools) { accs.push(pool.tokenVaultAKeypair.publicKey); accs.push(pool.tokenVaultBKeypair.publicKey); } return getTokenBalances(accs); } async function getTokenBalances(keys: PublicKey[]) { return Promise.all( keys.map( async (key) => new anchor.BN(await getTokenBalance(provider, key)), ), ); } });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_position_bundle_with_metadata.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import type { Account, Mint } from "@solana/spl-token"; import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js"; import * as assert from "assert"; import type { PositionBundleData } from "../../src"; import { METADATA_PROGRAM_ADDRESS, PDAUtil, POSITION_BUNDLE_SIZE, toTx, WHIRLPOOL_NFT_UPDATE_AUTH, WhirlpoolContext, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { createMintInstructions, mintToDestination } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initializePositionBundleWithMetadata } from "../utils/init-utils"; import { MetaplexHttpClient } from "../utils/metaplex"; describe("initialize_position_bundle_with_metadata", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const metaplex = new MetaplexHttpClient(); async function createInitializePositionBundleWithMetadataTx( ctx: WhirlpoolContext, overwrite: object, mintKeypair?: Keypair, ) { const positionBundleMintKeypair = mintKeypair ?? Keypair.generate(); const positionBundlePda = PDAUtil.getPositionBundle( ctx.program.programId, positionBundleMintKeypair.publicKey, ); const positionBundleMetadataPda = PDAUtil.getPositionBundleMetadata( positionBundleMintKeypair.publicKey, ); const positionBundleTokenAccount = getAssociatedTokenAddressSync( positionBundleMintKeypair.publicKey, ctx.wallet.publicKey, ); const defaultAccounts = { positionBundle: positionBundlePda.publicKey, positionBundleMint: positionBundleMintKeypair.publicKey, positionBundleMetadata: positionBundleMetadataPda.publicKey, positionBundleTokenAccount, positionBundleOwner: ctx.wallet.publicKey, funder: ctx.wallet.publicKey, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, metadataProgram: METADATA_PROGRAM_ADDRESS, metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH, }; const ix = program.instruction.initializePositionBundleWithMetadata({ accounts: { ...defaultAccounts, ...overwrite, }, }); return toTx(ctx, { instructions: [ix], cleanupInstructions: [], signers: [positionBundleMintKeypair], }); } async function checkPositionBundleMint(positionBundleMintPubkey: PublicKey) { // verify position bundle Mint account const positionBundleMint = (await ctx.fetcher.getMintInfo( positionBundleMintPubkey, IGNORE_CACHE, )) as Mint; // should have NFT characteristics assert.strictEqual(positionBundleMint.decimals, 0); assert.ok(positionBundleMint.supply === 1n); // mint auth & freeze auth should be set to None assert.ok(positionBundleMint.mintAuthority === null); assert.ok(positionBundleMint.freezeAuthority === null); } async function checkPositionBundleTokenAccount( positionBundleTokenAccountPubkey: PublicKey, owner: PublicKey, positionBundleMintPubkey: PublicKey, ) { // verify position bundle Token account const positionBundleTokenAccount = (await ctx.fetcher.getTokenInfo( positionBundleTokenAccountPubkey, IGNORE_CACHE, )) as Account; assert.ok(positionBundleTokenAccount.amount === 1n); assert.ok(positionBundleTokenAccount.mint.equals(positionBundleMintPubkey)); assert.ok(positionBundleTokenAccount.owner.equals(owner)); } async function checkPositionBundle( positionBundlePubkey: PublicKey, positionBundleMintPubkey: PublicKey, ) { // verify PositionBundle account const positionBundle = (await ctx.fetcher.getPositionBundle( positionBundlePubkey, IGNORE_CACHE, )) as PositionBundleData; assert.ok( positionBundle.positionBundleMint.equals(positionBundleMintPubkey), ); assert.strictEqual( positionBundle.positionBitmap.length * 8, POSITION_BUNDLE_SIZE, ); for (const bitmap of positionBundle.positionBitmap) { assert.strictEqual(bitmap, 0); } } async function checkPositionBundleMetadata( metadataPda: PDA, positionMint: PublicKey, ) { const WPB_METADATA_NAME_PREFIX = "Orca Position Bundle"; const WPB_METADATA_SYMBOL = "OPB"; const WPB_METADATA_URI = "https://arweave.net/A_Wo8dx2_3lSUwMIi7bdT_sqxi8soghRNAWXXiqXpgE"; const mintAddress = positionMint.toBase58(); const nftName = WPB_METADATA_NAME_PREFIX + " " + mintAddress.slice(0, 4) + "..." + mintAddress.slice(-4); assert.ok(metadataPda != null); const metadataAccountInfo = await provider.connection.getAccountInfo( metadataPda.publicKey, ); assert.ok(metadataAccountInfo !== null); const metadata = metaplex.parseOnChainMetadata( metadataPda.publicKey, metadataAccountInfo!.data, ); assert.ok(metadata !== null); assert.ok(metadata.mint.toBase58() === positionMint.toString()); assert.ok( metadata.updateAuthority.toBase58() === WHIRLPOOL_NFT_UPDATE_AUTH.toBase58(), ); assert.ok(metadata.isMutable); assert.strictEqual(metadata.name.replace(/\0/g, ""), nftName); assert.strictEqual(metadata.symbol.replace(/\0/g, ""), WPB_METADATA_SYMBOL); assert.strictEqual(metadata.uri.replace(/\0/g, ""), WPB_METADATA_URI); } async function createOtherWallet(): Promise<Keypair> { const keypair = Keypair.generate(); const signature = await provider.connection.requestAirdrop( keypair.publicKey, 100 * LAMPORTS_PER_SOL, ); await provider.connection.confirmTransaction(signature, "confirmed"); return keypair; } it("successfully initialize position bundle and verify initialized account contents", async () => { const positionBundleInfo = await initializePositionBundleWithMetadata( ctx, ctx.wallet.publicKey, // funder = ctx.wallet.publicKey ); const { positionBundleMintKeypair, positionBundlePda, positionBundleMetadataPda, positionBundleTokenAccount, } = positionBundleInfo; await checkPositionBundleMint(positionBundleMintKeypair.publicKey); await checkPositionBundleTokenAccount( positionBundleTokenAccount, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundle( positionBundlePda.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundleMetadata( positionBundleMetadataPda, positionBundleMintKeypair.publicKey, ); }); it("successfully initialize when funder is different than account paying for transaction fee", async () => { const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const otherWallet = await createOtherWallet(); const positionBundleInfo = await initializePositionBundleWithMetadata( ctx, ctx.wallet.publicKey, otherWallet, ); const postBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const diffBalance = preBalance - postBalance; const minRent = await ctx.connection.getMinimumBalanceForRentExemption(0); assert.ok(diffBalance < minRent); // ctx.wallet didn't pay any rent const { positionBundleMintKeypair, positionBundlePda, positionBundleMetadataPda, positionBundleTokenAccount, } = positionBundleInfo; await checkPositionBundleMint(positionBundleMintKeypair.publicKey); await checkPositionBundleTokenAccount( positionBundleTokenAccount, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundle( positionBundlePda.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundleMetadata( positionBundleMetadataPda, positionBundleMintKeypair.publicKey, ); }); it("PositionBundle account has reserved space", async () => { const positionBundleAccountSizeIncludingReserve = 8 + 32 + 32 + 64; const positionBundleInfo = await initializePositionBundleWithMetadata( ctx, ctx.wallet.publicKey, ); const account = await ctx.connection.getAccountInfo( positionBundleInfo.positionBundlePda.publicKey, "confirmed", ); assert.equal( account!.data.length, positionBundleAccountSizeIncludingReserve, ); }); it("should be failed: cannot mint additional NFT by owner", async () => { const positionBundleInfo = await initializePositionBundleWithMetadata( ctx, ctx.wallet.publicKey, ); await assert.rejects( mintToDestination( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleInfo.positionBundleTokenAccount, 1, ), /0x5/, // the total supply of this token is fixed ); }); it("should be failed: already used mint is passed as position bundle mint", async () => { const positionBundleMintKeypair = Keypair.generate(); // create mint const createMintIx = await createMintInstructions( provider, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); const createMintTx = toTx(ctx, { instructions: createMintIx, cleanupInstructions: [], signers: [positionBundleMintKeypair], }); await createMintTx.buildAndExecute(); const tx = await createInitializePositionBundleWithMetadataTx( ctx, {}, positionBundleMintKeypair, ); await assert.rejects(tx.buildAndExecute(), (err) => { return JSON.stringify(err).includes("already in use"); }); }); describe("invalid input account", () => { it("should be failed: invalid position bundle address", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter positionBundle: PDAUtil.getPositionBundle( ctx.program.programId, Keypair.generate().publicKey, ).publicKey, }); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds ); }); it("should be failed: invalid metadata address", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter positionBundleMetadata: PDAUtil.getPositionBundleMetadata( Keypair.generate().publicKey, ).publicKey, }); await assert.rejects( tx.buildAndExecute(), /0x5/, // InvalidMetadataKey: cannot create Metadata ); }); it("should be failed: invalid ATA address", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter positionBundleTokenAccount: getAssociatedTokenAddressSync( Keypair.generate().publicKey, ctx.wallet.publicKey, ), }); await assert.rejects( tx.buildAndExecute(), /An account required by the instruction is missing/, // Anchor cannot create derived ATA ); }); it("should be failed: invalid update auth", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter metadataUpdateAuth: Keypair.generate().publicKey, }); await assert.rejects( tx.buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("should be failed: invalid token program", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter tokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid system program", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter systemProgram: TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid rent sysvar", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter rent: anchor.web3.SYSVAR_CLOCK_PUBKEY, }); await assert.rejects( tx.buildAndExecute(), /0xbc7/, // AccountSysvarMismatch ); }); it("should be failed: invalid associated token program", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter associatedTokenProgram: TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid metadata program", async () => { const tx = await createInitializePositionBundleWithMetadataTx(ctx, { // invalid parameter metadataProgram: TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_position_bundle.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { Account, Mint } from "@solana/spl-token"; import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js"; import * as assert from "assert"; import type { PositionBundleData } from "../../src"; import { PDAUtil, POSITION_BUNDLE_SIZE, toTx, WhirlpoolContext, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { createMintInstructions, mintToDestination } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initializePositionBundle } from "../utils/init-utils"; describe("initialize_position_bundle", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); async function createInitializePositionBundleTx( ctx: WhirlpoolContext, overwrite: object, mintKeypair?: Keypair, ) { const positionBundleMintKeypair = mintKeypair ?? Keypair.generate(); const positionBundlePda = PDAUtil.getPositionBundle( ctx.program.programId, positionBundleMintKeypair.publicKey, ); const positionBundleTokenAccount = getAssociatedTokenAddressSync( positionBundleMintKeypair.publicKey, ctx.wallet.publicKey, ); const defaultAccounts = { positionBundle: positionBundlePda.publicKey, positionBundleMint: positionBundleMintKeypair.publicKey, positionBundleTokenAccount, positionBundleOwner: ctx.wallet.publicKey, funder: ctx.wallet.publicKey, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, }; const ix = program.instruction.initializePositionBundle({ accounts: { ...defaultAccounts, ...overwrite, }, }); return toTx(ctx, { instructions: [ix], cleanupInstructions: [], signers: [positionBundleMintKeypair], }); } async function checkPositionBundleMint(positionBundleMintPubkey: PublicKey) { // verify position bundle Mint account const positionBundleMint = (await ctx.fetcher.getMintInfo( positionBundleMintPubkey, IGNORE_CACHE, )) as Mint; // should have NFT characteristics assert.strictEqual(positionBundleMint.decimals, 0); assert.ok(positionBundleMint.supply === 1n); // mint auth & freeze auth should be set to None assert.ok(positionBundleMint.mintAuthority === null); assert.ok(positionBundleMint.freezeAuthority === null); } async function checkPositionBundleTokenAccount( positionBundleTokenAccountPubkey: PublicKey, owner: PublicKey, positionBundleMintPubkey: PublicKey, ) { // verify position bundle Token account const positionBundleTokenAccount = (await ctx.fetcher.getTokenInfo( positionBundleTokenAccountPubkey, IGNORE_CACHE, )) as Account; assert.ok(positionBundleTokenAccount.amount === 1n); assert.ok(positionBundleTokenAccount.mint.equals(positionBundleMintPubkey)); assert.ok(positionBundleTokenAccount.owner.equals(owner)); } async function checkPositionBundle( positionBundlePubkey: PublicKey, positionBundleMintPubkey: PublicKey, ) { // verify PositionBundle account const positionBundle = (await ctx.fetcher.getPositionBundle( positionBundlePubkey, IGNORE_CACHE, )) as PositionBundleData; assert.ok( positionBundle.positionBundleMint.equals(positionBundleMintPubkey), ); assert.strictEqual( positionBundle.positionBitmap.length * 8, POSITION_BUNDLE_SIZE, ); for (const bitmap of positionBundle.positionBitmap) { assert.strictEqual(bitmap, 0); } } async function createOtherWallet(): Promise<Keypair> { const keypair = Keypair.generate(); const signature = await provider.connection.requestAirdrop( keypair.publicKey, 100 * LAMPORTS_PER_SOL, ); await provider.connection.confirmTransaction(signature, "confirmed"); return keypair; } it("successfully initialize position bundle and verify initialized account contents", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, // funder = ctx.wallet.publicKey ); const { positionBundleMintKeypair, positionBundlePda, positionBundleTokenAccount, } = positionBundleInfo; await checkPositionBundleMint(positionBundleMintKeypair.publicKey); await checkPositionBundleTokenAccount( positionBundleTokenAccount, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundle( positionBundlePda.publicKey, positionBundleMintKeypair.publicKey, ); }); it("successfully initialize when funder is different than account paying for transaction fee", async () => { const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const otherWallet = await createOtherWallet(); const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, otherWallet, ); const postBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const diffBalance = preBalance - postBalance; const minRent = await ctx.connection.getMinimumBalanceForRentExemption(0); assert.ok(diffBalance < minRent); // ctx.wallet didn't pay any rent const { positionBundleMintKeypair, positionBundlePda, positionBundleTokenAccount, } = positionBundleInfo; await checkPositionBundleMint(positionBundleMintKeypair.publicKey); await checkPositionBundleTokenAccount( positionBundleTokenAccount, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); await checkPositionBundle( positionBundlePda.publicKey, positionBundleMintKeypair.publicKey, ); }); it("PositionBundle account has reserved space", async () => { const positionBundleAccountSizeIncludingReserve = 8 + 32 + 32 + 64; const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const account = await ctx.connection.getAccountInfo( positionBundleInfo.positionBundlePda.publicKey, "confirmed", ); assert.equal( account!.data.length, positionBundleAccountSizeIncludingReserve, ); }); it("should be failed: cannot mint additional NFT by owner", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); await assert.rejects( mintToDestination( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleInfo.positionBundleTokenAccount, 1, ), /0x5/, // the total supply of this token is fixed ); }); it("should be failed: already used mint is passed as position bundle mint", async () => { const positionBundleMintKeypair = Keypair.generate(); // create mint const createMintIx = await createMintInstructions( provider, ctx.wallet.publicKey, positionBundleMintKeypair.publicKey, ); const createMintTx = toTx(ctx, { instructions: createMintIx, cleanupInstructions: [], signers: [positionBundleMintKeypair], }); await createMintTx.buildAndExecute(); const tx = await createInitializePositionBundleTx( ctx, {}, positionBundleMintKeypair, ); await assert.rejects(tx.buildAndExecute(), (err) => { return JSON.stringify(err).includes("already in use"); }); }); describe("invalid input account", () => { it("should be failed: invalid position bundle address", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter positionBundle: PDAUtil.getPositionBundle( ctx.program.programId, Keypair.generate().publicKey, ).publicKey, }); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds ); }); it("should be failed: invalid ATA address", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter positionBundleTokenAccount: getAssociatedTokenAddressSync( Keypair.generate().publicKey, ctx.wallet.publicKey, ), }); await assert.rejects( tx.buildAndExecute(), /An account required by the instruction is missing/, // Anchor cannot create derived ATA ); }); it("should be failed: invalid token program", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter tokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid system program", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter systemProgram: TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid rent sysvar", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter rent: anchor.web3.SYSVAR_CLOCK_PUBKEY, }); await assert.rejects( tx.buildAndExecute(), /0xbc7/, // AccountSysvarMismatch ); }); it("should be failed: invalid associated token program", async () => { const tx = await createInitializePositionBundleTx(ctx, { // invalid parameter associatedTokenProgram: TOKEN_PROGRAM_ID, }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_default_fee_rate.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { InitPoolParams, WhirlpoolData } from "../../src"; import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; import { createInOrderMints, generateDefaultConfigParams, } from "../utils/test-builders"; describe("set_default_fee_rate", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_default_fee_rate", async () => { const { poolInitInfo, configInitInfo, configKeypairs, feeTierParams } = await initTestPool(ctx, TickSpacing.Standard); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultFeeRate = 45; // Fetch initial whirlpool and check it is default let whirlpool_0 = (await fetcher.getPool(whirlpoolKey)) as WhirlpoolData; assert.equal(whirlpool_0.feeRate, feeTierParams.defaultFeeRate); await toTx( ctx, WhirlpoolIx.setDefaultFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, tickSpacing: TickSpacing.Standard, defaultFeeRate: newDefaultFeeRate, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(); // Setting the default rate did not change existing whirlpool fee rate whirlpool_0 = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; assert.equal(whirlpool_0.feeRate, feeTierParams.defaultFeeRate); // Newly initialized whirlpools have new default fee rate const [tokenMintA, tokenMintB] = await createInOrderMints(ctx); const whirlpoolPda = PDAUtil.getWhirlpool( ctx.program.programId, whirlpoolsConfigKey, tokenMintA, tokenMintB, TickSpacing.Standard, ); const tokenVaultAKeypair = anchor.web3.Keypair.generate(); const tokenVaultBKeypair = anchor.web3.Keypair.generate(); const newPoolInitInfo: InitPoolParams = { ...poolInitInfo, tokenMintA, tokenMintB, whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tickSpacing: TickSpacing.Standard, }; await toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, newPoolInitInfo), ).buildAndExecute(); const whirlpool_1 = (await fetcher.getPool( whirlpoolPda.publicKey, )) as WhirlpoolData; assert.equal(whirlpool_1.feeRate, newDefaultFeeRate); }); it("successfully set_default_fee_rate max", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultFeeRate = 30_000; await toTx( ctx, WhirlpoolIx.setDefaultFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, tickSpacing: TickSpacing.Standard, defaultFeeRate: newDefaultFeeRate, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(); // Newly initialized whirlpools have new default fee rate const [tokenMintA, tokenMintB] = await createInOrderMints(ctx); const whirlpoolPda = PDAUtil.getWhirlpool( ctx.program.programId, whirlpoolsConfigKey, tokenMintA, tokenMintB, TickSpacing.Standard, ); const tokenVaultAKeypair = anchor.web3.Keypair.generate(); const tokenVaultBKeypair = anchor.web3.Keypair.generate(); const newPoolInitInfo: InitPoolParams = { ...poolInitInfo, tokenMintA, tokenMintB, whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tickSpacing: TickSpacing.Standard, }; await toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, newPoolInitInfo), ).buildAndExecute(); const whirlpool_1 = (await fetcher.getPool( whirlpoolPda.publicKey, )) as WhirlpoolData; assert.equal(whirlpool_1.feeRate, newDefaultFeeRate); }); it("fails when default fee rate exceeds max", async () => { const { configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultFeeRate = 30_000 + 1; await assert.rejects( toTx( ctx, WhirlpoolIx.setDefaultFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, tickSpacing: TickSpacing.Standard, defaultFeeRate: newDefaultFeeRate, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(), /0x178c/, // FeeRateMaxExceeded ); }); it("fails when fee tier account has not been initialized", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; await assert.rejects( toTx( ctx, WhirlpoolIx.setDefaultFeeRateIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, feeAuthority: feeAuthorityKeypair.publicKey, tickSpacing: TickSpacing.Standard, defaultFeeRate: 500, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(), /0xbc4/, // AccountNotInitialized ); }); it("fails when fee authority is not a signer", async () => { const { configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const feeTierPda = PDAUtil.getFeeTier( ctx.program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, TickSpacing.Standard, ); const newDefaultFeeRate = 1000; await assert.rejects( program.rpc.setDefaultFeeRate(newDefaultFeeRate, { accounts: { whirlpoolsConfig: whirlpoolsConfigKey, feeTier: feeTierPda.publicKey, feeAuthority: feeAuthorityKeypair.publicKey, }, }), /.*signature verification fail.*/i, ); }); it("fails when invalid fee authority provided", async () => { const { configInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const fakeFeeAuthorityKeypair = anchor.web3.Keypair.generate(); const feeTierPda = PDAUtil.getFeeTier( ctx.program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, TickSpacing.Standard, ); const newDefaultFeeRate = 1000; await assert.rejects( program.rpc.setDefaultFeeRate(newDefaultFeeRate, { accounts: { whirlpoolsConfig: whirlpoolsConfigKey, feeTier: feeTierPda.publicKey, feeAuthority: fakeFeeAuthorityKeypair.publicKey, }, signers: [fakeFeeAuthorityKeypair], }), /An address constraint was violated/, // ConstraintAddress ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/open_bundled_position.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import * as assert from "assert"; import type { InitPoolParams, PositionBundleData, PositionData, } from "../../src"; import { MAX_TICK_INDEX, MIN_TICK_INDEX, PDAUtil, POSITION_BUNDLE_SIZE, TickUtil, toTx, WhirlpoolContext, WhirlpoolIx, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { approveToken, createAssociatedTokenAccount, ONE_SOL, systemTransferTx, TickSpacing, transferToken, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initializePositionBundle, initTestPool, openBundledPosition, } from "../utils/init-utils"; describe("open_bundled_position", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const tickLowerIndex = 0; const tickUpperIndex = 32768; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; let fullRangeOnlyPoolInitInfo: InitPoolParams; let fullRangeOnlyWhirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; fullRangeOnlyPoolInitInfo = ( await initTestPool(ctx, TickSpacing.FullRangeOnly) ).poolInitInfo; fullRangeOnlyWhirlpoolPda = fullRangeOnlyPoolInitInfo.whirlpoolPda; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); async function createOpenBundledPositionTx( ctx: WhirlpoolContext, positionBundleMint: PublicKey, bundleIndex: number, overwrite: object, ) { const bundledPositionPda = PDAUtil.getBundledPosition( ctx.program.programId, positionBundleMint, bundleIndex, ); const positionBundle = PDAUtil.getPositionBundle( ctx.program.programId, positionBundleMint, ).publicKey; const positionBundleTokenAccount = getAssociatedTokenAddressSync( positionBundleMint, ctx.wallet.publicKey, ); const defaultAccounts = { bundledPosition: bundledPositionPda.publicKey, positionBundle, positionBundleTokenAccount, positionBundleAuthority: ctx.wallet.publicKey, whirlpool: whirlpoolPda.publicKey, funder: ctx.wallet.publicKey, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, }; const ix = program.instruction.openBundledPosition( bundleIndex, tickLowerIndex, tickUpperIndex, { accounts: { ...defaultAccounts, ...overwrite, }, }, ); return toTx(ctx, { instructions: [ix], cleanupInstructions: [], signers: [], }); } function checkPositionAccountContents( position: PositionData, mint: PublicKey, whirlpool: PublicKey = poolInitInfo.whirlpoolPda.publicKey, lowerTick: number = tickLowerIndex, upperTick: number = tickUpperIndex, ) { assert.strictEqual(position.tickLowerIndex, lowerTick); assert.strictEqual(position.tickUpperIndex, upperTick); assert.ok(position.whirlpool.equals(whirlpool)); assert.ok(position.positionMint.equals(mint)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); assert.ok(position.rewardInfos[0].amountOwed.eq(ZERO_BN)); assert.ok(position.rewardInfos[1].amountOwed.eq(ZERO_BN)); assert.ok(position.rewardInfos[2].amountOwed.eq(ZERO_BN)); assert.ok(position.rewardInfos[0].growthInsideCheckpoint.eq(ZERO_BN)); assert.ok(position.rewardInfos[1].growthInsideCheckpoint.eq(ZERO_BN)); assert.ok(position.rewardInfos[2].growthInsideCheckpoint.eq(ZERO_BN)); } function checkBitmapIsOpened( account: PositionBundleData, bundleIndex: number, ): boolean { if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE) throw Error("bundleIndex is out of bounds"); const bitmapIndex = Math.floor(bundleIndex / 8); const bitmapOffset = bundleIndex % 8; return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) > 0; } function checkBitmapIsClosed( account: PositionBundleData, bundleIndex: number, ): boolean { if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE) throw Error("bundleIndex is out of bounds"); const bitmapIndex = Math.floor(bundleIndex / 8); const bitmapOffset = bundleIndex % 8; return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) === 0; } function checkBitmap( account: PositionBundleData, openedBundleIndexes: number[], ) { for (let i = 0; i < POSITION_BUNDLE_SIZE; i++) { if (openedBundleIndexes.includes(i)) { assert.ok(checkBitmapIsOpened(account, i)); } else { assert.ok(checkBitmapIsClosed(account, i)); } } } it("successfully opens bundled position and verify position address contents", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const position = (await fetcher.getPosition( bundledPositionPda.publicKey, )) as PositionData; checkPositionAccountContents( position, positionBundleInfo.positionBundleMintKeypair.publicKey, ); const positionBundle = (await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, )) as PositionBundleData; checkBitmap(positionBundle, [bundleIndex]); }); it("successfully opens bundled position when funder is different than account paying for transaction fee", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const bundleIndex = POSITION_BUNDLE_SIZE - 1; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, funderKeypair, ); const { bundledPositionPda } = positionInitInfo.params; const postBalance = await ctx.connection.getBalance(ctx.wallet.publicKey); const diffBalance = preBalance - postBalance; const minRent = await ctx.connection.getMinimumBalanceForRentExemption(0); assert.ok(diffBalance < minRent); // ctx.wallet didn't any rent const position = (await fetcher.getPosition( bundledPositionPda.publicKey, )) as PositionData; checkPositionAccountContents( position, positionBundleInfo.positionBundleMintKeypair.publicKey, ); const positionBundle = (await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, )) as PositionBundleData; checkBitmap(positionBundle, [bundleIndex]); }); it("successfully opens multiple bundled position and verify bitmap", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndexes = [1, 7, 8, 64, 127, 128, 254, 255]; for (const bundleIndex of bundleIndexes) { const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const position = (await fetcher.getPosition( bundledPositionPda.publicKey, )) as PositionData; checkPositionAccountContents( position, positionBundleInfo.positionBundleMintKeypair.publicKey, ); } const positionBundle = (await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, )) as PositionBundleData; checkBitmap(positionBundle, bundleIndexes); }); it("successfully opens bundled position for full-range only pool", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const [lowerTickIndex, upperTickIndex] = TickUtil.getFullRangeTickIndex( TickSpacing.FullRangeOnly, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, fullRangeOnlyWhirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, lowerTickIndex, upperTickIndex, ); const { bundledPositionPda } = positionInitInfo.params; const position = (await fetcher.getPosition( bundledPositionPda.publicKey, )) as PositionData; checkPositionAccountContents( position, positionBundleInfo.positionBundleMintKeypair.publicKey, fullRangeOnlyWhirlpoolPda.publicKey, lowerTickIndex, upperTickIndex, ); const positionBundle = (await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, )) as PositionBundleData; checkBitmap(positionBundle, [bundleIndex]); }); describe("invalid bundle index", () => { it("should be failed: invalid bundle index (< 0)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = -1; await assert.rejects( openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ), /It must be >= 0 and <= 65535/, // rejected by client ); }); it("should be failed: invalid bundle index (POSITION_BUNDLE_SIZE)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = POSITION_BUNDLE_SIZE; await assert.rejects( openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ), /0x179b/, // InvalidBundleIndex ); }); it("should be failed: invalid bundle index (u16 max)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 2 ** 16 - 1; await assert.rejects( openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ), /0x179b/, // InvalidBundleIndex ); }); }); describe("invalid tick index", () => { async function assertTicksFail(lowerTick: number, upperTick: number) { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; await assert.rejects( openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, lowerTick, upperTick, provider.wallet.publicKey, funderKeypair, ), /0x177a/, // InvalidTickIndex ); } it("should be failed: user pass in an out of bound tick index for upper-index", async () => { await assertTicksFail(0, MAX_TICK_INDEX + 1); }); it("should be failed: user pass in a lower tick index that is higher than the upper-index", async () => { await assertTicksFail(-22534, -22534 - 1); }); it("should be failed: user pass in a lower tick index that equals the upper-index", async () => { await assertTicksFail(22365, 22365); }); it("should be failed: user pass in an out of bound tick index for lower-index", async () => { await assertTicksFail(MIN_TICK_INDEX - 1, 0); }); it("should be failed: user pass in a non-initializable tick index for upper-index", async () => { await assertTicksFail(0, 1); }); it("should be failed: user pass in a non-initializable tick index for lower-index", async () => { await assertTicksFail(1, 2); }); }); it("should be fail: user opens bundled position with bundle index whose state is opened", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const positionBundle = (await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, )) as PositionBundleData; assert.ok(checkBitmapIsOpened(positionBundle, bundleIndex)); await assert.rejects( openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ), (err) => { return JSON.stringify(err).includes("already in use"); }, ); }); describe("invalid input account", () => { it("should be failed: invalid bundled position", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter bundledPosition: PDAUtil.getBundledPosition( ctx.program.programId, positionBundleInfo.positionBundleMintKeypair.publicKey, 1, // another bundle index ).publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds ); }); it("should be failed: invalid position bundle", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const otherPositionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter positionBundle: otherPositionBundleInfo.positionBundlePda.publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0x7d6/, // ConstraintSeeds ); }); it("should be failed: invalid ATA (amount is zero)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, funderKeypair.publicKey, funderKeypair, ); const ata = await createAssociatedTokenAccount( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, ctx.wallet.publicKey, ctx.wallet.publicKey, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter positionBundleTokenAccount: ata, }, ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw (amount == 1) ); }); it("should be failed: invalid ATA (invalid mint)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, funderKeypair.publicKey, funderKeypair, ); const otherPositionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter positionBundleTokenAccount: otherPositionBundleInfo.positionBundleTokenAccount, }, ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw (mint == position_bundle.position_bundle_mint) ); }); it("should be failed: invalid position bundle authority", async () => { const positionBundleInfo = await initializePositionBundle( ctx, funderKeypair.publicKey, funderKeypair, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, // invalid parameter positionBundleAuthority: ctx.wallet.publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("should be failed: invalid whirlpool", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter whirlpool: positionBundleInfo.positionBundlePda.publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0xbba/, // AccountDiscriminatorMismatch ); }); it("should be failed: invalid system program", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter systemProgram: TOKEN_PROGRAM_ID, }, ); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); it("should be failed: invalid rent", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { // invalid parameter rent: anchor.web3.SYSVAR_CLOCK_PUBKEY, }, ); await assert.rejects( tx.buildAndExecute(), /0xbc7/, // AccountSysvarMismatch ); }); }); describe("authority delegation", () => { it("successfully opens bundled position with delegated authority", async () => { const positionBundleInfo = await initializePositionBundle( ctx, funderKeypair.publicKey, funderKeypair, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, positionBundleAuthority: ctx.wallet.publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); // delegate 1 token from funder to ctx.wallet await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, ctx.wallet.publicKey, 1, funderKeypair, ); await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsOpened(positionBundle!, 0); }); it("successfully opens bundled position even if delegation exists", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, positionBundleAuthority: ctx.wallet.publicKey, }, ); // delegate 1 token from ctx.wallet to funder await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, funderKeypair.publicKey, 1, ); // owner can open even if delegation exists await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsOpened(positionBundle!, 0); }); it("should be failed: delegated amount is zero", async () => { const positionBundleInfo = await initializePositionBundle( ctx, funderKeypair.publicKey, funderKeypair, ); const tx = await createOpenBundledPositionTx( ctx, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, { positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, positionBundleAuthority: ctx.wallet.publicKey, }, ); await assert.rejects( tx.buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); // delegate ZERO token from funder to ctx.wallet await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, ctx.wallet.publicKey, 0, funderKeypair, ); await assert.rejects( tx.buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); }); describe("transfer position bundle", () => { it("successfully opens bundled position after position bundle token transfer", async () => { const positionBundleInfo = await initializePositionBundle(ctx); const funderATA = await createAssociatedTokenAccount( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, funderKeypair.publicKey, ctx.wallet.publicKey, ); await transferToken( provider, positionBundleInfo.positionBundleTokenAccount, funderATA, 1, ); const tokenInfo = await fetcher.getTokenInfo(funderATA, IGNORE_CACHE); assert.ok(tokenInfo?.amount === 1n); const tx = toTx( ctx, WhirlpoolIx.openBundledPositionIx(ctx.program, { bundledPositionPda: PDAUtil.getBundledPosition( ctx.program.programId, positionBundleInfo.positionBundleMintKeypair.publicKey, 0, ), bundleIndex: 0, funder: funderKeypair.publicKey, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: funderKeypair.publicKey, positionBundleTokenAccount: funderATA, tickLowerIndex, tickUpperIndex, whirlpool: whirlpoolPda.publicKey, }), ); tx.addSigner(funderKeypair); await tx.buildAndExecute(); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsOpened(positionBundle!, 0); }); }); it("fail when opening a non-full range position in an full-range only pool", async () => { const [fullRangeTickLowerIndex, fullRangeTickUpperIndex] = TickUtil.getFullRangeTickIndex(fullRangeOnlyPoolInitInfo.tickSpacing); assert.notEqual(fullRangeTickLowerIndex, tickLowerIndex); assert.notEqual(fullRangeTickUpperIndex, tickUpperIndex); const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; await assert.rejects( openBundledPosition( ctx, fullRangeOnlyWhirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ), /0x17a6/, // FullRangeOnlyPool ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_reward_emissions_super_authority.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolsConfigData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { defaultConfirmOptions } from "../utils/const"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("set_reward_emissions_super_authority", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_reward_emissions_super_authority with super authority keypair", async () => { const { configInitInfo, configKeypairs: { rewardEmissionsSuperAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const newAuthorityKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.setRewardEmissionsSuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, rewardEmissionsSuperAuthority: rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardEmissionsSuperAuthority: newAuthorityKeypair.publicKey, }), ) .addSigner(rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(); const config = (await fetcher.getConfig( configInitInfo.whirlpoolsConfigKeypair.publicKey, )) as WhirlpoolsConfigData; assert.ok( config.rewardEmissionsSuperAuthority.equals( newAuthorityKeypair.publicKey, ), ); }); it("fails if current reward_emissions_super_authority is not a signer", async () => { const { configInitInfo, configKeypairs: { rewardEmissionsSuperAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( ctx.program.rpc.setRewardEmissionsSuperAuthority({ accounts: { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, rewardEmissionsSuperAuthority: rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardEmissionsSuperAuthority: provider.wallet.publicKey, }, }), /.*signature verification fail.*/i, ); }); it("fails if incorrect reward_emissions_super_authority is passed in", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardEmissionsSuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, rewardEmissionsSuperAuthority: provider.wallet.publicKey, newRewardEmissionsSuperAuthority: provider.wallet.publicKey, }), ).buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_reward_authority.test.ts
import * as anchor from "@coral-xyz/anchor"; import { TransactionBuilder } from "@orca-so/common-sdk"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { NUM_REWARDS, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; describe("set_reward_authority", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_reward_authority at every reward index", async () => { const { configKeypairs, poolInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const newKeypairs = generateKeypairs(NUM_REWARDS); const txBuilder = new TransactionBuilder( provider.connection, provider.wallet, ctx.txBuilderOpts, ); for (let i = 0; i < NUM_REWARDS; i++) { txBuilder.addInstruction( WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: newKeypairs[i].publicKey, rewardIndex: i, }), ); } await txBuilder .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute({ maxSupportedTransactionVersion: undefined, }); const pool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; for (let i = 0; i < NUM_REWARDS; i++) { assert.ok(pool.rewardInfos[i].authority.equals(newKeypairs[i].publicKey)); } }); it("fails when provided reward_authority does not match whirlpool reward authority", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const fakeAuthority = anchor.web3.Keypair.generate(); const newAuthority = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: fakeAuthority.publicKey, newRewardAuthority: newAuthority.publicKey, rewardIndex: 0, }), ) .addSigner(fakeAuthority) .buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); it("fails on invalid reward index", async () => { const { configKeypairs, poolInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const newAuthority = anchor.web3.Keypair.generate(); assert.throws(() => { toTx( ctx, WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: newAuthority.publicKey, rewardIndex: -1, }), ).buildAndExecute(); }, /out of range/); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: newAuthority.publicKey, rewardIndex: 255, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), // /failed to send transaction/ ); }); it("fails when reward_authority is not a signer", async () => { const { configKeypairs, poolInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const newAuthority = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: newAuthority.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); }); function generateKeypairs(n: number): anchor.web3.Keypair[] { const keypairs: anchor.web3.Keypair[] = []; for (let i = 0; i < n; i++) { keypairs.push(anchor.web3.Keypair.generate()); } return keypairs; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_pool.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { MathUtil } from "@orca-so/common-sdk"; import * as assert from "assert"; import Decimal from "decimal.js"; import type { InitPoolParams, WhirlpoolData } from "../../src"; import { IGNORE_CACHE, MAX_SQRT_PRICE, MIN_SQRT_PRICE, PDAUtil, PriceMath, WhirlpoolContext, WhirlpoolIx, toTx, } from "../../src"; import { ONE_SOL, TickSpacing, ZERO_BN, asyncAssertTokenVault, createMint, systemTransferTx, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { buildTestPoolParams, initFeeTier, initTestPool, } from "../utils/init-utils"; describe("initialize_pool", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully init a Standard account", async () => { const price = MathUtil.toX64(new Decimal(5)); const { configInitInfo, poolInitInfo, feeTierParams } = await initTestPool( ctx, TickSpacing.Standard, price, ); const whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; const expectedWhirlpoolPda = PDAUtil.getWhirlpool( program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, poolInitInfo.tokenMintA, poolInitInfo.tokenMintB, TickSpacing.Standard, ); assert.ok( poolInitInfo.whirlpoolPda.publicKey.equals( expectedWhirlpoolPda.publicKey, ), ); assert.equal(expectedWhirlpoolPda.bump, whirlpool.whirlpoolBump[0]); assert.ok(whirlpool.whirlpoolsConfig.equals(poolInitInfo.whirlpoolsConfig)); assert.ok(whirlpool.tokenMintA.equals(poolInitInfo.tokenMintA)); assert.ok( whirlpool.tokenVaultA.equals(poolInitInfo.tokenVaultAKeypair.publicKey), ); assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB)); assert.ok( whirlpool.tokenVaultB.equals(poolInitInfo.tokenVaultBKeypair.publicKey), ); assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate); assert.equal( whirlpool.protocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); assert.ok( whirlpool.sqrtPrice.eq( new anchor.BN(poolInitInfo.initSqrtPrice.toString()), ), ); assert.ok(whirlpool.liquidity.eq(ZERO_BN)); assert.equal( whirlpool.tickCurrentIndex, PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice), ); assert.ok(whirlpool.protocolFeeOwedA.eq(ZERO_BN)); assert.ok(whirlpool.protocolFeeOwedB.eq(ZERO_BN)); assert.ok(whirlpool.feeGrowthGlobalA.eq(ZERO_BN)); assert.ok(whirlpool.feeGrowthGlobalB.eq(ZERO_BN)); assert.ok(whirlpool.tickSpacing === TickSpacing.Standard); await asyncAssertTokenVault( program, poolInitInfo.tokenVaultAKeypair.publicKey, { expectedOwner: poolInitInfo.whirlpoolPda.publicKey, expectedMint: poolInitInfo.tokenMintA, }, ); await asyncAssertTokenVault( program, poolInitInfo.tokenVaultBKeypair.publicKey, { expectedOwner: poolInitInfo.whirlpoolPda.publicKey, expectedMint: poolInitInfo.tokenMintB, }, ); whirlpool.rewardInfos.forEach((rewardInfo) => { assert.equal(rewardInfo.emissionsPerSecondX64, 0); assert.equal(rewardInfo.growthGlobalX64, 0); assert.ok( rewardInfo.authority.equals( configInitInfo.rewardEmissionsSuperAuthority, ), ); assert.ok(rewardInfo.mint.equals(anchor.web3.PublicKey.default)); assert.ok(rewardInfo.vault.equals(anchor.web3.PublicKey.default)); }); }); it("successfully init a Stable account", async () => { const price = MathUtil.toX64(new Decimal(5)); const { configInitInfo, poolInitInfo, feeTierParams } = await initTestPool( ctx, TickSpacing.Stable, price, ); const whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; assert.ok(whirlpool.whirlpoolsConfig.equals(poolInitInfo.whirlpoolsConfig)); assert.ok(whirlpool.tokenMintA.equals(poolInitInfo.tokenMintA)); assert.ok( whirlpool.tokenVaultA.equals(poolInitInfo.tokenVaultAKeypair.publicKey), ); assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB)); assert.ok( whirlpool.tokenVaultB.equals(poolInitInfo.tokenVaultBKeypair.publicKey), ); assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate); assert.equal( whirlpool.protocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); assert.ok( whirlpool.sqrtPrice.eq( new anchor.BN(poolInitInfo.initSqrtPrice.toString()), ), ); assert.ok(whirlpool.liquidity.eq(ZERO_BN)); assert.equal( whirlpool.tickCurrentIndex, PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice), ); assert.ok(whirlpool.protocolFeeOwedA.eq(ZERO_BN)); assert.ok(whirlpool.protocolFeeOwedB.eq(ZERO_BN)); assert.ok(whirlpool.feeGrowthGlobalA.eq(ZERO_BN)); assert.ok(whirlpool.feeGrowthGlobalB.eq(ZERO_BN)); assert.ok(whirlpool.tickSpacing === TickSpacing.Stable); await asyncAssertTokenVault( program, poolInitInfo.tokenVaultAKeypair.publicKey, { expectedOwner: poolInitInfo.whirlpoolPda.publicKey, expectedMint: poolInitInfo.tokenMintA, }, ); await asyncAssertTokenVault( program, poolInitInfo.tokenVaultBKeypair.publicKey, { expectedOwner: poolInitInfo.whirlpoolPda.publicKey, expectedMint: poolInitInfo.tokenMintB, }, ); whirlpool.rewardInfos.forEach((rewardInfo) => { assert.equal(rewardInfo.emissionsPerSecondX64, 0); assert.equal(rewardInfo.growthGlobalX64, 0); assert.ok( rewardInfo.authority.equals( configInitInfo.rewardEmissionsSuperAuthority, ), ); assert.ok(rewardInfo.mint.equals(anchor.web3.PublicKey.default)); assert.ok(rewardInfo.vault.equals(anchor.web3.PublicKey.default)); }); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const funderKeypair = anchor.web3.Keypair.generate(); await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); await initTestPool( ctx, TickSpacing.Standard, MathUtil.toX64(new Decimal(5)), funderKeypair, ); }); it("fails when tokenVaultA mint does not match tokenA mint", async () => { const { poolInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const otherTokenPublicKey = await createMint(provider); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, tokenMintA: otherTokenPublicKey, }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x7d6/, // ConstraintSeeds ); }); it("fails when tokenVaultB mint does not match tokenB mint", async () => { const { poolInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const otherTokenPublicKey = await createMint(provider); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, tokenMintB: otherTokenPublicKey, }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x7d6/, // ConstraintSeeds ); }); it("fails when token mints are in the wrong order", async () => { const { poolInitInfo, configInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const whirlpoolPda = PDAUtil.getWhirlpool( ctx.program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, poolInitInfo.tokenMintB, poolInitInfo.tokenMintA, TickSpacing.Standard, ); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, whirlpoolPda, tickSpacing: TickSpacing.Standard, tokenMintA: poolInitInfo.tokenMintB, tokenMintB: poolInitInfo.tokenMintA, }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x1788/, // InvalidTokenMintOrder ); }); it("fails when the same token mint is passed in", async () => { const { poolInitInfo, configInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const whirlpoolPda = PDAUtil.getWhirlpool( ctx.program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, poolInitInfo.tokenMintA, poolInitInfo.tokenMintA, TickSpacing.Standard, ); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, whirlpoolPda, tickSpacing: TickSpacing.Standard, tokenMintB: poolInitInfo.tokenMintA, }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x1788/, // InvalidTokenMintOrder ); }); it("fails when sqrt-price exceeds max", async () => { const { poolInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); await createMint(provider); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, initSqrtPrice: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)), }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x177b/, // SqrtPriceOutOfBounds ); }); it("fails when sqrt-price subceeds min", async () => { const { poolInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, initSqrtPrice: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)), }; await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(), /custom program error: 0x177b/, // SqrtPriceOutOfBounds ); }); it("fails when FeeTier and tick_spacing passed unmatch", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await buildTestPoolParams(ctx, TickSpacing.Standard); // now FeeTier for TickSpacing.Standard is initialized, but not for TickSpacing.Stable const config = poolInitInfo.whirlpoolsConfig; const feeTierStandardPda = PDAUtil.getFeeTier( ctx.program.programId, config, TickSpacing.Standard, ); const feeTierStablePda = PDAUtil.getFeeTier( ctx.program.programId, config, TickSpacing.Stable, ); const feeTierStandard = await fetcher.getFeeTier( feeTierStandardPda.publicKey, IGNORE_CACHE, ); const feeTierStable = await fetcher.getFeeTier( feeTierStablePda.publicKey, IGNORE_CACHE, ); assert.ok(feeTierStandard !== null); // should be initialized assert.ok(feeTierStable === null); // shoud be NOT initialized const whirlpoolWithStableTickSpacing = PDAUtil.getWhirlpool( ctx.program.programId, config, poolInitInfo.tokenMintA, poolInitInfo.tokenMintB, TickSpacing.Stable, ); await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, { ...poolInitInfo, whirlpoolPda: whirlpoolWithStableTickSpacing, tickSpacing: TickSpacing.Stable, feeTierKey: feeTierStandardPda.publicKey, // tickSpacing is Stable, but FeeTier is standard }), ).buildAndExecute(), /custom program error: 0x7d3/, // ConstraintRaw ); await assert.rejects( toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, { ...poolInitInfo, whirlpoolPda: whirlpoolWithStableTickSpacing, tickSpacing: TickSpacing.Stable, feeTierKey: feeTierStablePda.publicKey, // FeeTier is stable, but not initialized }), ).buildAndExecute(), /custom program error: 0xbc4/, // AccountNotInitialized ); await initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, TickSpacing.Stable, 3000, ); const feeTierStableAfterInit = await fetcher.getFeeTier( feeTierStablePda.publicKey, IGNORE_CACHE, ); assert.ok(feeTierStableAfterInit !== null); // Now it should work because FeeTier for stable have been initialized await toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, { ...poolInitInfo, whirlpoolPda: whirlpoolWithStableTickSpacing, tickSpacing: TickSpacing.Stable, feeTierKey: feeTierStablePda.publicKey, }), ).buildAndExecute(); }); it("ignore passed bump", async () => { const { poolInitInfo } = await buildTestPoolParams( ctx, TickSpacing.Standard, ); const whirlpoolPda = poolInitInfo.whirlpoolPda; const validBump = whirlpoolPda.bump; const invalidBump = (validBump + 1) % 256; // +1 shift mod 256 const modifiedWhirlpoolPda: PDA = { publicKey: whirlpoolPda.publicKey, bump: invalidBump, }; const modifiedPoolInitInfo: InitPoolParams = { ...poolInitInfo, whirlpoolPda: modifiedWhirlpoolPda, }; await toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, modifiedPoolInitInfo), ).buildAndExecute(); // check if passed invalid bump was ignored const whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; assert.equal(whirlpool.whirlpoolBump, validBump); assert.notEqual(whirlpool.whirlpoolBump, invalidBump); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_default_protocol_fee_rate.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { InitPoolParams, WhirlpoolData } from "../../src"; import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; import { createInOrderMints } from "../utils/test-builders"; describe("set_default_protocol_fee_rate", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_default_protocol_fee_rate", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultProtocolFeeRate = 45; // Fetch initial whirlpool and check it is default let whirlpool_0 = (await fetcher.getPool(whirlpoolKey)) as WhirlpoolData; assert.equal( whirlpool_0.protocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); await toTx( ctx, WhirlpoolIx.setDefaultProtocolFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, defaultProtocolFeeRate: newDefaultProtocolFeeRate, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(); // Setting the default rate did not change existing whirlpool fee rate whirlpool_0 = (await fetcher.getPool(whirlpoolKey)) as WhirlpoolData; assert.equal( whirlpool_0.protocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); const [tokenMintA, tokenMintB] = await createInOrderMints(ctx); const whirlpoolPda = PDAUtil.getWhirlpool( ctx.program.programId, whirlpoolsConfigKey, tokenMintA, tokenMintB, TickSpacing.Standard, ); const tokenVaultAKeypair = anchor.web3.Keypair.generate(); const tokenVaultBKeypair = anchor.web3.Keypair.generate(); const newPoolInitInfo: InitPoolParams = { ...poolInitInfo, tokenMintA, tokenMintB, whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tickSpacing: TickSpacing.Standard, }; await toTx( ctx, WhirlpoolIx.initializePoolIx(ctx.program, newPoolInitInfo), ).buildAndExecute(); const whirlpool_1 = (await fetcher.getPool( whirlpoolPda.publicKey, )) as WhirlpoolData; assert.equal(whirlpool_1.protocolFeeRate, newDefaultProtocolFeeRate); }); it("fails when default fee rate exceeds max", async () => { const { configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultProtocolFeeRate = 20_000; await assert.rejects( toTx( ctx, WhirlpoolIx.setDefaultProtocolFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, defaultProtocolFeeRate: newDefaultProtocolFeeRate, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(), /0x178d/, // ProtocolFeeRateMaxExceeded ); }); it("fails when fee authority is not a signer", async () => { const { configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newDefaultProtocolFeeRate = 1000; await assert.rejects( program.rpc.setDefaultProtocolFeeRate(newDefaultProtocolFeeRate, { accounts: { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, }, }), /.*signature verification fail.*/i, ); }); it("fails when invalid fee authority provided", async () => { const { configInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const fakeFeeAuthorityKeypair = anchor.web3.Keypair.generate(); const newDefaultProtocolFeeRate = 1000; await assert.rejects( program.rpc.setDefaultProtocolFeeRate(newDefaultProtocolFeeRate, { accounts: { whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: fakeFeeAuthorityKeypair.publicKey, }, signers: [fakeFeeAuthorityKeypair], }), /An address constraint was violated/, ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_reward.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { createMint, ONE_SOL, systemTransferTx, TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initializeReward, initTestPool } from "../utils/init-utils"; describe("initialize_reward", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully initializes reward at index 0", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const { params } = await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 0, ); const whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok(whirlpool.rewardInfos[0].mint.equals(params.rewardMint)); assert.ok( whirlpool.rewardInfos[0].vault.equals( params.rewardVaultKeypair.publicKey, ), ); await assert.rejects( initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 0, ), /custom program error: 0x178a/, // InvalidRewardIndex ); const { params: params2 } = await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 1, ); const whirlpool2 = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok(whirlpool2.rewardInfos[0].mint.equals(params.rewardMint)); assert.ok( whirlpool2.rewardInfos[0].vault.equals( params.rewardVaultKeypair.publicKey, ), ); assert.ok(whirlpool2.rewardInfos[1].mint.equals(params2.rewardMint)); assert.ok( whirlpool2.rewardInfos[1].vault.equals( params2.rewardVaultKeypair.publicKey, ), ); assert.ok( whirlpool2.rewardInfos[2].mint.equals(anchor.web3.PublicKey.default), ); assert.ok( whirlpool2.rewardInfos[2].vault.equals(anchor.web3.PublicKey.default), ); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const funderKeypair = anchor.web3.Keypair.generate(); await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 0, funderKeypair, ); }); it("fails to initialize reward at index 1", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); await assert.rejects( initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 1, ), /custom program error: 0x178a/, // InvalidRewardIndex ); }); it("fails to initialize reward at out-of-bound index", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); await assert.rejects( initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, 3, ), ); }); it("fails to initialize if authority signature is missing", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); await assert.rejects( toTx( ctx, WhirlpoolIx.initializeRewardIx(ctx.program, { rewardAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, funder: provider.wallet.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardMint: await createMint(provider), rewardVaultKeypair: anchor.web3.Keypair.generate(), rewardIndex: 0, }), ).buildAndExecute(), ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/open_position.test.ts
import * as anchor from "@coral-xyz/anchor"; import { web3 } from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { getAccount, getAssociatedTokenAddressSync } from "@solana/spl-token"; import type { Keypair } from "@solana/web3.js"; import * as assert from "assert"; import type { InitPoolParams, OpenPositionParams, PositionData, } from "../../src"; import { MAX_TICK_INDEX, MIN_TICK_INDEX, PDAUtil, TickUtil, WhirlpoolContext, WhirlpoolIx, toTx, } from "../../src"; import { ONE_SOL, TickSpacing, ZERO_BN, createMint, createMintInstructions, mintToDestination, systemTransferTx, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool, openPosition } from "../utils/init-utils"; import { generateDefaultOpenPositionParams } from "../utils/test-builders"; describe("open_position", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; let defaultParams: OpenPositionParams; let defaultMint: Keypair; const tickLowerIndex = 0; const tickUpperIndex = 32768; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; let fullRangeOnlyPoolInitInfo: InitPoolParams; let fullRangeOnlyWhirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; fullRangeOnlyPoolInitInfo = ( await initTestPool(ctx, TickSpacing.FullRangeOnly) ).poolInitInfo; fullRangeOnlyWhirlpoolPda = fullRangeOnlyPoolInitInfo.whirlpoolPda; const { params, mint } = await generateDefaultOpenPositionParams( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); defaultParams = params; defaultMint = mint; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); it("successfully opens position and verify position address contents", async () => { const positionInitInfo = await openPosition( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, ); const { positionPda, positionMintAddress } = positionInitInfo.params; const position = (await fetcher.getPosition( positionPda.publicKey, )) as PositionData; assert.strictEqual(position.tickLowerIndex, tickLowerIndex); assert.strictEqual(position.tickUpperIndex, tickUpperIndex); assert.ok(position.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey)); assert.ok(position.positionMint.equals(positionMintAddress)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); // TODO: Add tests for rewards }); it("successfully open position and verify position address contents for full-range only pool", async () => { const [lowerTickIndex, upperTickIndex] = TickUtil.getFullRangeTickIndex( TickSpacing.FullRangeOnly, ); const positionInitInfo = await openPosition( ctx, fullRangeOnlyWhirlpoolPda.publicKey, lowerTickIndex, upperTickIndex, ); const { positionPda, positionMintAddress } = positionInitInfo.params; const position = (await fetcher.getPosition( positionPda.publicKey, )) as PositionData; assert.strictEqual(position.tickLowerIndex, lowerTickIndex); assert.strictEqual(position.tickUpperIndex, upperTickIndex); assert.ok( position.whirlpool.equals( fullRangeOnlyPoolInitInfo.whirlpoolPda.publicKey, ), ); assert.ok(position.positionMint.equals(positionMintAddress)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); }); it("succeeds when funder is different than account paying for transaction fee", async () => { await openPosition( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, funderKeypair, ); }); it("open position & verify position mint behavior", async () => { const newOwner = web3.Keypair.generate(); const positionInitInfo = await openPosition( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, newOwner.publicKey, ); const { positionMintAddress, positionTokenAccount: positionTokenAccountAddress, } = positionInitInfo.params; const userTokenAccount = await getAccount( ctx.connection, positionTokenAccountAddress, ); assert.ok(userTokenAccount.amount === 1n); assert.ok(userTokenAccount.owner.equals(newOwner.publicKey)); await assert.rejects( mintToDestination( provider, positionMintAddress, positionTokenAccountAddress, 1, ), /0x5/, // the total supply of this token is fixed ); }); it("user must pass the valid token ATA account", async () => { const anotherMintKey = await createMint( provider, provider.wallet.publicKey, ); const positionTokenAccountAddress = getAssociatedTokenAddressSync( anotherMintKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionIx(ctx.program, { ...defaultParams, positionTokenAccount: positionTokenAccountAddress, }), ) .addSigner(defaultMint) .buildAndExecute(), /An account required by the instruction is missing/, ); }); describe("invalid ticks", () => { async function assertTicksFail(lowerTick: number, upperTick: number) { await assert.rejects( openPosition( ctx, whirlpoolPda.publicKey, lowerTick, upperTick, provider.wallet.publicKey, funderKeypair, ), /0x177a/, // InvalidTickIndex ); } it("fail when user pass in an out of bound tick index for upper-index", async () => { await assertTicksFail(0, MAX_TICK_INDEX + 1); }); it("fail when user pass in a lower tick index that is higher than the upper-index", async () => { await assertTicksFail(-22534, -22534 - 1); }); it("fail when user pass in a lower tick index that equals the upper-index", async () => { await assertTicksFail(22365, 22365); }); it("fail when user pass in an out of bound tick index for lower-index", async () => { await assertTicksFail(MIN_TICK_INDEX - 1, 0); }); it("fail when user pass in a non-initializable tick index for upper-index", async () => { await assertTicksFail(0, 1); }); it("fail when user pass in a non-initializable tick index for lower-index", async () => { await assertTicksFail(1, 2); }); }); it("fail when position mint already exists", async () => { const positionMintKeypair = anchor.web3.Keypair.generate(); const positionPda = PDAUtil.getPosition( ctx.program.programId, positionMintKeypair.publicKey, ); const positionTokenAccountAddress = getAssociatedTokenAddressSync( positionMintKeypair.publicKey, provider.wallet.publicKey, ); const tx = new web3.Transaction(); tx.add( ...(await createMintInstructions( provider, provider.wallet.publicKey, positionMintKeypair.publicKey, )), ); await provider.sendAndConfirm(tx, [positionMintKeypair], { commitment: "confirmed", }); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionIx(ctx.program, { funder: provider.wallet.publicKey, owner: provider.wallet.publicKey, positionPda, positionMintAddress: positionMintKeypair.publicKey, positionTokenAccount: positionTokenAccountAddress, whirlpool: whirlpoolPda.publicKey, tickLowerIndex: 0, tickUpperIndex: 128, }), ) .addSigner(positionMintKeypair) .buildAndExecute(), /0x0/, ); }); it("fail when opening a non-full range position in an full-range only pool", async () => { await assert.rejects( openPosition( ctx, fullRangeOnlyWhirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, funderKeypair, ), /0x17a6/, // FullRangeOnlyPool ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/close_position.test.ts
import * as anchor from "@coral-xyz/anchor"; import { AuthorityType } from "@solana/spl-token"; import * as assert from "assert"; import { toTx, WhirlpoolIx } from "../../src"; import { WhirlpoolContext } from "../../src/context"; import { approveToken, createAndMintToTokenAccount, createTokenAccount, setAuthority, TickSpacing, transferToken, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initializePositionBundle, initTestPool, initTestPoolWithLiquidity, openBundledPosition, openPosition, } from "../utils/init-utils"; import { generateDefaultOpenPositionWithTokenExtensionsParams } from "../utils/test-builders"; describe("close_position", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); it("successfully closes an open position", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, ); const receiverKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: receiverKeypair.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(); const supplyResponse = await provider.connection.getTokenSupply( params.positionMintAddress, ); assert.equal(supplyResponse.value.uiAmount, 0); assert.equal( await provider.connection.getAccountInfo(params.positionPda.publicKey), undefined, ); assert.equal( await provider.connection.getAccountInfo(params.positionTokenAccount), undefined, ); const receiverAccount = await provider.connection.getAccountInfo( receiverKeypair.publicKey, ); const lamports = receiverAccount?.lamports; assert.ok(lamports != undefined && lamports > 0); }); it("succeeds if the position is delegated", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, ); await toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(delegate) .buildAndExecute(); }); it("succeeds with the owner's signature even if the token is delegated", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, ); await toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: owner.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(owner) .buildAndExecute(); }); it("succeeds with position token that was transferred to new owner", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: ZERO_BN }, ], }); const position = fixture.getInfos().positions[0]; const newOwner = anchor.web3.Keypair.generate(); const newOwnerPositionTokenAccount = await createTokenAccount( provider, position.mintKeypair.publicKey, newOwner.publicKey, ); await transferToken( provider, position.tokenAccount, newOwnerPositionTokenAccount, 1, ); await toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: newOwner.publicKey, receiver: newOwner.publicKey, position: position.publicKey, positionMint: position.mintKeypair.publicKey, positionTokenAccount: newOwnerPositionTokenAccount, }), ) .addSigner(newOwner) .buildAndExecute(); }); it("fails to close a position with liquidity", async () => { const { positionInfo } = await initTestPoolWithLiquidity(ctx); const receiverKeypair = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: receiverKeypair.publicKey, position: positionInfo.positionPda.publicKey, positionMint: positionInfo.positionMintAddress, positionTokenAccount: positionInfo.positionTokenAccount, }), ).buildAndExecute(), /0x1775/, // ClosePositionNotEmpty ); }); it("fails if owner is not signer", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: owner.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails if delegate is not signer", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails if the authority does not match", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const fakeOwner = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: fakeOwner.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(fakeOwner) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails if position token account does not contain exactly one token", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: ZERO_BN }, ], }); const position = fixture.getInfos().positions[0]; const fakePositionTokenAccount = await createTokenAccount( provider, position.mintKeypair.publicKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: position.publicKey, positionMint: position.mintKeypair.publicKey, positionTokenAccount: fakePositionTokenAccount, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails if delegated amount is 0", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 0, owner, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(delegate) .buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); it("fails if positionAuthority does not match delegate", async () => { const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const fakeDelegate = anchor.web3.Keypair.generate(); const { params } = await openPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, 0, 128, owner.publicKey, ); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: fakeDelegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(fakeDelegate) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails if position token account mint does not match position mint", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: ZERO_BN }, ], }); const { poolInitInfo: { tokenMintA }, positions, } = fixture.getInfos(); const position = positions[0]; const fakePositionTokenAccount = await createAndMintToTokenAccount( provider, tokenMintA, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: position.publicKey, positionMint: position.mintKeypair.publicKey, positionTokenAccount: fakePositionTokenAccount, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails if position_mint does not match position's position_mint field", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: ZERO_BN }, ], }); const { poolInitInfo: { tokenMintA }, positions, } = fixture.getInfos(); const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: position.publicKey, positionMint: tokenMintA, positionTokenAccount: position.tokenAccount, }), ).buildAndExecute(), // Seeds constraint added by adding PositionBundle, so ConstraintSeeds will be violated first /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); describe("bundled position and TokenExtensions based position", () => { it("fails if position is BUNDLED position", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [], }); const { poolInitInfo } = fixture.getInfos(); // open bundled position const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, 0, 128, ); // try to close bundled position await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: positionInitInfo.params.bundledPositionPda.publicKey, positionMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionTokenAccount: positionBundleInfo.positionBundleTokenAccount, }), ).buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("fails if position is TokenExtensions based position", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [], }); const { poolInitInfo } = fixture.getInfos(); // open position with TokenExtensions const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, poolInitInfo.whirlpoolPda.publicKey, true, 0, poolInitInfo.tickSpacing, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); // try to close bundled position await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(), /0xbbf/, // AccountOwnedByWrongProgram (Mint and TokenAccount must be owned by TokenProgram (but owned by Token-2022 program)) ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_protocol_fee_rate.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("set_protocol_fee_rate", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully sets_protocol_fee_rate", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newProtocolFeeRate = 50; let whirlpool = (await fetcher.getPool( whirlpoolKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal( whirlpool.protocolFeeRate, configInitInfo.defaultProtocolFeeRate, ); const txBuilder = toTx( ctx, WhirlpoolIx.setProtocolFeeRateIx(program, { whirlpool: whirlpoolKey, whirlpoolsConfig: whirlpoolsConfigKey, feeAuthority: feeAuthorityKeypair.publicKey, protocolFeeRate: newProtocolFeeRate, }), ).addSigner(feeAuthorityKeypair); await txBuilder.buildAndExecute(); whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.equal(whirlpool.protocolFeeRate, newProtocolFeeRate); }); it("fails when protocol fee rate exceeds max", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newProtocolFeeRate = 3_000; await assert.rejects( toTx( ctx, WhirlpoolIx.setProtocolFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, protocolFeeRate: newProtocolFeeRate, }), ) .addSigner(configKeypairs.feeAuthorityKeypair) .buildAndExecute(), /0x178d/, // ProtocolFeeRateMaxExceeded ); }); it("fails when fee authority is not signer", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const whirlpoolsConfigKey = configInitInfo.whirlpoolsConfigKeypair.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const newProtocolFeeRate = 1000; await assert.rejects( toTx( ctx, WhirlpoolIx.setProtocolFeeRateIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, protocolFeeRate: newProtocolFeeRate, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when whirlpool and whirlpools config don't match", async () => { const { poolInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const feeAuthorityKeypair = configKeypairs.feeAuthorityKeypair; const { configInitInfo: otherConfigInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, otherConfigInitInfo), ).buildAndExecute(); const newProtocolFeeRate = 1000; await assert.rejects( ctx.program.rpc.setProtocolFeeRate(newProtocolFeeRate, { accounts: { whirlpoolsConfig: otherConfigInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolKey, feeAuthority: feeAuthorityKeypair.publicKey, }, signers: [configKeypairs.feeAuthorityKeypair], }), // message have been changed // https://github.com/coral-xyz/anchor/pull/2101/files#diff-e564d6832afe5358ef129e96970ba1e5180b5e74aba761831e1923c06d7b839fR412 /A has[_ ]one constraint was violated/, // ConstraintHasOne ); }); it("fails when fee authority is invalid", async () => { const { poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey; const fakeAuthorityKeypair = anchor.web3.Keypair.generate(); const newProtocolFeeRate = 1000; await assert.rejects( ctx.program.rpc.setProtocolFeeRate(newProtocolFeeRate, { accounts: { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolKey, feeAuthority: fakeAuthorityKeypair.publicKey, }, signers: [fakeAuthorityKeypair], }), /An address constraint was violated/, // ConstraintAddress ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_fee_tier.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { FeeTierData } from "../../src"; import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { ONE_SOL, systemTransferTx, TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initFeeTier } from "../utils/init-utils"; import { generateDefaultConfigParams, generateDefaultInitFeeTierParams, } from "../utils/test-builders"; describe("initialize_fee_tier", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully init a FeeRate stable account", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const testTickSpacing = TickSpacing.Stable; const { params } = await initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, testTickSpacing, 800, ); const generatedPda = PDAUtil.getFeeTier( ctx.program.programId, configInitInfo.whirlpoolsConfigKeypair.publicKey, testTickSpacing, ); const feeTierAccount = (await fetcher.getFeeTier( generatedPda.publicKey, )) as FeeTierData; assert.ok(feeTierAccount.tickSpacing == params.tickSpacing); assert.ok(feeTierAccount.defaultFeeRate == params.defaultFeeRate); }); it("successfully init a FeeRate standard account", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const testTickSpacing = TickSpacing.Standard; const { params } = await initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, testTickSpacing, 3000, ); const feeTierAccount = (await fetcher.getFeeTier( params.feeTierPda.publicKey, )) as FeeTierData; assert.ok(feeTierAccount.tickSpacing == params.tickSpacing); assert.ok(feeTierAccount.defaultFeeRate == params.defaultFeeRate); }); it("successfully init a FeeRate max account", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const testTickSpacing = TickSpacing.Standard; const { params } = await initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, testTickSpacing, 30_000, // 3 % ); const feeTierAccount = (await fetcher.getFeeTier( params.feeTierPda.publicKey, )) as FeeTierData; assert.ok(feeTierAccount.tickSpacing == params.tickSpacing); assert.ok(feeTierAccount.defaultFeeRate == params.defaultFeeRate); assert.ok(params.defaultFeeRate === 30_000); }); it("successfully init a FeeRate with another funder wallet", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const funderKeypair = anchor.web3.Keypair.generate(); await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); await initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, TickSpacing.Stable, 3000, funderKeypair, ); }); it("fails when default fee rate exceeds max", async () => { const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( initFeeTier( ctx, configInitInfo, configKeypairs.feeAuthorityKeypair, TickSpacing.Stable, 30_000 + 1, ), /0x178c/, // FeeRateMaxExceeded ); }); it("fails when fee authority is not a signer", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.initializeFeeTierIx( ctx.program, generateDefaultInitFeeTierParams( ctx, configInitInfo.whirlpoolsConfigKeypair.publicKey, configInitInfo.feeAuthority, TickSpacing.Stable, 3000, ), ), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when invalid fee authority provided", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const fakeFeeAuthorityKeypair = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.initializeFeeTierIx( ctx.program, generateDefaultInitFeeTierParams( ctx, configInitInfo.whirlpoolsConfigKeypair.publicKey, fakeFeeAuthorityKeypair.publicKey, TickSpacing.Stable, 3000, ), ), ) .addSigner(fakeFeeAuthorityKeypair) .buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_reward_authority_by_super_authority.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { TickSpacing } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool } from "../utils/init-utils"; describe("set_reward_authority_by_super_authority", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_reward_authority_by_super_authority", async () => { const { configKeypairs, poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const newAuthorityKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardEmissionsSuperAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: newAuthorityKeypair.publicKey, rewardIndex: 0, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(); const pool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, )) as WhirlpoolData; assert.ok( pool.rewardInfos[0].authority.equals(newAuthorityKeypair.publicKey), ); }); it("fails if invalid whirlpool provided", async () => { const { configKeypairs, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const { poolInitInfo: { whirlpoolPda: invalidPool }, } = await initTestPool(ctx, TickSpacing.Standard); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: invalidPool.publicKey, rewardEmissionsSuperAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: provider.wallet.publicKey, rewardIndex: 0, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0x7d1/, // A has_one constraint was violated ); }); it("fails if invalid super authority provided", async () => { const { poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); const invalidSuperAuthorityKeypair = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardEmissionsSuperAuthority: invalidSuperAuthorityKeypair.publicKey, newRewardAuthority: provider.wallet.publicKey, rewardIndex: 0, }), ) .addSigner(invalidSuperAuthorityKeypair) .buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); it("fails if super authority is not a signer", async () => { const { configKeypairs, poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardEmissionsSuperAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: provider.wallet.publicKey, rewardIndex: 0, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails on invalid reward index", async () => { const { configKeypairs, poolInitInfo, configInitInfo } = await initTestPool( ctx, TickSpacing.Standard, ); assert.throws(() => { toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardEmissionsSuperAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: provider.wallet.publicKey, rewardIndex: -1, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(); }, /out of range/); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardAuthorityBySuperAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardEmissionsSuperAuthority: configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey, newRewardAuthority: provider.wallet.publicKey, rewardIndex: 200, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0x178a/, // InvalidRewardIndex ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/close_position_with_token_extensions.test.ts
import * as anchor from "@coral-xyz/anchor"; import { AuthorityType, createCloseAccountInstruction, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import * as assert from "assert"; import { IGNORE_CACHE, increaseLiquidityQuoteByLiquidityWithParams, NO_TOKEN_EXTENSION_CONTEXT, PDAUtil, TickUtil, toTx, WhirlpoolIx, } from "../../src"; import type { InitPoolParams } from "../../src"; import { WhirlpoolContext } from "../../src/context"; import { approveToken, createTokenAccount, mintToDestination, ONE_SOL, setAuthority, systemTransferTx, TickSpacing, transferToken, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initializePositionBundle, initTestPool, initTickArray, openBundledPosition, openPosition, } from "../utils/init-utils"; import { Percentage } from "@orca-so/common-sdk"; import type { PDA } from "@orca-so/common-sdk"; import { generateDefaultOpenPositionWithTokenExtensionsParams } from "../utils/test-builders"; import type { PublicKey } from "@solana/web3.js"; import { createTokenAccountV2 } from "../utils/v2/token-2022"; describe("close_position_with_token_extensions", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const tickLowerIndex = 0; const tickUpperIndex = 11392; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); async function getRent(address: PublicKey): Promise<number> { const rent = (await ctx.connection.getAccountInfo(address))?.lamports; assert.ok(rent !== undefined); return rent; } async function checkClosed(address: PublicKey): Promise<void> { assert.equal(await provider.connection.getAccountInfo(address), undefined); } describe("successfully closes an open position", () => { [true, false].map((withMetadata) => { it(`successfully closes an open position ${withMetadata ? "with" : "without"} metadata`, async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, withMetadata, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); const rentPosition = await getRent(params.positionPda.publicKey); const rentMint = await getRent(params.positionMint); const rentTokenAccount = await getRent(params.positionTokenAccount); const rent = rentPosition + rentMint + rentTokenAccount; assert.ok(rent > 0); const receiverKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: receiverKeypair.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(); // Position account should be closed await checkClosed(params.positionPda.publicKey); // Mint and TokenAccount should be closed await checkClosed(params.positionMint); await checkClosed(params.positionTokenAccount); const receiverAccount = await provider.connection.getAccountInfo( receiverKeypair.publicKey, ); const lamports = receiverAccount?.lamports; assert.ok(lamports === rent); }); }); }); it("succeeds if the position is delegated", async () => { const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, TOKEN_2022_PROGRAM_ID, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, TOKEN_2022_PROGRAM_ID, ); // check delegation const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!tokenAccount); assert.ok(tokenAccount.delegate?.equals(delegate.publicKey)); assert.ok(tokenAccount.delegatedAmount === 1n); assert.ok(tokenAccount.closeAuthority?.equals(delegate.publicKey)); // needed to close token account by delegate await toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ) // sign with delegate .addSigner(delegate) .buildAndExecute(); await Promise.all([ checkClosed(params.positionPda.publicKey), checkClosed(params.positionMint), checkClosed(params.positionTokenAccount), ]); }); it("succeeds with the owner's signature even if the token is delegated", async () => { const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, TOKEN_2022_PROGRAM_ID, ); // check delegation const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!tokenAccount); assert.ok(tokenAccount.delegate?.equals(delegate.publicKey)); assert.ok(tokenAccount.delegatedAmount === 1n); assert.ok(!tokenAccount.closeAuthority); // no close authority await toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: owner.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ) // sign with owner .addSigner(owner) .buildAndExecute(); await Promise.all([ checkClosed(params.positionPda.publicKey), checkClosed(params.positionMint), checkClosed(params.positionTokenAccount), ]); }); it("succeeds with position token that was transferred to new owner", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); const newOwner = anchor.web3.Keypair.generate(); const newOwnerPositionTokenAccount = await createTokenAccountV2( provider, { isToken2022: true }, mint.publicKey, newOwner.publicKey, ); await transferToken( provider, params.positionTokenAccount, newOwnerPositionTokenAccount, 1, TOKEN_2022_PROGRAM_ID, ); // check transfer const oldOwnerTokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!oldOwnerTokenAccount); assert.ok(oldOwnerTokenAccount.amount === 0n); const newOwnerTokenAccount = await fetcher.getTokenInfo( newOwnerPositionTokenAccount, IGNORE_CACHE, ); assert.ok(!!newOwnerTokenAccount); assert.ok(newOwnerTokenAccount.amount === 1n); await toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: newOwner.publicKey, receiver: newOwner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: newOwnerPositionTokenAccount, }), ) // sign with new owner .addSigner(newOwner) .buildAndExecute(); await Promise.all([ checkClosed(params.positionPda.publicKey), checkClosed(params.positionMint), checkClosed(newOwnerPositionTokenAccount), ]); // check original token account const oldOwnerTokenAccountAfter = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!oldOwnerTokenAccountAfter); assert.ok(oldOwnerTokenAccountAfter.amount === 0n); // closing token account should be possible even if Mint have been closed. await toTx(ctx, { instructions: [ createCloseAccountInstruction( params.positionTokenAccount, ctx.wallet.publicKey, ctx.wallet.publicKey, [], TOKEN_2022_PROGRAM_ID, ), ], cleanupInstructions: [], signers: [], }).buildAndExecute(); await checkClosed(params.positionTokenAccount); }); it("fails to close a position with liquidity", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); // add liquidity const pool = await fetcher.getPool(whirlpoolPda.publicKey, IGNORE_CACHE); const quote = increaseLiquidityQuoteByLiquidityWithParams({ liquidity: new anchor.BN(100000), slippageTolerance: Percentage.fromFraction(0, 1000), sqrtPrice: pool!.sqrtPrice, tickCurrentIndex: pool!.tickCurrentIndex, tickLowerIndex, tickUpperIndex, tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, }); const tokenOwnerAccountA = await createTokenAccount( provider, pool!.tokenMintA, provider.wallet.publicKey, ); await mintToDestination( provider, pool!.tokenMintA, tokenOwnerAccountA, quote.tokenMaxA, ); const tokenOwnerAccountB = await createTokenAccount( provider, pool!.tokenMintB, provider.wallet.publicKey, ); await mintToDestination( provider, pool!.tokenMintB, tokenOwnerAccountB, quote.tokenMaxB, ); const lowerStartTickIndex = TickUtil.getStartTickIndex( tickLowerIndex, pool!.tickSpacing, ); const upperStartTickIndex = TickUtil.getStartTickIndex( tickUpperIndex, pool!.tickSpacing, ); await initTickArray(ctx, whirlpoolPda.publicKey, lowerStartTickIndex); await initTickArray(ctx, whirlpoolPda.publicKey, upperStartTickIndex); await toTx( ctx, WhirlpoolIx.increaseLiquidityIx(ctx.program, { ...quote, position: params.positionPda.publicKey, positionAuthority: ctx.wallet.publicKey, positionTokenAccount: params.positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, whirlpool: whirlpoolPda.publicKey, tokenVaultA: pool!.tokenVaultA, tokenVaultB: pool!.tokenVaultB, tickArrayLower: PDAUtil.getTickArray( ctx.program.programId, whirlpoolPda.publicKey, lowerStartTickIndex, ).publicKey, tickArrayUpper: PDAUtil.getTickArray( ctx.program.programId, whirlpoolPda.publicKey, upperStartTickIndex, ).publicKey, }), ).buildAndExecute(); // check liquidity (not zero) const position = await fetcher.getPosition( params.positionPda.publicKey, IGNORE_CACHE, ); assert.ok(position!.liquidity.gtn(0)); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(), /0x1775/, // ClosePositionNotEmpty ); }); it("fails if owner is not signer", async () => { const owner = anchor.web3.Keypair.generate(); const receiver = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); const ix = WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: owner.publicKey, receiver: receiver.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }).instructions[0]; // drop isSigner flag const keysWithoutSign = ix.keys.map((key) => { if (key.pubkey.equals(owner.publicKey)) { return { pubkey: key.pubkey, isSigner: false, isWritable: key.isWritable, }; } return key; }); const ixWithoutSign = { ...ix, keys: keysWithoutSign, }; await assert.rejects( toTx(ctx, { instructions: [ixWithoutSign], cleanupInstructions: [], signers: [], }) // no signature of owner .buildAndExecute(), /0xbc2/, // AccountNotSigner ); }); it("fails if delegate is not signer", async () => { const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const receiver = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, TOKEN_2022_PROGRAM_ID, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, TOKEN_2022_PROGRAM_ID, ); // check delegation const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!tokenAccount); assert.ok(tokenAccount.delegate?.equals(delegate.publicKey)); assert.ok(tokenAccount.delegatedAmount === 1n); assert.ok(tokenAccount.closeAuthority?.equals(delegate.publicKey)); // needed to close token account by delegate const ix = WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: receiver.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }).instructions[0]; // drop isSigner flag const keysWithoutSign = ix.keys.map((key) => { if (key.pubkey.equals(delegate.publicKey)) { return { pubkey: key.pubkey, isSigner: false, isWritable: key.isWritable, }; } return key; }); const ixWithoutSign = { ...ix, keys: keysWithoutSign, }; await assert.rejects( toTx(ctx, { instructions: [ixWithoutSign], cleanupInstructions: [], signers: [], }) // no signature of delegate .buildAndExecute(), /0xbc2/, // AccountNotSigner ); }); it("fails if the authority does not match", async () => { const owner = anchor.web3.Keypair.generate(); const fakeOwner = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: fakeOwner.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(fakeOwner) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails if position token account does not contain exactly one token", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); // not ATA const fakePositionTokenAccount = await createTokenAccountV2( provider, { isToken2022: true }, mint.publicKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: fakePositionTokenAccount, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails if delegated amount is 0", async () => { const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 0, // 0 amount owner, TOKEN_2022_PROGRAM_ID, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, TOKEN_2022_PROGRAM_ID, ); // check delegation (delegated, but 0 amount) const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!tokenAccount); assert.ok(tokenAccount.delegate?.equals(delegate.publicKey)); assert.ok(tokenAccount.delegatedAmount === 0n); assert.ok(tokenAccount.closeAuthority?.equals(delegate.publicKey)); // needed to close token account by delegate await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: delegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(delegate) .buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); it("fails if positionAuthority does not match delegate", async () => { const owner = anchor.web3.Keypair.generate(); const delegate = anchor.web3.Keypair.generate(); const fakeDelegate = anchor.web3.Keypair.generate(); const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, owner.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); await approveToken( ctx.provider, params.positionTokenAccount, delegate.publicKey, 1, owner, TOKEN_2022_PROGRAM_ID, ); await setAuthority( ctx.provider, params.positionTokenAccount, delegate.publicKey, AuthorityType.CloseAccount, owner, TOKEN_2022_PROGRAM_ID, ); // check delegation const tokenAccount = await fetcher.getTokenInfo( params.positionTokenAccount, IGNORE_CACHE, ); assert.ok(!!tokenAccount); assert.ok(tokenAccount.delegate?.equals(delegate.publicKey)); assert.ok(tokenAccount.delegatedAmount === 1n); assert.ok(tokenAccount.closeAuthority?.equals(delegate.publicKey)); // needed to close token account by delegate await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: fakeDelegate.publicKey, receiver: owner.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }), ) .addSigner(fakeDelegate) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails if position token account mint does not match position mint", async () => { const { params: params1, mint: mint1 } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params1), ) .addSigner(mint1) .buildAndExecute(); const { params: params2, mint: mint2 } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params2), ) .addSigner(mint2) .buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params1.positionPda.publicKey, positionMint: params1.positionMint, positionTokenAccount: params2.positionTokenAccount, // params2 (fake) }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails if position_mint does not match position's position_mint field", async () => { const { params: params1, mint: mint1 } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params1), ) .addSigner(mint1) .buildAndExecute(); const { params: params2, mint: mint2 } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params2), ) .addSigner(mint2) .buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params1.positionPda.publicKey, positionMint: params2.positionMint, // params2 (fake) positionTokenAccount: params1.positionTokenAccount, }), ).buildAndExecute(), // Seeds constraint added by adding PositionBundle, so ConstraintSeeds will be violated first /0x7d6/, // ConstraintSeeds (seed constraint was violated) ); }); it("fails if token program is invalid", async () => { const { params, mint } = await generateDefaultOpenPositionWithTokenExtensionsParams( ctx, whirlpoolPda.publicKey, true, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params), ) .addSigner(mint) .buildAndExecute(); const ix = WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMint, positionTokenAccount: params.positionTokenAccount, }).instructions[0]; const ixWithWrongAccount = { ...ix, keys: ix.keys.map((key) => { if (key.pubkey.equals(TOKEN_2022_PROGRAM_ID)) { return { ...key, pubkey: TOKEN_PROGRAM_ID }; } return key; }), }; await assert.rejects( toTx(ctx, { instructions: [ixWithWrongAccount], cleanupInstructions: [], signers: [], }).buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); describe("TokenProgram based position and bundled position", () => { it("fails if position is TokenProgram based position", async () => { // TokenProgram based poition const { params } = await openPosition( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, ctx.wallet.publicKey, ); // try to close TokenProgram based position await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: params.positionPda.publicKey, positionMint: params.positionMintAddress, positionTokenAccount: params.positionTokenAccount, }), ).buildAndExecute(), /0x7d4/, // ConstraintOwner (The owner of Mint account must be Token-2022) ); }); it("fails if position is BUNDLED position", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, positions: [], }); const { poolInitInfo } = fixture.getInfos(); // open bundled position const positionBundleInfo = await initializePositionBundle(ctx); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, poolInitInfo.whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, 0, 128, ); // try to close bundled position await assert.rejects( toTx( ctx, WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, { positionAuthority: provider.wallet.publicKey, receiver: provider.wallet.publicKey, position: positionInitInfo.params.bundledPositionPda.publicKey, positionMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionTokenAccount: positionBundleInfo.positionBundleTokenAccount, }), ).buildAndExecute(), /0x7d6/, // ConstraintSeeds (seed constraint was violated because BundledPosition uses different seeds) ); }); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_collect_protocol_fee_authority.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolsConfigData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { defaultConfirmOptions } from "../utils/const"; import { generateDefaultConfigParams } from "../utils/test-builders"; describe("set_collect_protocol_fee_authority", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully set_collect_protocol_fee_authority", async () => { const { configInitInfo, configKeypairs: { collectProtocolFeesAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); const newAuthorityKeypair = anchor.web3.Keypair.generate(); await toTx( ctx, WhirlpoolIx.setCollectProtocolFeesAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, newCollectProtocolFeesAuthority: newAuthorityKeypair.publicKey, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(); const config = (await fetcher.getConfig( configInitInfo.whirlpoolsConfigKeypair.publicKey, )) as WhirlpoolsConfigData; assert.ok( config.collectProtocolFeesAuthority.equals(newAuthorityKeypair.publicKey), ); }); it("fails if current collect_protocol_fee_authority is not a signer", async () => { const { configInitInfo, configKeypairs: { collectProtocolFeesAuthorityKeypair }, } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.setCollectProtocolFeesAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, newCollectProtocolFeesAuthority: provider.wallet.publicKey, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails if invalid collect_protocol_fee_authority provided", async () => { const { configInitInfo } = generateDefaultConfigParams(ctx); await toTx( ctx, WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo), ).buildAndExecute(); await assert.rejects( toTx( ctx, WhirlpoolIx.setCollectProtocolFeesAuthorityIx(ctx.program, { whirlpoolsConfig: configInitInfo.whirlpoolsConfigKeypair.publicKey, collectProtocolFeesAuthority: provider.wallet.publicKey, newCollectProtocolFeesAuthority: provider.wallet.publicKey, }), ).buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/decrease_liquidity.test.ts
import * as anchor from "@coral-xyz/anchor"; import { MathUtil, Percentage } from "@orca-so/common-sdk"; import * as assert from "assert"; import BN from "bn.js"; import Decimal from "decimal.js"; import type { PositionData, TickArrayData, WhirlpoolData } from "../../src"; import { WhirlpoolContext, WhirlpoolIx, toTx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { decreaseLiquidityQuoteByLiquidityWithParams } from "../../src/quotes/public/decrease-liquidity-quote"; import { TickSpacing, ZERO_BN, approveToken, assertTick, createAndMintToTokenAccount, createMint, createTokenAccount, sleep, transferToken, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initTestPool, initTickArray, openPosition } from "../utils/init-utils"; import { TokenExtensionUtil } from "../../src/utils/public/token-extension-util"; describe("decrease_liquidity", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully decrease liquidity from position in one tick array", async () => { const liquidityAmount = new anchor.BN(1_250_000); const tickLower = 7168, tickUpper = 8960; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)), positions: [ { tickLowerIndex: tickLower, tickUpperIndex: tickUpper, liquidityAmount, }, ], }); const { poolInitInfo, tokenAccountA, tokenAccountB, positions } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const poolBefore = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; // To check if rewardLastUpdatedTimestamp is updated await sleep(1200); const removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({ liquidity: new anchor.BN(1_000_000), sqrtPrice: poolBefore.sqrtPrice, slippageTolerance: Percentage.fromFraction(1, 100), tickCurrentIndex: poolBefore.tickCurrentIndex, tickLowerIndex: tickLower, tickUpperIndex: tickUpper, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( fetcher, poolBefore, IGNORE_CACHE, ), }); await toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { ...removalQuote, whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: positions[0].tickArrayLower, tickArrayUpper: positions[0].tickArrayUpper, }), ).buildAndExecute(); const remainingLiquidity = liquidityAmount.sub( removalQuote.liquidityAmount, ); const poolAfter = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok( poolAfter.rewardLastUpdatedTimestamp.gt( poolBefore.rewardLastUpdatedTimestamp, ), ); assert.ok(poolAfter.liquidity.eq(remainingLiquidity)); const position = await fetcher.getPosition( positions[0].publicKey, IGNORE_CACHE, ); assert.ok(position?.liquidity.eq(remainingLiquidity)); const tickArray = (await fetcher.getTickArray( positions[0].tickArrayLower, IGNORE_CACHE, )) as TickArrayData; assertTick( tickArray.ticks[56], true, remainingLiquidity, remainingLiquidity, ); assertTick( tickArray.ticks[70], true, remainingLiquidity, remainingLiquidity.neg(), ); }); it("successfully decrease liquidity from position in two tick arrays", async () => { const liquidityAmount = new anchor.BN(1_250_000); const tickLower = -1280, tickUpper = 1280; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const position = positions[0]; const poolBefore = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; const removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({ liquidity: new anchor.BN(1_000_000), sqrtPrice: poolBefore.sqrtPrice, slippageTolerance: Percentage.fromFraction(1, 100), tickCurrentIndex: poolBefore.tickCurrentIndex, tickLowerIndex: tickLower, tickUpperIndex: tickUpper, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( fetcher, poolBefore, IGNORE_CACHE, ), }); await toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { ...removalQuote, whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(); const remainingLiquidity = liquidityAmount.sub( removalQuote.liquidityAmount, ); const poolAfter = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok( poolAfter.rewardLastUpdatedTimestamp.gte( poolBefore.rewardLastUpdatedTimestamp, ), ); assert.ok(poolAfter.liquidity.eq(remainingLiquidity)); const positionAfter = (await fetcher.getPosition( position.publicKey, IGNORE_CACHE, )) as PositionData; assert.ok(positionAfter.liquidity.eq(remainingLiquidity)); const tickArrayLower = (await fetcher.getTickArray( position.tickArrayLower, IGNORE_CACHE, )) as TickArrayData; assertTick( tickArrayLower.ticks[78], true, remainingLiquidity, remainingLiquidity, ); const tickArrayUpper = (await fetcher.getTickArray( position.tickArrayUpper, IGNORE_CACHE, )) as TickArrayData; assertTick( tickArrayUpper.ticks[10], true, remainingLiquidity, remainingLiquidity.neg(), ); }); it("successfully decrease liquidity with approved delegate", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000); await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000); const removeAmount = new anchor.BN(1_000_000); await toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount: removeAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ) .addSigner(delegate) .buildAndExecute(); }); it("successfully decrease liquidity with owner even if there is approved delegate", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000); await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000); const removeAmount = new anchor.BN(1_000_000); await toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount: removeAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(); }); it("successfully decrease liquidity with transferred position token", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const removeAmount = new anchor.BN(1_000_000); const newOwner = anchor.web3.Keypair.generate(); const newOwnerPositionTokenAccount = await createTokenAccount( provider, position.mintKeypair.publicKey, newOwner.publicKey, ); await transferToken( provider, position.tokenAccount, newOwnerPositionTokenAccount, 1, ); await toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount: removeAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: newOwner.publicKey, position: position.publicKey, positionTokenAccount: newOwnerPositionTokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ) .addSigner(newOwner) .buildAndExecute(); }); it("fails when liquidity amount is zero", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount: new anchor.BN(0), tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x177c/, // LiquidityZero ); }); it("fails when position has insufficient liquidity for the withdraw amount", async () => { const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(1)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount: ZERO_BN, }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount: new anchor.BN(1_000), tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x177f/, // LiquidityUnderflow ); }); it("fails when token min a subceeded", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(0.005)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(1_000_000), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x1782/, // TokenMinSubceeded ); }); it("fails when token min b subceeded", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(5)), positions: [ { tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } = poolInitInfo; const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(1_000_000), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x1782/, // TokenMinSubceeded ); }); it("fails when position account does not have exactly 1 token", async () => { const liquidityAmount = new anchor.BN(1_250_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; // Create a position token account that contains 0 tokens const newPositionTokenAccount = await createTokenAccount( provider, positions[0].mintKeypair.publicKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: newPositionTokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); // Send position token to other position token account await transferToken( provider, position.tokenAccount, newPositionTokenAccount, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when position token account mint does not match position mint", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenMintA } = poolInitInfo; const position = positions[0]; const invalidPositionTokenAccount = await createAndMintToTokenAccount( provider, tokenMintA, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: invalidPositionTokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // A raw constraint was violated ); }); it("fails when position does not match whirlpool", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const tickArray = positions[0].tickArrayLower; const { poolInitInfo: poolInitInfo2 } = await initTestPool( ctx, TickSpacing.Standard, ); const { params: { positionPda, positionTokenAccount: positionTokenAccountAddress, }, } = await openPosition( ctx, poolInitInfo2.whirlpoolPda.publicKey, 7168, 8960, ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positionPda.publicKey, positionTokenAccount: positionTokenAccountAddress, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: tickArray, tickArrayUpper: tickArray, }), ).buildAndExecute(), /0x7d1/, // A has_one constraint was violated ); }); it("fails when token vaults do not match whirlpool vaults", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo; const position = positions[0]; const fakeVaultA = await createAndMintToTokenAccount( provider, tokenMintA, 1_000, ); const fakeVaultB = await createAndMintToTokenAccount( provider, tokenMintB, 1_000, ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: fakeVaultA, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: fakeVaultB, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when owner token account mint does not match whirlpool token mint", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const invalidMint = await createMint(provider); const invalidTokenAccount = await createAndMintToTokenAccount( provider, invalidMint, 1_000_000, ); const position = positions[0]; await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: invalidTokenAccount, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: invalidTokenAccount, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when position authority is not approved delegate for position token account", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000); await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ) .addSigner(delegate) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails when position authority is not authorized for exactly 1 token", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken(provider, position.tokenAccount, delegate.publicKey, 0); await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000); await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ) .addSigner(delegate) .buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); it("fails when position authority was not a signer", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken(provider, position.tokenAccount, delegate.publicKey, 1); await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000); await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(167_000), whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: position.tickArrayLower, tickArrayUpper: position.tickArrayUpper, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when tick arrays do not match the position", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const { params: { tickArrayPda: tickArrayLowerPda }, } = await initTickArray(ctx, whirlpoolPda.publicKey, 11264); const { params: { tickArrayPda: tickArrayUpperPda }, } = await initTickArray(ctx, whirlpoolPda.publicKey, 22528); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: tickArrayLowerPda.publicKey, tickArrayUpper: tickArrayUpperPda.publicKey, }), ).buildAndExecute(), /0x1779/, // TicKNotFound ); }); it("fails when the tick arrays are for a different whirlpool", async () => { const liquidityAmount = new anchor.BN(6_500_000); const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing: TickSpacing.Standard, initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)), positions: [ { tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount }, ], }); const { poolInitInfo, positions, tokenAccountA, tokenAccountB } = fixture.getInfos(); const { whirlpoolPda } = poolInitInfo; const position = positions[0]; const { poolInitInfo: poolInitInfo2 } = await initTestPool( ctx, TickSpacing.Standard, ); const { params: { tickArrayPda: tickArrayLowerPda }, } = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, -11264); const { params: { tickArrayPda: tickArrayUpperPda }, } = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0); await assert.rejects( toTx( ctx, WhirlpoolIx.decreaseLiquidityIx(ctx.program, { liquidityAmount, tokenMinA: new BN(0), tokenMinB: new BN(0), whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey, tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey, tickArrayLower: tickArrayLowerPda.publicKey, tickArrayUpper: tickArrayUpperPda.publicKey, }), ).buildAndExecute(), /0x7d1/, // A has one constraint was violated ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/collect_fees.test.ts
import * as anchor from "@coral-xyz/anchor"; import { BN } from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import * as assert from "assert"; import Decimal from "decimal.js"; import type { PositionData, TickArrayData, WhirlpoolData } from "../../src"; import { collectFeesQuote, PDAUtil, TickArrayUtil, toTx, WhirlpoolContext, WhirlpoolIx, } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { approveToken, createTokenAccount, getTokenBalance, TickSpacing, transferToken, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initTestPool } from "../utils/init-utils"; import { TokenExtensionUtil } from "../../src/utils/public/token-extension-util"; describe("collect_fees", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully collect fees", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, // In range position { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: new anchor.BN(1_000_000), }, // Out of range position ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const tickArrayPda = PDAUtil.getTickArray( ctx.program.programId, whirlpoolPda.publicKey, 22528, ); const positionBeforeSwap = (await fetcher.getPosition( positions[0].publicKey, )) as PositionData; assert.ok(positionBeforeSwap.feeOwedA.eq(ZERO_BN)); assert.ok(positionBeforeSwap.feeOwedB.eq(ZERO_BN)); const oraclePda = PDAUtil.getOracle( ctx.program.programId, whirlpoolPda.publicKey, ); // Accrue fees in token A await toTx( ctx, WhirlpoolIx.swapIx(ctx.program, { amount: new BN(200_000), otherAmountThreshold: ZERO_BN, sqrtPriceLimit: MathUtil.toX64(new Decimal(4)), amountSpecifiedIsInput: true, aToB: true, whirlpool: whirlpoolPda.publicKey, tokenAuthority: ctx.wallet.publicKey, tokenOwnerAccountA: tokenAccountA, tokenVaultA: tokenVaultAKeypair.publicKey, tokenOwnerAccountB: tokenAccountB, tokenVaultB: tokenVaultBKeypair.publicKey, tickArray0: tickArrayPda.publicKey, tickArray1: tickArrayPda.publicKey, tickArray2: tickArrayPda.publicKey, oracle: oraclePda.publicKey, }), ).buildAndExecute(); // Accrue fees in token B await toTx( ctx, WhirlpoolIx.swapIx(ctx.program, { amount: new BN(200_000), otherAmountThreshold: ZERO_BN, sqrtPriceLimit: MathUtil.toX64(new Decimal(5)), amountSpecifiedIsInput: true, aToB: false, whirlpool: whirlpoolPda.publicKey, tokenAuthority: ctx.wallet.publicKey, tokenOwnerAccountA: tokenAccountA, tokenVaultA: tokenVaultAKeypair.publicKey, tokenOwnerAccountB: tokenAccountB, tokenVaultB: tokenVaultBKeypair.publicKey, tickArray0: tickArrayPda.publicKey, tickArray1: tickArrayPda.publicKey, tickArray2: tickArrayPda.publicKey, oracle: oraclePda.publicKey, }), ).buildAndExecute(); await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[0].publicKey, tickArrayLower: tickArrayPda.publicKey, tickArrayUpper: tickArrayPda.publicKey, }), ).buildAndExecute(); const positionBeforeCollect = (await fetcher.getPosition( positions[0].publicKey, IGNORE_CACHE, )) as PositionData; assert.ok(positionBeforeCollect.feeOwedA.eq(new BN(581))); assert.ok(positionBeforeCollect.feeOwedB.eq(new BN(581))); const feeAccountA = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); const feeAccountB = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); // Generate collect fees expectation const whirlpoolData = (await fetcher.getPool( whirlpoolPda.publicKey, )) as WhirlpoolData; const tickArrayData = (await fetcher.getTickArray( tickArrayPda.publicKey, )) as TickArrayData; const lowerTick = TickArrayUtil.getTickFromArray( tickArrayData, tickLowerIndex, tickSpacing, ); const upperTick = TickArrayUtil.getTickFromArray( tickArrayData, tickUpperIndex, tickSpacing, ); const expectation = collectFeesQuote({ whirlpool: whirlpoolData, position: positionBeforeCollect, tickLower: lowerTick, tickUpper: upperTick, tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext( fetcher, whirlpoolData, IGNORE_CACHE, ), }); // Perform collect fees tx await toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: feeAccountA, tokenOwnerAccountB: feeAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(); const positionAfter = (await fetcher.getPosition( positions[0].publicKey, IGNORE_CACHE, )) as PositionData; const feeBalanceA = await getTokenBalance(provider, feeAccountA); const feeBalanceB = await getTokenBalance(provider, feeAccountB); assert.equal(feeBalanceA, expectation.feeOwedA); assert.equal(feeBalanceB, expectation.feeOwedB); assert.ok(positionAfter.feeOwedA.eq(ZERO_BN)); assert.ok(positionAfter.feeOwedB.eq(ZERO_BN)); // Assert out of range position values await toTx( ctx, WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, position: positions[1].publicKey, tickArrayLower: positions[1].tickArrayLower, tickArrayUpper: positions[1].tickArrayUpper, }), ).buildAndExecute(); const outOfRangePosition = await fetcher.getPosition( positions[1].publicKey, IGNORE_CACHE, ); assert.ok(outOfRangePosition?.feeOwedA.eq(ZERO_BN)); assert.ok(outOfRangePosition?.feeOwedB.eq(ZERO_BN)); }); it("successfully collect fees with approved delegate", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: new anchor.BN(10_000_000), }, // In range position ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, positions, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken(provider, position.tokenAccount, delegate.publicKey, 1); await toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ) .addSigner(delegate) .buildAndExecute(); }); it("successfully collect fees with owner even if there is approved delegate", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: new anchor.BN(10_000_000), }, // In range position ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, positions, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const position = positions[0]; const delegate = anchor.web3.Keypair.generate(); await approveToken(provider, position.tokenAccount, delegate.publicKey, 1); await toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: position.publicKey, positionTokenAccount: position.tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(); }); it("successfully collect fees with transferred position token", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 0, tickUpperIndex: 128, liquidityAmount: new anchor.BN(10_000_000), }, // In range position ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, positions, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const position = positions[0]; const newOwner = anchor.web3.Keypair.generate(); const newOwnerPositionTokenAccount = await createTokenAccount( provider, position.mintKeypair.publicKey, newOwner.publicKey, ); await transferToken( provider, position.tokenAccount, newOwnerPositionTokenAccount, 1, ); await toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: newOwner.publicKey, position: position.publicKey, positionTokenAccount: newOwnerPositionTokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ) .addSigner(newOwner) .buildAndExecute(); }); it("fails when position does not match whirlpool", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { tokenVaultAKeypair, tokenVaultBKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const { poolInitInfo: { whirlpoolPda: whirlpoolPda2 }, } = await initTestPool(ctx, tickSpacing); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda2.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d1/, // ConstraintHasOne ); }); it("fails when position token account does not contain exactly one token", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const positionTokenAccount2 = await createTokenAccount( provider, positions[0].mintKeypair.publicKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positionTokenAccount2, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); await transferToken( provider, positions[0].tokenAccount, positionTokenAccount2, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when position authority is not approved delegate for position token account", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const delegate = anchor.web3.Keypair.generate(); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ) .addSigner(delegate) .buildAndExecute(), /0x1783/, // MissingOrInvalidDelegate ); }); it("fails when position authority is not authorized to transfer exactly one token", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 2, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ) .addSigner(delegate) .buildAndExecute(), /0x1784/, // InvalidPositionTokenAmount ); }); it("fails when position authority is not a signer", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const delegate = anchor.web3.Keypair.generate(); await approveToken( provider, positions[0].tokenAccount, delegate.publicKey, 1, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: delegate.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when position token account mint does not equal position mint", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const fakePositionTokenAccount = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: fakePositionTokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("fails when token vault does not match whirlpool token vault", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const fakeVaultA = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); const fakeVaultB = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: fakeVaultA, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7dc/, // ConstraintAddress ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: fakeVaultB, }), ).buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("fails when owner token account mint does not match whirlpool token mint", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); const invalidOwnerAccountA = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); const invalidOwnerAccountB = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: invalidOwnerAccountA, tokenOwnerAccountB: tokenAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectFeesIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, positionAuthority: provider.wallet.publicKey, position: positions[0].publicKey, positionTokenAccount: positions[0].tokenAccount, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: invalidOwnerAccountB, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, }), ).buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/open_position_with_metadata.test.ts
import * as anchor from "@coral-xyz/anchor"; import { web3 } from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import { TOKEN_PROGRAM_ID, getAccount, getAssociatedTokenAddressSync, } from "@solana/spl-token"; import { Keypair, PublicKey } from "@solana/web3.js"; import * as assert from "assert"; import type { InitPoolParams, OpenPositionParams, OpenPositionWithMetadataBumpsData, PositionData, } from "../../src"; import { MAX_TICK_INDEX, METADATA_PROGRAM_ADDRESS, MIN_TICK_INDEX, PDAUtil, TickUtil, WhirlpoolContext, WhirlpoolIx, toTx, } from "../../src"; import { openPositionAccounts } from "../../src/utils/instructions-util"; import { ONE_SOL, TickSpacing, ZERO_BN, createMint, createMintInstructions, mintToDestination, systemTransferTx, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool, openPositionWithMetadata } from "../utils/init-utils"; import { generateDefaultOpenPositionParams } from "../utils/test-builders"; import { MetaplexHttpClient } from "../utils/metaplex"; describe("open_position_with_metadata", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const metaplex = new MetaplexHttpClient(); let defaultParams: Required<OpenPositionParams & { metadataPda: PDA }>; let defaultMint: Keypair; const tickLowerIndex = 0; const tickUpperIndex = 32768; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; let fullRangeOnlyPoolInitInfo: InitPoolParams; let fullRangeOnlyWhirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; fullRangeOnlyPoolInitInfo = ( await initTestPool(ctx, TickSpacing.FullRangeOnly) ).poolInitInfo; fullRangeOnlyWhirlpoolPda = fullRangeOnlyPoolInitInfo.whirlpoolPda; const { params, mint } = await generateDefaultOpenPositionParams( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, ); defaultParams = params; defaultMint = mint; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); async function checkMetadata( metadataPda: PDA | undefined, positionMint: PublicKey, ) { assert.ok(metadataPda != null); const metadataAccountInfo = await provider.connection.getAccountInfo( metadataPda.publicKey, ); assert.ok(metadataAccountInfo !== null); const metadata = metaplex.parseOnChainMetadata( metadataPda.publicKey, metadataAccountInfo!.data, ); assert.ok(metadata !== null); assert.ok( metadata.updateAuthority.toBase58() === "3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr", ); assert.ok(metadata.mint.toBase58() === positionMint.toString()); assert.ok( metadata.uri.replace(/\0/g, "") === `https://arweave.net/E19ZNY2sqMqddm1Wx7mrXPUZ0ZZ5ISizhebb0UsVEws`, ); } it("successfully opens position and verify position address contents", async () => { const positionInitInfo = await openPositionWithMetadata( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, ); const { positionPda, metadataPda, positionMintAddress } = positionInitInfo.params; const position = (await fetcher.getPosition( positionPda.publicKey, )) as PositionData; assert.strictEqual(position.tickLowerIndex, tickLowerIndex); assert.strictEqual(position.tickUpperIndex, tickUpperIndex); assert.ok(position.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey)); assert.ok(position.positionMint.equals(positionMintAddress)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); await checkMetadata(metadataPda, position.positionMint); // TODO: Add tests for rewards }); it("successfully opens position and verify position address contents for full-range only pool", async () => { const [lowerTickIndex, upperTickIndex] = TickUtil.getFullRangeTickIndex( TickSpacing.FullRangeOnly, ); const positionInitInfo = await openPositionWithMetadata( ctx, fullRangeOnlyWhirlpoolPda.publicKey, lowerTickIndex, upperTickIndex, ); const { positionPda, metadataPda, positionMintAddress } = positionInitInfo.params; const position = (await fetcher.getPosition( positionPda.publicKey, )) as PositionData; assert.strictEqual(position.tickLowerIndex, lowerTickIndex); assert.strictEqual(position.tickUpperIndex, upperTickIndex); assert.ok( position.whirlpool.equals( fullRangeOnlyPoolInitInfo.whirlpoolPda.publicKey, ), ); assert.ok(position.positionMint.equals(positionMintAddress)); assert.ok(position.liquidity.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointA.eq(ZERO_BN)); assert.ok(position.feeGrowthCheckpointB.eq(ZERO_BN)); assert.ok(position.feeOwedA.eq(ZERO_BN)); assert.ok(position.feeOwedB.eq(ZERO_BN)); await checkMetadata(metadataPda, position.positionMint); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const { params } = await openPositionWithMetadata( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, funderKeypair, ); await checkMetadata(params.metadataPda, params.positionMintAddress); }); it("open position & verify position mint behavior", async () => { const newOwner = web3.Keypair.generate(); const positionInitInfo = await openPositionWithMetadata( ctx, whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, newOwner.publicKey, ); const { metadataPda, positionMintAddress, positionTokenAccount: positionTokenAccountAddress, } = positionInitInfo.params; await checkMetadata(metadataPda, positionMintAddress); const userTokenAccount = await getAccount( ctx.connection, positionTokenAccountAddress, ); assert.ok(userTokenAccount.amount === 1n); assert.ok(userTokenAccount.owner.equals(newOwner.publicKey)); await assert.rejects( mintToDestination( provider, positionMintAddress, positionTokenAccountAddress, 1, ), /0x5/, // the total supply of this token is fixed ); }); it("user must pass the valid token ATA account", async () => { const anotherMintKey = await createMint( provider, provider.wallet.publicKey, ); const positionTokenAccountAddress = getAssociatedTokenAddressSync( anotherMintKey, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithMetadataIx(ctx.program, { ...defaultParams, positionTokenAccount: positionTokenAccountAddress, }), ) .addSigner(defaultMint) .buildAndExecute(), /An account required by the instruction is missing/, ); }); describe("invalid ticks", () => { async function assertTicksFail(lowerTick: number, upperTick: number) { await assert.rejects( openPositionWithMetadata( ctx, whirlpoolPda.publicKey, lowerTick, upperTick, provider.wallet.publicKey, funderKeypair, ), /0x177a/, // InvalidTickIndex ); } it("fail when user pass in an out of bound tick index for upper-index", async () => { await assertTicksFail(0, MAX_TICK_INDEX + 1); }); it("fail when user pass in a lower tick index that is higher than the upper-index", async () => { await assertTicksFail(-22534, -22534 - 1); }); it("fail when user pass in a lower tick index that equals the upper-index", async () => { await assertTicksFail(22365, 22365); }); it("fail when user pass in an out of bound tick index for lower-index", async () => { await assertTicksFail(MIN_TICK_INDEX - 1, 0); }); it("fail when user pass in a non-initializable tick index for upper-index", async () => { await assertTicksFail(0, 1); }); it("fail when user pass in a non-initializable tick index for lower-index", async () => { await assertTicksFail(1, 2); }); }); it("fail when position mint already exists", async () => { const positionMintKeypair = anchor.web3.Keypair.generate(); const positionPda = PDAUtil.getPosition( ctx.program.programId, positionMintKeypair.publicKey, ); const metadataPda = PDAUtil.getPositionMetadata( positionMintKeypair.publicKey, ); const positionTokenAccountAddress = getAssociatedTokenAddressSync( positionMintKeypair.publicKey, provider.wallet.publicKey, ); const tx = new web3.Transaction(); tx.add( ...(await createMintInstructions( provider, provider.wallet.publicKey, positionMintKeypair.publicKey, )), ); await provider.sendAndConfirm(tx, [positionMintKeypair], { commitment: "confirmed", }); await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithMetadataIx(ctx.program, { ...defaultParams, positionPda, metadataPda, positionMintAddress: positionMintKeypair.publicKey, positionTokenAccount: positionTokenAccountAddress, whirlpool: whirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, }), ) .addSigner(positionMintKeypair) .buildAndExecute(), /0x0/, ); }); describe("invalid account constraints", () => { function buildOpenWithAccountOverrides( overrides: Partial< ReturnType<typeof openPositionAccounts> & { positionMetadataAccount: PublicKey; metadataProgram: PublicKey; metadataUpdateAuth: PublicKey; } >, ) { const { positionPda, metadataPda, tickLowerIndex, tickUpperIndex } = defaultParams; const bumps: OpenPositionWithMetadataBumpsData = { positionBump: positionPda.bump, metadataBump: metadataPda.bump, }; const ix = ctx.program.instruction.openPositionWithMetadata( bumps, tickLowerIndex, tickUpperIndex, { accounts: { ...openPositionAccounts(defaultParams), positionMetadataAccount: metadataPda.publicKey, metadataProgram: METADATA_PROGRAM_ADDRESS, metadataUpdateAuth: new PublicKey( "3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr", ), ...overrides, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; } it("fails with non-mint metadataPda", async () => { const notMintKeypair = Keypair.generate(); const invalidParams = { ...defaultParams, metadataPda: PDAUtil.getPositionMetadata(notMintKeypair.publicKey), }; await assert.rejects( toTx( ctx, WhirlpoolIx.openPositionWithMetadataIx(ctx.program, invalidParams), ) .addSigner(defaultMint) .buildAndExecute(), // Invalid Metadata Key // https://github.com/metaplex-foundation/mpl-token-metadata/blob/main/programs/token-metadata/program/src/error.rs#L34-L36 /0x5/, ); }); it("fails with non-program metadata program", async () => { const notMetadataProgram = Keypair.generate(); const tx = new TransactionBuilder( ctx.provider.connection, ctx.wallet, ctx.txBuilderOpts, ).addInstruction( buildOpenWithAccountOverrides({ metadataProgram: notMetadataProgram.publicKey, }), ); await assert.rejects( tx.addSigner(defaultMint).buildAndExecute(), // InvalidProgramId // https://github.com/coral-xyz/anchor/blob/v0.29.0/lang/src/error.rs#L178-L180 /0xbc0/, ); }); it("fails with non-metadata program ", async () => { const tx = new TransactionBuilder( ctx.provider.connection, ctx.wallet, ctx.txBuilderOpts, ).addInstruction( buildOpenWithAccountOverrides({ metadataProgram: TOKEN_PROGRAM_ID, }), ); await assert.rejects( tx.addSigner(defaultMint).buildAndExecute(), // InvalidProgramId // https://github.com/coral-xyz/anchor/blob/v0.29.0/lang/src/error.rs#L178-L180 /0xbc0/, ); }); it("fails with non-valid update_authority program", async () => { const notUpdateAuth = Keypair.generate(); const tx = new TransactionBuilder( ctx.provider.connection, ctx.wallet, ctx.txBuilderOpts, ).addInstruction( buildOpenWithAccountOverrides({ metadataUpdateAuth: notUpdateAuth.publicKey, }), ); await assert.rejects( tx.addSigner(defaultMint).buildAndExecute(), // ConstraintAddress // https://github.com/coral-xyz/anchor/blob/v0.29.0/lang/src/error.rs#L89-L91 /0x7dc/, ); }); }); it("fail when opening a non-full range position in an full-range only pool", async () => { await assert.rejects( openPositionWithMetadata( ctx, fullRangeOnlyWhirlpoolPda.publicKey, tickLowerIndex, tickUpperIndex, provider.wallet.publicKey, funderKeypair, ), /0x17a6/, // FullRangeOnlyPool ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/collect_protocol_fees.test.ts
import * as anchor from "@coral-xyz/anchor"; import { BN } from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import * as assert from "assert"; import Decimal from "decimal.js"; import type { WhirlpoolData } from "../../src"; import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { createTokenAccount, getTokenBalance, TickSpacing, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { WhirlpoolTestFixture } from "../utils/fixture"; import { initTestPool } from "../utils/init-utils"; describe("collect_protocol_fees", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully collects fees", async () => { // In same tick array - start index 22528 const tickLowerIndex = 29440; const tickUpperIndex = 33536; const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex, tickUpperIndex, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, configKeypairs: { feeAuthorityKeypair, collectProtocolFeesAuthorityKeypair, }, configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair }, tokenAccountA, tokenAccountB, positions, } = fixture.getInfos(); await toTx( ctx, WhirlpoolIx.setProtocolFeeRateIx(ctx.program, { whirlpool: whirlpoolPda.publicKey, whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, feeAuthority: feeAuthorityKeypair.publicKey, protocolFeeRate: 2500, }), ) .addSigner(feeAuthorityKeypair) .buildAndExecute(); const poolBefore = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok(poolBefore?.protocolFeeOwedA.eq(ZERO_BN)); assert.ok(poolBefore?.protocolFeeOwedB.eq(ZERO_BN)); const tickArrayPda = positions[0].tickArrayLower; const oraclePda = PDAUtil.getOracle( ctx.program.programId, whirlpoolPda.publicKey, ); // Accrue fees in token A await toTx( ctx, WhirlpoolIx.swapIx(ctx.program, { amount: new BN(200_000), otherAmountThreshold: ZERO_BN, sqrtPriceLimit: MathUtil.toX64(new Decimal(4)), amountSpecifiedIsInput: true, aToB: true, whirlpool: whirlpoolPda.publicKey, tokenAuthority: ctx.wallet.publicKey, tokenOwnerAccountA: tokenAccountA, tokenVaultA: tokenVaultAKeypair.publicKey, tokenOwnerAccountB: tokenAccountB, tokenVaultB: tokenVaultBKeypair.publicKey, tickArray0: tickArrayPda, tickArray1: tickArrayPda, tickArray2: tickArrayPda, oracle: oraclePda.publicKey, }), ).buildAndExecute(); // Accrue fees in token B await toTx( ctx, WhirlpoolIx.swapIx(ctx.program, { amount: new BN(200_000), otherAmountThreshold: ZERO_BN, sqrtPriceLimit: MathUtil.toX64(new Decimal(5)), amountSpecifiedIsInput: true, aToB: false, whirlpool: whirlpoolPda.publicKey, tokenAuthority: ctx.wallet.publicKey, tokenOwnerAccountA: tokenAccountA, tokenVaultA: tokenVaultAKeypair.publicKey, tokenOwnerAccountB: tokenAccountB, tokenVaultB: tokenVaultBKeypair.publicKey, tickArray0: tickArrayPda, tickArray1: tickArrayPda, tickArray2: tickArrayPda, oracle: oraclePda.publicKey, }), ).buildAndExecute(); const poolAfter = (await fetcher.getPool( whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok(poolAfter?.protocolFeeOwedA.eq(new BN(150))); assert.ok(poolAfter?.protocolFeeOwedB.eq(new BN(150))); const destA = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); const destB = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); await toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: destA, tokenOwnerAccountB: destB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(); const balanceDestA = await getTokenBalance(provider, destA); const balanceDestB = await getTokenBalance(provider, destB); assert.equal(balanceDestA, "150"); assert.equal(balanceDestB, "150"); assert.ok(poolBefore?.protocolFeeOwedA.eq(ZERO_BN)); assert.ok(poolBefore?.protocolFeeOwedB.eq(ZERO_BN)); }); it("fails to collect fees without the authority's signature", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 29440, tickUpperIndex: 33536, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, configKeypairs: { collectProtocolFeesAuthorityKeypair }, configInitInfo: { whirlpoolsConfigKeypair }, tokenAccountA, tokenAccountB, } = fixture.getInfos(); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); it("fails when collect_protocol_fees_authority is invalid", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 29440, tickUpperIndex: 33536, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair }, configKeypairs: { rewardEmissionsSuperAuthorityKeypair }, configInitInfo: { whirlpoolsConfigKeypair }, tokenAccountA, tokenAccountB, } = fixture.getInfos(); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: rewardEmissionsSuperAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, }), ) .addSigner(rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("fails when whirlpool does not match config", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 29440, tickUpperIndex: 33536, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { tokenVaultAKeypair, tokenVaultBKeypair }, configKeypairs: { collectProtocolFeesAuthorityKeypair }, configInitInfo: { whirlpoolsConfigKeypair }, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const { poolInitInfo: { whirlpoolPda: whirlpoolPda2 }, } = await initTestPool(ctx, tickSpacing); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda2.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(), /0x7d1/, // ConstraintHasOne ); }); it("fails when vaults do not match whirlpool vaults", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 29440, tickUpperIndex: 33536, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, configKeypairs: { collectProtocolFeesAuthorityKeypair }, configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair }, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const fakeVaultA = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); const fakeVaultB = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: fakeVaultA, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(), /0x7dc/, // ConstraintAddress ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: fakeVaultB, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: tokenAccountB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("fails when destination mints do not match whirlpool mints", async () => { const tickSpacing = TickSpacing.Standard; const fixture = await new WhirlpoolTestFixture(ctx).init({ tickSpacing, positions: [ { tickLowerIndex: 29440, tickUpperIndex: 33536, liquidityAmount: new anchor.BN(10_000_000), }, ], }); const { poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair, tokenMintA, tokenMintB, }, configKeypairs: { collectProtocolFeesAuthorityKeypair }, configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKepair }, tokenAccountA, tokenAccountB, } = fixture.getInfos(); const invalidDestA = await createTokenAccount( provider, tokenMintB, provider.wallet.publicKey, ); const invalidDestB = await createTokenAccount( provider, tokenMintA, provider.wallet.publicKey, ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKepair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: invalidDestA, tokenOwnerAccountB: tokenAccountB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(), /0x7d3/, // ConstraintRaw ); await assert.rejects( toTx( ctx, WhirlpoolIx.collectProtocolFeesIx(ctx.program, { whirlpoolsConfig: whirlpoolsConfigKepair.publicKey, whirlpool: whirlpoolPda.publicKey, collectProtocolFeesAuthority: collectProtocolFeesAuthorityKeypair.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, tokenOwnerAccountA: tokenAccountA, tokenOwnerAccountB: invalidDestB, }), ) .addSigner(collectProtocolFeesAuthorityKeypair) .buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/initialize_tick_array.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { InitPoolParams, InitTickArrayParams, TickArrayData, } from "../../src"; import { TICK_ARRAY_SIZE, WhirlpoolContext, WhirlpoolIx, toTx, } from "../../src"; import { ONE_SOL, TickSpacing, systemTransferTx } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool, initTickArray } from "../utils/init-utils"; import { generateDefaultInitTickArrayParams } from "../utils/test-builders"; describe("initialize_tick_array", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; it("successfully init a TickArray account", async () => { const tickSpacing = TickSpacing.Standard; const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); await fetcher.getPool(poolInitInfo.whirlpoolPda.publicKey); const startTick = TICK_ARRAY_SIZE * tickSpacing * 2; const tickArrayInitInfo = generateDefaultInitTickArrayParams( ctx, poolInitInfo.whirlpoolPda.publicKey, startTick, ); await toTx( ctx, WhirlpoolIx.initTickArrayIx(ctx.program, tickArrayInitInfo), ).buildAndExecute(); assertTickArrayInitialized(ctx, tickArrayInitInfo, poolInitInfo, startTick); }); it("successfully init a TickArray account with a negative index", async () => { const tickSpacing = TickSpacing.Standard; const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); await fetcher.getPool(poolInitInfo.whirlpoolPda.publicKey); const startTick = TICK_ARRAY_SIZE * tickSpacing * -2; const tickArrayInitInfo = generateDefaultInitTickArrayParams( ctx, poolInitInfo.whirlpoolPda.publicKey, startTick, ); await toTx( ctx, WhirlpoolIx.initTickArrayIx(ctx.program, tickArrayInitInfo), ).buildAndExecute(); assertTickArrayInitialized(ctx, tickArrayInitInfo, poolInitInfo, startTick); }); it("succeeds when funder is different than account paying for transaction fee", async () => { const tickSpacing = TickSpacing.Standard; const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); const funderKeypair = anchor.web3.Keypair.generate(); await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); await fetcher.getPool(poolInitInfo.whirlpoolPda.publicKey); const startTick = TICK_ARRAY_SIZE * tickSpacing * 3; await initTickArray( ctx, poolInitInfo.whirlpoolPda.publicKey, startTick, funderKeypair, ); }); it("fails when start tick index is not a valid start index", async () => { const tickSpacing = TickSpacing.Standard; const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard); await fetcher.getPool(poolInitInfo.whirlpoolPda.publicKey); const startTick = TICK_ARRAY_SIZE * tickSpacing * 2 + 1; const params = generateDefaultInitTickArrayParams( ctx, poolInitInfo.whirlpoolPda.publicKey, startTick, ); try { await toTx( ctx, WhirlpoolIx.initTickArrayIx(ctx.program, params), ).buildAndExecute(); assert.fail( "should fail if start-tick is not a multiple of tick spacing and num ticks in array", ); } catch (e) { const error = e as Error; assert.match(error.message, /0x1771/); // InvalidStartTick } }); async function assertTickArrayInitialized( ctx: WhirlpoolContext, tickArrayInitInfo: InitTickArrayParams, poolInitInfo: InitPoolParams, startTick: number, ) { let tickArrayData = (await fetcher.getTickArray( tickArrayInitInfo.tickArrayPda.publicKey, )) as TickArrayData; assert.ok( tickArrayData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey), ); assert.ok(tickArrayData.startTickIndex == startTick); } });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/set_reward_emissions.test.ts
import * as anchor from "@coral-xyz/anchor"; import * as assert from "assert"; import type { WhirlpoolData } from "../../src"; import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../src"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { createAndMintToTokenAccount, mintToDestination, TickSpacing, ZERO_BN, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initializeReward, initTestPool } from "../utils/init-utils"; describe("set_reward_emissions", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const emissionsPerSecondX64 = new anchor.BN(10_000) .shln(64) .div(new anchor.BN(60 * 60 * 24)); it("successfully set_reward_emissions", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const rewardIndex = 0; const { params: { rewardVaultKeypair, rewardMint }, } = await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, rewardIndex, ); await mintToDestination( provider, rewardMint, rewardVaultKeypair.publicKey, 10000, ); await toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardIndex, rewardVaultKey: rewardVaultKeypair.publicKey, emissionsPerSecondX64, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(); let whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok( whirlpool.rewardInfos[0].emissionsPerSecondX64.eq(emissionsPerSecondX64), ); // Successfuly set emissions back to zero await toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardIndex, rewardVaultKey: rewardVaultKeypair.publicKey, emissionsPerSecondX64: ZERO_BN, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(); whirlpool = (await fetcher.getPool( poolInitInfo.whirlpoolPda.publicKey, IGNORE_CACHE, )) as WhirlpoolData; assert.ok(whirlpool.rewardInfos[0].emissionsPerSecondX64.eq(ZERO_BN)); }); it("fails when token vault does not contain at least 1 day of emission runway", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const rewardIndex = 0; const { params: { rewardVaultKeypair }, } = await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, rewardIndex, ); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardIndex, rewardVaultKey: rewardVaultKeypair.publicKey, emissionsPerSecondX64, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0x178b/, // RewardVaultAmountInsufficient ); }); it("fails if provided reward vault does not match whirlpool reward vault", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const rewardIndex = 0; const { params: { rewardMint }, } = await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, rewardIndex, ); const fakeVault = await createAndMintToTokenAccount( provider, rewardMint, 10000, ); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, rewardVaultKey: fakeVault, rewardIndex, emissionsPerSecondX64, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0x7dc/, // An address constraint was violated ); }); it("cannot set emission for an uninitialized reward", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const rewardIndex = 0; await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, rewardVaultKey: anchor.web3.PublicKey.default, rewardIndex: rewardIndex, emissionsPerSecondX64, }), ) .addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair) .buildAndExecute(), /0xbbf/, // AccountOwnedByWrongProgram ); }); it("cannot set emission without the authority's signature", async () => { const { poolInitInfo, configInitInfo, configKeypairs } = await initTestPool( ctx, TickSpacing.Standard, ); const rewardIndex = 0; await initializeReward( ctx, configKeypairs.rewardEmissionsSuperAuthorityKeypair, poolInitInfo.whirlpoolPda.publicKey, rewardIndex, ); await assert.rejects( toTx( ctx, WhirlpoolIx.setRewardEmissionsIx(ctx.program, { rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority, whirlpool: poolInitInfo.whirlpoolPda.publicKey, rewardIndex, rewardVaultKey: provider.wallet.publicKey, // TODO fix emissionsPerSecondX64, }), ).buildAndExecute(), /.*signature verification fail.*/i, ); }); });
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/delete_position_bundle.test.ts
import * as anchor from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { ASSOCIATED_TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Keypair } from "@solana/web3.js"; import * as assert from "assert"; import type { InitPoolParams, PositionBundleData } from "../../src"; import { POSITION_BUNDLE_SIZE, WhirlpoolIx, toTx } from "../../src"; import { WhirlpoolContext } from "../../src/context"; import { IGNORE_CACHE } from "../../src/network/public/fetcher"; import { ONE_SOL, TickSpacing, approveToken, burnToken, createAssociatedTokenAccount, systemTransferTx, transferToken, } from "../utils"; import { defaultConfirmOptions } from "../utils/const"; import { initTestPool, initializePositionBundle, initializePositionBundleWithMetadata, openBundledPosition, } from "../utils/init-utils"; describe("delete_position_bundle", () => { const provider = anchor.AnchorProvider.local( undefined, defaultConfirmOptions, ); const program = anchor.workspace.Whirlpool; const ctx = WhirlpoolContext.fromWorkspace(provider, program); const fetcher = ctx.fetcher; const tickLowerIndex = 0; const tickUpperIndex = 128; let poolInitInfo: InitPoolParams; let whirlpoolPda: PDA; const funderKeypair = anchor.web3.Keypair.generate(); beforeAll(async () => { poolInitInfo = (await initTestPool(ctx, TickSpacing.Standard)).poolInitInfo; whirlpoolPda = poolInitInfo.whirlpoolPda; await systemTransferTx( provider, funderKeypair.publicKey, ONE_SOL, ).buildAndExecute(); }); function checkBitmapIsOpened( account: PositionBundleData, bundleIndex: number, ): boolean { if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE) throw Error("bundleIndex is out of bounds"); const bitmapIndex = Math.floor(bundleIndex / 8); const bitmapOffset = bundleIndex % 8; return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) > 0; } it("successfully closes an position bundle, with metadata", async () => { // with local-validator, ctx.wallet may have large lamports and it overflows number data type... const owner = funderKeypair; const positionBundleInfo = await initializePositionBundleWithMetadata( ctx, owner.publicKey, owner, ); // PositionBundle account exists const prePositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(prePositionBundle !== null); // NFT supply should be 1 const preSupplyResponse = await provider.connection.getTokenSupply( positionBundleInfo.positionBundleMintKeypair.publicKey, ); assert.equal(preSupplyResponse.value.uiAmount, 1); // ATA account exists assert.notEqual( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleTokenAccount, ), undefined, ); // Metadata account exists assert.notEqual( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleMetadataPda.publicKey, ), undefined, ); const preBalance = await provider.connection.getBalance( owner.publicKey, "confirmed", ); const rentPositionBundle = await provider.connection.getBalance( positionBundleInfo.positionBundlePda.publicKey, "confirmed", ); const rentTokenAccount = await provider.connection.getBalance( positionBundleInfo.positionBundleTokenAccount, "confirmed", ); await toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: owner.publicKey, receiver: owner.publicKey, }), ) .addSigner(owner) .buildAndExecute(); const postBalance = await provider.connection.getBalance( owner.publicKey, "confirmed", ); // PositionBundle account should be closed const postPositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(postPositionBundle === null); // NFT should be burned and its supply should be 0 const supplyResponse = await provider.connection.getTokenSupply( positionBundleInfo.positionBundleMintKeypair.publicKey, ); assert.equal(supplyResponse.value.uiAmount, 0); // ATA account should be closed assert.equal( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleTokenAccount, ), undefined, ); // Metadata account should NOT be closed assert.notEqual( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleMetadataPda.publicKey, ), undefined, ); // check if rent are refunded const diffBalance = postBalance - preBalance; const rentTotal = rentPositionBundle + rentTokenAccount; assert.equal(diffBalance, rentTotal); }); it("successfully closes an position bundle, without metadata", async () => { // with local-validator, ctx.wallet may have large lamports and it overflows number data type... const owner = funderKeypair; const positionBundleInfo = await initializePositionBundle( ctx, owner.publicKey, owner, ); // PositionBundle account exists const prePositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(prePositionBundle !== null); // NFT supply should be 1 const preSupplyResponse = await provider.connection.getTokenSupply( positionBundleInfo.positionBundleMintKeypair.publicKey, ); assert.equal(preSupplyResponse.value.uiAmount, 1); // ATA account exists assert.notEqual( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleTokenAccount, ), undefined, ); const preBalance = await provider.connection.getBalance( owner.publicKey, "confirmed", ); const rentPositionBundle = await provider.connection.getBalance( positionBundleInfo.positionBundlePda.publicKey, "confirmed", ); const rentTokenAccount = await provider.connection.getBalance( positionBundleInfo.positionBundleTokenAccount, "confirmed", ); await toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: owner.publicKey, receiver: owner.publicKey, }), ) .addSigner(owner) .buildAndExecute(); const postBalance = await provider.connection.getBalance( owner.publicKey, "confirmed", ); // PositionBundle account should be closed const postPositionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(postPositionBundle === null); // NFT should be burned and its supply should be 0 const supplyResponse = await provider.connection.getTokenSupply( positionBundleInfo.positionBundleMintKeypair.publicKey, ); assert.equal(supplyResponse.value.uiAmount, 0); // ATA account should be closed assert.equal( await provider.connection.getAccountInfo( positionBundleInfo.positionBundleTokenAccount, ), undefined, ); // check if rent are refunded const diffBalance = postBalance - preBalance; const rentTotal = rentPositionBundle + rentTokenAccount; assert.equal(diffBalance, rentTotal); }); it("successfully closes an position bundle, receiver != owner", async () => { const receiver = funderKeypair; const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const preBalance = await provider.connection.getBalance( receiver.publicKey, "confirmed", ); const rentPositionBundle = await provider.connection.getBalance( positionBundleInfo.positionBundlePda.publicKey, "confirmed", ); const rentTokenAccount = await provider.connection.getBalance( positionBundleInfo.positionBundleTokenAccount, "confirmed", ); await toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: ctx.wallet.publicKey, receiver: receiver.publicKey, }), ).buildAndExecute(); const postBalance = await provider.connection.getBalance( receiver.publicKey, "confirmed", ); // check if rent are refunded to receiver const diffBalance = postBalance - preBalance; const rentTotal = rentPositionBundle + rentTokenAccount; assert.equal(diffBalance, rentTotal); }); it("should be failed: position bundle has opened bundled position (bundleIndex = 0)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = 0; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const position = await fetcher.getPosition( positionInitInfo.params.bundledPositionPda.publicKey, IGNORE_CACHE, ); assert.equal(position!.tickLowerIndex, tickLowerIndex); assert.equal(position!.tickUpperIndex, tickUpperIndex); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsOpened(positionBundle!, bundleIndex); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); // should be failed await assert.rejects( tx.buildAndExecute(), /0x179e/, // PositionBundleNotDeletable ); // close bundled position await toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ).buildAndExecute(); // should be ok await tx.buildAndExecute(); const deleted = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(deleted === null); }); it("should be failed: position bundle has opened bundled position (bundleIndex = POSITION_BUNDLE_SIZE - 1)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const bundleIndex = POSITION_BUNDLE_SIZE - 1; const positionInitInfo = await openBundledPosition( ctx, whirlpoolPda.publicKey, positionBundleInfo.positionBundleMintKeypair.publicKey, bundleIndex, tickLowerIndex, tickUpperIndex, ); const { bundledPositionPda } = positionInitInfo.params; const position = await fetcher.getPosition( positionInitInfo.params.bundledPositionPda.publicKey, IGNORE_CACHE, ); assert.equal(position!.tickLowerIndex, tickLowerIndex); assert.equal(position!.tickUpperIndex, tickUpperIndex); const positionBundle = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); checkBitmapIsOpened(positionBundle!, bundleIndex); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); // should be failed await assert.rejects( tx.buildAndExecute(), /0x179e/, // PositionBundleNotDeletable ); // close bundled position await toTx( ctx, WhirlpoolIx.closeBundledPositionIx(ctx.program, { bundledPosition: bundledPositionPda.publicKey, bundleIndex, positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleAuthority: ctx.wallet.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, receiver: ctx.wallet.publicKey, }), ).buildAndExecute(); // should be ok await tx.buildAndExecute(); const deleted = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(deleted === null); }); it("should be failed: only owner can delete position bundle, delegated user cannot", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const delegate = Keypair.generate(); await approveToken( provider, positionBundleInfo.positionBundleTokenAccount, delegate.publicKey, 1, ); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, owner: delegate.publicKey, // not owner receiver: ctx.wallet.publicKey, }), ).addSigner(delegate); // should be failed await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw ); // ownership transfer to delegate const delegateTokenAccount = await createAssociatedTokenAccount( provider, positionBundleInfo.positionBundleMintKeypair.publicKey, delegate.publicKey, ctx.wallet.publicKey, ); await transferToken( provider, positionBundleInfo.positionBundleTokenAccount, delegateTokenAccount, 1, ); const txAfterTransfer = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: delegateTokenAccount, owner: delegate.publicKey, // now, delegate is owner receiver: ctx.wallet.publicKey, }), ).addSigner(delegate); await txAfterTransfer.buildAndExecute(); const deleted = await fetcher.getPositionBundle( positionBundleInfo.positionBundlePda.publicKey, IGNORE_CACHE, ); assert.ok(deleted === null); }); describe("invalid input account", () => { it("should be failed: invalid position bundle", async () => { const positionBundleInfo1 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const positionBundleInfo2 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo2.positionBundlePda.publicKey, // invalid positionBundleMint: positionBundleInfo1.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo1.positionBundleTokenAccount, owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("should be failed: invalid position bundle mint", async () => { const positionBundleInfo1 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const positionBundleInfo2 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo1.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo2.positionBundleMintKeypair.publicKey, // invalid positionBundleTokenAccount: positionBundleInfo1.positionBundleTokenAccount, owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7dc/, // ConstraintAddress ); }); it("should be failed: invalid ATA (amount is zero)", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); await burnToken( ctx.provider, positionBundleInfo.positionBundleTokenAccount, positionBundleInfo.positionBundleMintKeypair.publicKey, 1, ); const tokenAccount = await fetcher.getTokenInfo( positionBundleInfo.positionBundleTokenAccount, ); assert.equal(tokenAccount!.amount.toString(), "0"); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, // amount = 0 owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("should be failed: invalid ATA (invalid mint)", async () => { const positionBundleInfo1 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const positionBundleInfo2 = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo1.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo1.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo2.positionBundleTokenAccount, // invalid, owner: ctx.wallet.publicKey, receiver: ctx.wallet.publicKey, }), ); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("should be failed: invalid ATA (invalid owner), invalid owner", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const otherWallet = Keypair.generate(); const tx = toTx( ctx, WhirlpoolIx.deletePositionBundleIx(ctx.program, { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, // ata.owner != owner owner: otherWallet.publicKey, receiver: ctx.wallet.publicKey, }), ).addSigner(otherWallet); await assert.rejects( tx.buildAndExecute(), /0x7d3/, // ConstraintRaw ); }); it("should be failed: invalid token program", async () => { const positionBundleInfo = await initializePositionBundle( ctx, ctx.wallet.publicKey, ); const ix = program.instruction.deletePositionBundle({ accounts: { positionBundle: positionBundleInfo.positionBundlePda.publicKey, positionBundleMint: positionBundleInfo.positionBundleMintKeypair.publicKey, positionBundleTokenAccount: positionBundleInfo.positionBundleTokenAccount, positionBundleOwner: ctx.wallet.publicKey, tokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, // invalid receiver: ctx.wallet.publicKey, }, }); const tx = toTx(ctx, { instructions: [ix], cleanupInstructions: [], signers: [], }); await assert.rejects( tx.buildAndExecute(), /0xbc0/, // InvalidProgramId ); }); }); });
0