//! Instruction types #![allow(clippy::too_many_arguments)] #![allow(deprecated)] use crate::state::{AmmParams, Fees}; use arrayref::array_ref; use solana_program::{ instruction::{AccountMeta, Instruction}, program_error::ProgramError, program_pack::Pack, pubkey::Pubkey, sysvar, }; use std::convert::TryInto; use std::mem::size_of; #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct InitializeInstruction { /// nonce used to create valid program address pub nonce: u8, /// utc timestamps for pool open pub open_time: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct InitializeInstruction2 { /// nonce used to create valid program address pub nonce: u8, /// utc timestamps for pool open pub open_time: u64, /// init token pc amount pub init_pc_amount: u64, /// init token coin amount pub init_coin_amount: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct PreInitializeInstruction { /// nonce used to create valid program address pub nonce: u8, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct MonitorStepInstruction { /// max value of plan/new/cancel orders pub plan_order_limit: u16, pub place_order_limit: u16, pub cancel_order_limit: u16, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct DepositInstruction { /// Pool token amount to transfer. token_a and token_b amount are set by /// the current exchange rate and size of the pool pub max_coin_amount: u64, pub max_pc_amount: u64, pub base_side: u64, pub other_amount_min: Option, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct WithdrawInstruction { /// Pool token amount to transfer. token_a and token_b amount are set by /// the current exchange rate and size of the pool pub amount: u64, pub min_coin_amount: Option, pub min_pc_amount: Option, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct SetParamsInstruction { pub param: u8, pub value: Option, pub fees: Option, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct WithdrawSrmInstruction { pub amount: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct SwapInstructionBaseIn { // SOURCE amount to transfer, output to DESTINATION is based on the exchange rate pub amount_in: u64, /// Minimum amount of DESTINATION token to output, prevents excessive slippage pub minimum_amount_out: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct SwapInstructionBaseOut { // SOURCE amount to transfer, output to DESTINATION is based on the exchange rate pub max_amount_in: u64, /// Minimum amount of DESTINATION token to output, prevents excessive slippage pub amount_out: u64, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct SimulateInstruction { pub param: u8, pub swap_base_in_value: Option, pub swap_base_out_value: Option, } #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct AdminCancelOrdersInstruction { pub limit: u16, } /// Update config account params #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct ConfigArgs { pub param: u8, pub owner: Option, pub create_pool_fee: Option, } /// Instructions supported by the AmmInfo program. #[repr(C)] #[derive(Clone, Debug, PartialEq)] pub enum AmmInstruction { /// Initializes a new AmmInfo. /// /// Not supported yet, please use `Initialize2` to new a AMM pool #[deprecated(note = "Not supported yet, please use `Initialize2` instead")] Initialize(InitializeInstruction), /// Initializes a new AMM pool. /// /// 0. `[]` Spl Token program id /// 1. `[]` Associated Token program id /// 2. `[]` Sys program id /// 3. `[]` Rent program id /// 4. `[writable]` New AMM Account to create. /// 5. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 6. `[writable]` AMM open orders Account /// 7. `[writable]` AMM lp mint Account /// 8. `[]` AMM coin mint Account /// 9. `[]` AMM pc mint Account /// 10. `[writable]` AMM coin vault Account. Must be non zero, owned by $authority. /// 11. `[writable]` AMM pc vault Account. Must be non zero, owned by $authority. /// 12. `[writable]` AMM target orders Account. To store plan orders informations. /// 13. `[]` AMM config Account, derived from `find_program_address(&[&&AMM_CONFIG_SEED])`. /// 14. `[]` AMM create pool fee destination Account /// 15. `[]` Market program id /// 16. `[writable]` Market Account. Market program is the owner. /// 17. `[writable, signer]` User wallet Account /// 18. `[]` User token coin Account /// 19. '[]` User token pc Account /// 20. `[writable]` User destination lp token ATA Account Initialize2(InitializeInstruction2), /// MonitorStep. To monitor place Amm order state machine turn around step by step. #[deprecated(note = "Not supported yet")] MonitorStep(MonitorStepInstruction), /// Deposit some tokens into the pool. The output is a "pool" token representing ownership /// into the pool. Inputs are converted to the current ratio. /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[]` AMM open_orders Account /// 4. `[writable]` AMM target orders Account. To store plan orders infomations. /// 5. `[writable]` AMM lp mint Account. Owned by $authority. /// 6. `[writable]` AMM coin vault $authority can transfer amount, /// 7. `[writable]` AMM pc vault $authority can transfer amount, /// 8. `[]` Market Account. Market program is the owner. /// 9. `[writable]` User coin token Account to deposit into. /// 10. `[writable]` User pc token Account to deposit into. /// 11. `[writable]` User lp token. To deposit the generated tokens, user is the owner. /// 12. '[signer]` User wallet Account /// 13. `[]` Market event queue Account. Deposit(DepositInstruction), /// Withdraw the vault tokens from the pool at the current ratio. /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[writable]` AMM open orders Account /// 4. `[writable]` AMM target orders Account /// 5. `[writable]` AMM lp mint Account. Owned by $authority. /// 6. `[writable]` AMM coin vault Account to withdraw FROM, /// 7. `[writable]` AMM pc vault Account to withdraw FROM, /// 8. `[]` Market program id /// 9. `[writable]` Market Account. Market program is the owner. /// 10. `[writable]` Market coin vault Account /// 11. `[writable]` Market pc vault Account /// 12. '[]` Market vault signer Account /// 13. `[writable]` User lp token Account. /// 14. `[writable]` User token coin Account. user Account to credit. /// 15. `[writable]` User token pc Account. user Account to credit. /// 16. `[signer]` User wallet Account /// 17. `[writable]` Market event queue Account /// 18. `[writable]` Market bids Account /// 19. `[writable]` Market asks Account Withdraw(WithdrawInstruction), /// Migrate the associated market from Serum to OpenBook. #[deprecated(note = "Not supported yet")] MigrateToOpenBook, /// Set AMM params /// /// 0. `[writable]` AMM Account. /// 1. `[signer]` Admin Account SetParams(SetParamsInstruction), /// Withdraw Pnl from pool by protocol /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` AMM config Account, derived from `find_program_address(&[&&AMM_CONFIG_SEED])`. /// 3. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 5. `[writable]` AMM coin vault account to withdraw FROM, /// 6. `[writable]` AMM pc vault account to withdraw FROM, /// 7. `[writable]` User coin token Account to withdraw to /// 8. `[writable]` User pc token Account to withdraw to /// 9. `[signer]` User wallet account /// 10. `[writable]` AMM target orders Account WithdrawPnl, /// Withdraw (M)SRM from the (M)SRM Account used for fee discounts by admin #[deprecated(note = "Not supported yet")] WithdrawSrm(WithdrawSrmInstruction), /// Swap coin or pc from pool, base amount_in with a slippage of minimum_amount_out /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[writable]` AMM open orders Account /// 4. `[writable]` (optional)AMM target orders Account, no longer used in the contract, recommended no need to add this Account. /// 5. `[writable]` AMM coin vault Account to swap FROM or To. /// 6. `[writable]` AMM pc vault Account to swap FROM or To. /// 7. `[]` Market program id /// 8. `[writable]` Market Account. Market program is the owner. /// 9. `[writable]` Market bids Account /// 10. `[writable]` Market asks Account /// 11. `[writable]` Market event queue Account /// 12. `[writable]` Market coin vault Account /// 13. `[writable]` Market pc vault Account /// 14. '[]` Market vault signer Account /// 15. `[writable]` User source token Account. /// 16. `[writable]` User destination token Account. /// 17. `[signer]` User wallet Account SwapBaseIn(SwapInstructionBaseIn), /// Continue Initializes a new Amm pool because of compute units limit. /// Not supported yet, please use `Initialize2` to new a Amm pool #[deprecated(note = "Not supported yet, please use `Initialize2` instead")] PreInitialize(PreInitializeInstruction), /// Swap coin or pc from pool, base amount_out with a slippage of max_amount_in /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[writable]` AMM open orders Account /// 4. `[writable]` (optional)AMM target orders Account, no longer used in the contract, recommended no need to add this Account. /// 5. `[writable]` AMM coin vault Account to swap FROM or To. /// 6. `[writable]` AMM pc vault Account to swap FROM or To. /// 7. `[]` Market program id /// 8. `[writable]` Market Account. Market program is the owner. /// 9. `[writable]` Market bids Account /// 10. `[writable]` Market asks Account /// 11. `[writable]` Market event queue Account /// 12. `[writable]` Market coin vault Account /// 13. `[writable]` Market pc vault Account /// 14. '[]` Market vault signer Account /// 15. `[writable]` User source token Account. /// 16. `[writable]` User destination token Account. /// 17. `[signer]` User wallet Account SwapBaseOut(SwapInstructionBaseOut), #[deprecated(note = "Not supported yet")] SimulateInfo(SimulateInstruction), #[deprecated(note = "Not supported yet")] AdminCancelOrders(AdminCancelOrdersInstruction), /// Create amm config account by admin CreateConfigAccount, /// Update amm config account by admin UpdateConfigAccount(ConfigArgs), /// Swap coin or pc from pool with orderbook disable, base amount_in with a slippage of minimum_amount_out /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[writable]` AMM coin vault Account to swap FROM or To. /// 4. `[writable]` AMM pc vault Account to swap FROM or To. /// 5. `[writable]` User source token Account. /// 6. `[writable]` User destination token Account. /// 7. `[signer]` User wallet Account SwapBaseInV2(SwapInstructionBaseIn), /// Swap coin or pc from pool with orderbook disable, base amount_out with a slippage of max_amount_in /// /// 0. `[]` Spl Token program id /// 1. `[writable]` AMM Account /// 2. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 3. `[writable]` AMM coin vault Account to swap FROM or To. /// 4. `[writable]` AMM pc vault Account to swap FROM or To. /// 5. `[writable]` User source token Account. /// 6. `[writable]` User destination token Account. /// 7. `[signer]` User wallet Account SwapBaseOutV2(SwapInstructionBaseOut), /// Collect excess lamports, including accounts for SPL tokens owned by authority and Program PDA. /// /// 0. `[signer]` Collect lamports wallet /// 1. `[]` $authority derived from `create_program_address(&[AUTHORITY_AMM, &[nonce]])`. /// 2. `[]` Spl Token program id /// 3. `..+M` `[writable]` M source lamports accounts. WithdrawExcessLamports, } impl AmmInstruction { /// Unpacks a byte buffer into a [AmmInstruction](enum.AmmInstruction.html). pub fn unpack(input: &[u8]) -> Result { let (&tag, rest) = input .split_first() .ok_or(ProgramError::InvalidInstructionData)?; Ok(match tag { 1 => { let (nonce, rest) = Self::unpack_u8(rest)?; let (open_time, rest) = Self::unpack_u64(rest)?; let (init_pc_amount, rest) = Self::unpack_u64(rest)?; let (init_coin_amount, _reset) = Self::unpack_u64(rest)?; Self::Initialize2(InitializeInstruction2 { nonce, open_time, init_pc_amount, init_coin_amount, }) } 3 => { let (max_coin_amount, rest) = Self::unpack_u64(rest)?; let (max_pc_amount, rest) = Self::unpack_u64(rest)?; let (base_side, rest) = Self::unpack_u64(rest)?; let other_amount_min = if rest.len() >= 8 { let (other_amount_min, _rest) = Self::unpack_u64(rest)?; Some(other_amount_min) } else { None }; Self::Deposit(DepositInstruction { max_coin_amount, max_pc_amount, base_side, other_amount_min, }) } 4 => { let (amount, rest) = Self::unpack_u64(rest)?; let (min_coin_amount, min_pc_amount) = if rest.len() >= 16 { let (min_coin_amount, rest) = Self::unpack_u64(rest)?; let (min_pc_amount, _rest) = Self::unpack_u64(rest)?; (Some(min_coin_amount), Some(min_pc_amount)) } else { (None, None) }; Self::Withdraw(WithdrawInstruction { amount, min_coin_amount, min_pc_amount, }) } 6 => { let (param, rest) = Self::unpack_u8(rest)?; match AmmParams::from_u64(param as u64)? { AmmParams::Fees => { if rest.len() >= Fees::LEN { let (fees, _rest) = rest.split_at(Fees::LEN); let fees = Fees::unpack_from_slice(fees)?; Self::SetParams(SetParamsInstruction { param, value: None, fees: Some(fees), }) } else { return Err(ProgramError::InvalidInstructionData.into()); } } AmmParams::Status | AmmParams::State | AmmParams::SetOpenTime => { if rest.len() >= 8 { let (value, _rest) = Self::unpack_u64(rest)?; Self::SetParams(SetParamsInstruction { param, value: Some(value), fees: None, }) } else { return Err(ProgramError::InvalidInstructionData.into()); } } } } 7 => Self::WithdrawPnl, 9 => { let (amount_in, rest) = Self::unpack_u64(rest)?; let (minimum_amount_out, _rest) = Self::unpack_u64(rest)?; Self::SwapBaseIn(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) } 11 => { let (max_amount_in, rest) = Self::unpack_u64(rest)?; let (amount_out, _rest) = Self::unpack_u64(rest)?; Self::SwapBaseOut(SwapInstructionBaseOut { max_amount_in, amount_out, }) } 14 => Self::CreateConfigAccount, 15 => { let (param, rest) = Self::unpack_u8(rest)?; match param { 0 | 1 => { if rest.len() >= 32 { let pubkey = array_ref![rest, 0, 32]; Self::UpdateConfigAccount(ConfigArgs { param, owner: Some(Pubkey::new_from_array(*pubkey)), create_pool_fee: None, }) } else { return Err(ProgramError::InvalidInstructionData.into()); } } 2 => { let (create_pool_fee, _rest) = Self::unpack_u64(rest)?; Self::UpdateConfigAccount(ConfigArgs { param, owner: None, create_pool_fee: Some(create_pool_fee), }) } _ => { return Err(ProgramError::InvalidInstructionData.into()); } } } 16 => { let (amount_in, rest) = Self::unpack_u64(rest)?; let (minimum_amount_out, _rest) = Self::unpack_u64(rest)?; Self::SwapBaseInV2(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) } 17 => { let (max_amount_in, rest) = Self::unpack_u64(rest)?; let (amount_out, _rest) = Self::unpack_u64(rest)?; Self::SwapBaseOutV2(SwapInstructionBaseOut { max_amount_in, amount_out, }) } 18 => Self::WithdrawExcessLamports, 0 | 2 | 5 | 8 | 10 | 12 | 13 => { // Not support instructions: 0, 2, 5, 8, 10, 12, 13. unimplemented!("This instruction is not supported") } _ => { return Err(ProgramError::InvalidInstructionData.into()); } }) } fn unpack_u8(input: &[u8]) -> Result<(u8, &[u8]), ProgramError> { if input.len() >= 1 { let (amount, rest) = input.split_at(1); let amount = amount .get(..1) .and_then(|slice| slice.try_into().ok()) .map(u8::from_le_bytes) .ok_or(ProgramError::InvalidInstructionData)?; Ok((amount, rest)) } else { Err(ProgramError::InvalidInstructionData.into()) } } fn unpack_u64(input: &[u8]) -> Result<(u64, &[u8]), ProgramError> { if input.len() >= 8 { let (amount, rest) = input.split_at(8); let amount = amount .get(..8) .and_then(|slice| slice.try_into().ok()) .map(u64::from_le_bytes) .ok_or(ProgramError::InvalidInstructionData)?; Ok((amount, rest)) } else { Err(ProgramError::InvalidInstructionData.into()) } } /// Packs a [AmmInstruction](enum.AmmInstruction.html) into a byte buffer. pub fn pack(&self) -> Result, ProgramError> { let mut buf = Vec::with_capacity(size_of::()); match &*self { Self::Initialize2(InitializeInstruction2 { nonce, open_time, init_pc_amount, init_coin_amount, }) => { buf.push(1); buf.push(*nonce); buf.extend_from_slice(&open_time.to_le_bytes()); buf.extend_from_slice(&init_pc_amount.to_le_bytes()); buf.extend_from_slice(&init_coin_amount.to_le_bytes()); } Self::Deposit(DepositInstruction { max_coin_amount, max_pc_amount, base_side, other_amount_min, }) => { buf.push(3); buf.extend_from_slice(&max_coin_amount.to_le_bytes()); buf.extend_from_slice(&max_pc_amount.to_le_bytes()); buf.extend_from_slice(&base_side.to_le_bytes()); if other_amount_min.is_some() { buf.extend_from_slice(&other_amount_min.unwrap().to_le_bytes()); } } Self::Withdraw(WithdrawInstruction { amount, min_coin_amount, min_pc_amount, }) => { buf.push(4); buf.extend_from_slice(&amount.to_le_bytes()); if min_coin_amount.is_some() && min_pc_amount.is_some() { buf.extend_from_slice(&min_coin_amount.unwrap().to_le_bytes()); buf.extend_from_slice(&min_pc_amount.unwrap().to_le_bytes()); } } Self::SetParams(SetParamsInstruction { param, value, fees }) => { buf.push(6); buf.push(*param); match AmmParams::from_u64(*param as u64).unwrap() { AmmParams::Fees => { let fees = match fees { Some(a) => a, None => return Err(ProgramError::InvalidInstructionData.into()), }; let mut fees_slice = [0u8; Fees::LEN]; Pack::pack_into_slice(fees, &mut fees_slice[..]); buf.extend_from_slice(&fees_slice); } _ => { let value = match value { Some(a) => a, None => return Err(ProgramError::InvalidInstructionData.into()), }; buf.extend_from_slice(&value.to_le_bytes()); } } } Self::WithdrawPnl => { buf.push(7); } Self::SwapBaseIn(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) => { buf.push(9); buf.extend_from_slice(&amount_in.to_le_bytes()); buf.extend_from_slice(&minimum_amount_out.to_le_bytes()); } Self::SwapBaseOut(SwapInstructionBaseOut { max_amount_in, amount_out, }) => { buf.push(11); buf.extend_from_slice(&max_amount_in.to_le_bytes()); buf.extend_from_slice(&amount_out.to_le_bytes()); } Self::CreateConfigAccount => { buf.push(14); } Self::UpdateConfigAccount(ConfigArgs { param, owner, create_pool_fee, }) => { buf.push(15); buf.push(*param); match param { 0 | 1 => { let owner = match owner { Some(owner) => { if *owner == Pubkey::default() { return Err(ProgramError::InvalidInstructionData.into()); } else { owner } } None => return Err(ProgramError::InvalidInstructionData.into()), }; buf.extend_from_slice(&owner.to_bytes()); } 2 => { let create_pool_fee = match create_pool_fee { Some(create_pool_fee) => create_pool_fee, None => return Err(ProgramError::InvalidInstructionData.into()), }; buf.extend_from_slice(&create_pool_fee.to_le_bytes()); } _ => return Err(ProgramError::InvalidInstructionData.into()), } } Self::SwapBaseInV2(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) => { buf.push(16); buf.extend_from_slice(&amount_in.to_le_bytes()); buf.extend_from_slice(&minimum_amount_out.to_le_bytes()); } Self::SwapBaseOutV2(SwapInstructionBaseOut { max_amount_in, amount_out, }) => { buf.push(17); buf.extend_from_slice(&max_amount_in.to_le_bytes()); buf.extend_from_slice(&amount_out.to_le_bytes()); } Self::WithdrawExcessLamports => { buf.push(18); } _ => { // Not support instructions: 0, 2, 5, 8, 10, 12, 13, etc. return Err(ProgramError::InvalidInstructionData.into()); } } Ok(buf) } } /// Creates an 'initialize2' instruction. pub fn initialize2( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_open_orders: &Pubkey, amm_lp_mint: &Pubkey, amm_coin_mint: &Pubkey, amm_pc_mint: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, amm_target_orders: &Pubkey, amm_config: &Pubkey, create_fee_destination: &Pubkey, market_program: &Pubkey, market: &Pubkey, user_wallet: &Pubkey, user_token_coin: &Pubkey, user_token_pc: &Pubkey, user_token_lp: &Pubkey, nonce: u8, open_time: u64, init_pc_amount: u64, init_coin_amount: u64, ) -> Result { let init_data = AmmInstruction::Initialize2(InitializeInstruction2 { nonce, open_time, init_pc_amount, init_coin_amount, }); let data = init_data.pack()?; let accounts = vec![ // spl & sys AccountMeta::new_readonly(spl_token::id(), false), AccountMeta::new_readonly(spl_associated_token_account::id(), false), AccountMeta::new_readonly(solana_system_interface::program::id(), false), AccountMeta::new_readonly(sysvar::rent::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_open_orders, false), AccountMeta::new(*amm_lp_mint, false), AccountMeta::new_readonly(*amm_coin_mint, false), AccountMeta::new_readonly(*amm_pc_mint, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), AccountMeta::new(*amm_target_orders, false), AccountMeta::new_readonly(*amm_config, false), AccountMeta::new(*create_fee_destination, false), // market AccountMeta::new_readonly(*market_program, false), AccountMeta::new_readonly(*market, false), // user wallet AccountMeta::new(*user_wallet, true), AccountMeta::new(*user_token_coin, false), AccountMeta::new(*user_token_pc, false), AccountMeta::new(*user_token_lp, false), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'deposit' instruction. pub fn deposit( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_open_orders: &Pubkey, amm_target_orders: &Pubkey, amm_lp_mint: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, market: &Pubkey, market_event_queue: &Pubkey, user_token_coin: &Pubkey, user_token_pc: &Pubkey, user_token_lp: &Pubkey, user_owner: &Pubkey, max_coin_amount: u64, max_pc_amount: u64, base_side: u64, other_amount_min: Option, ) -> Result { let data = AmmInstruction::Deposit(DepositInstruction { max_coin_amount, max_pc_amount, base_side, other_amount_min, }) .pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new_readonly(*amm_open_orders, false), AccountMeta::new(*amm_target_orders, false), AccountMeta::new(*amm_lp_mint, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // market AccountMeta::new_readonly(*market, false), // user AccountMeta::new(*user_token_coin, false), AccountMeta::new(*user_token_pc, false), AccountMeta::new(*user_token_lp, false), AccountMeta::new_readonly(*user_owner, true), AccountMeta::new_readonly(*market_event_queue, false), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'withdraw' instruction. pub fn withdraw( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_open_orders: &Pubkey, amm_target_orders: &Pubkey, amm_lp_mint: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, market_program: &Pubkey, market: &Pubkey, market_coin_vault: &Pubkey, market_pc_vault: &Pubkey, market_vault_signer: &Pubkey, user_token_lp: &Pubkey, user_token_coin: &Pubkey, user_token_pc: &Pubkey, user_owner: &Pubkey, market_event_queue: &Pubkey, market_bids: &Pubkey, market_asks: &Pubkey, referrer_pc_account: Option<&Pubkey>, amount: u64, min_coin_amount: Option, min_pc_amount: Option, ) -> Result { let data = AmmInstruction::Withdraw(WithdrawInstruction { amount, min_coin_amount, min_pc_amount, }) .pack()?; let mut accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_open_orders, false), AccountMeta::new(*amm_target_orders, false), AccountMeta::new(*amm_lp_mint, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // market AccountMeta::new_readonly(*market_program, false), AccountMeta::new(*market, false), AccountMeta::new(*market_coin_vault, false), AccountMeta::new(*market_pc_vault, false), AccountMeta::new_readonly(*market_vault_signer, false), // user AccountMeta::new(*user_token_lp, false), AccountMeta::new(*user_token_coin, false), AccountMeta::new(*user_token_pc, false), AccountMeta::new_readonly(*user_owner, true), AccountMeta::new(*market_event_queue, false), AccountMeta::new(*market_bids, false), AccountMeta::new(*market_asks, false), ]; if let Some(referrer_pc_key) = referrer_pc_account { accounts.push(AccountMeta::new(*referrer_pc_key, false)); } Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'swap base in' instruction. pub fn swap_base_in( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_open_orders: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, market_program: &Pubkey, market: &Pubkey, market_bids: &Pubkey, market_asks: &Pubkey, market_event_queue: &Pubkey, market_coin_vault: &Pubkey, market_pc_vault: &Pubkey, market_vault_signer: &Pubkey, user_token_source: &Pubkey, user_token_destination: &Pubkey, user_source_owner: &Pubkey, amount_in: u64, minimum_amount_out: u64, ) -> Result { let data = AmmInstruction::SwapBaseIn(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) .pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_open_orders, false), // AccountMeta::new(*amm_target_orders, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // market AccountMeta::new_readonly(*market_program, false), AccountMeta::new(*market, false), AccountMeta::new(*market_bids, false), AccountMeta::new(*market_asks, false), AccountMeta::new(*market_event_queue, false), AccountMeta::new(*market_coin_vault, false), AccountMeta::new(*market_pc_vault, false), AccountMeta::new_readonly(*market_vault_signer, false), // user AccountMeta::new(*user_token_source, false), AccountMeta::new(*user_token_destination, false), AccountMeta::new_readonly(*user_source_owner, true), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'swap base in v2' instruction. pub fn swap_base_in_v2( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, user_token_source: &Pubkey, user_token_destination: &Pubkey, user_source_owner: &Pubkey, amount_in: u64, minimum_amount_out: u64, ) -> Result { let data = AmmInstruction::SwapBaseInV2(SwapInstructionBaseIn { amount_in, minimum_amount_out, }) .pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // user AccountMeta::new(*user_token_source, false), AccountMeta::new(*user_token_destination, false), AccountMeta::new_readonly(*user_source_owner, true), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'swap base out' instruction. pub fn swap_base_out( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_open_orders: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, market_program: &Pubkey, market: &Pubkey, market_bids: &Pubkey, market_asks: &Pubkey, market_event_queue: &Pubkey, market_coin_vault: &Pubkey, market_pc_vault: &Pubkey, market_vault_signer: &Pubkey, user_token_source: &Pubkey, user_token_destination: &Pubkey, user_source_owner: &Pubkey, max_amount_in: u64, amount_out: u64, ) -> Result { let data = AmmInstruction::SwapBaseOut(SwapInstructionBaseOut { max_amount_in, amount_out, }) .pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_open_orders, false), // AccountMeta::new(*amm_target_orders, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // market AccountMeta::new_readonly(*market_program, false), AccountMeta::new(*market, false), AccountMeta::new(*market_bids, false), AccountMeta::new(*market_asks, false), AccountMeta::new(*market_event_queue, false), AccountMeta::new(*market_coin_vault, false), AccountMeta::new(*market_pc_vault, false), AccountMeta::new_readonly(*market_vault_signer, false), // user AccountMeta::new(*user_token_source, false), AccountMeta::new(*user_token_destination, false), AccountMeta::new_readonly(*user_source_owner, true), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'swap base out v2' instruction. pub fn swap_base_out_v2( amm_program: &Pubkey, amm_pool: &Pubkey, amm_authority: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, user_token_source: &Pubkey, user_token_destination: &Pubkey, user_source_owner: &Pubkey, max_amount_in: u64, amount_out: u64, ) -> Result { let data = AmmInstruction::SwapBaseOutV2(SwapInstructionBaseOut { max_amount_in, amount_out, }) .pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), // user AccountMeta::new(*user_token_source, false), AccountMeta::new(*user_token_destination, false), AccountMeta::new_readonly(*user_source_owner, true), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'withdrawpnl' instruction pub fn withdrawpnl( amm_program: &Pubkey, amm_pool: &Pubkey, amm_config: &Pubkey, amm_authority: &Pubkey, amm_coin_vault: &Pubkey, amm_pc_vault: &Pubkey, user_token_coin: &Pubkey, user_token_pc: &Pubkey, user_owner: &Pubkey, amm_target_orders: &Pubkey, ) -> Result { let data = AmmInstruction::WithdrawPnl.pack()?; let accounts = vec![ // spl token AccountMeta::new_readonly(spl_token::id(), false), // amm AccountMeta::new(*amm_pool, false), AccountMeta::new_readonly(*amm_config, false), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new(*amm_coin_vault, false), AccountMeta::new(*amm_pc_vault, false), AccountMeta::new(*user_token_coin, false), AccountMeta::new(*user_token_pc, false), AccountMeta::new_readonly(*user_owner, true), AccountMeta::new(*amm_target_orders, false), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates a 'SetParams' instruction. pub fn set_params( amm_program: &Pubkey, amm_pool: &Pubkey, admin: &Pubkey, param: u8, value: Option, fees: Option, ) -> Result { let data = AmmInstruction::SetParams(SetParamsInstruction { param, value, fees }).pack()?; let accounts = vec![ // amm AccountMeta::new(*amm_pool, false), // admin AccountMeta::new_readonly(*admin, true), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates an 'create_config_account' instruction. pub fn create_config_account( amm_program: &Pubkey, admin: &Pubkey, amm_config: &Pubkey, pnl_owner: &Pubkey, ) -> Result { let data = AmmInstruction::CreateConfigAccount.pack()?; let accounts = vec![ AccountMeta::new(*admin, true), AccountMeta::new(*amm_config, false), AccountMeta::new_readonly(*pnl_owner, false), AccountMeta::new_readonly(solana_system_interface::program::id(), false), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates an 'update_config_account' instruction. pub fn update_config_account( amm_program: &Pubkey, admin: &Pubkey, amm_config: &Pubkey, config_args: ConfigArgs, ) -> Result { let data = AmmInstruction::UpdateConfigAccount(config_args).pack()?; let accounts = vec![ AccountMeta::new_readonly(*admin, true), AccountMeta::new(*amm_config, false), ]; Ok(Instruction { program_id: *amm_program, accounts, data, }) } /// Creates an 'withdraw_excess_lamports' instruction. pub fn withdraw_excess_lamports( amm_program: &Pubkey, collect_lamports: &Pubkey, amm_authority: &Pubkey, source_lamports_pubkeys: &[&Pubkey], ) -> Result { let data = AmmInstruction::WithdrawExcessLamports.pack()?; let mut accounts = vec![ AccountMeta::new(*collect_lamports, true), AccountMeta::new_readonly(*amm_authority, false), AccountMeta::new_readonly(spl_token::id(), false), ]; for source_pubkey in source_lamports_pubkeys.iter() { accounts.push(AccountMeta::new(**source_pubkey, false)); } Ok(Instruction { program_id: *amm_program, accounts, data, }) } #[cfg(test)] mod test_withdraw_excess_lamports_helper { use super::*; #[test] fn test_withdraw_excess_lamports_helper_account_layout() { // The processor (process_withdraw_excess_lamports) asserts that account // index 2 is the SPL Token program. The client helper must therefore // place spl_token::id() there, not the system program, otherwise every // transaction built with this helper fails with InvalidSplTokenProgram. let amm_program = Pubkey::new_unique(); let collect_lamports = Pubkey::new_unique(); let amm_authority = Pubkey::new_unique(); let source_a = Pubkey::new_unique(); let source_b = Pubkey::new_unique(); let ix = withdraw_excess_lamports( &amm_program, &collect_lamports, &amm_authority, &[&source_a, &source_b], ) .unwrap(); // tag 18 round-trips through unpack assert_eq!( AmmInstruction::unpack(&ix.data).unwrap(), AmmInstruction::WithdrawExcessLamports ); assert_eq!(ix.accounts.len(), 3 + 2); assert_eq!(ix.accounts[0].pubkey, collect_lamports); assert!(ix.accounts[0].is_signer); assert_eq!(ix.accounts[1].pubkey, amm_authority); // index 2 must be the SPL Token program id, matching the processor's // check_assert_eq!(*token_program_info.key, spl_token::id(), ...) assert_eq!(ix.accounts[2].pubkey, spl_token::id()); assert!(!ix.accounts[2].is_signer); // source accounts follow, all writable, non-signer assert_eq!(ix.accounts[3].pubkey, source_a); assert!(ix.accounts[3].is_writable); assert_eq!(ix.accounts[4].pubkey, source_b); assert!(ix.accounts[4].is_writable); } }