Skip to content
This repository has been archived by the owner on Jan 22, 2025. It is now read-only.

rpc: optimize getTokenLargestAccounts #35315

Merged
merged 4 commits into from
Feb 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 29 additions & 26 deletions rpc/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ use {
},
std::{
any::type_name,
cmp::{max, min},
collections::{HashMap, HashSet},
cmp::{max, min, Reverse},
collections::{BinaryHeap, HashMap, HashSet},
convert::TryFrom,
net::SocketAddr,
str::FromStr,
Expand Down Expand Up @@ -1861,36 +1861,39 @@ impl JsonRpcRequestProcessor {
"Invalid param: not a Token mint".to_string(),
));
}
let mut token_balances: Vec<_> = self
.get_filtered_spl_token_accounts_by_mint(&bank, &mint_owner, mint, vec![])?
.into_iter()
.map(|(address, account)| {
let amount = StateWithExtensions::<TokenAccount>::unpack(account.data())
.map(|account| account.base.amount)
.unwrap_or(0);
(address, amount)
})
.collect();

let sort_largest = |a: &(_, u64), b: &(_, u64)| b.1.cmp(&a.1);
let mut token_balances =
BinaryHeap::<Reverse<(u64, Pubkey)>>::with_capacity(NUM_LARGEST_ACCOUNTS);
for (address, account) in
self.get_filtered_spl_token_accounts_by_mint(&bank, &mint_owner, mint, vec![])?
{
let amount = StateWithExtensions::<TokenAccount>::unpack(account.data())
.map(|account| account.base.amount)
.unwrap_or(0);

let largest_token_balances = if token_balances.len() > NUM_LARGEST_ACCOUNTS {
token_balances
.select_nth_unstable_by(NUM_LARGEST_ACCOUNTS, sort_largest)
.0
} else {
token_balances.as_mut_slice()
};
largest_token_balances.sort_unstable_by(sort_largest);
let new_entry = (amount, address);
if token_balances.len() >= NUM_LARGEST_ACCOUNTS {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically, == should be sufficient here, but I suppose there's no harm in >=

let Reverse(entry) = token_balances
.peek()
.expect("BinaryHeap::peek should succeed when len > 0");
if *entry >= new_entry {
continue;
}
token_balances.pop();
}
token_balances.push(Reverse(new_entry));
}

let largest_token_balances = largest_token_balances
.iter()
.map(|(address, amount)| RpcTokenAccountBalance {
let token_balances = token_balances
.into_sorted_vec()
.into_iter()
.map(|Reverse((amount, address))| RpcTokenAccountBalance {
address: address.to_string(),
amount: token_amount_to_ui_amount(*amount, decimals),
amount: token_amount_to_ui_amount(amount, decimals),
})
.collect();
Ok(new_response(&bank, largest_token_balances))

Ok(new_response(&bank, token_balances))
}

pub fn get_token_accounts_by_owner(
Expand Down
Loading