repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
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/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/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
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/update_fees_and_rewards.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { PositionData } from "../../src";
import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { sleep, TickSpacing, ZERO_BN } from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import { WhirlpoolTestFixture } from "../utils/fixture";
import { initTestPool } from "../utils/init-utils";
describe("update_fees_and_rewards", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
it("successfully updates fees and rewards", 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(1_000_000),
},
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair },
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const positionBefore = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionBefore.feeGrowthCheckpointA.eq(ZERO_BN));
assert.ok(positionBefore.feeGrowthCheckpointB.eq(ZERO_BN));
assert.ok(positionBefore.rewardInfos[0].amountOwed.eq(ZERO_BN));
assert.ok(positionBefore.rewardInfos[0].growthInsideCheckpoint.eq(ZERO_BN));
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(100_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
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();
await sleep(2_000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const positionAfter = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionAfter.feeOwedA.gt(positionBefore.feeOwedA));
assert.ok(positionAfter.feeOwedB.eq(ZERO_BN));
assert.ok(
positionAfter.feeGrowthCheckpointA.gt(
positionBefore.feeGrowthCheckpointA,
),
);
assert.ok(
positionAfter.feeGrowthCheckpointB.eq(
positionBefore.feeGrowthCheckpointB,
),
);
assert.ok(
positionAfter.rewardInfos[0].amountOwed.gt(
positionBefore.rewardInfos[0].amountOwed,
),
);
assert.ok(
positionAfter.rewardInfos[0].growthInsideCheckpoint.gt(
positionBefore.rewardInfos[0].growthInsideCheckpoint,
),
);
assert.ok(positionAfter.liquidity.eq(positionBefore.liquidity));
});
it("fails when position has zero liquidity", 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: ZERO_BN }],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const {
poolInitInfo: { whirlpoolPda },
} = await initTestPool(ctx, tickSpacing);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const other = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
});
const { positions: otherPositions } = other.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: otherPositions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fails when tick arrays do not match position", 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(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
0,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fails when tick arrays do 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: ZERO_BN }],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const {
poolInitInfo: { whirlpoolPda: otherWhirlpoolPda },
} = await initTestPool(ctx, tickSpacing);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
otherWhirlpoolPda.publicKey,
22528,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/increase_liquidity.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder } 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 {
PDAUtil,
PriceMath,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { PoolUtil, toTokenAmount } from "../../src/utils/public/pool-utils";
import {
MAX_U64,
TickSpacing,
ZERO_BN,
approveToken,
assertTick,
createAndMintToTokenAccount,
createMint,
createTokenAccount,
getTokenBalance,
sleep,
transferToken,
} from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import { WhirlpoolTestFixture } from "../utils/fixture";
import { initTestPool, initTickArray, openPosition } from "../utils/init-utils";
import {
generateDefaultInitTickArrayParams,
generateDefaultOpenPositionParams,
} from "../utils/test-builders";
describe("increase_liquidity", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
it("increase liquidity of a position spanning two tick arrays", async () => {
const currTick = 0;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(167_000, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// To check if rewardLastUpdatedTimestamp is updated
await sleep(1200);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gt(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.ok(poolAfter.liquidity.eq(new anchor.BN(liquidityAmount)));
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("increase liquidity of a position contained in one tick array", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(tickArray.ticks[56], true, expectedLiquidity, expectedLiquidity);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("initialize and increase liquidity of a position in a single transaction", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const { whirlpoolPda, tickSpacing } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const { params, mint } = await generateDefaultOpenPositionParams(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
ctx.wallet.publicKey,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing),
).publicKey;
await new TransactionBuilder(
ctx.provider.connection,
ctx.provider.wallet,
ctx.txBuilderOpts,
)
// TODO: create a ComputeBudgetInstruction to request more compute
.addInstruction(
WhirlpoolIx.initTickArrayIx(
ctx.program,
generateDefaultInitTickArrayParams(
ctx,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
),
),
)
// .addInstruction(
// buildtoTx(ctx, WhirlpoolIx.initTickArrayIx(generateDefaultInitTickArrayParams(
// ctx,
// whirlpoolPda.publicKey,
// getStartTickIndex(pos[0].tickLowerIndex + TICK_ARRAY_SIZE * tickSpacing, tickSpacing),
// ))
// )
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, params))
// .addInstruction(
// buildWhirlpoolIx.openPositionWithMetadataIx(ctx.program, params)
// )
.addSigner(mint)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: params.positionPda.publicKey,
positionTokenAccount: params.positionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLower,
tickArrayUpper: tickArrayUpper,
}),
)
.buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
params.positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(tickArray.ticks[56], true, expectedLiquidity, expectedLiquidity);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("increase liquidity of a position with an approved position authority delegate", async () => {
const currTick = 1300;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(0, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.equal(poolAfter.liquidity, 0);
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("add maximum amount of liquidity near minimum price", async () => {
const currTick = -443621;
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(currTick),
);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
const tokenAccountA = await createAndMintToTokenAccount(
provider,
tokenMintA,
MAX_U64,
);
const tokenAccountB = await createAndMintToTokenAccount(
provider,
tokenMintB,
MAX_U64,
);
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, -444224);
const tickLowerIndex = -443632;
const tickUpperIndex = -443624;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
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: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("add maximum amount of liquidity near maximum price", async () => {
const currTick = 443635;
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(currTick),
);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
const tokenAccountA = await createAndMintToTokenAccount(
provider,
tokenMintA,
MAX_U64,
);
const tokenAccountB = await createAndMintToTokenAccount(
provider,
tokenMintB,
MAX_U64,
);
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 436480);
const tickLowerIndex = 436488;
const tickUpperIndex = 436496;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
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: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("fails with zero liquidity amount", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: ZERO_BN,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when token max a exceeded", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(999_999_999),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when token max b exceeded", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(999_999_999),
tokenMaxB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when position account does not have exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const newPositionTokenAccount = await createTokenAccount(
provider,
positionInitInfo.mintKeypair.publicKey,
provider.wallet.publicKey,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
// Send position token to other position token account
await transferToken(
provider,
positionInitInfo.tokenAccount,
newPositionTokenAccount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).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,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const invalidPositionTokenAccount = await createAndMintToTokenAccount(
provider,
tokenMintA,
1,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // A raw constraint was violated
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
});
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const { poolInitInfo: poolInitInfo2 } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const positionInitInfo = await openPosition(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInitInfo.params;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
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: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has_one constraint was violated
);
});
it("fails when token vaults do not match whirlpool vaults", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const fakeVaultA = await createAndMintToTokenAccount(
provider,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccount(
provider,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const invalidMint = await createMint(provider);
const invalidTokenAccount = await createAndMintToTokenAccount(
provider,
invalidMint,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: invalidTokenAccount,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccount,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).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,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.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.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.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,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.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.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when position authority is not approved for token owner accounts", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x4/, // owner does not match
);
});
it("fails when tick arrays do not match the position", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 22528);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.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 fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = 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);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.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/swap.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import type { PDA } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { InitPoolParams, SwapParams, TickArrayData } from "../../src";
import {
MAX_SQRT_PRICE,
MAX_SQRT_PRICE_BN,
MIN_SQRT_PRICE,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteByOutputToken,
toTx,
} from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { MAX_U64, TickSpacing, ZERO_BN, getTokenBalance } from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import type { FundedPositionParams } from "../utils/init-utils";
import {
fundPositions,
initTestPool,
initTestPoolWithLiquidity,
initTestPoolWithTokens,
initTickArrayRange,
withdrawPositions,
} from "../utils/init-utils";
import type { PublicKey } from "@solana/web3.js";
describe("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);
it("fail on token vault mint a does not match whirlpool token a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: anotherPoolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token vault mint b does not match whirlpool token b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: anotherPoolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token owner account a does not match vault a mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { tokenAccountA: anotherTokenAccountA } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: anotherTokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fail on token owner account b does not match vault b mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { tokenAccountB: anotherTokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: anotherTokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails to swap with incorrect token authority", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const otherTokenAuthority = web3.Keypair.generate();
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: otherTokenAuthority.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
)
.addSigner(otherTokenAuthority)
.buildAndExecute(),
/0x4/, // OwnerMismatch
);
});
it("fails on passing in the wrong tick-array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
ctx,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(0.0242).sqrt()),
); // Negative Tick
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(-50000),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fails on passing in the wrong whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails on passing in the tick-arrays from another whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// This test case violates the constraint on vault (before tickarray)
/0x7d3/, // ConstraintRaw
);
});
it("fails on passing in the tick-arrays from another whirlpool (tickarray only)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherTickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// invalid tickArrays[0]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: anotherTickArrays[0].publicKey, // invalid
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// sparse-swap changes error code (has_one constraint -> check in the handler)
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
// invalid tickArrays[1]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: anotherTickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
// invalid tickArrays[2]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: anotherTickArrays[2].publicKey, // invalid
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fails on passing in an account of another type for the oracle", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: tickArrays[0].publicKey,
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fails on passing in an incorrectly hashed oracle PDA", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherOraclePda = PDAUtil.getOracle(
ctx.program.programId,
anotherPoolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: anotherOraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fail on passing in zero tradable amount", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
// sparse-swap: We didn't provide valid initialized tick arrays.
// The current pool tick index is 32190, so we need to provide tick array with start_tick_index 22528.
// Using sparse-swap, the validity of provided tick arrays will be evaluated before evaluating trade amount.
22528,
3,
TickSpacing.Standard,
true,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(0),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount
);
});
it("swaps across one tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const tokenVaultABefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const tokenVaultBBefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(100000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenVaultABefore.sub(quote.estimatedAmountOut).toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenVaultBBefore.add(quote.estimatedAmountIn).toString(),
);
});
it("swaps aToB across initialized tick with no movement", async () => {
const startingTick = 91720;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable, startSqrtPrice);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionParams[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
let whirlpoolData = whirlpool.getData();
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionParams[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 2,
tickUpperIndex: startingTick,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will decrement since it
// is an aToB swap ending on initialized tick, and since the tick is crossed,
// the liquidity will be added
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remaing the same, the starting tick will not decrement
// since it is an aToB swap ending on an uninitialized tick, no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
});
it("swaps aToB with small remainder across initialized tick", async () => {
const startingTick = 91728;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable, startSqrtPrice);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionParams[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
let whirlpoolData = whirlpool.getData();
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionParams[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 3,
tickUpperIndex: startingTick - tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will stay the same since it
// is an aToB swap ending on initialized tick and no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(43),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, there will be a small amount remaining that crosses
// an initialized tick index, but isn't enough to move the sqrt price.
assert.equal(
whirlpoolData.tickCurrentIndex,
startingTick - tickSpacing - 1,
);
assert.ok(
whirlpoolData.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(startingTick - tickSpacing),
),
);
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
});
it("swaps across three tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 28160, 28864
5,
TickSpacing.Stable,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27456,
tickUpperIndex: 27840,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 28864,
tickUpperIndex: 28928,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 28928,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1977429",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"869058",
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(7051000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(28500),
amountSpecifiedIsInput: true,
aToB: aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1535201",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"7920058",
);
// TODO: Verify fees and other whirlpool params
});
/* using sparse-swap, we can handle uninitialized tick-array. so this test is no longer needed.
it("Error on passing in uninitialized tick-array", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const uninitializedTickArrayPda = PDAUtil.getTickArray(ctx.program.programId, whirlpool, 0);
const oraclePda = PDAUtil.getOracle(ctx.program.programId, poolInitInfo.whirlpoolPda.publicKey);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: uninitializedTickArrayPda.publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(ctx, WhirlpoolIx.swapIx(ctx.program, params)).buildAndExecute();
assert.fail("should fail if a tick-array is uninitialized");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0xbbf/); // AccountOwnedByWrongProgram
}
});
*/
it("Error if sqrt_price_limit exceeds max", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price exceeds maximum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if sqrt_price_limit subceed min", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price subceeds minimum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if a to b swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if b to a swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if a to b swap above maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("Error if b to a swap below maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("swaps across ten tick arrays", async () => {
const {
poolInitInfo,
configKeypairs,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 30528
3,
TickSpacing.Stable,
aToB,
);
// tick array range: 27658 to 29386
// tick arrays: (27456, 28152), (28160, 28856), (28864, 29,560)
// current tick: 27727
// initialized ticks:
// 27712, 27736, 27840, 28288, 28296, 28304, 28416, 28576, 28736, 29112, 29120, 29240, 29360
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 29360,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27736,
tickUpperIndex: 29240,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27840,
tickUpperIndex: 29120,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28416,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 28304,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28296,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28576,
tickUpperIndex: 28736,
},
];
const positionInfos = await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await withdrawPositions(ctx, positionInfos, tokenAccountA, tokenAccountB);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesIx(ctx.program, {
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
configKeypairs.collectProtocolFeesAuthorityKeypair.publicKey,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(configKeypairs.collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
});
describe("partial fill, b to a", () => {
const tickSpacing = 128;
const aToB = false;
let poolInitInfo: InitPoolParams;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokens(
ctx,
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(439296 + 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
439296, // right most TickArray
1,
tickSpacing,
aToB,
);
// a: 1 (round up)
// b: 223379095563402706 (to get 1, need >= 223379095563402706)
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: 439424,
tickUpperIndex: 439552,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
});
describe("partial fill, a to b", () => {
const tickSpacing = 128;
const aToB = true;
let poolInitInfo: InitPoolParams;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokens(
ctx,
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
-450560, // left most TickArray
1,
tickSpacing,
aToB,
);
// a: 223379098170764880 (to get 1, need >= 223379098170764880)
// b: 1 (round up)
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: -439552,
tickUpperIndex: -439424,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MIN_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/initialize_reward_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import type { WhirlpoolData } from "../../../src";
import {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { ONE_SOL, systemTransferTx, TickSpacing } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
initTestPoolV2,
initializeRewardV2,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
createMintV2,
} from "../../utils/v2/token-2022";
import { TEST_TOKEN_2022_PROGRAM_ID, TEST_TOKEN_PROGRAM_ID } from "../../utils";
import { AccountState } from "@solana/spl-token";
import { Keypair } from "@solana/web3.js";
describe("initialize_reward_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully initializes reward at index 0", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const { params } = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
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(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
/custom program error: 0x178a/, // InvalidRewardIndex
);
const { params: params2 } = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
1,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
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,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool2.rewardInfos[0].vault,
tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool2.rewardInfos[1].mint.equals(params2.rewardMint));
assert.ok(
whirlpool2.rewardInfos[1].vault.equals(
params2.rewardVaultKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool2.rewardInfos[1].vault,
tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
funderKeypair,
);
});
it("fails to initialize reward at index 1", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
await assert.rejects(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
1,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
/custom program error: 0x178a/, // InvalidRewardIndex
);
});
it("fails to initialize reward at out-of-bound index", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
await assert.rejects(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
3,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
);
});
it("fails to initialize if authority signature is missing", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardMint = await createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
).buildAndExecute(),
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed reward_token_program is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: false });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed reward_token_program is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: true });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: TEST_TOKEN_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed reward_token_program is token_metadata", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: true });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: METADATA_PROGRAM_ADDRESS,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
describe("invalid badge account", () => {
it("fails when reward_token_badge address invalid (uninitialized)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const fakeAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when reward_token_badge address invalid (initialized, same config / different mint)", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const anotherMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
// initialize another badge
const config = poolInitInfo.whirlpoolsConfig;
const configExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
);
const anotherMintTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
anotherMint,
);
const tokenBadgeAuthority =
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair;
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension: configExtensionPda.publicKey,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: tokenBadgeAuthority.publicKey,
tokenBadgePda: anotherMintTokenBadgePda,
tokenMint: anotherMint,
}),
)
.addSigner(tokenBadgeAuthority)
.buildAndExecute();
const badge = fetcher.getTokenBadge(
anotherMintTokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(badge !== null);
const fakeAddress = anotherMintTokenBadgePda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when reward_token_badge address invalid (initialized, account owned by WhirlpoolProgram)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const fakeAddress = poolInitInfo.whirlpoolPda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
});
});
describe("Supported Tokens", () => {
async function runTest(params: {
supported: boolean;
createTokenBadge: boolean;
tokenTrait: TokenTrait;
anchorPatch?: boolean;
}) {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const config = poolInitInfo.whirlpoolsConfig;
const rewardToken = await createMintV2(provider, params.tokenTrait);
const tokenProgram = (await provider.connection.getAccountInfo(
rewardToken,
))!.owner;
// create token badge if wanted
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
rewardToken,
);
if (params.createTokenBadge) {
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension:
configExtension.configExtensionInitInfo
.whirlpoolsConfigExtensionPda.publicKey,
funder: provider.wallet.publicKey,
tokenBadgeAuthority:
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair
.publicKey,
tokenBadgePda,
tokenMint: rewardToken,
}),
)
.addSigner(
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
)
.buildAndExecute();
}
// try to initialize reward
const promise = toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint: rewardToken,
rewardTokenBadge: tokenBadgePda.publicKey,
rewardTokenProgram: tokenProgram,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
if (params.supported) {
await promise;
const whirlpoolData = await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpoolData!.rewardInfos[0].mint.equals(rewardToken));
} else {
await assert.rejects(
promise,
!params.anchorPatch
? /0x179f/ // UnsupportedTokenMint
: /invalid account data for instruction/, // Anchor v0.29 doesn't recognize some new extensions (GroupPointer, Group, MemberPointer, Member)
);
}
}
it("Token: mint without FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
},
});
});
it("Token: mint with FreezeAuthority", async () => {
// not good, but allowed for compatibility to initialize_pool
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
hasFreezeAuthority: true,
},
});
});
it("Token: native mint (WSOL)", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
isNativeMint: true,
},
});
});
it("Token-2022: with TransferFeeConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
},
});
});
it("Token-2022: with InterestBearingConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasInterestBearingExtension: true,
},
});
});
it("Token-2022: with MetadataPointer & TokenMetadata", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTokenMetadataExtension: true,
hasMetadataPointerExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
});
});
it("Token-2022: with TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: with TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: with TokenBadge with TransferHook", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: with TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: with TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] with TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with TransferHook", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] with/without TokenBadge, native mint (WSOL-2022)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
isNativeMint: true,
},
});
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
isNativeMint: true,
},
});
});
// [11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Group", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Group
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with GroupPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize GroupPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Member", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Member
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with MemberPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize MemberPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with NonTransferable", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasNonTransferableExtension: true,
};
await runTest({ supported: false, createTokenBadge: true, tokenTrait });
await runTest({ supported: false, createTokenBadge: false, tokenTrait });
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/increase_liquidity_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder } 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 {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
PriceMath,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { PoolUtil, toTokenAmount } from "../../../src/utils/public/pool-utils";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
approveToken as approveTokenForPosition,
assertTick,
getTokenBalance,
sleep,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { initTickArray, openPosition } from "../../utils/init-utils";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createMintV2,
createAndMintToTokenAccountV2,
approveTokenV2,
} from "../../utils/v2/token-2022";
import {
createTokenAccount as createTokenAccountForPosition,
createAndMintToTokenAccount as createAndMintToTokenAccountForPosition,
} from "../../utils/token";
import {
generateDefaultInitTickArrayParams,
generateDefaultOpenPositionParams,
} from "../../utils/test-builders";
describe("increase_liquidity_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("increase liquidity of a position spanning two tick arrays", async () => {
const currTick = 0;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(167_000, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// To check if rewardLastUpdatedTimestamp is updated
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gt(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.ok(poolAfter.liquidity.eq(new anchor.BN(liquidityAmount)));
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("increase liquidity of a position contained in one tick array", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArray.ticks[56],
true,
expectedLiquidity,
expectedLiquidity,
);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("initialize and increase liquidity of a position in a single transaction", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tickSpacing } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const { params, mint } = await generateDefaultOpenPositionParams(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
ctx.wallet.publicKey,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing),
).publicKey;
await new TransactionBuilder(
ctx.provider.connection,
ctx.provider.wallet,
ctx.txBuilderOpts,
)
// TODO: create a ComputeBudgetInstruction to request more compute
.addInstruction(
WhirlpoolIx.initTickArrayIx(
ctx.program,
generateDefaultInitTickArrayParams(
ctx,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
),
),
)
// .addInstruction(
// buildtoTx(ctx, WhirlpoolIx.initTickArrayIx(generateDefaultInitTickArrayParams(
// ctx,
// whirlpoolPda.publicKey,
// getStartTickIndex(pos[0].tickLowerIndex + TICK_ARRAY_SIZE * tickSpacing, tickSpacing),
// ))
// )
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, params))
// .addInstruction(
// buildWhirlpoolIx.openPositionWithMetadataIx(ctx.program, params)
// )
.addSigner(mint)
.addInstruction(
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: params.positionPda.publicKey,
positionTokenAccount: params.positionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLower,
tickArrayUpper: tickArrayUpper,
}),
)
.buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
params.positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArray.ticks[56],
true,
expectedLiquidity,
expectedLiquidity,
);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("increase liquidity of a position with an approved position authority delegate", async () => {
const currTick = 1300;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(0, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.equal(poolAfter.liquidity, 0);
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("add maximum amount of liquidity near minimum price", async () => {
const currTick = -443621;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Stable,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
mintAmount: MAX_U64,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, -444224);
const tickLowerIndex = -443632;
const tickUpperIndex = -443624;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("add maximum amount of liquidity near maximum price", async () => {
const currTick = 443635;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Stable,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
mintAmount: MAX_U64,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 436480);
const tickLowerIndex = 436488;
const tickUpperIndex = 436496;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("fails with zero liquidity amount", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: ZERO_BN,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when token max a exceeded", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(999_999_999),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when token max b exceeded", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(999_999_999),
tokenMaxB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when position account does not have exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const newPositionTokenAccount = await createTokenAccountForPosition(
provider,
positionInitInfo.mintKeypair.publicKey,
provider.wallet.publicKey,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
// Send position token to other position token account
await transferToken(
provider,
positionInitInfo.tokenAccount,
newPositionTokenAccount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position token account mint does not match position mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const fakeMint = await createMintV2(provider, { isToken2022: false });
const invalidPositionTokenAccount =
await createAndMintToTokenAccountForPosition(provider, fakeMint, 1);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // A raw constraint was violated
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
const positionInitInfo = await openPosition(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInitInfo.params;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has_one constraint was violated
);
});
it("fails when token vaults do not match whirlpool vaults", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const fakeVaultA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const invalidMintA = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const invalidTokenAccountA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
invalidMintA,
1_000_000,
);
const invalidMintB = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const invalidTokenAccountB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
invalidMintB,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: invalidTokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
0,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority was not a signer", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when position authority is not approved for token owner accounts", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x4/, // owner does not match
);
});
it("fails when tick arrays do not match the position", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 22528);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
-11264,
);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.increaseLiquidityV2(
liquidityAmount,
tokenAmount.tokenA, // maxA
tokenAmount.tokenB, // maxB
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_reward_v2.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 {
buildWhirlpoolClient,
collectRewardsQuote,
METADATA_PROGRAM_ADDRESS,
NUM_REWARDS,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
approveToken,
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
transferToken,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createTokenAccountV2, createMintV2 } from "../../utils/v2/token-2022";
import { createTokenAccount as createTokenAccountForPosition } from "../../utils/token";
import { NATIVE_MINT } from "@solana/spl-token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("collect_reward_v2", () => {
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);
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully collect rewards", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
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: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[i].rewardMint,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
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.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
const delegatePositionAccount = await createTokenAccountForPosition(
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.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: delegatePositionAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
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.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute();
});
it("fails when reward index references an uninitialized reward", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
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 createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
fakeRewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: fakeRewardMint,
rewardTokenProgram: tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
rewardOwnerAccount,
rewardVault: anchor.web3.PublicKey.default,
rewardIndex: 0,
}),
).buildAndExecute(),
/0xbbf/, // AccountNotInitialized
);
});
it("fails when position does not match whirlpool", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const { positions, rewards } = fixture.getInfos();
// accrue rewards
await sleep(1200);
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
});
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const otherPositionAcount = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await transferToken(
provider,
positions[0].tokenAccount,
otherPositionAcount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const fakePositionTokenAccount = await createTokenAccountForPosition(
provider,
NATIVE_MINT,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: fakePositionTokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
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.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
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.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 fakeMint = await createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
fakeMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
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 WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 4,
}),
).buildAndExecute(),
/Program failed to complete/, // index out of bounds
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed reward_mint does not match whirlpool's reward_infos", async () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
{ isToken2022: true },
];
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits[0],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits[1],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits[2],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits[i],
rewards[i].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: otherTokenPublicKey, // invalid
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is not token program (token-2022 is passed)", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: false },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is not token-2022 program (token is passed)", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: true },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: TEST_TOKEN_PROGRAM_ID, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is token_metadata", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: true },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: METADATA_PROGRAM_ADDRESS, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
}
});
it("fails when passed memo_program is token_metadata", async () => {});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_fees_v2.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,
METADATA_PROGRAM_ADDRESS,
PDAUtil,
TickArrayUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
approveToken,
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
transferToken,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createMintV2, createTokenAccountV2 } from "../../utils/v2/token-2022";
import { createTokenAccount as createTokenAccountForPosition } from "../../utils/token";
import { NATIVE_MINT } from "@solana/spl-token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("collect_fees_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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,
tokenProgramA,
tokenProgramB,
},
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const feeAccountB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const position = positions[0];
const newOwner = anchor.web3.Keypair.generate();
const newOwnerPositionTokenAccount =
await createTokenAccountForPosition(
provider,
position.mintKeypair.publicKey,
newOwner.publicKey,
);
await transferToken(
provider,
position.tokenAccount,
newOwnerPositionTokenAccount,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: newOwner.publicKey,
position: position.publicKey,
positionTokenAccount: newOwnerPositionTokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const positionTokenAccount2 = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positionTokenAccount2,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const delegate = anchor.web3.Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
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.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const fakePositionTokenAccount = await createTokenAccountForPosition(
provider,
NATIVE_MINT,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: fakePositionTokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const fakeVaultA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const fakeVaultB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const invalidOwnerAccountA = await createTokenAccountV2(
provider,
// invalid token trait & mint
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
const invalidOwnerAccountB = await createTokenAccountV2(
provider,
// invalid token trait & mint
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: invalidOwnerAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidOwnerAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
//tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
//tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.collectFeesV2(
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenProgramA,
tokenProgramB,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/two_hop_swap_v2.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, WhirlpoolData } from "../../../src";
import {
buildWhirlpoolClient,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
SwapUtils,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import type {
InitPoolV2Params,
TwoHopSwapV2Params,
} from "../../../src/instructions";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { InitAquariumV2Params } from "../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../utils/v2/aquarium-v2";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
createMintV2,
} from "../../utils/v2/token-2022";
import {
NO_TOKEN_EXTENSION_CONTEXT,
TokenExtensionUtil,
} from "../../../src/utils/public/token-extension-util";
describe("two_hop_swap_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
// 8 patterns for tokenTraitA, tokenTraitB, tokenTraitC
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tokenTraitC: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitC: ${tokenTraits.tokenTraitC.isToken2022 ? "Token2022" : "Token"}`, () => {
let aqConfig: InitAquariumV2Params;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
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: FundedPositionV2Params[] = [
{
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: TwoHopSwapV2Params;
beforeEach(async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[0],
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[1],
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[2],
tokenTraits.tokenTraitC.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo =
whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
it("fails invalid whirlpool", async () => {
await rejectParams(
{
...baseIxParams,
whirlpoolOne: baseIxParams.whirlpoolTwo,
},
///0x7d3/ // ConstraintRaw
// V2 has token_mint_one_a and it has address constraint
/0x7dc/, // ConstraintAddress
);
});
it("fails invalid token account", async () => {
await rejectParams(
{
...baseIxParams,
tokenOwnerAccountInput: baseIxParams.tokenOwnerAccountOutput,
},
/0x7d3/, // ConstraintRaw
);
await rejectParams(
{
...baseIxParams,
tokenOwnerAccountOutput: baseIxParams.tokenOwnerAccountInput,
},
/0x7d3/, // ConstraintRaw
);
});
it("fails invalid token vault", async () => {
await rejectParams(
{
...baseIxParams,
tokenVaultOneInput: baseIxParams.tokenVaultOneIntermediate,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultOneIntermediate: baseIxParams.tokenVaultOneInput,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultTwoIntermediate: baseIxParams.tokenVaultTwoOutput,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultTwoOutput: baseIxParams.tokenVaultTwoIntermediate,
},
/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.tokenVaultOneInput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayOne1: baseIxParams.tokenVaultOneInput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayOne2: baseIxParams.tokenVaultOneInput,
},
/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.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayTwo1: baseIxParams.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayTwo2: baseIxParams.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
});
});
it("swaps [2] with two-hop swap, amountSpecifiedIsInput=true", async () => {
const aquarium = (await buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [tokenA, tokenB, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBOne = whirlpoolDataOne.tokenMintA.equals(tokenA);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(tokenB);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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 aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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({ tokenTrait: { isToken2022: true } });
aqConfig.initTokenAccParams.push({ mintIndex: 3 });
aqConfig.initPoolParams[1].mintIndices = [2, 3];
const aquarium = (await buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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 aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// 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(
whirlpoolDataOne.sqrtPrice
.sub(quote.estimatedEndSqrtPrice)
.mul(new anchor.BN("5"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postWhirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
//const postWhirlpoolDataTwo = await fetcher.getPool(whirlpoolTwoKey, IGNORE_CACHE) as WhirlpoolData;
assert.equal(
postWhirlpoolDataOne.sqrtPrice.eq(quote.sqrtPriceLimit),
true,
);
});
it("fails: swaps [2] with two-hop swap, amount_specified_is_input=true, second swap price limit", async () => {
// ATTENTION: v1 and v2 are different
// v2 use vault to vault transfer, so the output of first swap MUST be equal to the input of the second swap.
// So not-full-filled swap will be rejected.
const aquarium = (await buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is less than the 1% slippage threshold,
// which will result non-full-filled second swap
quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add(
whirlpoolDataTwo.sqrtPrice
.sub(quote2.estimatedEndSqrtPrice)
.mul(new anchor.BN("5"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
});
it("fails: swaps [2] with two-hop swap, amount_specified_is_input=false, first swap price limit", async () => {
// ATTENTION: v1 and v2 are different
// v2 use vault to vault transfer, so the output of first swap MUST be equal to the input of the second swap.
// So not-full-filled swap will be rejected.
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// add sqrtPriceLimit on quote
quote.sqrtPriceLimit = aToBOne
? quote.estimatedEndSqrtPrice.addn(1)
: quote.estimatedEndSqrtPrice.subn(1);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// 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(
whirlpoolDataOne.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.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
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 buildTestAquariumsV2(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 whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
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
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is greater than the 1% slippage threshold,
// which will cause the swap to fail
quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add(
whirlpoolDataTwo.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.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
);
});
});
});
});
describe("v2 specific accounts", () => {
describe("with Token-2022", () => {
const tokenTraits = {
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
};
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let otherTokenPublicKey: PublicKey;
beforeEach(async () => {
otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
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: FundedPositionV2Params[] = [
{
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 buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
describe("fails when passed token_mint_* does not match whirlpool's token_mint_*_*", () => {
it("token_mint_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintInput: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_mint_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintIntermediate: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_mint_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintOutput: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
});
describe("fails when passed token_program_* is not token-2022 program (token is passed)", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
});
describe("fails when passed token_program_*_* is token_metadata", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
});
it("fails when passed memo_program is token_metadata", async () => {
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
{ slices: [] },
{
accounts: {
...baseIxParams,
memoProgram: METADATA_PROGRAM_ADDRESS,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
describe("with Token", () => {
const tokenTraits = {
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
};
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
beforeEach(async () => {
await createMintV2(provider, {
isToken2022: false,
});
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
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: FundedPositionV2Params[] = [
{
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 buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
describe("fails when passed token_program_* is not token program (token-2022 is passed)", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
});
});
});
describe("partial fill", () => {
const client = buildWhirlpoolClient(ctx);
const aqConfig = {
...getDefaultAquariumV2(),
initMintParams: [
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
],
initTokenAccParams: [
{ mintIndex: 0 },
{ mintIndex: 1 },
{ mintIndex: 2 },
],
initPoolParams: [
{ mintIndices: [0, 1] as [number, number], tickSpacing: 128 },
{ mintIndices: [1, 2] as [number, number], tickSpacing: 128 },
],
};
// 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 buildTestAquariumsV2(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.twoHopSwapV2Ix(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]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum.
);
assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(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]],
[true, true],
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 buildTestAquariumsV2(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.twoHopSwapV2Ix(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]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(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]],
[true, true],
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 buildTestAquariumsV2(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.twoHopSwapV2Ix(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]],
[true, true],
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
// This case must be rejected due to vault to vault transfer
// |-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 buildTestAquariumsV2(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.twoHopSwapV2Ix(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]],
[true, true],
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 buildTestAquariumsV2(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.twoHopSwapV2Ix(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]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(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]],
[true, true],
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 buildTestAquariumsV2(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.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1002), // Partial fill
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
assert.ok(quoteSecond.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(999),
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
});
});
async function rejectParams(
params: TwoHopSwapV2Params,
error: assert.AssertPredicate,
) {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, params),
).buildAndExecute(),
error,
);
}
function getParamsFromPools(
pools: [InitPoolV2Params, InitPoolV2Params],
aToBs: boolean[],
tokenAccounts: {
mint: PublicKey;
account: PublicKey;
tokenTrait: TokenTrait;
}[],
) {
const [aToBOne, aToBTwo] = aToBs;
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const whirlpoolOne = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwo = pools[1].whirlpoolPda.publicKey;
const tokenMintOneA = pools[0].tokenMintA;
const tokenMintOneB = pools[0].tokenMintB;
const tokenMintTwoA = pools[1].tokenMintA;
const tokenMintTwoB = pools[1].tokenMintB;
const tokenProgramOneA = pools[0].tokenProgramA;
const tokenProgramOneB = pools[0].tokenProgramB;
const tokenProgramTwoA = pools[1].tokenProgramA;
const tokenProgramTwoB = pools[1].tokenProgramB;
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,
oracleOne,
oracleTwo,
// mints
tokenMintInput: aToBOne ? tokenMintOneA : tokenMintOneB,
tokenMintIntermediate: aToBOne ? tokenMintOneB : tokenMintOneA,
tokenMintOutput: aToBTwo ? tokenMintTwoB : tokenMintTwoA,
// token programs
tokenProgramInput: aToBOne ? tokenProgramOneA : tokenProgramOneB,
tokenProgramIntermediate: aToBOne ? tokenProgramOneB : tokenProgramOneA,
tokenProgramOutput: aToBTwo ? tokenProgramTwoB : tokenProgramTwoA,
// accounts
tokenOwnerAccountInput: aToBOne ? tokenAccKeys[0] : tokenAccKeys[1],
tokenVaultOneInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo ? tokenAccKeys[3] : tokenAccKeys[2],
};
}
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/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/swap_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import type { PDA } from "@orca-so/common-sdk";
import * as assert from "assert";
import { BN } from "bn.js";
import Decimal from "decimal.js";
import type {
InitPoolV2Params,
SwapV2Params,
TickArrayData,
WhirlpoolData,
} from "../../../src";
import {
MAX_SQRT_PRICE,
MAX_SQRT_PRICE_BN,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
SwapUtils,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
getTokenBalance,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { initTickArrayRange } from "../../utils/init-utils";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolV2,
initTestPoolWithLiquidityV2,
initTestPoolWithTokensV2,
withdrawPositionsV2,
} from "../../utils/v2/init-utils-v2";
import { createMintV2 } from "../../utils/v2/token-2022";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import type { PublicKey } from "@solana/web3.js";
describe("swap_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitR: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("fail on token vault mint a does not match whirlpool token a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: anotherPoolInitInfo.tokenVaultAKeypair.publicKey, // invalid
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token vault mint b does not match whirlpool token b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: anotherPoolInitInfo.tokenVaultBKeypair.publicKey, // invalid
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token owner account a does not match vault a mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { tokenAccountA: anotherTokenAccountA } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: anotherTokenAccountA, // invalid
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fail on token owner account b does not match vault b mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { tokenAccountB: anotherTokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: anotherTokenAccountB, // invalid
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails to swap with incorrect token authority", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const otherTokenAuthority = web3.Keypair.generate();
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: otherTokenAuthority.publicKey, // invalid
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
)
.addSigner(otherTokenAuthority)
.buildAndExecute(),
/0x4/, // OwnerMismatch
);
});
it("fails on passing in the wrong tick-array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(0.0242).sqrt()),
); // Negative Tick
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(-50000),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fails on passing in the wrong whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey, // invalid
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress at token_mint_a (V1: 0x7d3 (ConstraaintRaw) at token_owner_account_a)
);
});
it("fails on passing in the tick-arrays from another whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey, // invalid
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// sparse-swap changes error code (has_one constraint -> check in the handler)
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fails on passing in an account of another type for the oracle", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: tickArrays[0].publicKey, // invalid
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fails on passing in an incorrectly hashed oracle PDA", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherOraclePda = PDAUtil.getOracle(
ctx.program.programId,
anotherPoolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: anotherOraclePda.publicKey, // invalid
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fail on passing in zero tradable amount", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
// sparse-swap: We didn't provide valid initialized tick arrays.
// The current pool tick index is 32190, so we need to provide tick array with start_tick_index 22528.
// Using sparse-swap, the validity of provided tick arrays will be evaluated before evaluating trade amount.
22528,
3,
TickSpacing.Standard,
true,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(0),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount
);
});
it("swaps across one tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const tokenVaultABefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const tokenVaultBBefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
/* replaceed by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(100000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenVaultABefore.sub(quote.estimatedAmountOut).toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenVaultBBefore.add(quote.estimatedAmountIn).toString(),
);
});
it("swaps aToB across initialized tick with no movement", async () => {
const startingTick = 91720;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
startSqrtPrice,
);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionV2Params[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionV2Params[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 2,
tickUpperIndex: startingTick,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will decrement since it
// is an aToB swap ending on initialized tick, and since the tick is crossed,
// the liquidity will be added
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remaing the same, the starting tick will not decrement
// since it is an aToB swap ending on an uninitialized tick, no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
});
it("swaps aToB with small remainder across initialized tick", async () => {
const startingTick = 91728;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
startSqrtPrice,
);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionV2Params[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionV2Params[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 3,
tickUpperIndex: startingTick - tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will stay the same since it
// is an aToB swap ending on initialized tick and no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(43),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(43),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, there will be a small amount remaining that crosses
// an initialized tick index, but isn't enough to move the sqrt price.
assert.equal(
whirlpoolData.tickCurrentIndex,
startingTick - tickSpacing - 1,
);
assert.ok(
whirlpoolData.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(startingTick - tickSpacing),
),
);
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
});
it("swaps across three tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 28160, 28864
5,
TickSpacing.Stable,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27456,
tickUpperIndex: 27840,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 28864,
tickUpperIndex: 28928,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 28928,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1977429",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"869058",
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(7051000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(28500),
amountSpecifiedIsInput: true,
aToB: aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1535201",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"7920058",
);
// TODO: Verify fees and other whirlpool params
});
/* using sparse-swap, we can handle uninitialized tick-array. so this test is no longer needed.
it("Error on passing in uninitialized tick-array", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const uninitializedTickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
0
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: uninitializedTickArrayPda.publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(ctx, WhirlpoolIx.swapV2Ix(ctx.program, params)).buildAndExecute();
assert.fail("should fail if a tick-array is uninitialized");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0xbbf/); // AccountOwnedByWrongProgram
}
});
*/
it("Error if sqrt_price_limit exceeds max", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price exceeds maximum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if sqrt_price_limit subceed min", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price subceeds minimum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if a to b swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if b to a swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if a to b swap above maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("Error if b to a swap below maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("swaps across ten tick arrays", async () => {
const {
poolInitInfo,
configKeypairs,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 30528
3,
TickSpacing.Stable,
aToB,
);
// tick array range: 27658 to 29386
// tick arrays: (27456, 28152), (28160, 28856), (28864, 29,560)
// current tick: 27727
// initialized ticks:
// 27712, 27736, 27840, 28288, 28296, 28304, 28416, 28576, 28736, 29112, 29120, 29240, 29360
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 29360,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27736,
tickUpperIndex: 29240,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27840,
tickUpperIndex: 29120,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28416,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 28304,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28296,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28576,
tickUpperIndex: 28736,
},
];
const positionInfos = await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await withdrawPositionsV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
positionInfos,
tokenAccountA,
tokenAccountB,
);
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
configKeypairs.collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(configKeypairs.collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
});
});
});
describe("partial fill, b to a", () => {
const tickSpacing = 128;
const aToB = false;
const client = buildWhirlpoolClient(ctx);
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(439296 + 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
439296, // right most TickArray
1,
tickSpacing,
aToB,
);
// a: 1 (round up)
// b: 223379095563402706 (to get 1, need >= 223379095563402706)
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: 439424,
tickUpperIndex: 439552,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[anchor.BN, anchor.BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
});
describe("partial fill, a to b", () => {
const tickSpacing = 128;
const aToB = true;
const client = buildWhirlpoolClient(ctx);
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
-450560, // left most TickArray
1,
tickSpacing,
aToB,
);
// a: 223379098170764880 (to get 1, need >= 223379098170764880)
// b: 1 (round up)
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: -439552,
tickUpperIndex: -439424,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[anchor.BN, anchor.BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MIN_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.swapV2(
new BN(10), // amount
ZERO_BN, // otherAmountThreshold
MathUtil.toX64(new Decimal(4.95)), // sqrtPriceLimit
true, // amountSpecifiedIsInput
true, // aToB
{ slices: [] },
{
accounts: {
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/initialize_pool_v2.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 { InitPoolV2Params, WhirlpoolData } from "../../../src";
import {
IGNORE_CACHE,
MAX_SQRT_PRICE,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE,
PDAUtil,
PoolUtil,
PriceMath,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import {
ONE_SOL,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
systemTransferTx,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
buildTestPoolV2Params,
initTestPoolV2,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
asyncAssertTokenVaultV2,
createMintV2,
initializeNativeMint2022Idempotent,
} from "../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import { AccountState, NATIVE_MINT, NATIVE_MINT_2022 } from "@solana/spl-token";
import { initFeeTier } from "../../utils/init-utils";
describe("initialize_pool_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully init a Standard account", async () => {
const price = MathUtil.toX64(new Decimal(5));
const { configInitInfo, poolInitInfo, feeTierParams } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
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,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintA,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB));
assert.ok(
whirlpool.tokenVaultB.equals(
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintB,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
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,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintA,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB));
assert.ok(
whirlpool.tokenVaultB.equals(
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintB,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
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 initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(5)),
funderKeypair,
);
});
it("fails when tokenVaultA mint does not match tokenA mint", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const otherTokenPublicKey = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenMintA: otherTokenPublicKey,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when tokenVaultB mint does not match tokenB mint", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const otherTokenPublicKey = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenMintB: otherTokenPublicKey,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token mints are in the wrong order", async () => {
const { poolInitInfo, configInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda,
tickSpacing: TickSpacing.Standard,
tokenMintA: poolInitInfo.tokenMintB,
tokenBadgeA: poolInitInfo.tokenBadgeB,
tokenProgramA: tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
tokenMintB: poolInitInfo.tokenMintA,
tokenBadgeB: poolInitInfo.tokenBadgeA,
tokenProgramB: tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x1788/, // InvalidTokenMintOrder
);
});
it("fails when the same token mint is passed in", async () => {
const { poolInitInfo, configInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintA,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda,
tickSpacing: TickSpacing.Standard,
tokenMintB: poolInitInfo.tokenMintA,
tokenBadgeB: poolInitInfo.tokenBadgeA,
tokenProgramB: tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x1788/, // InvalidTokenMintOrder
);
});
it("fails when sqrt-price exceeds max", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
initSqrtPrice: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x177b/, // SqrtPriceOutOfBounds
);
});
it("fails when sqrt-price subceeds min", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
initSqrtPrice: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x177b/, // SqrtPriceOutOfBounds
);
});
it("ignore passed bump", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
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: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda: modifiedWhirlpoolPda,
};
await toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(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);
});
});
});
});
it("fails when FeeTier and tick_spacing passed unmatch", async () => {
const { poolInitInfo, configInitInfo, configKeypairs } =
await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
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.initializePoolV2Ix(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.initializePoolV2Ix(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.initializePoolV2Ix(ctx.program, {
...poolInitInfo,
whirlpoolPda: whirlpoolWithStableTickSpacing,
tickSpacing: TickSpacing.Stable,
feeTierKey: feeTierStablePda.publicKey,
}),
).buildAndExecute();
});
describe("v2 specific accounts", () => {
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: METADATA_PROGRAM_ADDRESS,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: METADATA_PROGRAM_ADDRESS,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
describe("invalid badge account", () => {
let baseIxParams: InitPoolV2Params;
beforeEach(async () => {
// create tokens
const [tokenAKeypair, tokenBKeypair] = [
Keypair.generate(),
Keypair.generate(),
].sort((a, b) => PoolUtil.compareMints(a.publicKey, b.publicKey));
await createMintV2(
provider,
{ isToken2022: true, hasPermanentDelegate: true },
undefined,
tokenAKeypair,
);
await createMintV2(
provider,
{ isToken2022: true, hasPermanentDelegate: true },
undefined,
tokenBKeypair,
);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = TickSpacing.SixtyFour;
const feeTierPda = PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
);
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: feeTierPda,
}),
).buildAndExecute();
// create config extension
const configExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: configExtensionPda,
}),
).buildAndExecute();
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configKeypair.publicKey,
tokenAKeypair.publicKey,
tokenBKeypair.publicKey,
tickSpacing,
);
baseIxParams = {
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
funder: provider.wallet.publicKey,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tickSpacing,
tokenMintA: tokenAKeypair.publicKey,
tokenMintB: tokenBKeypair.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
feeTierKey: feeTierPda.publicKey,
tokenBadgeA: PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenAKeypair.publicKey,
).publicKey,
tokenBadgeB: PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenBKeypair.publicKey,
).publicKey,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
whirlpoolPda,
};
});
it("fails when token_badge_a/b address invalid (uninitialized)", async () => {
const fakeAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token_badge_a/b address invalid (initialized, same config / different mint)", async () => {
const config = baseIxParams.whirlpoolsConfig;
const anotherTokenKeypair = Keypair.generate();
await createMintV2(
provider,
{ isToken2022: true },
undefined,
anotherTokenKeypair,
);
// initialize another badge
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
anotherTokenKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: anotherTokenKeypair.publicKey,
}),
).buildAndExecute();
const badge = fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(badge !== null);
const fakeAddress = tokenBadgePda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token_badge_a/b address invalid (account owned by WhirlpoolProgram)", async () => {
// use Whirlpool address
const { poolInitInfo } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const fakeAddress = poolInitInfo.whirlpoolPda.publicKey;
const whirlpool = fetcher.getPool(fakeAddress);
assert.ok(whirlpool !== null);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
});
});
describe("Supported Tokens", () => {
function generate3MintAddress(): [Keypair, Keypair, Keypair] {
const keypairs = [
Keypair.generate(),
Keypair.generate(),
Keypair.generate(),
].sort((a, b) => PoolUtil.compareMints(a.publicKey, b.publicKey));
return [keypairs[0], keypairs[1], keypairs[2]];
}
async function checkSupported(
supported: boolean,
whirlpoolsConfig: PublicKey,
tokenMintA: PublicKey,
tokenMintB: PublicKey,
tickSpacing: number,
anchorPatch: boolean = false,
) {
const tokenVaultAKeypair = Keypair.generate();
const tokenVaultBKeypair = Keypair.generate();
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
whirlpoolsConfig,
tokenMintA,
tokenMintB,
tickSpacing,
);
const feeTierKey = PDAUtil.getFeeTier(
ctx.program.programId,
whirlpoolsConfig,
tickSpacing,
).publicKey;
const tokenBadgeA = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfig,
tokenMintA,
).publicKey;
const tokenBadgeB = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfig,
tokenMintB,
).publicKey;
const tokenProgramA = (await provider.connection.getAccountInfo(
tokenMintA,
))!.owner;
const tokenProgramB = (await provider.connection.getAccountInfo(
tokenMintB,
))!.owner;
const promise = toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
tokenVaultAKeypair,
tokenVaultBKeypair,
funder: provider.wallet.publicKey,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tickSpacing,
tokenMintA,
tokenMintB,
whirlpoolsConfig,
feeTierKey,
tokenBadgeA,
tokenBadgeB,
tokenProgramA,
tokenProgramB,
whirlpoolPda,
}),
).buildAndExecute();
if (supported) {
await promise;
const whirlpoolData = await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpoolData!.tokenMintA.equals(tokenMintA));
assert.ok(whirlpoolData!.tokenMintB.equals(tokenMintB));
} else {
await assert.rejects(
promise,
!anchorPatch
? /0x179f/ // UnsupportedTokenMint
: /invalid account data for instruction/, // Anchor v0.29 doesn't recognize some new extensions (GroupPointer, Group, MemberPointer, Member)
);
}
}
async function runTest(params: {
supported: boolean;
createTokenBadge: boolean;
tokenTrait: TokenTrait;
anchorPatch?: boolean;
}) {
// create tokens
const [tokenA, tokenTarget, tokenB] = generate3MintAddress();
await createMintV2(provider, { isToken2022: false }, undefined, tokenA);
await createMintV2(provider, { isToken2022: false }, undefined, tokenB);
await createMintV2(provider, params.tokenTrait, undefined, tokenTarget);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = 64;
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
),
}),
).buildAndExecute();
// create token badge if wanted
if (params.createTokenBadge) {
const pda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: pda,
}),
).buildAndExecute();
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenTarget.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: tokenTarget.publicKey,
}),
).buildAndExecute();
}
const isSupportedToken = await PoolUtil.isSupportedToken(
ctx,
configKeypair.publicKey,
tokenTarget.publicKey,
);
assert.equal(isSupportedToken, params.supported);
// try to initialize pool
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenA.publicKey,
tokenTarget.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenB
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenTarget.publicKey,
tokenB.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenA
}
async function runTestWithNativeMint(params: {
supported: boolean;
createTokenBadge: boolean;
isToken2022NativeMint: boolean;
anchorPatch?: boolean;
}) {
// We need to call this to use NATIVE_MINT_2022
await initializeNativeMint2022Idempotent(provider);
// create tokens
const nativeMint = params.isToken2022NativeMint
? NATIVE_MINT_2022
: NATIVE_MINT;
let tokenA = Keypair.generate();
while (PoolUtil.compareMints(tokenA.publicKey, nativeMint) >= 0)
tokenA = Keypair.generate();
let tokenB = Keypair.generate();
while (PoolUtil.compareMints(nativeMint, tokenB.publicKey) >= 0)
tokenB = Keypair.generate();
assert.ok(
PoolUtil.orderMints(tokenA.publicKey, nativeMint)[1].toString() ===
nativeMint.toString(),
);
assert.ok(
PoolUtil.orderMints(nativeMint, tokenB.publicKey)[0].toString() ===
nativeMint.toString(),
);
await createMintV2(provider, { isToken2022: false }, undefined, tokenA);
await createMintV2(provider, { isToken2022: false }, undefined, tokenB);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = 64;
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
),
}),
).buildAndExecute();
// create token badge if wanted
if (params.createTokenBadge) {
const pda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: pda,
}),
).buildAndExecute();
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
nativeMint,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: nativeMint,
}),
).buildAndExecute();
}
// try to initialize pool
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenA.publicKey,
nativeMint,
tickSpacing,
params.anchorPatch,
); // as TokenB
await checkSupported(
params.supported,
configKeypair.publicKey,
nativeMint,
tokenB.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenA
}
it("Token: mint without FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
},
});
});
it("Token: mint with FreezeAuthority", async () => {
// not good, but allowed for compatibility to initialize_pool
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
hasFreezeAuthority: true,
},
});
});
it("Token: native mint (WSOL)", async () => {
await runTestWithNativeMint({
supported: true,
createTokenBadge: false,
isToken2022NativeMint: false,
});
});
it("Token-2022: with TransferFeeConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
},
});
});
it("Token-2022: with InterestBearingConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasInterestBearingExtension: true,
},
});
});
it("Token-2022: with MetadataPointer & TokenMetadata", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTokenMetadataExtension: true,
hasMetadataPointerExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint & TransferFeeConfig (& ConfidentialTransferFeeConfig)", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
// test util will automatically initialize ConfidentialTransferFeeConfig
},
});
});
it("Token-2022: with TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: with TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: with TokenBadge with TransferHook", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: with TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: with TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] with TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with TransferHook", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] with/without TokenBadge, native mint (WSOL-2022)", async () => {
await runTestWithNativeMint({
supported: false,
createTokenBadge: false,
isToken2022NativeMint: true,
});
await runTestWithNativeMint({
supported: false,
createTokenBadge: true,
isToken2022NativeMint: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Group", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Group
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with GroupPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize GroupPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Member", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Member
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with MemberPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize MemberPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with NonTransferable", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasNonTransferableExtension: true,
};
await runTest({ supported: false, createTokenBadge: true, tokenTrait });
await runTest({ supported: false, createTokenBadge: false, tokenTrait });
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/decrease_liquidity_v2.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 {
METADATA_PROGRAM_ADDRESS,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { decreaseLiquidityQuoteByLiquidityWithParams } from "../../../src/quotes/public/decrease-liquidity-quote";
import {
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
approveToken as approveTokenForPosition,
assertTick,
sleep,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { initTickArray, openPosition } from "../../utils/init-utils";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createMintV2,
createAndMintToTokenAccountV2,
approveTokenV2,
} from "../../utils/v2/token-2022";
import {
createTokenAccount as createTokenAccountForPosition,
createAndMintToTokenAccount as createAndMintToTokenAccountForPosition,
} from "../../utils/token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("decrease_liquidity_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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(3000);
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.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 approveTokenForPosition(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
const removeAmount = new anchor.BN(1_000_000);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: removeAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 approveTokenForPosition(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
const removeAmount = new anchor.BN(1_000_000);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(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,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 createTokenAccountForPosition(
provider,
position.mintKeypair.publicKey,
newOwner.publicKey,
);
await transferToken(
provider,
position.tokenAccount,
newOwnerPositionTokenAccount,
1,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: removeAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: newOwner.publicKey,
position: position.publicKey,
positionTokenAccount: newOwnerPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(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,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(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,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(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,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(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,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 fakeMint = await createMintV2(provider, { isToken2022: false });
const invalidPositionTokenAccount =
await createAndMintToTokenAccountForPosition(provider, fakeMint, 1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 invalidMintA = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const invalidTokenAccountA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
invalidMintA,
1_000_000,
);
const invalidMintB = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const invalidTokenAccountB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
invalidMintB,
1_000_000,
);
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: invalidTokenAccountA,
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.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccountB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 approveTokenForPosition(
provider,
position.tokenAccount,
delegate.publicKey,
0,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 approveTokenForPosition(
provider,
position.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
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 anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
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.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
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
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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 {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.decreaseLiquidityV2(
liquidityAmount,
new BN(0), // minA
new BN(0), // minB
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/set_reward_emissions_v2.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, ZERO_BN } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import {
initTestPoolV2,
initializeRewardV2,
} from "../../utils/v2/init-utils-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createAndMintToTokenAccountV2,
mintToDestinationV2,
} from "../../utils/v2/token-2022";
describe("set_reward_emissions_v2", () => {
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));
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully set_reward_emissions", async () => {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardVaultKeypair, rewardMint },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await mintToDestinationV2(
provider,
tokenTraits.tokenTraitR,
rewardMint,
rewardVaultKeypair.publicKey,
10000,
);
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(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.setRewardEmissionsV2Ix(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,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardVaultKeypair },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(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,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardMint },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
const fakeVault = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewardMint,
10000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(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 initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(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,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(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/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_protocol_fees_v2.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 {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createMintV2, createTokenAccountV2 } from "../../utils/v2/token-2022";
describe("collect_protocol_fees_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const destB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { rewardEmissionsSuperAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: {
whirlpoolsConfigKeypair: whirlpoolsConfigKeypair,
},
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const fakeVaultA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const fakeVaultB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: fakeVaultA,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKepair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const invalidDestA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
const invalidDestB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKepair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: invalidDestA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKepair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidDestB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
//tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
//tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.collectProtocolFeesV2(
{ slices: [] },
{
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenDestinationA: tokenAccountA,
tokenDestinationB: tokenAccountB,
memoProgram: invalidMemoProgram,
},
},
),
],
})
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/transfer-fee.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { MintWithTokenProgram, PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityV2Params,
IncreaseLiquidityV2Params,
InitPoolV2Params,
PositionData,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
MEMO_PROGRAM_ADDRESS,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
TickUtil,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import {
calculateTransferFeeExcludedAmount,
calculateTransferFeeIncludedAmount,
createTokenAccountV2,
} from "../../../utils/v2/token-2022";
import { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type {
InitAquariumV2Params,
TestAquarium,
} from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import type { TransferFee, TransferFeeConfig } from "@solana/spl-token";
import {
MAX_FEE_BASIS_POINTS,
getAccount,
getEpochFee,
getMint,
getTransferFeeAmount,
getTransferFeeConfig,
} from "@solana/spl-token";
import { createSetTransferFeeInstruction } from "../../../utils/v2/transfer-fee";
import type { TokenExtensionContext } from "../../../../src/utils/public/token-extension-util";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/TransferFee", () => {
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);
const dummyTokenMintWithProgram: MintWithTokenProgram = {
address: PublicKey.default,
decimals: 0,
freezeAuthority: null,
isInitialized: true,
mintAuthority: null,
supply: 1_000_000_000n,
tlvData: Buffer.from([]),
tokenProgram: TEST_TOKEN_PROGRAM_ID,
};
const withNoExtension: TokenExtensionContext = {
currentEpoch: 100,
tokenMintWithProgramA: dummyTokenMintWithProgram,
tokenMintWithProgramB: dummyTokenMintWithProgram,
rewardTokenMintsWithProgram: [
dummyTokenMintWithProgram,
dummyTokenMintWithProgram,
dummyTokenMintWithProgram,
],
};
async function getTransferFee(mint: PublicKey): Promise<TransferFee> {
const mintData = await getMint(
provider.connection,
mint,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfig = getTransferFeeConfig(mintData);
assert.ok(transferFeeConfig !== null);
const epochInfo = await provider.connection.getEpochInfo();
const transferFee = getEpochFee(transferFeeConfig, BigInt(epochInfo.epoch));
return transferFee;
}
const WAIT_EPOCH_TIMEOUT_MS = 30 * 1000;
async function getCurrentEpoch(): Promise<number> {
const epochInfo = await provider.connection.getEpochInfo("confirmed");
return epochInfo.epoch;
}
async function waitEpoch(waitForEpoch: number) {
const startWait = Date.now();
while (Date.now() - startWait < WAIT_EPOCH_TIMEOUT_MS) {
const epoch = await getCurrentEpoch();
if (epoch >= waitForEpoch) return;
sleep(1000);
}
throw Error(
"waitEpoch Timeout, Please set slots_per_epoch smaller in Anchor.toml",
);
}
async function fetchTransferFeeConfig(
mint: PublicKey,
): Promise<TransferFeeConfig> {
const mintData = await getMint(
provider.connection,
mint,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const config = getTransferFeeConfig(mintData);
assert.ok(config !== null);
return config!;
}
async function fetchTransferFeeWithheldAmount(
account: PublicKey,
): Promise<BN> {
const accountData = await getAccount(
provider.connection,
account,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const amount = getTransferFeeAmount(accountData);
assert.ok(amount !== null);
return new BN(amount.withheldAmount.toString());
}
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
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,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: with transfer fee", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be non zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
//console.info("A", positionBeforeCollect.feeOwedA.toString(), feeBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", positionBeforeCollect.feeOwedB.toString(), feeBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
// all owed amount should be collected
const positionAfterCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionAfterCollect.feeOwedA.isZero());
assert.ok(positionAfterCollect.feeOwedB.isZero());
});
it("collect_fees_v2: feeOwed is zero", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// collect owed fees
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionBeforeCollect.feeOwedA.isZero());
assert.ok(positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA).sub(new BN(postVaultBalanceA)).isZero(),
);
assert.ok(
new BN(preVaultBalanceB).sub(new BN(postVaultBalanceB)).isZero(),
);
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(postFeeBalanceA).sub(new BN(preFeeBalanceA)).isZero());
assert.ok(new BN(postFeeBalanceB).sub(new BN(preFeeBalanceB)).isZero());
});
it("collect_fees_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
positionBeforeCollect.feeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(
positionBeforeCollect.feeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(
positionBeforeCollect.feeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("collect_fees_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(
positionBeforeCollect.feeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(
positionBeforeCollect.feeOwedB,
),
);
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received 0 tokens
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).isZero());
assert.ok(new BN(feeBalanceB).isZero());
// all tokens should be withheld as transfer fee
const transferFeeWithheldA =
await fetchTransferFeeWithheldAmount(feeAccountA);
const transferFeeWithheldB =
await fetchTransferFeeWithheldAmount(feeAccountB);
assert.ok(transferFeeWithheldA.eq(positionBeforeCollect.feeOwedA));
assert.ok(transferFeeWithheldB.eq(positionBeforeCollect.feeOwedB));
});
it("collect_protocol_fees_v2: with transfer fee", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be non zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all owed amount should be collected
const poolAfterCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolAfterCollect.protocolFeeOwedA.isZero());
assert.ok(poolAfterCollect.protocolFeeOwedB.isZero());
});
it("collect_protocol_fees_v2: protocolFeeOwed is zero", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// collect
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(preVaultBalanceA).eq(new BN(postVaultBalanceA)));
assert.ok(new BN(preVaultBalanceB).eq(new BN(postVaultBalanceB)));
// protocol received 0 tokens
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(preFeeBalanceA).eq(new BN(postFeeBalanceA)));
assert.ok(new BN(preFeeBalanceB).eq(new BN(postFeeBalanceB)));
});
it("collect_protocol_fees_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(
poolBeforeCollect.protocolFeeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(
poolBeforeCollect.protocolFeeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received all owed amount
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(postFeeBalanceA)
.sub(new BN(preFeeBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(postFeeBalanceB)
.sub(new BN(preFeeBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
});
it("collect_protocol_fees_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be 100%
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(
poolBeforeCollect.protocolFeeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(
poolBeforeCollect.protocolFeeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received 0 tokens
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).isZero());
assert.ok(new BN(feeBalanceB).isZero());
// all tokens should be withheld as transfer fee
const transferFeeWithheldA =
await fetchTransferFeeWithheldAmount(feeAccountA);
const transferFeeWithheldB =
await fetchTransferFeeWithheldAmount(feeAccountB);
assert.ok(transferFeeWithheldA.eq(poolBeforeCollect.protocolFeeOwedA));
assert.ok(transferFeeWithheldB.eq(poolBeforeCollect.protocolFeeOwedB));
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 5000,
}, // 50%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
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: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
assert.ok(!expectation.transferFee.deductedFromRewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: with transfer fee", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: withNoExtension, // no TransferFee consideration because it is taken into account later
});
for (let i = 0; i < NUM_REWARDS; i++) {
const transferFee = await getTransferFee(rewards[i].rewardMint);
assert.equal(transferFee.transferFeeBasisPoints, [500, 1000, 5000][i]);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
expectation.rewardOwed[i]!,
);
assert.ok(expectedTransferFeeExcludedAmount.fee.gtn(0));
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(expectation.rewardOwed[i]!),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(
new BN(rewardBalance).eq(expectedTransferFeeExcludedAmount.amount),
);
//console.info("R", expectation[i]?.toString(), rewardBalance.toString(), expectedTransferFeeExcludedAmount.amount.toString(), expectedTransferFeeExcludedAmount.fee.toString());
}
const positionPostCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const expectationPostCollect = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPostCollect.getData(),
tickLower: positionPostCollect.getLowerTickData(),
tickUpper: positionPostCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: withNoExtension,
});
assert.ok(expectationPostCollect.rewardOwed.every((n) => n!.isZero()));
});
it("collect_reward_v2: rewardOwed is zero", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// collect
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
}
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const transferFee = await getTransferFee(rewards[i].rewardMint);
assert.equal(transferFee.transferFeeBasisPoints, [500, 1000, 5000][i]);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(expectedTransferFeeExcludedAmount.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmount.fee.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
const preRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(new BN(preVaultBalance).eq(new BN(postVaultBalance)));
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(postRewardBalance).eq(new BN(preRewardBalance)));
}
});
it("collect_reward_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: whirlpoolData.rewardInfos.map((rewardInfo) =>
createSetTransferFeeInstruction(
rewardInfo.mint,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
),
}).buildAndExecute();
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const updatedFeeConfig = await fetchTransferFeeConfig(
rewards[i].rewardMint,
);
assert.equal(
updatedFeeConfig.newerTransferFee.transferFeeBasisPoints,
0,
);
await waitEpoch(Number(updatedFeeConfig.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfig.newerTransferFee.epoch,
);
const transferFee = await getTransferFee(rewards[i].rewardMint);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(
expectedTransferFeeExcludedAmount.amount.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
assert.ok(expectedTransferFeeExcludedAmount.fee.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(positionPreCollect.getData().rewardInfos[i].amountOwed),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(
new BN(postRewardBalance).eq(
expectedTransferFeeExcludedAmount.amount,
),
);
}
});
it("collect_reward_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: whirlpoolData.rewardInfos.map((rewardInfo) =>
createSetTransferFeeInstruction(
rewardInfo.mint,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
),
}).buildAndExecute();
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const updatedFeeConfig = await fetchTransferFeeConfig(
rewards[i].rewardMint,
);
assert.equal(
updatedFeeConfig.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
await waitEpoch(Number(updatedFeeConfig.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfig.newerTransferFee.epoch,
);
const transferFee = await getTransferFee(rewards[i].rewardMint);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(
expectedTransferFeeExcludedAmount.fee.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
assert.ok(expectedTransferFeeExcludedAmount.amount.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(positionPreCollect.getData().rewardInfos[i].amountOwed),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(postRewardBalance).isZero());
const withheldAmount = await fetchTransferFeeWithheldAmount(
rewardAccounts[i],
);
assert.ok(
withheldAmount.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount: ZERO_BN,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount: ZERO_BN,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: transfer fee rate is 0%", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.isZero());
assert.ok(
expectedTransferFeeIncludedAmountA.amount.eq(
requiredAmountDelta.tokenA,
),
);
assert.ok(
expectedTransferFeeIncludedAmountB.amount.eq(
requiredAmountDelta.tokenB,
),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees (0)
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(requiredAmountDelta.tokenA),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(requiredAmountDelta.tokenB),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: [FAIL] transfer fee rate is 100% without cap", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
// overflow at client-side
assert.throws(() => {
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
});
assert.throws(() => {
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
});
// overflow at contract-side
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: U64_MAX,
tokenMaxB: U64_MAX,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
});
it("increase_liquidity_v2: transfer fee rate is 100% with cap", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(updatedFeeConfigA.newerTransferFee.maximumFee, 99n);
assert.equal(updatedFeeConfigB.newerTransferFee.maximumFee, 99n);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.eq(new BN(99)));
assert.ok(expectedTransferFeeIncludedAmountB.fee.eq(new BN(99)));
assert.ok(
expectedTransferFeeIncludedAmountA.amount
.sub(expectedTransferFeeIncludedAmountA.fee)
.eq(requiredAmountDelta.tokenA),
);
assert.ok(
expectedTransferFeeIncludedAmountB.amount
.sub(expectedTransferFeeIncludedAmountB.fee)
.eq(requiredAmountDelta.tokenB),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
const withheldAmountA = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const withheldAmountB = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(withheldAmountA).eq(new BN(99)));
assert.ok(new BN(withheldAmountB).eq(new BN(99)));
});
it("increase_liquidity_v2: out or range (above, tokenB amount is zero)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[1];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
aboveLowerIndex,
aboveUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(aboveLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(aboveUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.isZero()); // out of range, all asset is in tokenA
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.amount.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.isZero());
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(preOwnerAccountBalanceB.sub(postOwnerAccountBalanceB).isZero());
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(postVaultBalanceB.sub(preVaultBalanceB).isZero());
});
it("increase_liquidity_v2: out or range (below, tokenA amount is zero)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[2];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
belowLowerIndex,
belowUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(belowLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(belowUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.isZero()); // out of range, all asset is in tokenB
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeIncludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(preOwnerAccountBalanceA.sub(postOwnerAccountBalanceA).isZero());
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(postVaultBalanceA.sub(preVaultBalanceA).isZero());
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: [FAIL] TokenMaxExceeded due to transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const normalParams: IncreaseLiquidityV2Params = {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMaxA: requiredAmountDelta.tokenA,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMaxB: requiredAmountDelta.tokenB,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set maxA to expected - 1
tokenMaxA: requiredAmountDelta.tokenA
.add(expectedTransferFeeIncludedAmountA.fee)
.subn(1),
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set maxB to expected - 1
tokenMaxB: requiredAmountDelta.tokenB
.add(expectedTransferFeeIncludedAmountB.fee)
.subn(1),
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
// success with normal params
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, normalParams),
).buildAndExecute();
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (transferFeeExcludedAmount)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
//console.info("A", destBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", destBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all liquidity have been decreased
const positionDataAfterWithdraw = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionDataAfterWithdraw.liquidity.isZero());
});
it("decrease_liquidity_v2: transfer fee rate is 0%", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(expectedAmount.tokenA),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(expectedAmount.tokenB),
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (0)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("decrease_liquidity_v2: transfer fee rate is 100% without cap", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(expectedAmount.tokenA),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(expectedAmount.tokenB),
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received 0 tokens
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
// all amount is collected as transfer fee
assert.ok(new BN(destBalanceA).isZero());
assert.ok(new BN(destBalanceB).isZero());
const withheldAmountA =
await fetchTransferFeeWithheldAmount(destAccountA);
const withheldAmountB =
await fetchTransferFeeWithheldAmount(destAccountB);
assert.ok(withheldAmountA.eq(expectedAmount.tokenA));
assert.ok(withheldAmountB.eq(expectedAmount.tokenB));
});
it("decrease_liquidity_v2: transfer fee rate is 100% with cap", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.eqn(99));
assert.ok(expectedTransferFeeExcludedAmountB.fee.eqn(99));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received expectedAmount minus capped transfer fee
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
// all amount is collected as transfer fee
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
const withheldAmountA =
await fetchTransferFeeWithheldAmount(destAccountA);
const withheldAmountB =
await fetchTransferFeeWithheldAmount(destAccountB);
assert.ok(withheldAmountA.eqn(99));
assert.ok(withheldAmountB.eqn(99));
});
it("decrease_liquidity_v2: out or range (above, tokenB amount is zero", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[1]; // [1] for above
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.isZero());
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB).sub(new BN(postVaultBalanceB)).isZero(),
);
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(new BN(destBalanceB).isZero());
});
it("decrease_liquidity_v2: out or range (above, tokenA amount is zero", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[2]; // [2] for below
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
assert.ok(expectedAmount.tokenA.isZero());
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA).sub(new BN(postVaultBalanceA)).isZero(),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).isZero());
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("decrease_liquidity_v2: [FAIL] TokenMinSubceeded due to transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const normalParams: DecreaseLiquidityV2Params = {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMinA: expectedAmount.tokenA,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMinB: expectedAmount.tokenB,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set minA to expected + 1
tokenMinA: expectedAmount.tokenA
.sub(expectedTransferFeeExcludedAmountA.fee)
.addn(1),
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set minB to expected + 1
tokenMinB: expectedAmount.tokenB
.sub(expectedTransferFeeExcludedAmountB.fee)
.addn(1),
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
// success with normal params
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, normalParams),
).buildAndExecute();
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let transferFeeA: TransferFee | null;
let transferFeeB: TransferFee | null;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
const variations: { tokenA: TokenTrait; tokenB: TokenTrait }[] = [
// both A & B has transfer fee
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
},
// only A has transfer fee
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
tokenB: { isToken2022: true, hasTransferFeeExtension: false },
},
// only B has transfer fee
{
tokenA: { isToken2022: true, hasTransferFeeExtension: false },
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
},
// both A & B has transfer fee extension, but bps is zero
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
];
variations.forEach(({ tokenA, tokenB }) => {
const labelA = `TokenA: transfer fee bps = ${
tokenA.hasTransferFeeExtension
? tokenA.transferFeeInitialBps?.toString()
: "none"
}`;
const labelB = `TokenB: transfer fee bps = ${
tokenB.hasTransferFeeExtension
? tokenB.transferFeeInitialBps?.toString()
: "none"
}`;
describe(`${labelA}, ${labelB}`, () => {
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
tokenA,
tokenB,
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
transferFeeA = tokenA.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintA)
: null;
transferFeeB = tokenB.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintB)
: null;
if (transferFeeA)
assert.equal(
transferFeeA.transferFeeBasisPoints,
tokenA.transferFeeInitialBps!,
);
if (transferFeeB)
assert.equal(
transferFeeB.transferFeeBasisPoints,
tokenB.transferFeeInitialBps!,
);
});
it("A --> B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(transferFeeA, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(
transferFeeB,
quoteAToB.estimatedAmountOut,
)
: { amount: quoteAToB.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = inputAmount.neg(); // out
const expectedOwnerAccountBDelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedVaultAccountADelta =
transferFeeExcludedInputAmount.amount; // in
const expectedVaultAccountBDelta = quoteAToB.estimatedAmountOut.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(transferFeeB, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(
transferFeeA,
quoteBToA.estimatedAmountOut,
)
: { amount: quoteBToA.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedOwnerAccountBDelta = inputAmount.neg(); // out
const expectedVaultAccountADelta = quoteBToA.estimatedAmountOut.neg(); // out
const expectedVaultAccountBDelta =
transferFeeExcludedInputAmount.amount; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A --> B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const outputAmount = new BN(2000000);
const transferFeeIncludedOutputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(transferFeeB, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(
transferFeeA,
quoteAToB.estimatedAmountIn,
)
: { amount: quoteAToB.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountBDelta = outputAmount; // in
const expectedVaultAccountADelta = quoteAToB.estimatedAmountIn; // in
const expectedVaultAccountBDelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const outputAmount = new BN(100000);
const transferFeeIncludedOutputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(transferFeeA, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(
transferFeeB,
quoteBToA.estimatedAmountIn,
)
: { amount: quoteBToA.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = outputAmount; // in
const expectedOwnerAccountBDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedVaultAccountADelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
const expectedVaultAccountBDelta = quoteBToA.estimatedAmountIn; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
});
});
const variationsWith100PercentFee: {
tokenA: TokenTrait;
tokenB: TokenTrait;
}[] = [
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
},
];
variationsWith100PercentFee.forEach(({ tokenA, tokenB }) => {
const labelA = `TokenA: transfer fee bps = ${tokenA.transferFeeInitialBps ? "100%" + (tokenA.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const labelB = `TokenB: transfer fee bps = ${tokenB.transferFeeInitialBps ? "100%" + (tokenB.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
describe(`${labelA}, ${labelB}`, () => {
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
tokenA.transferFeeInitialBps!,
tokenA.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
tokenB.transferFeeInitialBps!,
tokenB.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
// wait for epoch to enable updated fee rate
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
transferFeeA = tokenA.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintA)
: null;
transferFeeB = tokenB.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintB)
: null;
assert.equal(
transferFeeA!.transferFeeBasisPoints,
tokenA.transferFeeInitialBps!,
);
assert.equal(
transferFeeA!.maximumFee,
tokenA.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFeeB!.transferFeeBasisPoints,
tokenB.transferFeeInitialBps!,
);
assert.equal(
transferFeeB!.maximumFee,
tokenB.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
});
it("A --> B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(100000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: true,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount (All amount is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(transferFeeA, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(
transferFeeB,
quoteAToB.estimatedAmountOut,
)
: { amount: quoteAToB.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = inputAmount.neg(); // out
const expectedOwnerAccountBDelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedVaultAccountADelta =
transferFeeExcludedInputAmount.amount; // in
const expectedVaultAccountBDelta = quoteAToB.estimatedAmountOut.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const inputAmount = new BN(100000);
// edge-case
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: true,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount (All amount is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(transferFeeB, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(
transferFeeA,
quoteBToA.estimatedAmountOut,
)
: { amount: quoteBToA.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedOwnerAccountBDelta = inputAmount.neg(); // out
const expectedVaultAccountADelta = quoteBToA.estimatedAmountOut.neg(); // out
const expectedVaultAccountBDelta =
transferFeeExcludedInputAmount.amount; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A --> B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const outputAmount = new BN(2000000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine output size including transfer fee because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(transferFeeB, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(
transferFeeA,
quoteAToB.estimatedAmountIn,
)
: { amount: quoteAToB.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountBDelta = outputAmount; // in
const expectedVaultAccountADelta = quoteAToB.estimatedAmountIn; // in
const expectedVaultAccountBDelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const outputAmount = new BN(100000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine output size including transfer fee because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(transferFeeA, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(
transferFeeB,
quoteBToA.estimatedAmountIn,
)
: { amount: quoteBToA.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = outputAmount; // in
const expectedOwnerAccountBDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedVaultAccountADelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
const expectedVaultAccountBDelta = quoteBToA.estimatedAmountIn; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
});
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let aquarium: TestAquarium;
let whirlpoolOneKey: PublicKey;
let whirlpoolTwoKey: PublicKey;
let whirlpoolDataOne: WhirlpoolData;
let whirlpoolDataTwo: WhirlpoolData;
const variations: TokenTrait[][] = [
// all token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// input token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{ isToken2022: true, hasTransferFeeExtension: false },
{ isToken2022: true, hasTransferFeeExtension: false },
],
// input and mid token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{ isToken2022: true, hasTransferFeeExtension: false },
],
// output token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// output and mid token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// mid token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{ isToken2022: true, hasTransferFeeExtension: false },
],
// input and output token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// all token has transfer fee, but bps are zero
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
];
variations.forEach(([token0, token1, token2]) => {
const label0 = `Token0: transfer fee bps = ${
token0.hasTransferFeeExtension
? token0.transferFeeInitialBps?.toString()
: "none"
}`;
const label1 = `Token1: transfer fee bps = ${
token1.hasTransferFeeExtension
? token1.transferFeeInitialBps?.toString()
: "none"
}`;
const label2 = `Token2: transfer fee bps = ${
token2.hasTransferFeeExtension
? token2.transferFeeInitialBps?.toString()
: "none"
}`;
describe(`${label0}, ${label1}, ${label2}`, () => {
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: token0 },
{ tokenTrait: token1 },
{ tokenTrait: token2 },
];
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: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { pools } = aquarium;
whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
});
it("T0 --> T1 --> T2, ExactIn", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(1000);
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(midToken);
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactIn", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintA.equals(midToken);
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 --> T1 --> T2, ExactOut", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(500000);
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintB.equals(midToken);
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactOut", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(1000);
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataOne.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataTwo.tokenMintB.equals(midToken);
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
});
});
const variationsWith100PercentFee: TokenTrait[][] = [
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
],
];
variationsWith100PercentFee.forEach(([token0, token1, token2]) => {
const label0 = `Token0: transfer fee bps = ${token0.transferFeeInitialBps ? "100%" + (token0.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const label1 = `Token1: transfer fee bps = ${token1.transferFeeInitialBps ? "100%" + (token1.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const label2 = `Token2: transfer fee bps = ${token2.transferFeeInitialBps ? "100%" + (token2.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
describe(`${label0}, ${label1}, ${label2}`, () => {
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
];
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: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { pools } = aquarium;
whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
pools[0].tokenMintA,
token0.transferFeeInitialBps!,
token0.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
pools[0].tokenMintB,
token1.transferFeeInitialBps!,
token1.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
pools[1].tokenMintB,
token2.transferFeeInitialBps!,
token2.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
// wait for epoch to enable updated fee rate
const updatedFeeConfig0 = await fetchTransferFeeConfig(
pools[0].tokenMintA,
);
await waitEpoch(Number(updatedFeeConfig0.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfig0.newerTransferFee.epoch,
);
const transferFee0 = await getTransferFee(pools[0].tokenMintA);
const transferFee1 = await getTransferFee(pools[0].tokenMintB);
const transferFee2 = await getTransferFee(pools[1].tokenMintB);
assert.equal(
transferFee0!.transferFeeBasisPoints,
token0.transferFeeInitialBps!,
);
assert.equal(
transferFee0!.maximumFee,
token0.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFee1!.transferFeeBasisPoints,
token1.transferFeeInitialBps!,
);
assert.equal(
transferFee1!.maximumFee,
token1.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFee2!.transferFeeBasisPoints,
token2.transferFeeInitialBps!,
);
assert.equal(
transferFee2!.maximumFee,
token2.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
});
it("T0 --> T1 --> T2, ExactIn", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(1000);
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || midWithoutCap) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: true,
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
aToBOne,
aToBTwo,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolOneKey,
whirlpoolTwo: whirlpoolTwoKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultOneIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenVaultTwoIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultTwoOutput: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenOwnerAccountInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysOne[0].address,
tickArrayOne1: tickArraysOne[0].address,
tickArrayOne2: tickArraysOne[0].address,
tickArrayTwo0: tickArraysTwo[0].address,
tickArrayTwo1: tickArraysTwo[0].address,
tickArrayTwo2: tickArraysTwo[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
}),
).buildAndExecute(),
inputWithoutCap
? /0x1793/ // ZeroTradableAmount (All amount is collected as transfer fee...)
: /0x1793/, // ZeroTradableAmount (all intermediate token is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactIn", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(100000);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(inputToken);
const aToBOne = whirlpoolDataOne.tokenMintA.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || midWithoutCap) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: true,
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
aToBOne: aToBTwo,
aToBTwo: aToBOne,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolTwoKey,
whirlpoolTwo: whirlpoolOneKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultOneIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenVaultTwoIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultTwoOutput: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenOwnerAccountInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysTwo[0].address,
tickArrayOne1: tickArraysTwo[0].address,
tickArrayOne2: tickArraysTwo[0].address,
tickArrayTwo0: tickArraysOne[0].address,
tickArrayTwo1: tickArraysOne[0].address,
tickArrayTwo2: tickArraysOne[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
}),
).buildAndExecute(),
inputWithoutCap
? /0x1793/ // ZeroTradableAmount (All amount is collected as transfer fee...)
: /0x1793/, // ZeroTradableAmount (all intermediate token is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 --> T1 --> T2, ExactOut", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(500000);
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
const outputWithoutCap =
transferFeeOutput!.transferFeeBasisPoints ===
MAX_FEE_BASIS_POINTS &&
transferFeeOutput!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || outputWithoutCap || midWithoutCap) {
// we cannot determine input/output size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: false,
amount: outputAmount,
otherAmountThreshold: new BN(U64_MAX.toString()),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
aToBOne,
aToBTwo,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolOneKey,
whirlpoolTwo: whirlpoolTwoKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultOneIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenVaultTwoIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultTwoOutput: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenOwnerAccountInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysOne[0].address,
tickArrayOne1: tickArraysOne[0].address,
tickArrayOne2: tickArraysOne[0].address,
tickArrayTwo0: tickArraysTwo[0].address,
tickArrayTwo1: tickArraysTwo[0].address,
tickArrayTwo2: tickArraysTwo[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactOut", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(1000);
const aToBTwo = whirlpoolDataOne.tokenMintB.equals(outputToken);
const aToBOne = whirlpoolDataTwo.tokenMintB.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
const outputWithoutCap =
transferFeeOutput!.transferFeeBasisPoints ===
MAX_FEE_BASIS_POINTS &&
transferFeeOutput!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || outputWithoutCap || midWithoutCap) {
// we cannot determine input/output size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: false,
amount: outputAmount,
otherAmountThreshold: new BN(U64_MAX.toString()),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
aToBOne: aToBTwo,
aToBTwo: aToBOne,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolTwoKey,
whirlpoolTwo: whirlpoolOneKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultOneIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenVaultTwoIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultTwoOutput: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenOwnerAccountInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysTwo[0].address,
tickArrayOne1: tickArraysTwo[0].address,
tickArrayOne2: tickArraysTwo[0].address,
tickArrayTwo0: tickArraysOne[0].address,
tickArrayTwo1: tickArraysOne[0].address,
tickArrayTwo2: tickArraysOne[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
});
});
});
describe("Special cases", () => {
// We know that all transfers are executed 2 functions depending on the direction, so 2 test cases.
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
const mintAmount = new BN(2_000_000_000);
const tickSpacing = 1;
const rangeLowerTickIndex = -64;
const rangeUpperTickIndex = +64;
const currentTickIndex = 0;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex,
rangeLowerTickIndex,
rangeUpperTickIndex,
{
// half deposit (50:50)
tokenA: mintAmount.divn(2),
tokenB: mintAmount.divn(2),
},
);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
transferFeeInitialMax: 100_000n,
},
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
transferFeeInitialMax: 200_000n,
},
tickSpacing,
// pool has much liquidity in both direction
positions: [
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
});
describe("use current fee rate even if next fee rate exists", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints,
500,
);
assert.equal(
initialFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
initialFeeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.lt(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
// PREPEND setTransferFee ix
tx.prependInstruction({
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
2000,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
});
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
// but newer fee bps have been updated
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
2000,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
});
it("vault to owner", async () => {
// in A to B, vault to owner is output
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1000,
);
assert.equal(
initialFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
initialFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.lt(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
// PREPEND setTransferFee ix
tx.prependInstruction({
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
1500,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
});
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
// but newer fee bps have been updated
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1500,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
});
});
describe("use updated fee rate once epoch comes", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints,
500,
);
assert.equal(
initialFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
const newBpsList = [2000, 3000];
let oldBps = 500;
for (let i = 0; i < newBpsList.length; i++) {
const newBps = newBpsList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
newBps,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
newBps,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.transferFeeBasisPoints,
oldBps,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
updatedFeeConfigA,
BigInt(await getCurrentEpoch()),
);
assert.ok(transferFeeA.transferFeeBasisPoints === newBps);
// non zero, but not limited by maximum
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.lt(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
oldBps = newBps;
}
});
it("vault to owner", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1000,
);
assert.equal(
initialFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
const newBpsList = [2000, 3000];
let oldBps = 1000;
for (let i = 0; i < newBpsList.length; i++) {
const newBps = newBpsList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
newBps,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
newBps,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.transferFeeBasisPoints,
oldBps,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigB.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
updatedFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.lt(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
oldBps = newBps;
}
});
});
describe("use maximum limit", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(initialFeeConfigA.newerTransferFee.maximumFee, 100_000n);
assert.equal(initialFeeConfigA.olderTransferFee.maximumFee, 100_000n);
const newMaximumFeeList = [10_000n, 1_000n];
let oldMaximumFee = 100_000n;
for (let i = 0; i < newMaximumFeeList.length; i++) {
const newMaximumFee = newMaximumFeeList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints, // no change
newMaximumFee,
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.maximumFee,
newMaximumFee,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.maximumFee,
oldMaximumFee,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
updatedFeeConfigA,
BigInt(await getCurrentEpoch()),
);
assert.ok(transferFeeA.maximumFee === newMaximumFee);
// non zero, and limited by maximum
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.eq(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current maximum
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
oldMaximumFee = newMaximumFee;
}
});
it("vault to owner", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(initialFeeConfigB.newerTransferFee.maximumFee, 200_000n);
assert.equal(initialFeeConfigB.olderTransferFee.maximumFee, 200_000n);
const newMaximumFeeList = [10_000n, 1_000n];
let oldMaximumFee = 200_000n;
for (let i = 0; i < newMaximumFeeList.length; i++) {
const newMaximumFee = newMaximumFeeList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints, // no change
newMaximumFee,
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.maximumFee,
newMaximumFee,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.maximumFee,
oldMaximumFee,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigB.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
updatedFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, and limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.eq(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current maximum
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
oldMaximumFee = newMaximumFee;
}
});
});
it("logging applied TransferFee config info", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const feeConfigB = await fetchTransferFeeConfig(tokenB);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeB = getEpochFee(
feeConfigB,
BigInt(await getCurrentEpoch()),
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeExcludedInputAmount = calculateTransferFeeExcludedAmount(
transferFeeA,
inputAmount,
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const sig = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
).buildAndExecute();
const parsedTx = await provider.connection.getParsedTransaction(sig, {
maxSupportedTransactionVersion: 0,
});
assert.ok(parsedTx?.meta?.innerInstructions);
assert.ok(parsedTx!.meta!.innerInstructions.length === 1); // twoHopSwap only (top-level ix)
const memoLogs = parsedTx!.meta!.innerInstructions[0].instructions.filter(
(ix) => ix.programId.equals(MEMO_PROGRAM_ADDRESS),
);
assert.ok(memoLogs.length === 2);
assert.ok(
(memoLogs[0] as { parsed: string }).parsed ===
`TFe: ${transferFeeA.transferFeeBasisPoints}, ${transferFeeA.maximumFee}`,
);
assert.ok(
(memoLogs[1] as { parsed: string }).parsed ===
`TFe: ${transferFeeB.transferFeeBasisPoints}, ${transferFeeB.maximumFee}`,
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/non-confidential-transfer.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import { createTokenAccountV2 } from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import { hasConfidentialTransferMintExtension } from "../../../utils/v2/confidential-transfer";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/ConfidentialTransfer (NON confidential transfer only)", () => {
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);
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
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,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: non confidential transfer", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintA),
);
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintB),
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
});
it("collect_protocol_fees_v2: non confidential transfer", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintA),
);
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintB),
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
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: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: non confidential transfer", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(
hasConfidentialTransferMintExtension(provider, rewards[i].rewardMint),
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: non confidential transfer", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: non confidential transfer", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true, hasConfidentialTransferExtension: true },
{ isToken2022: true, hasConfidentialTransferExtension: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
});
it("swap_v2: non confidential transfer, a to b", async () => {
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(postBalanceA.lt(preBalanceA));
assert.ok(postBalanceB.gt(preBalanceB));
});
it("swap_v2: non confidential transfer, b to a", async () => {
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(postBalanceA.gt(preBalanceA));
assert.ok(postBalanceB.lt(preBalanceB));
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenAccountIn: PublicKey;
let tokenAccountOut: PublicKey;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
];
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: FundedPositionV2Params[] = [
{
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 buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
tokenAccountIn = baseIxParams.tokenOwnerAccountInput;
tokenAccountOut = baseIxParams.tokenOwnerAccountOutput;
});
it("two_hop_swap_v2: non confidential transfer", async () => {
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/memo-transfer.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
NUM_REWARDS,
PDAUtil,
swapQuoteWithParams,
SwapUtils,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
} from "../../../utils/v2/init-utils-v2";
import {
createTokenAccountV2,
disableRequiredMemoTransfers,
enableRequiredMemoTransfers,
isRequiredMemoTransfersEnabled,
} from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/MemoTransfer", () => {
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);
const MEMO_TRANSFER_COLLECT_FEES = "Orca CollectFees";
const MEMO_TRANSFER_COLLECT_PROTOCOL_FEES = "Orca CollectProtocolFees";
const MEMO_TRANSFER_COLLECT_REWARD = "Orca CollectReward";
const MEMO_TRANSFER_DECREASE_LIQUIDITY = "Orca Withdraw";
const MEMO_TRANSFER_SWAP = "Orca Trade";
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
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,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: without memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_fees_v2: with memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 2);
});
it("collect_fees_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
await disableRequiredMemoTransfers(provider, feeAccountA);
await disableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_protocol_fees_v2: without memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_protocol_fees_v2: with memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 2);
});
it("collect_protocol_fees_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
await disableRequiredMemoTransfers(provider, feeAccountA);
await disableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 0);
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
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 whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
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: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: without memo", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i])),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 0);
}
});
it("collect_reward_v2: with memo", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await enableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i]),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 1);
}
});
it("collect_reward_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await enableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i]),
);
await disableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i])),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 0);
}
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: without memo", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 0);
});
it("decrease_liquidity_v2: with memo", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await enableRequiredMemoTransfers(provider, destAccountA);
await enableRequiredMemoTransfers(provider, destAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 2);
});
it("decrease_liquidity_v2: without memo (has extension, but disabled)", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await enableRequiredMemoTransfers(provider, destAccountA);
await enableRequiredMemoTransfers(provider, destAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountB));
await disableRequiredMemoTransfers(provider, destAccountA);
await disableRequiredMemoTransfers(provider, destAccountB);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, destAccountA)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, destAccountB)),
);
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 0);
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
});
it("swap_v2: without memo", async () => {
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 0);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 0);
});
it("swap_v2: with memo", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountA);
await enableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountB));
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 1);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 1);
});
it("swap_v2: without memo (has extension, but disabled", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountA);
await enableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountB));
await disableRequiredMemoTransfers(provider, tokenAccountA);
await disableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountA)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountB)),
);
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 0);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 0);
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenAccountIn: PublicKey;
let tokenAccountOut: PublicKey;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
];
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: FundedPositionV2Params[] = [
{
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 buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
tokenAccountIn = baseIxParams.tokenOwnerAccountInput;
tokenAccountOut = baseIxParams.tokenOwnerAccountOutput;
});
it("two_hop_swap_v2: without memo", async () => {
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 0);
});
it("two_hop_swap_v2: with memo", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountIn);
await enableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn));
assert.ok(
await isRequiredMemoTransfersEnabled(provider, tokenAccountOut),
);
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 1); // mid token uses vault to vault transfer, so no memo
});
it("two_hop_swap_v2: without memo (has extension, but disabled", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountIn);
await enableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn));
assert.ok(
await isRequiredMemoTransfersEnabled(provider, tokenAccountOut),
);
await disableRequiredMemoTransfers(provider, tokenAccountIn);
await disableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountOut)),
);
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 0);
});
});
});
async function countMemoLog(
provider: anchor.AnchorProvider,
signature: string,
logMessage: string,
): Promise<number> {
const logLen = logMessage.length;
const logFormat = `Program log: Memo (len ${logLen}): "${logMessage}"`;
const tx = await provider.connection.getParsedTransaction(signature, {
maxSupportedTransactionVersion: 0,
});
const memos = tx?.meta?.logMessages?.filter((msg) => msg === logFormat);
return memos!.length;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/non-confidential-transfer+transfer-fee.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import * as assert from "assert";
import type { PositionData, WhirlpoolData } from "../../../../src";
import {
PoolUtil,
PriceMath,
TickUtil,
toTokenAmount,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import {
calculateTransferFeeExcludedAmount,
calculateTransferFeeIncludedAmount,
createTokenAccountV2,
} from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import {
hasConfidentialTransferFeeConfigExtension,
hasConfidentialTransferMintExtension,
} from "../../../utils/v2/confidential-transfer";
import type { TransferFee } from "@solana/spl-token";
import { getEpochFee, getMint, getTransferFeeConfig } from "@solana/spl-token";
describe("TokenExtension/ConfidentialTransfer (NON confidential transfer only) + TransferFee", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
// ConfidentialTransfer + TransferFee is combination test
// We'll test owner to vault transfer by increase liquidity, vault to owner transfer by decrease liquidity
async function getTransferFee(mint: PublicKey): Promise<TransferFee> {
const mintData = await getMint(
provider.connection,
mint,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfig = getTransferFeeConfig(mintData);
assert.ok(transferFeeConfig !== null);
const epochInfo = await provider.connection.getEpochInfo();
const transferFee = getEpochFee(transferFeeConfig, BigInt(epochInfo.epoch));
return transferFee;
}
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount: ZERO_BN,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount: ZERO_BN,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// transfer fee
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// confidential transfer
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
// confidential transfer fee config
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// transfer fee
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// confidential transfer
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
// confidential transfer fee config
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (transferFeeExcludedAmount)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
//console.info("A", destBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", destBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all liquidity have been decreased
const positionDataAfterWithdraw = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionDataAfterWithdraw.liquidity.isZero());
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/interest-bearing.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import type { WhirlpoolData } from "../../../../src";
import {
PDAUtil,
swapQuoteWithParams,
SwapUtils,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
} from "../../../utils/v2/init-utils-v2";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
import {
amountToUiAmount,
updateRateInterestBearingMint,
} from "@solana/spl-token";
describe("TokenExtension/InterestBearing", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const payer = (ctx.wallet as NodeWallet).payer;
async function rawAmountToUIAmount(
mint: PublicKey,
rawAmount: BN,
): Promise<string> {
const result = await amountToUiAmount(
ctx.connection,
payer,
mint,
rawAmount.toNumber(),
TEST_TOKEN_2022_PROGRAM_ID,
);
if (typeof result === "string") {
return result;
}
throw new Error("Failed to convert raw amount to UI amount");
}
// Since InterestBearing is no different from normal mint as far as handling raw amounts (u64 amounts),
// swap_v2 is executed to check the owner to vault and vault to owner logic.
// |----------|-----*S*T*|****------| (*: liquidity, S: start, T: end)
it("swap_v2 (covers both owner to vault and vault to owner transfer)", async () => {
const { whirlpoolPda, poolInitInfo, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{
isToken2022: true,
hasInterestBearingExtension: true,
interestBearingRate: 0,
}, // 0%
{
isToken2022: true,
hasInterestBearingExtension: true,
interestBearingRate: 0,
}, // 0%
TickSpacing.Standard,
);
const initialRawBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const initialRawBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
const initialUIBalanceA = await rawAmountToUIAmount(
poolInitInfo.tokenMintA,
initialRawBalanceA,
);
const initialUIBalanceB = await rawAmountToUIAmount(
poolInitInfo.tokenMintB,
initialRawBalanceB,
);
// rate is 0%, so these values should be equal
assert.ok(
initialRawBalanceA.eq(new BN(Number.parseInt(initialUIBalanceA))),
);
assert.ok(
initialRawBalanceB.eq(new BN(Number.parseInt(initialUIBalanceB))),
);
// set rate > 0%
const sigA = await updateRateInterestBearingMint(
ctx.connection,
payer,
poolInitInfo.tokenMintA,
payer,
30_000, // 300%
);
const sigB = await updateRateInterestBearingMint(
ctx.connection,
payer,
poolInitInfo.tokenMintB,
payer,
10_000, // 100%
);
await Promise.all([
ctx.connection.confirmTransaction(sigA),
ctx.connection.confirmTransaction(sigB),
]);
await sleep(10 * 1000);
const newUIBalanceA = await rawAmountToUIAmount(
poolInitInfo.tokenMintA,
initialRawBalanceA,
);
const newUIBalanceB = await rawAmountToUIAmount(
poolInitInfo.tokenMintB,
initialRawBalanceB,
);
// rate is >0%, so these values should NOT be equal
assert.ok(initialRawBalanceA.lt(new BN(Number.parseInt(newUIBalanceA))));
assert.ok(initialRawBalanceB.lt(new BN(Number.parseInt(newUIBalanceB))));
// now we can assure that InterestBearing works as expected on both tokens
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
await fundPositionsV2(ctx, poolInitInfo, tokenAccountA, tokenAccountB, [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
]);
const oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// tick: 32190 -> 32269
const quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(200000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteBToA.estimatedAmountIn.gtn(0));
assert.ok(quoteBToA.estimatedAmountOut.gtn(0));
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
const diffA = balanceA1.sub(balanceA0);
const diffB = balanceB1.sub(balanceB0);
assert.ok(diffA.eq(quoteBToA.estimatedAmountOut));
assert.ok(diffB.eq(quoteBToA.estimatedAmountIn.neg()));
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/transfer-hook.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
MEMO_PROGRAM_ADDRESS,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import { createTokenAccountV2 } from "../../../utils/v2/token-2022";
import type { AccountMeta } from "@solana/web3.js";
import { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import {
getExtraAccountMetasForTestTransferHookProgram,
getTestTransferHookCounter,
updateTransferHookProgram,
} from "../../../utils/v2/test-transfer-hook-program";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
} from "../../../../src/utils/remaining-accounts-util";
describe("TokenExtension/TransferHook", () => {
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);
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
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,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// TransferHook
const tokenTransferHookAccountsAForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
tokenMintA,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
const tokenTransferHookAccountsBForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintB,
tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
);
const tokenTransferHookAccountsAForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintA,
tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
);
const tokenTransferHookAccountsBForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
tokenMintB,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintA,
tokenVaultAKeypair.publicKey,
feeAccountA,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintB,
tokenVaultBKeypair.publicKey,
feeAccountB,
whirlpoolPda.publicKey,
);
});
it("collect_fees_v2: with transfer hook", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("collect_fees_v2: without transfer hook (has extension, but set null)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await updateTransferHookProgram(provider, tokenMintA, PublicKey.default);
await updateTransferHookProgram(provider, tokenMintB, PublicKey.default);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: undefined, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA);
assert.equal(postCounterB, preCounterB);
});
it("collect_fees_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_fees_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(counter)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// counter account is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(account_order_verifier)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// account_order_verifier account is missing
const insufficientTransferHookAccountsA = [
// counter_account
...tokenTransferHookAccountsA!.slice(0, 1),
// skip account_order_verifier
// extra account metas, hook program
...tokenTransferHookAccountsA!.slice(2),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(ExtraAccountMetas)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// ExtraAccountMetas is missing
const insufficientTransferHookAccountsA = [
// counter_account, account_order_verifier
...tokenTransferHookAccountsA!.slice(0, 2),
// skip extra account metas
// hook program
...tokenTransferHookAccountsA!.slice(3),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(HookProgram)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// HookProgram is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(0, 3);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("collect_fees_v2: [Fail] with TransferHookReward", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// invalid accounts type
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccountsA,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a0/, // RemainingAccountsInvalidSlice
);
});
it("collect_fees_v2: [Fail] with insufficient remaining accounts", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
.build();
const missingRemainingAccounts = remainingAccounts!.slice(
0,
remainingAccounts!.length - 1,
); // drop last 1 accounts
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: missingRemainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a1/, // RemainingAccountsInsufficient
);
});
it("collect_fees_v2: [Fail] with duplicated remaining accounts (TransferHookA)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("collect_fees_v2: [Fail] with duplicated remaining accounts (TransferHookB)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("collect_protocol_fees_v2: with transfer hook", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("collect_protocol_fees_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_protocol_fees_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
let tokenTransferHookAccounts: (AccountMeta[] | undefined)[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
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: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
tokenTransferHookAccounts = await Promise.all(
rewards.map((reward, i) => {
return getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
reward.rewardMint,
reward.rewardVaultKeypair.publicKey,
rewardAccounts[i],
whirlpoolPda.publicKey,
);
}),
);
});
it("collect_reward_v2: with transfer hook", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const preCounter = await getTestTransferHookCounter(
provider,
rewards[i].rewardMint,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
rewardTransferHookAccounts: tokenTransferHookAccounts[i], // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const postCounter = await getTestTransferHookCounter(
provider,
rewards[i].rewardMint,
);
assert.equal(postCounter, preCounter + 1);
}
});
it("collect_reward_v2: [Fail] with transfer hook, but no extra accounts provided for rewardToken", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await getTestTransferHookCounter(provider, rewards[i].rewardMint);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
rewardTransferHookAccounts: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
}
});
it("collect_reward_v2: [Fail] with duplicated remaining accounts (TransferHookReward)", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccounts[i],
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccounts[i],
)
.build();
const ix = ctx.program.instruction.collectRewardV2(
i,
remainingAccountsInfo,
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
let fixture: WhirlpoolTestFixtureV2;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo } = fixture.getInfos();
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintA,
fixture.getInfos().tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintB,
fixture.getInfos().tokenAccountB,
poolInitInfo.tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
});
it("increase_liquidity_v2: with transfer hook", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("increase_liquidity_v2: without transfer hook (has extension, but set null)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await updateTransferHookProgram(
provider,
poolInitInfo.tokenMintA,
PublicKey.default,
);
await updateTransferHookProgram(
provider,
poolInitInfo.tokenMintB,
PublicKey.default,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA);
assert.equal(postCounterB, preCounterB);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(counter)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// counter account is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(account_order_verifier)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// account_order_verifier account is missing
const insufficientTransferHookAccountsA = [
// counter_account
...tokenTransferHookAccountsA!.slice(0, 1),
// skip account_order_verifier
// extra account metas, hook program
...tokenTransferHookAccountsA!.slice(2),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(ExtraAccountMetas)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// ExtraAccountMetas is missing
const insufficientTransferHookAccountsA = [
// counter_account, account_order_verifier
...tokenTransferHookAccountsA!.slice(0, 2),
// skip extra account metas
// hook program
...tokenTransferHookAccountsA!.slice(3),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(HookProgram)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// HookProgram is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(0, 3);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
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,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintA,
poolInitInfo.tokenVaultAKeypair.publicKey,
destAccountA,
poolInitInfo.whirlpoolPda.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
destAccountB,
poolInitInfo.whirlpoolPda.publicKey,
);
});
it("decrease_liquidity_v2: with transfer hook", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("decrease_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("decrease_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
let tokenTransferHookAccountsAForAToB: AccountMeta[] | undefined;
let tokenTransferHookAccountsBForAToB: AccountMeta[] | undefined;
let tokenTransferHookAccountsAForBToA: AccountMeta[] | undefined;
let tokenTransferHookAccountsBForBToA: AccountMeta[] | undefined;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true, hasTransferHookExtension: true },
{ isToken2022: true, hasTransferHookExtension: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
// TransferHook
tokenTransferHookAccountsAForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintA,
tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
tokenTransferHookAccountsBForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsAForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintA,
poolInitInfo.tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsBForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintB,
tokenAccountB,
poolInitInfo.tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
});
it("swap_v2: with transfer hook, a to b", async () => {
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("swap_v2: with transfer hook, b to a", async () => {
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("swap_v2: [Fail] with transfer hook, a to b, but no extra accounts provided for A", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, a to b, but no extra accounts provided for B", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, b to a, but no extra accounts provided for A", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, b to a, but no extra accounts provided for B", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenMintIn: PublicKey;
let tokenMintOut: PublicKey;
let tokenMintMid: PublicKey;
let tokenTransferHookAccountsInput: AccountMeta[] | undefined;
let tokenTransferHookAccountsMid: AccountMeta[] | undefined;
let tokenTransferHookAccountsOutput: AccountMeta[] | undefined;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
];
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: FundedPositionV2Params[] = [
{
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 buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
// TransferHook
tokenMintIn = baseIxParams.tokenMintInput;
tokenMintOut = baseIxParams.tokenMintOutput;
tokenMintMid = baseIxParams.tokenMintIntermediate;
tokenTransferHookAccountsInput =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// input: owner to vault
baseIxParams.tokenMintInput,
baseIxParams.tokenOwnerAccountInput,
baseIxParams.tokenVaultOneInput,
baseIxParams.tokenAuthority,
);
tokenTransferHookAccountsMid =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// intermediate: vault to vault (vault to owner logic is used)
baseIxParams.tokenMintIntermediate,
baseIxParams.tokenVaultOneIntermediate,
baseIxParams.tokenVaultTwoIntermediate,
baseIxParams.whirlpoolOne,
);
tokenTransferHookAccountsOutput =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// output: vault to owner
baseIxParams.tokenMintOutput,
baseIxParams.tokenVaultTwoOutput,
baseIxParams.tokenOwnerAccountOutput,
baseIxParams.whirlpoolTwo,
);
});
it("two_hop_swap_v2: with transfer hook", async () => {
const preCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const preCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const preCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
const tx = toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput,
}),
);
// add Compute units (because it calls 3 external hooks)
tx.prependInstruction(useMaxCU());
await tx.buildAndExecute();
const postCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const postCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const postCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
assert.equal(postCounterIn, preCounterIn + 1);
assert.equal(postCounterOut, preCounterOut + 1);
assert.equal(
postCounterMid,
preCounterMid + 1 /* must be 1 (vault to vault) */,
);
});
it("two_hop_swap_v2: without transfer hook (has extension, but set null)", async () => {
const preCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const preCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const preCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
await updateTransferHookProgram(provider, tokenMintIn, PublicKey.default);
await updateTransferHookProgram(
provider,
tokenMintOut,
PublicKey.default,
);
await updateTransferHookProgram(
provider,
tokenMintMid,
PublicKey.default,
);
const tx = toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput: undefined,
tokenTransferHookAccountsIntermediate: undefined,
tokenTransferHookAccountsOutput: undefined,
}),
);
// add Compute units (because it calls 3 external hooks)
tx.prependInstruction(useMaxCU());
await tx.buildAndExecute();
const postCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const postCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const postCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
assert.equal(postCounterIn, preCounterIn);
assert.equal(postCounterOut, preCounterOut);
assert.equal(postCounterMid, preCounterMid);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenInput", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput: undefined,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenIntermediate", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: undefined,
tokenTransferHookAccountsOutput,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenOutput", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput: undefined,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookInput)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookIntermediate)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookOutput)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
});
describe("Special Errors", () => {
describe("TransferHook program rejects transfer", () => {
const TOO_LARGE_THRESHOLD_U64 = new BN(1_000_000_000_000);
// We know that all transfers are executed 2 functions depending on the direction, so 2 test cases.
it("[FAIL] owner to vault, amount too large", async () => {
// tokenA has transfer hook (so increase liquidity with large tokenB amount will not fail)
const mintAmount = TOO_LARGE_THRESHOLD_U64.muln(2);
const tickSpacing = 1;
const rangeLowerTickIndex = -1;
const rangeUpperTickIndex = +1;
const currentTickIndex = +2;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex, // price is above range ([-1, +1] p)
rangeLowerTickIndex,
rangeUpperTickIndex,
{
tokenA: mintAmount,
tokenB: mintAmount,
},
);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
// tokenA has transfer hook
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: false },
tickSpacing,
positions: [
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const inputTokenAmount = TOO_LARGE_THRESHOLD_U64.addn(1); // exceed threshold by 1
const whirlpoolData = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB,
tokenAmount: inputTokenAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
assert.ok(quote.estimatedAmountIn.gt(TOO_LARGE_THRESHOLD_U64));
// TransferHook
const tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// a to b, owner to vault (input token is tokenA)
poolInitInfo.tokenMintA,
tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
const tokenTransferHookAccountsB = undefined;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
).publicKey,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
(err) => {
// error code is 0x1770 from transfer hook program and it is ambiguous, so use message string
return JSON.stringify(err).includes("AmountTooBig");
},
);
});
it("[FAIL] vault to owner, amount too large", async () => {
// all tokenB is deposited into [-1, +1] (one side)
const mintAmount = TOO_LARGE_THRESHOLD_U64.muln(2);
const tickSpacing = 1;
const rangeLowerTickIndex = -1;
const rangeUpperTickIndex = +1;
const currentTickIndex = +2;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex, // price is above range ([-1, +1] p)
rangeLowerTickIndex,
rangeUpperTickIndex,
{
tokenA: TOO_LARGE_THRESHOLD_U64.muln(3).divn(4), // 3/4 of threshold
tokenB: TOO_LARGE_THRESHOLD_U64.muln(3).divn(4), // 3/4 of threshold
},
);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
// tokenB has transfer hook
tokenTraitA: { isToken2022: true, hasTransferHookExtension: false },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing,
positions: [
// to avoid large amount increase liquidity, 2 3/4 deposit will be made.
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const inputTokenAmount = TOO_LARGE_THRESHOLD_U64.muln(130).divn(100); // 130% of threshold
const whirlpoolData = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB,
tokenAmount: inputTokenAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
assert.ok(quote.estimatedAmountOut.gt(TOO_LARGE_THRESHOLD_U64));
// TransferHook
const tokenTransferHookAccountsA = undefined;
const tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// a to b, vault to owner (output token is tokenB)
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
tokenAccountB,
poolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
).publicKey,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
(err) => {
// error code is 0x1770 from transfer hook program and it is ambiguous, so use message string
return JSON.stringify(err).includes("AmountTooBig");
},
);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/initialize_config_extension.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitConfigExtensionParams } from "../../../../src/instructions";
describe("initialize_config_extension", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
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;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(
config: PublicKey,
overwrite: Partial<InitConfigExtensionParams>,
signers: Keypair[] = [feeAuthorityKeypair],
) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
const tx = toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
it("successfully initialize config extension and verify initialized account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
const configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(
configExtension!.configExtensionAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
assert.ok(
configExtension!.tokenBadgeAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
});
it("successfully initialize when funder is different than account paying for transaction fee", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const otherWallet = await createOtherWallet();
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{
funder: otherWallet.publicKey,
},
[feeAuthorityKeypair, 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 configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(
configExtension!.configExtensionAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
assert.ok(
configExtension!.tokenBadgeAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
});
it("WhirlpoolsConfigExtension account has reserved space", async () => {
const whirlpoolsConfigExtensionAccountSizeIncludingReserve =
8 + 32 + 32 + 32 + 512;
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
const account = await ctx.connection.getAccountInfo(
configExtensionPubkey,
"confirmed",
);
assert.equal(
account!.data.length,
whirlpoolsConfigExtensionAccountSizeIncludingReserve,
);
});
it("should be failed: already initialized", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
// initialized
const configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
// re-initialize
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
),
(err) => {
return JSON.stringify(err).includes("already in use");
},
);
});
describe("invalid input account", () => {
it("should be failed: invalid config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
// config not initialized
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
),
/0xbc4/, // AccountNotInitialized
);
});
it("should be failed: invalid config_extension address", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidPda = PDAUtil.getFeeTier(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
64,
);
await assert.rejects(
initializeWhirlpoolsConfigExtension(whirlpoolsConfigKeypair.publicKey, {
whirlpoolsConfigExtensionPda: invalidPda,
}),
/0x7d6/, // ConstraintSeeds
);
});
it("should be failed: funder is not signer", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const whirlpoolsConfigExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
);
const ix: TransactionInstruction =
program.instruction.initializeConfigExtension({
accounts: {
config: whirlpoolsConfigKeypair.publicKey,
configExtension: whirlpoolsConfigExtensionPda.publicKey,
funder: otherWallet.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 5);
assert.ok(ix.keys[2].pubkey.equals(otherWallet.publicKey));
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [feeAuthorityKeypair], // no otherWallet
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid fee_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidAuthorityKeypair = Keypair.generate();
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{
feeAuthority: invalidAuthorityKeypair.publicKey,
},
[invalidAuthorityKeypair],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: invalid system program", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidSystemProgram = TOKEN_PROGRAM_ID;
const whirlpoolsConfigExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
);
const ix: TransactionInstruction =
program.instruction.initializeConfigExtension({
accounts: {
config: whirlpoolsConfigKeypair.publicKey,
configExtension: whirlpoolsConfigExtensionPda.publicKey,
funder: ctx.wallet.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
systemProgram: invalidSystemProgram,
},
});
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [feeAuthorityKeypair],
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/set_config_extension_authority.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
describe("set_config_extension_authority", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedConfigExtensionAuthorityKeypair = Keypair.generate();
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function setConfigExtensionAuthority(
config: PublicKey,
configExtensionAuthority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: configExtensionAuthority.publicKey,
newConfigExtensionAuthority: newAuthority,
}),
)
.addSigner(configExtensionAuthority)
.buildAndExecute();
}
it("successfully set config extension authority and verify updated account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.configExtensionAuthority.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialConfigExtensionAuthorityKeypair.publicKey.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedConfigExtensionAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.configExtensionAuthority.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
// set back to initialConfigExtension with updateConfigExtensionAuthority
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
updatedConfigExtensionAuthorityKeypair,
initialConfigExtensionAuthorityKeypair.publicKey,
);
const backExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
backExtensionData!.configExtensionAuthority.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
// config_extension not initialized
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
const anotherWhirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension: anotherWhirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const fakeAuthority = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority: fakeAuthority.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(fakeAuthority)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedConfigExtensionAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.configExtensionAuthority.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.setConfigExtensionAuthority({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority: Keypair.generate().publicKey,
},
});
assert.equal(ix.keys.length, 4);
assert.ok(
ix.keys[2].pubkey.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedConfigExtensionAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/initialize_token_badge.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitializeTokenBadgeParams } from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
import type { TokenTrait } from "../../../utils/v2/init-utils-v2";
describe("initialize_token_badge", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
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;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function updateTokenBadgeAuthority(
config: PublicKey,
authority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: authority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(authority)
.buildAndExecute();
}
describe("successfully initialize token badge and verify initialized account contents", () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
];
tokenTraits.forEach((tokenTrait) => {
it(`Mint TokenProgram: ${tokenTrait.isToken2022 ? "Token-2022" : "Token"}`, async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, tokenTrait);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
});
});
it("successfully initialize when funder is different than account paying for transaction fee", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const otherWallet = await createOtherWallet();
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
funder: otherWallet.publicKey,
},
[initialTokenBadgeAuthorityKeypair, 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 tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
it("TokenBadge account has reserved space", async () => {
const tokenBadgeAccountSizeIncludingReserve = 8 + 32 + 32 + 128;
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const account = await ctx.connection.getAccountInfo(
tokenBadgePda.publicKey,
"confirmed",
);
assert.equal(account!.data.length, tokenBadgeAccountSizeIncludingReserve);
});
it("should be failed: already initialized", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
// initialized
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeData !== null);
// re-initialize
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {}),
(err) => {
return JSON.stringify(err).includes("already in use");
},
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
// with fake PDA
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
tokenBadgePda: PDAUtil.getTokenBadge(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
mint,
),
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
// config_extension not initialized
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const fakeAuthority = Keypair.generate();
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: ctx.wallet.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 7);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: config_extension_authority is passed as token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const fakeAuthority = initialConfigExtensionAuthorityKeypair;
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: invalid token_mint", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
// mint is not uninitialized
const uninitializedMint = Keypair.generate().publicKey;
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
uninitializedMint,
{},
),
/0xbc4/, // AccountNotInitialized
);
// different mint
const mintA = await createMintV2(provider, { isToken2022: true });
const mintB = await createMintV2(provider, { isToken2022: true });
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mintA, {
tokenMint: mintB,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: invalid token_badge", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
// different mint
const mintA = await createMintV2(provider, { isToken2022: true });
const mintB = await createMintV2(provider, { isToken2022: true });
const pdaForMintB = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mintB,
);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mintA, {
tokenBadgePda: pdaForMintB,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: funder is not signer", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: otherWallet.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 7);
assert.ok(ix.keys[5].pubkey.equals(otherWallet.publicKey));
// unset signer flag
ix.keys[5].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [initialTokenBadgeAuthorityKeypair], // no otherWallet
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid system program", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const invalidSystemProgram = TOKEN_PROGRAM_ID;
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: ctx.wallet.publicKey,
systemProgram: invalidSystemProgram,
},
});
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [initialTokenBadgeAuthorityKeypair],
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/set_token_badge_authority.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitializeTokenBadgeParams } from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
describe("set_token_badge_authority", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function setTokenBadgeAuthority(
config: PublicKey,
configExtensionAuthority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: configExtensionAuthority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(configExtensionAuthority)
.buildAndExecute();
}
it("successfully set token badge authority and verify updated account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialTokenBadgeAuthorityKeypair.publicKey.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
// initialize TokenBadge with updated authority
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
},
[updatedTokenBadgeAuthorityKeypair],
);
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
// config_extension not initialized
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
const anotherWhirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension: anotherWhirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const fakeAuthority = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority: fakeAuthority.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(fakeAuthority)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority != config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialTokenBadgeAuthorityKeypair.publicKey.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!updatedTokenBadgeAuthorityKeypair.publicKey.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
await assert.rejects(
setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
updatedTokenBadgeAuthorityKeypair,
Keypair.generate().publicKey,
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialTokenBadgeAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.setTokenBadgeAuthority({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
updatedTokenBadgeAuthorityKeypair.publicKey,
newTokenBadgeAuthority: Keypair.generate().publicKey,
},
});
assert.equal(ix.keys.length, 4);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/delete_token_badge.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type {
DeleteTokenBadgeParams,
InitializeTokenBadgeParams,
} from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
import type { TokenTrait } from "../../../utils/v2/init-utils-v2";
describe("delete_token_badge", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
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;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function updateTokenBadgeAuthority(
config: PublicKey,
authority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: authority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(authority)
.buildAndExecute();
}
async function deleteTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<DeleteTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.deleteTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: tokenBadgePda.publicKey,
receiver: provider.wallet.publicKey,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
describe("successfully delete token badge", () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
];
tokenTraits.forEach((tokenTrait) => {
it(`Mint TokenProgram: ${tokenTrait.isToken2022 ? "Token-2022" : "Token"}`, async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, tokenTrait);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
const preBalance = await provider.connection.getBalance(
provider.wallet.publicKey,
);
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
const postBalance = await provider.connection.getBalance(
provider.wallet.publicKey,
);
// wallet paid network fee, but receive rent. so balance should be increased.
assert.ok(postBalance > preBalance);
});
});
});
it("successfully delete when receiver is different than account paying for transaction fee", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
const preBalance = await provider.connection.getBalance(
otherWallet.publicKey,
);
const rent = await provider.connection.getBalance(tokenBadgePda.publicKey);
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
receiver: otherWallet.publicKey,
});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
const postBalance = await provider.connection.getBalance(
otherWallet.publicKey,
);
assert.equal(postBalance, preBalance + rent);
});
it("should be failed: already deleted", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
// delete again
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {}),
/0xbc4/, // AccountNotInitialized
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
// config_extension not initialized
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const fakeAuthority = Keypair.generate();
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is passed as token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const fakeAuthority = initialConfigExtensionAuthorityKeypair;
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction = program.instruction.deleteTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
receiver: ctx.wallet.publicKey,
},
});
assert.equal(ix.keys.length, 6);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid token_mint", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// mint is not uninitialized
const uninitializedMint = Keypair.generate().publicKey;
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
uninitializedMint,
{},
),
/0xbc4/, // AccountNotInitialized
);
// different mint
const anotherMint = await createMintV2(provider, { isToken2022: true });
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenMint: anotherMint,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: invalid token_badge", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// different mint (PDA not initialized)
const anotherMint = await createMintV2(provider, { isToken2022: true });
const pdaForAnotherMint = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
anotherMint,
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenBadge: pdaForAnotherMint.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// different mint (PDA initialized)
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
anotherMint,
{},
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenBadge: pdaForAnotherMint.publicKey,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
});
describe("lifecycle", () => {
it("initialize / delete / (re)initialize / (re)delete", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeData1 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData1!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData1!.tokenMint.equals(mint));
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved1 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved1 === null);
// re-initialize
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeData2 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData2!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData2!.tokenMint.equals(mint));
// re-delete
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved2 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved2 === null);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/position_with_token_extensions_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil, Percentage, TransactionBuilder } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import {
buildWhirlpoolClient,
increaseLiquidityQuoteByLiquidityWithParams,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { sleep, TickSpacing, ZERO_BN } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { createTokenAccountV2 } from "../../utils/v2/token-2022";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { generateDefaultOpenPositionWithTokenExtensionsParams } from "../../utils/test-builders";
import { initTestPool } from "../../utils/init-utils";
import { Keypair } from "@solana/web3.js";
import type { PublicKey } from "@solana/web3.js";
describe("position with token extensions management tests", () => {
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;
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);
}
const isToken2022Variations = [false, true];
isToken2022Variations.forEach((isToken2022) => {
it(`open, deposit, update fees and reward, withdraw, collect fees, collect reward, close (${isToken2022 ? "V2" : "V1"} instructions)`, async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
// pool init
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022 },
tokenTraitB: { isToken2022 },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1000),
}, // In range position
],
rewards: [
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA: tokenOwnerAccountA,
tokenAccountB: tokenOwnerAccountB,
} = fixture.getInfos();
const pool = await client.getPool(whirlpoolPda.publicKey);
const tokenVaultA = tokenVaultAKeypair.publicKey;
const tokenVaultB = tokenVaultBKeypair.publicKey;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const tickArrayLower = tickArrayPda.publicKey;
const tickArrayUpper = tickArrayPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// open position
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint)
.buildAndExecute();
const position = params.positionPda.publicKey;
const positionTokenAccount = params.positionTokenAccount;
const baseParams = {
position,
positionTokenAccount,
positionAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenProgramA,
tokenProgramB,
tokenVaultA,
tokenVaultB,
whirlpool: whirlpoolPda.publicKey,
tickArrayLower,
tickArrayUpper,
};
// deposit
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(10_000_000),
slippageTolerance: Percentage.fromFraction(0, 1000),
tickLowerIndex,
tickUpperIndex,
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMaxA: depositQuote.tokenMaxA,
tokenMaxB: depositQuote.tokenMaxB,
...baseParams,
})
: // test V1
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMaxA: depositQuote.tokenMaxA,
tokenMaxB: depositQuote.tokenMaxB,
...baseParams,
}),
).buildAndExecute();
const positionStep1 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep1!.liquidity.eq(depositQuote.liquidityAmount));
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB,
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.swapV2Ix(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,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// accrue rewards
await sleep(2000);
const positionStep2 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep2!.feeOwedA.isZero());
assert.ok(positionStep2!.feeOwedB.isZero());
assert.ok(positionStep2!.rewardInfos[0].amountOwed.isZero());
// update fees and rewards
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position,
tickArrayLower,
tickArrayUpper,
}),
).buildAndExecute();
const positionStep3 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(!positionStep3!.feeOwedA.isZero());
assert.ok(!positionStep3!.feeOwedB.isZero());
assert.ok(!positionStep3!.rewardInfos[0].amountOwed.isZero());
// withdraw
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMinA: ZERO_BN,
tokenMinB: ZERO_BN,
...baseParams,
})
: // test V1
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMinA: ZERO_BN,
tokenMinB: ZERO_BN,
...baseParams,
}),
).buildAndExecute();
const positionStep4 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep4!.liquidity.isZero());
// collect fees
const feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022 },
tokenMintA,
provider.wallet.publicKey,
);
const feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022 },
tokenMintB,
provider.wallet.publicKey,
);
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
...baseParams,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
})
: // test V1
WhirlpoolIx.collectFeesIx(ctx.program, {
...baseParams,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
).buildAndExecute();
const positionStep5 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep5!.feeOwedA.isZero());
assert.ok(positionStep5!.feeOwedB.isZero());
// collect reward
const rewardAccount = await createTokenAccountV2(
provider,
{ isToken2022: false },
pool.getData().rewardInfos[0].mint,
provider.wallet.publicKey,
);
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
...baseParams,
rewardIndex: 0,
rewardMint: pool.getData().rewardInfos[0].mint,
rewardOwnerAccount: rewardAccount,
rewardVault: pool.getData().rewardInfos[0].vault,
rewardTokenProgram: TOKEN_PROGRAM_ID,
})
: // test V1
WhirlpoolIx.collectRewardIx(ctx.program, {
...baseParams,
rewardIndex: 0,
rewardOwnerAccount: rewardAccount,
rewardVault: pool.getData().rewardInfos[0].vault,
}),
).buildAndExecute();
const positionStep6 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep6!.rewardInfos[0].amountOwed.isZero());
// close position
await toTx(
ctx,
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
).buildAndExecute();
checkClosed(params.positionPda.publicKey);
});
});
it("successfully opens and closes a position in one transaction", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
// open
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
await builder.buildAndExecute();
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
});
it("successfully opens and closes a position repeatedly with same Mint keypair (one transaction)", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
const numRepeat = 3;
for (let i = 0; i < numRepeat; i++) {
// open
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
}
await builder.buildAndExecute();
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
});
it("successfully opens and closes a position repeatedly with same Mint keypair (different transactions)", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
const numRepeat = 3;
for (let i = 0; i < numRepeat; i++) {
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
// open
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
await builder.buildAndExecute(undefined, { skipPreflight: true });
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
}
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/position_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import { toTx, WhirlpoolIx } from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { TickSpacing } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { initTestPool, openPosition } from "../../utils/init-utils";
import { generateDefaultOpenPositionParams } from "../../utils/test-builders";
describe("position management tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
it("successfully closes and opens a position in one transaction", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const { params } = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
0,
128,
);
const receiverKeypair = anchor.web3.Keypair.generate();
const { params: newParams, mint } = await generateDefaultOpenPositionParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
0,
128,
ctx.wallet.publicKey,
ctx.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.closePositionIx(ctx.program, {
positionAuthority: provider.wallet.publicKey,
receiver: receiverKeypair.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMintAddress,
positionTokenAccount: params.positionTokenAccount,
}),
)
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, newParams))
.addSigner(mint)
.buildAndExecute();
const closedResponse = await provider.connection.getTokenSupply(
params.positionMintAddress,
);
assert.equal(closedResponse.value.uiAmount, 0);
const openResponse = await provider.connection.getTokenSupply(
newParams.positionMintAddress,
);
assert.equal(openResponse.value.uiAmount, 1);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/bundled_position_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder, ZERO } from "@orca-so/common-sdk";
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import { Keypair, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type {
PositionBundleData,
Whirlpool,
WhirlpoolClient,
} from "../../../src";
import {
NUM_REWARDS,
PDAUtil,
POSITION_BUNDLE_SIZE,
PoolUtil,
PriceMath,
WhirlpoolIx,
buildWhirlpoolClient,
collectFeesQuote,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { TickSpacing, ZERO_BN, createTokenAccount } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import {
initializePositionBundle,
openBundledPosition,
} from "../../utils/init-utils";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("bundled position management tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const vaultStartBalance = 1_000_000;
const liquidityAmount = new BN(10_000_000);
const sleep = (second: number) =>
new Promise((resolve) => setTimeout(resolve, second * 1000));
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
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));
}
}
}
async function accrueFees(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(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();
// all position should get some fees
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
}
async function stopRewardsEmission(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, configKeypairs } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsIx(ctx.program, {
whirlpool: pool.getAddress(),
rewardVaultKey: pool.getData().rewardInfos[i].vault,
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
rewardIndex: i,
emissionsPerSecondX64: ZERO,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
}
}
it(`successfully open POSITION_BUNDLE_SIZE(${POSITION_BUNDLE_SIZE}) bundled positions and then close them`, async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const positionBundlePubkey = positionBundleInfo.positionBundlePda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const batchSize = 12;
const openedBundleIndexes: number[] = [];
// open all
for (
let startBundleIndex = 0;
startBundleIndex < POSITION_BUNDLE_SIZE;
startBundleIndex += batchSize
) {
const minBundleIndex = startBundleIndex;
const maxBundleIndex =
Math.min(startBundleIndex + batchSize, POSITION_BUNDLE_SIZE) - 1;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
for (
let bundleIndex = minBundleIndex;
bundleIndex <= maxBundleIndex;
bundleIndex++
) {
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
builder.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundlePubkey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
);
openedBundleIndexes.push(bundleIndex);
}
await builder.buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
checkBitmap(positionBundleAccount!, openedBundleIndexes);
}
assert.equal(openedBundleIndexes.length, POSITION_BUNDLE_SIZE);
// close all
for (
let startBundleIndex = 0;
startBundleIndex < POSITION_BUNDLE_SIZE;
startBundleIndex += batchSize
) {
const minBundleIndex = startBundleIndex;
const maxBundleIndex =
Math.min(startBundleIndex + batchSize, POSITION_BUNDLE_SIZE) - 1;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
for (
let bundleIndex = minBundleIndex;
bundleIndex <= maxBundleIndex;
bundleIndex++
) {
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
builder.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPda.publicKey,
bundleIndex,
positionBundle: positionBundlePubkey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
);
openedBundleIndexes.shift();
}
await builder.buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
checkBitmap(positionBundleAccount!, openedBundleIndexes);
}
assert.equal(openedBundleIndexes.length, 0);
// delete position bundle
await toTx(
ctx,
WhirlpoolIx.deletePositionBundleIx(ctx.program, {
positionBundle: positionBundlePubkey,
positionBundleMint:
positionBundleInfo.positionBundleMintKeypair.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
owner: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
assert.ok(positionBundleAccount === null);
});
it("successfully increase/decrease liquidity and harvest on bundled position", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
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, rewards } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
// open bundled position
const bundleIndex = 0;
const positionInitInfo = await openBundledPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
);
const { bundledPositionPda } = positionInitInfo.params;
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
// increaseLiquidity
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const preIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preIncrease!.liquidity.isZero());
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
).buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
await sleep(2); // accrueRewards
await accrueFees(fixture);
await stopRewardsEmission(fixture);
// updateFeesAndRewards
const preUpdate = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preUpdate!.feeOwedA.isZero());
assert.ok(preUpdate!.feeOwedB.isZero());
assert.ok(preUpdate!.rewardInfos.every((r) => r.amountOwed.isZero()));
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
position: bundledPositionPubkey,
tickArrayLower,
tickArrayUpper,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postUpdate = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postUpdate!.feeOwedA.gtn(0));
assert.ok(postUpdate!.feeOwedB.gtn(0));
assert.ok(postUpdate!.rewardInfos.every((r) => r.amountOwed.gtn(0)));
// collectFees
await toTx(
ctx,
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectFees = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectFees!.feeOwedA.isZero());
assert.ok(postCollectFees!.feeOwedB.isZero());
// collectReward
for (let i = 0; i < NUM_REWARDS; i++) {
const ata = await createTokenAccount(
provider,
rewards[i].rewardMint,
ctx.wallet.publicKey,
);
const preCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preCollectReward!.rewardInfos[i].amountOwed.gtn(0));
await toTx(
ctx,
WhirlpoolIx.collectRewardIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
rewardIndex: i,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardOwnerAccount: ata,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectReward!.rewardInfos[i].amountOwed.isZero());
}
// decreaseLiquidity
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const preDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preDecrease!.liquidity.eq(liquidityAmount));
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
).buildAndExecute();
const postDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postDecrease!.liquidity.isZero());
// close bundled position
await toTx(
ctx,
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
});
it("successfully repeatedly open bundled position & close bundled position", async () => {
const openCloseIterationNum = 5;
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
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, rewards } = fixture.getInfos();
// increase feeGrowth
await accrueFees(fixture);
// increase rewardGrowth
await sleep(2);
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
for (let iter = 0; iter < openCloseIterationNum; iter++) {
// open bundled position
const positionInitInfo = await openBundledPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
);
const { bundledPositionPda } = positionInitInfo.params;
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
// initialized check (No data left over from previous opening)
const postOpen = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postOpen!.feeGrowthCheckpointA.isZero());
assert.ok(postOpen!.feeGrowthCheckpointB.isZero());
assert.ok(
postOpen!.rewardInfos.every((r) => r.growthInsideCheckpoint.isZero()),
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
// increaseLiquidity
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const preIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preIncrease!.liquidity.isZero());
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
).buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
// non-zero check
assert.ok(postIncrease!.feeGrowthCheckpointA.gtn(0));
assert.ok(postIncrease!.feeGrowthCheckpointB.gtn(0));
assert.ok(
postIncrease!.rewardInfos.every((r) => r.growthInsideCheckpoint.gtn(0)),
);
await sleep(2); // accrueRewards
await accrueFees(fixture);
// decreaseLiquidity
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const preDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preDecrease!.liquidity.eq(liquidityAmount));
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
).buildAndExecute();
const postDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postDecrease!.liquidity.isZero());
// collectFees
await toTx(
ctx,
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectFees = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectFees!.feeOwedA.isZero());
assert.ok(postCollectFees!.feeOwedB.isZero());
// collectReward
for (let i = 0; i < NUM_REWARDS; i++) {
const ata = await createTokenAccount(
provider,
rewards[i].rewardMint,
ctx.wallet.publicKey,
);
const preCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preCollectReward!.rewardInfos[i].amountOwed.gtn(0));
await toTx(
ctx,
WhirlpoolIx.collectRewardIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
rewardIndex: i,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardOwnerAccount: ata,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectReward!.rewardInfos[i].amountOwed.isZero());
}
// close bundled position
await toTx(
ctx,
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
}
});
describe("Single Transaction", () => {
it("successfully openBundledPosition+increaseLiquidity / decreaseLiquidity+closeBundledPosition in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// openBundledPosition + increaseLiquidity
const openIncreaseBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
openIncreaseBuilder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
);
await openIncreaseBuilder.buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const decreaseCloseBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
decreaseCloseBuilder
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
);
await decreaseCloseBuilder.buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
});
it("successfully open bundled position & close bundled position in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
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 } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const receiver = Keypair.generate();
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: receiver.publicKey,
}),
);
await builder.buildAndExecute();
const receiverBalance = await ctx.connection.getBalance(
receiver.publicKey,
"confirmed",
);
assert.ok(receiverBalance > 0);
});
it("successfully close & re-open bundled position with the same bundle index in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// open
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// reopen bundled position with same bundleIndex in single Tx
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex: tickLowerIndex + tickSpacing,
tickUpperIndex: tickUpperIndex + tickSpacing,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
);
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
// in Anchor v0.26.0, close & open in same Tx will success.
await builder.buildAndExecute();
const postReopen = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postReopen!.liquidity.isZero());
assert.ok(postReopen!.tickLowerIndex === tickLowerIndex + tickSpacing);
assert.ok(postReopen!.tickUpperIndex === tickUpperIndex + tickSpacing);
});
it("successfully open bundled position & swap & close bundled position in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
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 } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPubkey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPubkey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const swapInput = new BN(200_000);
const poolLiquidity = new BN(liquidityAmount.muln(2).toString());
const estimatedFee = new BN(swapInput.toString())
.muln(3)
.divn(1000) // feeRate 0.3%
.muln(97)
.divn(100) // minus protocolFee 3%
.shln(64)
.div(poolLiquidity) // to X64 growth
.mul(liquidityAmount)
.shrn(64)
.toNumber();
const receiver = Keypair.generate();
const receiverAtaA = await createTokenAccount(
provider,
poolInitInfo.tokenMintA,
receiver.publicKey,
);
const receiverAtaB = await createTokenAccount(
provider,
poolInitInfo.tokenMintB,
receiver.publicKey,
);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.swapIx(ctx.program, {
amount: swapInput,
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.swapIx(ctx.program, {
amount: swapInput,
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
}),
)
.addInstruction(
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA: receiverAtaA,
tokenOwnerAccountB: receiverAtaB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: receiver.publicKey,
}),
);
await builder.buildAndExecute();
assert.ok(
(await ctx.fetcher.getTokenInfo(receiverAtaA, IGNORE_CACHE))!.amount ===
BigInt(estimatedFee.toString()),
);
assert.ok(
(await ctx.fetcher.getTokenInfo(receiverAtaB, IGNORE_CACHE))!.amount ===
BigInt(estimatedFee.toString()),
);
});
});
describe("Ensuring that the account is closed", () => {
it("The discriminator of the deleted position bundle is marked as closed", async () => {
const ctx = testCtx.whirlpoolCtx;
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const preClose = await ctx.connection.getAccountInfo(
positionBundleInfo.positionBundlePda.publicKey,
"confirmed",
);
assert.ok(preClose !== null);
const rentOfPositionBundle = preClose.lamports;
assert.ok(rentOfPositionBundle > 0);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// close
.addInstruction(
WhirlpoolIx.deletePositionBundleIx(ctx.program, {
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleMint:
positionBundleInfo.positionBundleMintKeypair.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
owner: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
}),
)
// fund rent
.addInstruction({
instructions: [
SystemProgram.transfer({
fromPubkey: ctx.wallet.publicKey,
toPubkey: positionBundleInfo.positionBundlePda.publicKey,
lamports: rentOfPositionBundle,
}),
],
cleanupInstructions: [],
signers: [],
});
await builder.buildAndExecute();
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
const postClose = await ctx.connection.getAccountInfo(
positionBundleInfo.positionBundlePda.publicKey,
"confirmed",
);
assert.ok(postClose !== null);
assert.ok(postClose.owner.equals(SystemProgram.programId));
assert.ok(postClose.data.length === 0);
});
it("The owner of closed account should be system program", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
// open
await toTx(
ctx,
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
).buildAndExecute();
const preClose = await ctx.connection.getAccountInfo(
bundledPositionPubkey,
"confirmed",
);
assert.ok(preClose !== null);
const rentOfBundledPosition = preClose.lamports;
assert.ok(rentOfBundledPosition > 0);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// fund rent
.addInstruction({
instructions: [
SystemProgram.transfer({
fromPubkey: ctx.wallet.publicKey,
toPubkey: bundledPositionPubkey,
lamports: rentOfBundledPosition,
}),
],
cleanupInstructions: [],
signers: [],
});
await builder.buildAndExecute();
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
const postClose = await ctx.connection.getAccountInfo(
bundledPositionPubkey,
"confirmed",
);
assert.ok(postClose !== null);
assert.ok(postClose.owner.equals(SystemProgram.programId));
assert.ok(postClose.data.length === 0);
});
it("should be failed: close bundled position and then updateFeesAndRewards in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// open
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// try to use closed bundled position
.addInstruction(
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
position: bundledPositionPubkey,
tickArrayLower,
tickArrayUpper,
whirlpool: whirlpoolPubkey,
}),
);
await assert.rejects(
builder.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/sparse_swap.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { DecimalUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { AccountMeta } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import type {
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolClient,
WhirlpoolData,
} from "../../../src";
import {
MEMO_PROGRAM_ADDRESS,
PDAUtil,
PriceMath,
SwapUtils,
TickUtil,
WhirlpoolIx,
buildWhirlpoolClient,
increaseLiquidityQuoteByInputToken,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { defaultConfirmOptions } from "../../utils/const";
import {
buildTestAquariums,
getDefaultAquarium,
initTestPoolWithTokens,
} from "../../utils/init-utils";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { buildTickArrayData } from "../../utils/testDataTypes";
import type { SwapV2Params } from "../../../src/instructions";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
} from "../../../src/utils/remaining-accounts-util";
interface SharedTestContext {
provider: anchor.AnchorProvider;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("sparse swap tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
whirlpoolCtx,
whirlpoolClient,
};
});
const tickSpacing64 = 64;
const tickSpacing8192 = 8192;
describe("TickArray order adjustment", () => {
it("reverse order(ta2, ta1, ta0 => ta0, ta1, ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// reverse
tickArray0: params.tickArray2,
tickArray1: params.tickArray1,
tickArray2: params.tickArray0,
}),
).buildAndExecute();
// 3000 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("reverse order(ta2, ta1, ta0 => ta0, ta1, ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-3000), // tickCurrentIndex = -3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [-2944, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
-2944,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-2944, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// reverse
tickArray0: params.tickArray2,
tickArray1: params.tickArray1,
tickArray2: params.tickArray0,
}),
).buildAndExecute();
// -3000 --> larger than 5632
assert.ok((await pool.refreshData()).tickCurrentIndex > 5632);
});
it("skip ta0(ta0, ta1, ta2 => ta1, ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(64), // tickCurrentIndex = 64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, -128], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
-128,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, -128, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 64);
// another swap push tickCurrentIndex to less than -128
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex <= -128);
assert.ok((await pool.refreshData()).tickCurrentIndex > -5632);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// less than -128 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("skip ta0, ta1(ta0, ta1, ta2 => ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(64), // tickCurrentIndex = 64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, -5760], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
-5760,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, -5760, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 64);
// another swap push tickCurrentIndex to less than -5760
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex <= -5760);
assert.ok((await pool.refreshData()).tickCurrentIndex > -9984);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// less than -5760 --> less than -5760
assert.ok((await pool.refreshData()).tickCurrentIndex < -5760);
});
it("skip ta0(ta0, ta1, ta2 => ta1, ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-64), // tickCurrentIndex = -64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [128, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
128,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(128, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -64);
// another swap push tickCurrentIndex to greater than 128
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex >= 128);
assert.ok((await pool.refreshData()).tickCurrentIndex < 5632);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// greater than 128 --> greater than 5632
assert.ok((await pool.refreshData()).tickCurrentIndex > 5632);
});
it("skip ta0, ta1(ta0, ta1, ta2 => ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-64), // tickCurrentIndex = -64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [5760, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
5760,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(5760, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -64);
// another swap push tickCurrentIndex to greater than 5760
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex >= 5760);
assert.ok((await pool.refreshData()).tickCurrentIndex < 9984);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// greater than 5760 --> greater than 5760
assert.ok((await pool.refreshData()).tickCurrentIndex > 5760);
});
it("a to b & b to a with same TickArray list", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing8192,
PriceMath.tickIndexToSqrtPriceX64(0),
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-720896 ][0 ]
await (await pool.initTickArrayForTicks([-720896, 0]))!.buildAndExecute();
// deposit FullRange, 100_000_000
const fullrange = TickUtil.getFullRangeTickIndex(tickSpacing8192);
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
fullrange[0],
fullrange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(fullrange[0], fullrange[1], depositQuote)
).tx.buildAndExecute();
const ta0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
whirlpoolPda.publicKey,
-720896,
).publicKey;
const ta1 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
whirlpoolPda.publicKey,
0,
).publicKey;
// a to b
await pool.refreshData();
const aToBParams = SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...aToBParams,
// always use ta0, ta1, ta1
tickArray0: ta0,
tickArray1: ta1,
tickArray2: ta1,
}),
).buildAndExecute();
// b to a
await pool.refreshData();
const bToAParams = SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...bToAParams,
// always use ta0, ta1, ta1
tickArray0: ta0,
tickArray1: ta1,
tickArray2: ta1,
}),
).buildAndExecute();
});
describe("failures", () => {
async function buildTestEnvironment() {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
return { poolInitInfo, params };
}
it("fail: invalid tick array (owned by other program)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tokenVaultA, // owned by TokenProgram
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tokenVaultA, // owned by TokenProgram
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: params.tokenVaultA, // owned by TokenProgram
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [params.tokenVaultA],
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fail: invalid tick array (owned by Whirlpool program, but not TickArray account)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [
params.whirlpool, // owned by Whirlpool program, but Whirlpool account
],
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
});
it("fail: invalid tick array (initialized TickArray account, but for other whirlpool)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const { whirlpoolPda: anotherWhirlpoolPda } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const anotherPool = await testCtx.whirlpoolClient.getPool(
anotherWhirlpoolPda.publicKey,
);
await (await anotherPool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
const anotherWhirlpoolTickArray0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
anotherWhirlpoolPda.publicKey,
0,
).publicKey;
const fetched = await testCtx.whirlpoolCtx.fetcher.getTickArray(
anotherWhirlpoolTickArray0,
IGNORE_CACHE,
);
assert.ok(fetched !== null);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: anotherWhirlpoolTickArray0, // for another Whirlpool
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: anotherWhirlpoolTickArray0, // for another Whirlpool
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: anotherWhirlpoolTickArray0, // for another Whirlpool
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [
anotherWhirlpoolTickArray0, // for another Whirlpool
],
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fail: no appropriate tick array (initialized TickArray, but start_tick_index mismatch)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const tickArrayNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
-5632,
).publicKey;
const fetched = await testCtx.whirlpoolCtx.fetcher.getTickArray(
tickArrayNeg5632,
IGNORE_CACHE,
);
assert.ok(fetched !== null);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// expected first tick array should start from 0
tickArray0: tickArrayNeg5632,
tickArray1: tickArrayNeg5632,
tickArray2: tickArrayNeg5632,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// expected first tick array should start from 0
tickArray0: tickArrayNeg5632,
tickArray1: tickArrayNeg5632,
tickArray2: tickArrayNeg5632,
// supplemental
supplementalTickArrays: [
tickArrayNeg5632,
tickArrayNeg5632,
tickArrayNeg5632,
],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fail: no appropriate tick array (uninitialized TickArray, and PDA mismatch)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const uninitializedRandomAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// expected first tick array should start from 0
tickArray0: uninitializedRandomAddress,
tickArray1: uninitializedRandomAddress,
tickArray2: uninitializedRandomAddress,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// expected first tick array should start from 0
tickArray0: uninitializedRandomAddress,
tickArray1: uninitializedRandomAddress,
tickArray2: uninitializedRandomAddress,
// supplemental
supplementalTickArrays: [
uninitializedRandomAddress,
uninitializedRandomAddress,
uninitializedRandomAddress,
],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
});
});
describe("swap through uninitialized TickArrays(*: init, -: uninit, S: start, T: end)", () => {
// |--------| uninitialized
// |********| initialized
// S: swap start / T: swap end
async function buildTestEnvironment() {
// ts: 64
// liquidity provided from full range
const initResult = await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(2816),
new BN(1_000_000_000),
);
const { poolInitInfo, whirlpoolPda } = initResult;
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
const fullrange = TickUtil.getFullRangeTickIndex(tickSpacing8192);
await (await pool.initTickArrayForTicks([
fullrange[0],
fullrange[1],
]))!.buildAndExecute();
// deposit FullRange, 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000_000), 0),
fullrange[0],
fullrange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(fullrange[0], fullrange[1], depositQuote)
).tx.buildAndExecute();
const data = await pool.refreshData();
assert.ok(data.tickCurrentIndex == 2816);
assert.ok(data.liquidity.gtn(0));
return initResult;
}
describe("swap, b to a: 2816 --> 2816 + (64 * 88) * 2", () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{ quote: SwapQuote; poolData: WhirlpoolData }> {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const startTickIndexes = [0, 5632, 11264];
const init = [init0, init1, init2];
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays = await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays[i].data === null);
tickArrays[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays[i].data!.whirlpool = pool.getAddress();
} else {
assert.ok(tickArrays[i].data !== null);
}
});
const quote = swapQuoteWithParams(
{
whirlpoolData: pool.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote.estimatedAmountIn.gtn(0));
assert.ok(quote.estimatedAmountOut.gtn(0));
const params = {
...SwapUtils.getSwapParamsFromQuote(
quote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
amountSpecifiedIsInput: true,
amount: quote.estimatedAmountIn,
otherAmountThreshold: quote.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool.refreshData()).tickCurrentIndex === targetTickIndex,
);
return { quote, poolData: pool.getData() };
}
let referenceResult: { quote: SwapQuote; poolData: WhirlpoolData };
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta0}${ta1}${ta2}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote.estimatedAmountIn.eq(
referenceResult.quote.estimatedAmountIn,
),
);
assert.ok(
result.quote.estimatedAmountOut.eq(
referenceResult.quote.estimatedAmountOut,
),
);
assert.ok(
result.poolData.tickCurrentIndex ===
referenceResult.poolData.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("swap, a to b: 2816 - (64 * 88) * 2 <-- 2816", () => {
const aToB = true;
const initialTickIndex = 2816;
const targetTickIndex = 2816 - tickSpacing64 * 88 * 2; // <-- 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{ quote: SwapQuote; poolData: WhirlpoolData }> {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const startTickIndexes = [0, -5632, -11264];
const init = [init0, init1, init2];
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays = await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays[i].data === null);
tickArrays[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays[i].data!.whirlpool = pool.getAddress();
} else {
assert.ok(tickArrays[i].data !== null);
}
});
const quote = swapQuoteWithParams(
{
whirlpoolData: pool.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote.estimatedAmountIn.gtn(0));
assert.ok(quote.estimatedAmountOut.gtn(0));
const params = {
...SwapUtils.getSwapParamsFromQuote(
quote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
amountSpecifiedIsInput: true,
amount: quote.estimatedAmountIn,
otherAmountThreshold: quote.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool.refreshData()).tickCurrentIndex ===
targetTickIndex - 1 /* shift */,
);
return { quote, poolData: pool.getData() };
}
let referenceResult: { quote: SwapQuote; poolData: WhirlpoolData };
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta2}${ta1}${ta0}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote.estimatedAmountIn.eq(
referenceResult.quote.estimatedAmountIn,
),
);
assert.ok(
result.quote.estimatedAmountOut.eq(
referenceResult.quote.estimatedAmountOut,
),
);
assert.ok(
result.poolData.tickCurrentIndex ===
referenceResult.poolData.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("twoHopSwap, b to a: 2816 --> 2816 + (64 * 88) * 2", () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
}> {
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const init = [init0, init1, init2];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool0.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays0[i].data === null);
tickArrays0[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays0[i].data!.whirlpool = pool0.getAddress();
assert.ok(tickArrays1[i].data === null);
tickArrays1[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays1[i].data!.whirlpool = pool1.getAddress();
} else {
assert.ok(tickArrays0[i].data !== null);
assert.ok(tickArrays1[i].data !== null);
}
});
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const params = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays1[0].address,
tickArrayOne1: tickArrays1[1].address,
tickArrayOne2: tickArrays1[2].address,
tickArrayTwo0: tickArrays0[0].address,
tickArrayTwo1: tickArrays0[1].address,
tickArrayTwo2: tickArrays0[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.twoHopSwapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool0.refreshData()).tickCurrentIndex >= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex >= targetTickIndex,
);
return {
quote0,
poolData0: pool0.getData(),
quote1,
poolData1: pool1.getData(),
};
}
let referenceResult: {
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
};
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta0}${ta1}${ta2} -> ${ta0}${ta1}${ta2}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote0.estimatedAmountIn.eq(
referenceResult.quote0.estimatedAmountIn,
),
);
assert.ok(
result.quote0.estimatedAmountOut.eq(
referenceResult.quote0.estimatedAmountOut,
),
);
assert.ok(
result.poolData0.tickCurrentIndex ===
referenceResult.poolData0.tickCurrentIndex,
);
assert.ok(
result.quote1.estimatedAmountIn.eq(
referenceResult.quote1.estimatedAmountIn,
),
);
assert.ok(
result.quote1.estimatedAmountOut.eq(
referenceResult.quote1.estimatedAmountOut,
),
);
assert.ok(
result.poolData1.tickCurrentIndex ===
referenceResult.poolData1.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("twoHopSwap, a to b: 2816 + (64 * 88) * 2 <-- 2816", () => {
const aToB = true;
const initialTickIndex = 2816;
const targetTickIndex = 2816 - tickSpacing64 * 88 * 2; // <-- 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
}> {
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool0(a(0) -> b(1)) --> pool1(a(1) -> b(2)) (so pool1 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(7_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, -5632, -11264];
const init = [init0, init1, init2];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool0.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays0[i].data === null);
tickArrays0[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays0[i].data!.whirlpool = pool0.getAddress();
assert.ok(tickArrays1[i].data === null);
tickArrays1[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays1[i].data!.whirlpool = pool1.getAddress();
} else {
assert.ok(tickArrays0[i].data !== null);
assert.ok(tickArrays1[i].data !== null);
}
});
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote0.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const params = {
amount: quote0.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays0[0].address,
tickArrayOne1: tickArrays0[1].address,
tickArrayOne2: tickArrays0[2].address,
tickArrayTwo0: tickArrays1[0].address,
tickArrayTwo1: tickArrays1[1].address,
tickArrayTwo2: tickArrays1[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool0.getAddress(),
whirlpoolTwo: pool1.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[1].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[2].account,
tokenVaultOneA: pool0.getData().tokenVaultA,
tokenVaultOneB: pool0.getData().tokenVaultB,
tokenVaultTwoA: pool1.getData().tokenVaultA,
tokenVaultTwoB: pool1.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[0].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[2].account,
tokenVaultOneInput: pool0.getData().tokenVaultA,
tokenVaultOneIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoOutput: pool1.getData().tokenVaultB,
tokenMintInput: pool0.getData().tokenMintA,
tokenMintIntermediate: pool0.getData().tokenMintB,
tokenMintOutput: pool1.getData().tokenMintB,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.twoHopSwapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool0.refreshData()).tickCurrentIndex <= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex <= targetTickIndex,
);
return {
quote0,
poolData0: pool0.getData(),
quote1,
poolData1: pool1.getData(),
};
}
let referenceResult: {
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
};
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta2}${ta1}${ta0} <- ${ta2}${ta1}${ta0}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote0.estimatedAmountIn.eq(
referenceResult.quote0.estimatedAmountIn,
),
);
assert.ok(
result.quote0.estimatedAmountOut.eq(
referenceResult.quote0.estimatedAmountOut,
),
);
assert.ok(
result.poolData0.tickCurrentIndex ===
referenceResult.poolData0.tickCurrentIndex,
);
assert.ok(
result.quote1.estimatedAmountIn.eq(
referenceResult.quote1.estimatedAmountIn,
),
);
assert.ok(
result.quote1.estimatedAmountOut.eq(
referenceResult.quote1.estimatedAmountOut,
),
);
assert.ok(
result.poolData1.tickCurrentIndex ===
referenceResult.poolData1.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
});
describe("supplemental TickArrays (v2 only)", () => {
describe("swapV2", () => {
async function buildTestEnvironment() {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
return { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB };
}
it("using 3 supplemental tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
5632,
).publicKey;
const taStart0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
0,
).publicKey;
const taStartNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-5632,
).publicKey;
const taStartNeg11264 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-11264,
).publicKey;
const paramsWithoutSupplemental = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// TA starting with 5632 will not be used...
tickArray0: taStart5632,
tickArray1: taStart5632,
tickArray2: taStart5632,
};
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
const paramsWithSupplemental = {
...paramsWithoutSupplemental,
supplementalTickArrays: [
// should be adjusted at the program side
taStartNeg11264,
taStart0,
taStartNeg5632,
],
};
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute(undefined, { skipPreflight: true });
// 3000 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("fail: 4 supplemental tick arrays (too many)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
5632,
).publicKey;
const supplementalTickArrays = [
taStart5632,
taStart5632,
taStart5632,
taStart5632,
];
const params: SwapV2Params = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// too many
supplementalTickArrays,
};
assert.throws(
() => WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
/Too many supplemental tick arrays provided/, // SDK error
);
// bypass SDK
const supplementalTickArrayAccountMetas: AccountMeta[] =
supplementalTickArrays.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArrays,
supplementalTickArrayAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.swapV2(
params.amount,
params.otherAmountThreshold,
params.sqrtPriceLimit,
params.amountSpecifiedIsInput,
params.aToB,
remainingAccountsInfo,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
});
it("go back to the previous tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-128), // tickCurrentIndex = -128
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(80_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
0,
).publicKey;
const taStartNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-5632,
).publicKey;
const paramsWithoutSupplemental = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
// it should start from TA with startTickIndex -5632
assert.ok(pool.getData().tickCurrentIndex == -128);
assert.ok(paramsWithoutSupplemental.tickArray0.equals(taStartNeg5632));
// another swap to push tickCurrentIndex to > 0
const anotherSwapQuote = await swapQuoteByInputToken(
pool,
poolInitInfo.tokenMintB,
new BN(10_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
assert.ok(anotherSwapQuote.estimatedEndTickIndex > 128);
await (await pool.swap(anotherSwapQuote)).buildAndExecute();
await pool.refreshData();
assert.ok(pool.getData().tickCurrentIndex > 128);
const preOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
paramsWithoutSupplemental.tokenOwnerAccountB,
);
// now tickCurrentIndex was push backed to > 128, so TickArray with startTickIndex 0 should be used as the first one
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
// If TickArray with startTickIndex 0 is included in supplementalTickArrays, it should work.
const paramsWithSupplemental = {
...paramsWithoutSupplemental,
supplementalTickArrays: [taStart0],
};
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok((await pool.refreshData()).tickCurrentIndex < 0);
const postOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
paramsWithoutSupplemental.tokenOwnerAccountB,
);
// output balance should be increased (actual output will be better than quote due to the push back)
assert.ok(
new BN(postOutputBalance.value.amount)
.sub(new BN(preOutputBalance.value.amount))
.gte(swapQuote.estimatedAmountOut),
);
});
});
describe("twoHopSwapV2", () => {
it("using 3 supplemental tick arrays", async () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const wrongAddress = Keypair.generate().publicKey;
const paramsWithoutSupplemental = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: wrongAddress,
tickArrayOne1: wrongAddress,
tickArrayOne2: wrongAddress,
tickArrayTwo0: wrongAddress,
tickArrayTwo1: wrongAddress,
tickArrayTwo2: wrongAddress,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
const supplementalTickArraysOne = [
// should be adjusted at the program side
tickArrays1[2].address,
tickArrays1[0].address,
tickArrays1[1].address,
];
const supplementalTickArraysTwo = [
// should be adjusted at the program side
tickArrays0[2].address,
tickArrays0[0].address,
tickArrays0[1].address,
];
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
const paramsWithSupplemental: TwoHopSwapV2Params = {
...paramsWithoutSupplemental,
supplementalTickArraysOne,
supplementalTickArraysTwo,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute();
assert.ok(
(await pool0.refreshData()).tickCurrentIndex >= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex >= targetTickIndex,
);
});
it("fail: 4 supplemental tick arrays (too many)", async () => {
const aToB = false;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const wrongAddress = Keypair.generate().publicKey;
const supplementalTickArraysOne = [
wrongAddress,
wrongAddress,
wrongAddress,
wrongAddress,
];
const supplementalTickArraysTwo = [
wrongAddress,
wrongAddress,
wrongAddress,
wrongAddress,
];
const params = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: wrongAddress,
tickArrayOne1: wrongAddress,
tickArrayOne2: wrongAddress,
tickArrayTwo0: wrongAddress,
tickArrayTwo1: wrongAddress,
tickArrayTwo2: wrongAddress,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
// too many
supplementalTickArraysOne,
supplementalTickArraysTwo,
};
assert.throws(
() =>
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
/Too many supplemental tick arrays provided/, // SDK error
);
// bypass SDK
const supplementalTickArrayOneAccountMetas: AccountMeta[] =
supplementalTickArraysOne.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfoOne, remainingAccountsOne] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArraysOne,
supplementalTickArrayOneAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.twoHopSwapV2(
params.amount,
params.otherAmountThreshold,
params.amountSpecifiedIsInput,
params.aToBOne,
params.aToBTwo,
params.sqrtPriceLimitOne,
params.sqrtPriceLimitTwo,
remainingAccountsInfoOne,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: remainingAccountsOne,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
// bypass SDK
const supplementalTickArrayTwoAccountMetas: AccountMeta[] =
supplementalTickArraysTwo.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfoTwo, remainingAccountsTwo] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArraysTwo,
supplementalTickArrayTwoAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.twoHopSwapV2(
params.amount,
params.otherAmountThreshold,
params.amountSpecifiedIsInput,
params.aToBOne,
params.aToBTwo,
params.sqrtPriceLimitOne,
params.sqrtPriceLimitTwo,
remainingAccountsInfoTwo,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: remainingAccountsTwo,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
});
it("go back to the previous tick array", async () => {
const aToB = false;
const initialTickIndex = 256;
const targetTickIndex = 256 + tickSpacing64 * 88 * 1; // --> 1 tick array
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(256),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(256),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [-5632, 0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const taStart0One = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
0,
).publicKey;
const taStart0Two = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
0,
).publicKey;
const taStartNeg5632One = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
-5632,
).publicKey;
const taStartNeg5632Two = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
-5632,
).publicKey;
const paramsWithoutSupplemental = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays1[0].address,
tickArrayOne1: tickArrays1[1].address,
tickArrayOne2: tickArrays1[2].address,
tickArrayTwo0: tickArrays0[0].address,
tickArrayTwo1: tickArrays0[1].address,
tickArrayTwo2: tickArrays0[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
// it should start from TA with startTickIndex 0
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(paramsWithoutSupplemental.tickArrayOne0.equals(taStart0One));
assert.ok(paramsWithoutSupplemental.tickArrayTwo0.equals(taStart0Two));
// another swap to push tickCurrentIndex to <= -128
const anotherSwapQuoteOne = await swapQuoteByInputToken(
pool1,
pool1.getData().tokenMintA,
new BN(200_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const anotherSwapQuoteTwo = await swapQuoteByInputToken(
pool0,
pool0.getData().tokenMintA,
new BN(90_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
anotherSwapQuoteOne,
testCtx.whirlpoolCtx,
pool1,
aquarium.tokenAccounts[1].account,
aquarium.tokenAccounts[2].account,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
anotherSwapQuoteTwo,
testCtx.whirlpoolCtx,
pool0,
aquarium.tokenAccounts[0].account,
aquarium.tokenAccounts[1].account,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool1.refreshData()).tickCurrentIndex <= -128);
assert.ok((await pool0.refreshData()).tickCurrentIndex <= -128);
const preOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
aquarium.tokenAccounts[0].account,
);
// now tickCurrentIndex was push backed to <= -128, so TickArray with startTickIndex -5632 should be used as the first one
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysOne: [taStartNeg5632One],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysTwo: [taStartNeg5632Two],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysOne: [taStartNeg5632One],
supplementalTickArraysTwo: [taStartNeg5632Two],
}),
).buildAndExecute();
const postOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
aquarium.tokenAccounts[0].account,
);
// output balance should be increased (actual output will be better than quote due to the push back)
assert.ok(
new BN(postOutputBalance.value.amount)
.sub(new BN(preOutputBalance.value.amount))
.gte(quote0.estimatedAmountOut),
);
assert.ok((await pool1.refreshData()).tickCurrentIndex > 0);
assert.ok((await pool0.refreshData()).tickCurrentIndex > 0);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/splash_pool.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { DecimalUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import type { WhirlpoolClient } from "../../../src";
import {
MAX_SQRT_PRICE_BN,
MAX_TICK_INDEX,
MIN_SQRT_PRICE_BN,
MIN_TICK_INDEX,
PDAUtil,
PriceMath,
SwapUtils,
TickUtil,
WhirlpoolIx,
buildWhirlpoolClient,
increaseLiquidityQuoteByInputToken,
increaseLiquidityQuoteByLiquidityWithParams,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { defaultConfirmOptions } from "../../utils/const";
import { initTestPoolWithTokens } from "../../utils/init-utils";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { MAX_U64, getTokenBalance } from "../../utils";
interface SharedTestContext {
provider: anchor.AnchorProvider;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
const DEBUG_OUTPUT = false;
describe("splash pool tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
whirlpoolCtx,
whirlpoolClient,
};
});
describe("trades on splash pool", () => {
type TestVariation = {
figure: string;
poolTickSpacing: number;
poolInitialTickIndex: number;
poolLiquidity: BN;
tradeMode: "exactIn" | "exactOut";
tradeDirection: "AtoB" | "BtoA";
tradeTokenAmount: BN;
expectedPartialFill: boolean;
};
const testVariations: TestVariation[] = [
// Notation
//
// l: lower tick index for FullRange
// u: upper tick index for FullRange
// m: MIN_TICK_INDEX (-443636)
// x: MAX_TICK_INDEX (+443636)
// *: liquidity (flat distribution)
// S: trade start
// T: trade end
//
// Limit
//
// 2^33 is almost max liquidity to realize single side deposit at tick index MIN_TICK_INDEX or MAX_TICK_INDEX
// 2^64 is almost max liquidity to realize 50:50 deposit at tick index 0
//
////////////////////////////////////////////////////////////////////////////////
// ExactIn
////////////////////////////////////////////////////////////////////////////////
// ExactIn, BtoA, min to ...
{
figure:
"(toB) |-----mS----l**********T*********|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(20000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|**********T*********u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(200000000000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|********************u----Tx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactIn, AtoB, max to ...
{
figure:
"(toB) |-----m-----l********************|**********T*********u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(20000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----m-----l**********T*********|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(200000000000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mT----l********************|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactIn, BtoA, 1 to ...
{
figure:
"(toB) |-----m-----l********************|S****T**************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64).divn(2),
expectedPartialFill: false,
},
// ExactIn, AtoB, 1 to ...
{
figure:
"(toB) |-----m-----l**************T****S|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64).divn(2),
expectedPartialFill: false,
},
////////////////////////////////////////////////////////////////////////////////
// ExactOut
////////////////////////////////////////////////////////////////////////////////
// ExactOut, BtoA, min to ...
{
figure:
"(toB) |-----mS----l**********T*********|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("16583913771126114400"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|**********T*********u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("16587613395589958784"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|********************u----Tx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactOut, AtoB, max to ...
{
figure:
"(toB) |-----m-----l********************|**********T*********u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("16583913770960970547"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----m-----l**********T*********|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("16587613395424814923"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mT----l********************|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactOut, BtoA, 1 to ...
{
figure:
"(toB) |-----m-----l********************|S****T**************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("4604758097518383314"),
expectedPartialFill: false,
},
// ExactOut, AtoB, 1 to ...
{
figure:
"(toB) |-----m-----l**************T****S|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("4604758097518383314"),
expectedPartialFill: false,
},
];
testVariations.forEach((variation) => {
const caseName = `${variation.figure}, mode=${variation.tradeMode}, liq=${variation.poolLiquidity}, amount=${variation.tradeTokenAmount}`;
it(caseName, async () => {
const {
poolTickSpacing,
poolInitialTickIndex,
poolLiquidity,
tradeMode,
tradeDirection,
tradeTokenAmount,
} = variation;
const tradeAmountSpecifiedIsInput = tradeMode === "exactIn";
const tradeAToB = tradeDirection === "AtoB";
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// SplashPool has only 2 TickArrays for negative and positive ticks
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
debug(
`pool state: tick = ${pool.getData().tickCurrentIndex}, liquidity = ${depositQuote.liquidityAmount.toString()}, tokenA = ${depositQuote.tokenEstA.toString()}, tokenB = ${depositQuote.tokenEstB.toString()}`,
);
const swapQuote = swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const preTickIndex = pool.getData().tickCurrentIndex;
const [preOwnerA, preOwnerB] = await getTokenBalances(
tokenAccountA,
tokenAccountB,
);
const [preVaultA, preVaultB] = await getTokenBalances(
pool.getData().tokenVaultA,
pool.getData().tokenVaultB,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
swapQuote.aToB ? tokenAccountA : tokenAccountB,
swapQuote.aToB ? tokenAccountB : tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
await pool.refreshData(); // reflect new tickCurrentIndex
const postTickIndex = pool.getData().tickCurrentIndex;
const [postOwnerA, postOwnerB] = await getTokenBalances(
tokenAccountA,
tokenAccountB,
);
const [postVaultA, postVaultB] = await getTokenBalances(
pool.getData().tokenVaultA,
pool.getData().tokenVaultB,
);
// display pre & post
debug(`amount: ${tradeTokenAmount.toString()}`);
debug(
`estimate: ${swapQuote.estimatedAmountIn.toString()} --> ${swapQuote.estimatedAmountOut.toString()}`,
);
debug(
`owner: A = ${preOwnerA.toString()} -> ${postOwnerA.toString()}, B = ${preOwnerB.toString()} -> ${postOwnerB.toString()}`,
);
debug(
`vault: A = ${preVaultA.toString()} -> ${postVaultA.toString()}, B = ${preVaultB.toString()} -> ${postVaultB.toString()}`,
);
debug(`tick index: ${preTickIndex} --> ${postTickIndex}`);
// verify: partial fill
const actualAmount = swapQuote.amountSpecifiedIsInput
? swapQuote.estimatedAmountIn
: swapQuote.estimatedAmountOut;
if (variation.expectedPartialFill) {
assert.ok(actualAmount.lt(tradeTokenAmount));
} else {
assert.ok(actualAmount.eq(tradeTokenAmount));
}
// verify: quote on SDK == realized trade
const diffOwnerA = postOwnerA.sub(preOwnerA);
const diffOwnerB = postOwnerB.sub(preOwnerB);
const diffVaultA = postVaultA.sub(preVaultA);
const diffVaultB = postVaultB.sub(preVaultB);
debug(
`diff: owner A = ${diffOwnerA.toString()}, owner B = ${diffOwnerB.toString()}`,
);
debug(
`estimated: in = ${swapQuote.estimatedAmountIn.toString()}, out = ${swapQuote.estimatedAmountOut.toString()}`,
);
debug(
`sqrtPrice: quote = ${swapQuote.estimatedEndSqrtPrice.toString()}, pool = ${pool.getData().sqrtPrice.toString()}`,
);
assert.ok(diffOwnerA.eq(diffVaultA.neg()));
assert.ok(diffOwnerB.eq(diffVaultB.neg()));
assert.ok(
diffOwnerA.eq(
tradeAToB
? swapQuote.estimatedAmountIn.neg()
: swapQuote.estimatedAmountOut,
),
);
assert.ok(
diffOwnerB.eq(
tradeAToB
? swapQuote.estimatedAmountOut
: swapQuote.estimatedAmountIn.neg(),
),
);
assert.ok(swapQuote.estimatedEndSqrtPrice.eq(pool.getData().sqrtPrice));
assert.ok(
swapQuote.estimatedEndTickIndex === pool.getData().tickCurrentIndex,
);
});
});
});
async function getTokenBalances(
tokenAccountA: PublicKey,
tokenAccountB: PublicKey,
): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
describe("ExactOut overflow (required input token is over u64 max)", () => {
// Since trade mode is ExactOut, the outputt amount must be within u64 max, but the input token may over u64 max.
// It is okay to fail with overflow error because the trade is impossible.
// B to A (too much tokenB is required)
it("(toB) |-----m-----l********************|S******************Tu-----x-----| (toA), too much tokenB is required", async () => {
const poolTickSpacing = 32768 + 128;
const poolInitialTickIndex = 0;
const poolLiquidity = powBN(2, 34);
const tradeAmountSpecifiedIsInput = false;
const tradeAToB = false;
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
// try to output all tokenA
const tradeTokenAmount = depositQuote.tokenEstA;
await assert.rejects(
async () =>
swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
),
/MulShiftRight overflowed u128/, // at getAmountUnfixedDelta for tokenB (too much tokenB is required)
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
amount: tradeTokenAmount,
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tokenAuthority: testCtx.provider.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: pool.getData().tokenVaultA,
tokenVaultB: pool.getData().tokenVaultB,
whirlpool: pool.getAddress(),
tickArray0: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray1: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray2: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
oracle: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
).publicKey,
}),
).buildAndExecute(),
/MultiplicationShiftRightOverflow/, // at get_amount_unfixed_delta for tokenB (too much tokenB is required)
);
});
// A to B (too much tokenA is required)
it("(toB) |-----m-----lT******************S|********************u-----x-----| (toA), too much tokenA is required", async () => {
const poolTickSpacing = 32768 + 128;
const poolInitialTickIndex = 0;
const poolLiquidity = powBN(2, 34);
const tradeAmountSpecifiedIsInput = false;
const tradeAToB = true;
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
// try to output all tokenB
const tradeTokenAmount = depositQuote.tokenEstB;
await assert.rejects(
async () =>
swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
),
/Results larger than U64/, // at getAmountUnfixedDelta for tokenA (too much tokenA is required)
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
amount: tradeTokenAmount,
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tokenAuthority: testCtx.provider.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: pool.getData().tokenVaultA,
tokenVaultB: pool.getData().tokenVaultB,
whirlpool: pool.getAddress(),
tickArray0: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray1: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
-1,
).publicKey,
tickArray2: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
-1,
).publicKey,
oracle: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
).publicKey,
}),
).buildAndExecute(),
/TokenMaxExceeded/, // at get_amount_unfixed_delta for tokenA (too much tokenA is required)
);
});
});
it("ExactOut Sandwitch attack senario", async () => {
const tickSpacingSplash128 = 32768 + 128;
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacingSplash128,
PriceMath.tickIndexToSqrtPriceX64(0), // 1 B/A
new BN(2_000_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
// [-2,894,848 ][0 ][
await (await pool.initTickArrayForTicks([
// SplashPool has only 2 TickArrays for negative and positive ticks
-1, +1,
]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// create 2 position (small & large)
const depositQuoteSmall = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(1), 0), // very thin liquidity
fullRange[0],
fullRange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
const small = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuoteSmall,
);
await small.tx.buildAndExecute();
const depositQuoteLarge = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(1_000_000_000), 0), // extremely larger than small position
fullRange[0],
fullRange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
const large = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuoteLarge,
);
await large.tx.buildAndExecute();
await pool.refreshData();
const preLiquidity = pool.getData().liquidity;
// get quote with small and large position liquidity
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(800_000_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
// close large position
const largePosition = PDAUtil.getPosition(
testCtx.whirlpoolCtx.program.programId,
large.positionMint,
).publicKey;
const closeTx = await pool.closePosition(
largePosition,
Percentage.fromFraction(0, 100),
);
for (const tx of closeTx) {
await tx.buildAndExecute();
}
// liquidity should be decreased
await pool.refreshData();
const postLiquidity = pool.getData().liquidity;
assert.ok(preLiquidity.gt(postLiquidity));
const [preA, preB] = await getTokenBalances(tokenAccountA, tokenAccountB);
// with sqrtPriceLimit = 0, partial fill will be rejected
// so trade will be protected from sandwich attack if sqrtPriceLimit = 0 is used.
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
sqrtPriceLimit: new BN(0),
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
// with sqrtPriceLimit != 0, partial fill will be allowed
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
}),
).buildAndExecute();
const [postA, postB] = await getTokenBalances(tokenAccountA, tokenAccountB);
await pool.refreshData();
// input (partial)
assert.ok(preA.sub(postA).lt(swapQuote.estimatedAmountIn));
// output (partial)
assert.ok(postB.sub(preB).lt(swapQuote.estimatedAmountOut));
// hit min
assert.ok(pool.getData().sqrtPrice.eq(MIN_SQRT_PRICE_BN));
});
});
function powBN(base: number, exp: number): BN {
return new BN(base).pow(new BN(exp));
}
function debug(msg: string) {
if (!DEBUG_OUTPUT) return;
console.debug(msg);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/const.ts
|
import type { ConfirmOptions } from "@solana/web3.js";
export const defaultConfirmOptions: ConfirmOptions = {
commitment: "confirmed",
preflightCommitment: "confirmed",
};
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.