Skip to content

Commit

Permalink
Feat: ALT | Chore: Some warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
LevBeta committed Jun 12, 2024
1 parent 617e294 commit e36c732
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 51 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ solana-client = "1.16"
solana-program = "1.16"
solana-rpc-client-api = "1.16"
solana-sdk = "1.16"
solana-address-lookup-table-program = "1.16"
spl-associated-token-account = "2.0.0"
spl-token = "=4.0.0"
thiserror = "1.0.56"
Expand Down
3 changes: 2 additions & 1 deletion src/cli/setup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub async fn setup() -> anyhow::Result<()> {
marginfi_program_id: GeneralConfig::default_marginfi_program_id(),
marginfi_group_address: GeneralConfig::default_marginfi_group_address(),
account_whitelist: GeneralConfig::default_account_whitelist(),
address_lookup_tables: GeneralConfig::default_address_lookup_tables(),
};

let liquidator_config = LiquidatorCfg {
Expand Down Expand Up @@ -129,7 +130,7 @@ fn prompt_user(prompt_text: &str) -> anyhow::Result<String> {
/// Simply asks the keypair path until it is a valid one,
/// Returns (keypair_path, signer_keypair)
fn ask_keypair_until_valid() -> anyhow::Result<(String, Keypair)> {
print!("Keypair file path\n");
println!("Keypair file path");
loop {
let keypair_path = prompt_user("> ")?;
match read_keypair_file(&keypair_path) {
Expand Down
10 changes: 10 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
};
use fixed::types::I80F48;
use fixed_macro::types::I80F48;
use rayon::vec;
use solana_sdk::{pubkey, pubkey::Pubkey};
use std::{
error::Error,
Expand Down Expand Up @@ -82,6 +83,8 @@ pub struct GeneralConfig {
default = "GeneralConfig::default_account_whitelist"
)]
pub account_whitelist: Option<Vec<Pubkey>>,
#[serde(default = "GeneralConfig::default_address_lookup_tables")]
pub address_lookup_tables: Vec<Pubkey>,
}

impl std::fmt::Display for GeneralConfig {
Expand Down Expand Up @@ -148,6 +151,13 @@ impl GeneralConfig {
String::from("https://ny.mainnet.block-engine.jito.wtf")
}

pub fn default_address_lookup_tables() -> Vec<Pubkey> {
vec![
pubkey!("HGmknUTUmeovMc9ryERNWG6UFZDFDVr9xrum3ZhyL4fC"),
pubkey!("5FuKF7C1tJji2mXZuJ14U9oDb37is5mmvYLf4KwojoF1"),
]
}

pub fn get_tx_config(&self) -> TxConfig {
TxConfig {
compute_unit_price_micro_lamports: self.compute_unit_price_micro_lamports,
Expand Down
2 changes: 1 addition & 1 deletion src/geyser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl GeyserService {
let traked_accounts_cl = tracked_accounts.clone();
let liquidator_sender = liquidator_sender.clone();
let rebalancer_sender = rebalancer_sender.clone();
let handle = tokio::spawn(async move {
tokio::spawn(async move {
if let Err(e) = Self::subscribe_and_run(
traked_accounts_cl,
marginfi_program_id,
Expand Down
46 changes: 33 additions & 13 deletions src/jito/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
use jito_protos::{
bundle::{bundle_result::Result as BundleResultType, rejected::Reason, Bundle},
block,
searcher::{
searcher_service_client::SearcherServiceClient, GetTipAccountsRequest,
NextScheduledLeaderRequest, SubscribeBundleResultsRequest,
},
};

use futures::stream::{FuturesUnordered, StreamExt};
use jito_searcher_client::{get_searcher_client_no_auth, send_bundle_with_confirmation};
use log::{error, info};
use log::error;
use solana_address_lookup_table_program::state::AddressLookupTable;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
address_lookup_table_account::AddressLookupTableAccount,
commitment_config::CommitmentConfig,
instruction::Instruction,
message::{v0, VersionedMessage},
pubkey::Pubkey,
signature::{Keypair, Signer},
system_instruction::transfer,
transaction::{Transaction, VersionedTransaction},
};
use std::{str::FromStr, sync::Arc};
use std::{ops::Add, str::FromStr};
use tokio::time::sleep;
use tonic::transport::Channel;

Expand All @@ -27,21 +32,35 @@ pub struct JitoClient {
searcher_client: SearcherServiceClient<Channel>,
keypair: Keypair,
tip_accounts: Vec<String>,
lookup_tables: Vec<AddressLookupTableAccount>,
}

impl JitoClient {
pub async fn new(config: GeneralConfig, signer: Keypair) -> Self {
pub async fn new(config: GeneralConfig, signer: Keypair) -> anyhow::Result<Self> {
let rpc = RpcClient::new_with_commitment(config.rpc_url, CommitmentConfig::confirmed());
let searcher_client = get_searcher_client_no_auth(&config.block_engine_url)
.await
.expect("Failed to create a searcher client");

Self {

let mut lookup_tables = vec![];
for table_address in &config.address_lookup_tables {
let raw_account = rpc.get_account(&table_address).await?;
let address_lookup_table = AddressLookupTable::deserialize(&raw_account.data)?;
let lookup_table = AddressLookupTableAccount {
key: table_address.clone(),
addresses: address_lookup_table.addresses.to_vec(),
};
lookup_tables.push(lookup_table);
}

Ok(Self {
rpc,
searcher_client,
keypair: signer,
tip_accounts: Vec::new(),
}
lookup_tables,
})
}

pub async fn send_transaction(
Expand All @@ -68,7 +87,7 @@ impl JitoClient {
.into_inner();

let num_slots = next_leader.next_leader_slot - next_leader.current_slot;
is_jito_leader = (num_slots <= 2).into();
is_jito_leader = num_slots <= 2;
sleep(std::time::Duration::from_millis(500)).await;
}

Expand All @@ -78,14 +97,15 @@ impl JitoClient {
lamports,
));

let txs = vec![VersionedTransaction::from(
Transaction::new_signed_with_payer(
let txs = vec![VersionedTransaction::try_new(
VersionedMessage::V0(v0::Message::try_compile(
&self.keypair.pubkey(),
&ixs,
Some(&self.keypair.pubkey()),
&[&self.keypair],
&self.lookup_tables,
blockhash,
),
)];
)?),
&[&self.keypair],
)?];

if let Err(err) = send_bundle_with_confirmation(
&txs,
Expand Down
15 changes: 3 additions & 12 deletions src/liquidator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,7 @@ use solana_client::{
rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
};
use solana_program::pubkey::Pubkey;
use solana_sdk::{
account_info::IntoAccountInfo,
blake3::Hash,
bs58,
signature::{read_keypair_file, Keypair, Signature},
};
use solana_sdk::{account_info::IntoAccountInfo, bs58, signature::Keypair};
use std::{cmp::min, collections::HashMap, sync::Arc};

/// Bank group private key offset
Expand Down Expand Up @@ -190,7 +185,6 @@ impl Liquidator {
/// Starts processing/evaluate all account, checking
/// if a liquidation is necessary/needed
fn process_all_accounts(&self) -> anyhow::Result<Vec<PreparedLiquidatableAccount>> {
let start = std::time::Instant::now();
let accounts = self
.marginfi_accounts
.par_iter()
Expand Down Expand Up @@ -219,7 +213,7 @@ impl Liquidator {
let liab_bank = self.banks.get(&liab_bank_pk).unwrap();
let asset_bank = self.banks.get(&asset_bank_pk).unwrap();

let mut liquidation_asset_amount_capacity = liab_bank
let liquidation_asset_amount_capacity = liab_bank
.calc_value(
max_liab_coverage_amount,
BalanceSide::Liabilities,
Expand Down Expand Up @@ -625,10 +619,7 @@ impl Liquidator {
let mut tracked_accounts: HashMap<Pubkey, AccountType> = HashMap::new();

for bank in self.banks.values() {
tracked_accounts.insert(
bank.oracle_adapter.address.clone(),
AccountType::OracleAccount,
);
tracked_accounts.insert(bank.oracle_adapter.address, AccountType::OracleAccount);
}

tracked_accounts
Expand Down
20 changes: 10 additions & 10 deletions src/rebalancer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{
};
use anyhow::anyhow;
use crossbeam::channel::Receiver;
use fixed::{traits::Fixed, types::I80F48};
use fixed::types::I80F48;
use fixed_macro::types::I80F48;
use jupiter_swap_api_client::{
quote::QuoteRequest,
Expand Down Expand Up @@ -293,9 +293,9 @@ impl Rebalancer {
let balance = self
.liquidator_account
.account_wrapper
.get_balance_for_bank(&bank_pk, &bank)?;
.get_balance_for_bank(&bank_pk, bank)?;

if matches!(balance, None) || matches!(balance, Some((_, BalanceSide::Assets))) {
if balance.is_none() || matches!(balance, Some((_, BalanceSide::Assets))) {
return Ok(());
}

Expand Down Expand Up @@ -414,7 +414,7 @@ impl Rebalancer {
fn has_tokens_in_token_accounts(&self) -> bool {
let has_tokens_in_tas = self.token_accounts.values().any(|account| {
let bank = self.banks.get(&account.bank_address).unwrap();
let value = account.get_value(&bank).unwrap();
let value = account.get_value(bank).unwrap();
value > self.config.token_account_dust_threshold
});
has_tokens_in_tas
Expand All @@ -433,7 +433,7 @@ impl Rebalancer {
let mint = self
.banks
.get(&balance.bank_pk)
.and_then(|bank| Some(bank.bank.mint))
.map(|bank| bank.bank.mint)
.unwrap();

matches!(balance.get_side(), Some(BalanceSide::Assets))
Expand All @@ -454,7 +454,7 @@ impl Rebalancer {
.values()
.map(|account| {
let bank = self.banks.get(&account.bank_address).unwrap();
let value = account.get_value(&bank).unwrap();
let value = account.get_value(bank).unwrap();
(
value,
account.get_amount(),
Expand All @@ -465,7 +465,7 @@ impl Rebalancer {
.collect();

// Step 2: Iterate over the collected data
for (value, amount, bank_address, mint) in accounts_data {
for (value, amount, bank_address, _) in accounts_data {
if value > self.config.token_account_dust_threshold {
self.swap(
amount.to_num(),
Expand Down Expand Up @@ -552,7 +552,7 @@ impl Rebalancer {
compute_unit_price_micro_lamports: self
.config
.compute_unit_price_micro_lamports
.map(|v| ComputeUnitPriceMicroLamports::MicroLamports(v)),
.map(ComputeUnitPriceMicroLamports::MicroLamports),
..Default::default()
},
})
Expand Down Expand Up @@ -586,7 +586,7 @@ impl Rebalancer {
Some((balance, BalanceSide::Assets)) => {
let value = self.get_value(
balance,
&bank_pk,
bank_pk,
RequirementType::Initial,
BalanceSide::Assets,
)?;
Expand Down Expand Up @@ -677,7 +677,7 @@ impl Rebalancer {
let balance = self
.token_accounts
.get(&mint)
.and_then(|account| Some(account.get_amount()));
.map(|account| account.get_amount());

Ok(balance)
}
Expand Down
11 changes: 4 additions & 7 deletions src/sender.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use crate::jito;
use crate::{config::GeneralConfig, jito::JitoClient, wrappers::marginfi_account::TxConfig};
use log::{error, info};
use serde::Deserialize;
use solana_client::rpc_client::{RpcClient, SerializableTransaction};
use solana_client::rpc_config::RpcSimulateTransactionConfig;
use solana_sdk::signature::{read_keypair_file, Signature};
use solana_sdk::signer::keypair;
use solana_sdk::{commitment_config, compute_budget};
use solana_sdk::{
commitment_config::CommitmentConfig,
compute_budget::ComputeBudgetInstruction,
Expand Down Expand Up @@ -72,17 +69,17 @@ pub enum TransactionType {
}

impl TransactionSender {
pub async fn new(config: GeneralConfig) -> Self {
pub async fn new(config: GeneralConfig) -> anyhow::Result<Self> {
let signer = read_keypair_file(&config.keypair_path).unwrap();
let mut jito_client = JitoClient::new(config, signer).await;
let mut jito_client = JitoClient::new(config, signer).await?;
let _ = jito_client.get_tip_accounts().await;
TransactionSender { jito_client }
Ok(TransactionSender { jito_client })
}

pub async fn send_jito_ix(
&mut self,
ix: Instruction,
tx_config: Option<TxConfig>,
_tx_config: Option<TxConfig>,
) -> anyhow::Result<()> {
let mut ixs = vec![ix];

Expand Down
5 changes: 2 additions & 3 deletions src/token_account_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,6 @@ impl TokenAccountManager {
.par_iter()
.chunks(MAX_INIT_TA_IXS)
.try_for_each(|chunk| {
let recent_blockhash = recent_blockhash.clone();
let rpc = rpc_client.clone();

let ixs = chunk.iter().map(|ix| (*ix).clone()).collect::<Vec<_>>();
Expand Down Expand Up @@ -198,8 +197,8 @@ fn get_keypair_for_token_account(
seed: &[u8],
) -> Result<Keypair, TokenAccountManagerError> {
let keypair_seed = get_liquidator_seed(signer, mint, seed);
Ok(Keypair::from_seed(&keypair_seed)
.map_err(|_| TokenAccountManagerError::SetupFailed("Keypair::from_seed failed"))?)
Keypair::from_seed(&keypair_seed)
.map_err(|_| TokenAccountManagerError::SetupFailed("Keypair::from_seed failed"))
}

fn get_address_for_token_account(
Expand Down
6 changes: 2 additions & 4 deletions src/wrappers/liquidator_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ use crate::{
marginfi_ixs::{make_deposit_ix, make_liquidate_ix, make_repay_ix, make_withdraw_ix},
sender::{SenderCfg, TransactionSender},
};
use anchor_lang::accounts::signer;
use log::info;
use marginfi::state::{marginfi_account::MarginfiAccount, marginfi_group::BankVaultType};
use solana_client::rpc_client::RpcClient;
use solana_program::pubkey::Pubkey;
use solana_sdk::{
quic,
signature::{read_keypair_file, Keypair},
signer::Signer,
};
Expand Down Expand Up @@ -54,7 +52,7 @@ impl LiquidatorAccount {
program_id,
token_program,
group,
transaction_sender: TransactionSender::new(config).await,
transaction_sender: TransactionSender::new(config).await?,
})
}

Expand Down Expand Up @@ -136,7 +134,7 @@ impl LiquidatorAccount {

let observation_accounts =
self.account_wrapper
.get_observation_accounts(&[], &banks_to_exclude, &banks);
.get_observation_accounts(&[], &banks_to_exclude, banks);

let withdraw_ix = make_withdraw_ix(
self.program_id,
Expand Down

0 comments on commit e36c732

Please sign in to comment.