Add try_find_program_address()

This commit is contained in:
Michael Vines
2020-10-28 17:26:56 -07:00
parent c2dbf53d76
commit 92d6521a7f

View File

@ -186,22 +186,31 @@ impl Pubkey {
}
}
/// Find a valid program address and its corresponding bump seed which must be passed
/// as an additional seed when calling `invoke_signed`.
///
/// Panics in the very unlikely event that the additional seed could not be found.
pub fn find_program_address(seeds: &[&[u8]], program_id: &Pubkey) -> (Pubkey, u8) {
Self::try_find_program_address(seeds, program_id)
.unwrap_or_else(|| panic!("Unable to find a viable program address bump seed"))
}
/// Find a valid program address and its corresponding bump seed which must be passed
/// as an additional seed when calling `invoke_signed`
#[allow(clippy::same_item_push)]
pub fn find_program_address(seeds: &[&[u8]], program_id: &Pubkey) -> (Pubkey, u8) {
pub fn try_find_program_address(seeds: &[&[u8]], program_id: &Pubkey) -> Option<(Pubkey, u8)> {
let mut bump_seed = [std::u8::MAX];
for _ in 0..std::u8::MAX {
{
let mut seeds_with_bump = seeds.to_vec();
seeds_with_bump.push(&bump_seed);
if let Ok(address) = Self::create_program_address(&seeds_with_bump, program_id) {
return (address, bump_seed[0]);
return Some((address, bump_seed[0]));
}
}
bump_seed[0] -= 1;
}
panic!("Unable to find a viable program address bump seed");
None
}
pub fn to_bytes(self) -> [u8; 32] {