delegate_registry/
lib.rs

1/// Returns the delegate registry program ID.
2#[macro_export]
3macro_rules! delegate_registry_program_id {
4    () => {{
5        use std::str::FromStr;
6        Pubkey::from_str("De1egateWvUcfjtzjz3Y19NdYFwX7QjHNZG9MPNeD3QK").unwrap()
7    }};
8}
9
10/// Returns true if the delegation account is valid, else false.
11#[macro_export]
12macro_rules! delegation_account_is_valid {
13    ($delegation:expr, $name:expr, $($key:expr),* $(,)?) => {{
14        let pda_owner = delegate_registry_program_id!();
15        let (pda, _bump) = Pubkey::find_program_address(&[$name, $($key.as_ref(),)*], &pda_owner);
16        pda == $delegation.key() && $delegation.owner == &pda_owner
17    }};
18}
19
20/// Returns a slice of the delegation account data.
21/// If the slice is out of bounds, returns a zeroed array.
22/// This macro does not check if the delegation account is valid.
23#[macro_export]
24macro_rules! delegation_account_slice {
25    ($delegation:expr, $start:expr, $len:expr) => {
26        $delegation.data.borrow()[$start..$start + $len]
27            .try_into()
28            .unwrap_or([0; $len])
29    };
30}
31
32/// Returns true if the all delegation account is valid and enabled, else false.
33#[macro_export]
34macro_rules! all_delegation_is_enabled {
35    ($delegation:expr, $rights:expr, $from:expr, $to:expr) => {
36        delegation_account_is_valid!($delegation, b"all", $rights, $from, $to)
37            && delegation_account_slice!($delegation, 8 + 32 * 3, 1)[0] != 0
38    };
39}
40
41/// Returns true if the program delegation account is valid and enabled, else false.
42#[macro_export]
43macro_rules! program_delegation_is_enabled {
44    ($delegation:expr, $rights:expr, $from:expr, $to:expr, $program:expr, $account:expr) => {
45        delegation_account_is_valid!(
46            $delegation,
47            b"program",
48            $rights,
49            $from,
50            $to,
51            $program,
52            $account
53        ) && delegation_account_slice!($delegation, 8 + 32 * 5, 1)[0] != 0
54    };
55}
56
57/// Returns the amount from a token delegation account.
58/// If the delegation account is not valid, returns 0.
59#[macro_export]
60macro_rules! token_delegation_amount {
61    ($delegation:expr, $rights:expr, $from:expr, $to:expr, $program:expr, $mint:expr, $account:expr) => {
62        if delegation_account_is_valid!(
63            $delegation,
64            b"token",
65            $rights,
66            $from,
67            $to,
68            $program,
69            $mint,
70            $account
71        ) {
72            u64::from_le_bytes(delegation_account_slice!($delegation, 8 + 32 * 6, 8))
73        } else {
74            0 as u64
75        }
76    };
77}