1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use {
    crate::parse_instruction::{
        check_num_accounts, ParsableProgram, ParseInstructionError, ParsedInstructionEnum,
    },
    borsh::BorshDeserialize,
    serde_json::json,
    solana_sdk::{instruction::CompiledInstruction, message::AccountKeys, pubkey::Pubkey},
    spl_associated_token_account::instruction::AssociatedTokenAccountInstruction,
};

// A helper function to convert spl_associated_token_account::id() as spl_sdk::pubkey::Pubkey
// to solana_sdk::pubkey::Pubkey
pub fn spl_associated_token_id() -> Pubkey {
    Pubkey::new_from_array(spl_associated_token_account::id().to_bytes())
}

pub fn parse_associated_token(
    instruction: &CompiledInstruction,
    account_keys: &AccountKeys,
) -> Result<ParsedInstructionEnum, ParseInstructionError> {
    match instruction.accounts.iter().max() {
        Some(index) if (*index as usize) < account_keys.len() => {}
        _ => {
            // Runtime should prevent this from ever happening
            return Err(ParseInstructionError::InstructionKeyMismatch(
                ParsableProgram::SplAssociatedTokenAccount,
            ));
        }
    }
    if instruction.data.is_empty() {
        check_num_associated_token_accounts(&instruction.accounts, 7)?;
        Ok(ParsedInstructionEnum {
            instruction_type: "create".to_string(),
            info: json!({
                "source": account_keys[instruction.accounts[0] as usize].to_string(),
                "account": account_keys[instruction.accounts[1] as usize].to_string(),
                "wallet": account_keys[instruction.accounts[2] as usize].to_string(),
                "mint": account_keys[instruction.accounts[3] as usize].to_string(),
                "systemProgram": account_keys[instruction.accounts[4] as usize].to_string(),
                "tokenProgram": account_keys[instruction.accounts[5] as usize].to_string(),
                "rentSysvar": account_keys[instruction.accounts[6] as usize].to_string(),
            }),
        })
    } else {
        let ata_instruction = AssociatedTokenAccountInstruction::try_from_slice(&instruction.data)
            .map_err(|_| {
                ParseInstructionError::InstructionNotParsable(ParsableProgram::SplToken)
            })?;
        match ata_instruction {
            AssociatedTokenAccountInstruction::Create => {
                check_num_associated_token_accounts(&instruction.accounts, 6)?;
                Ok(ParsedInstructionEnum {
                    instruction_type: "create".to_string(),
                    info: json!({
                        "source": account_keys[instruction.accounts[0] as usize].to_string(),
                        "account": account_keys[instruction.accounts[1] as usize].to_string(),
                        "wallet": account_keys[instruction.accounts[2] as usize].to_string(),
                        "mint": account_keys[instruction.accounts[3] as usize].to_string(),
                        "systemProgram": account_keys[instruction.accounts[4] as usize].to_string(),
                        "tokenProgram": account_keys[instruction.accounts[5] as usize].to_string(),
                    }),
                })
            }
        }
    }
}

fn check_num_associated_token_accounts(
    accounts: &[u8],
    num: usize,
) -> Result<(), ParseInstructionError> {
    check_num_accounts(accounts, num, ParsableProgram::SplAssociatedTokenAccount)
}

#[cfg(test)]
mod test {
    #[allow(deprecated)]
    use spl_associated_token_account::create_associated_token_account as create_associated_token_account_deprecated;
    use {
        super::*,
        solana_account_decoder::parse_token::pubkey_from_spl_token,
        spl_associated_token_account::{
            get_associated_token_address,
            instruction::create_associated_token_account,
            solana_program::{
                instruction::CompiledInstruction as SplAssociatedTokenCompiledInstruction,
                message::Message, pubkey::Pubkey as SplAssociatedTokenPubkey, sysvar,
            },
        },
    };

    fn convert_pubkey(pubkey: Pubkey) -> SplAssociatedTokenPubkey {
        SplAssociatedTokenPubkey::new_from_array(pubkey.to_bytes())
    }

    fn convert_compiled_instruction(
        instruction: &SplAssociatedTokenCompiledInstruction,
    ) -> CompiledInstruction {
        CompiledInstruction {
            program_id_index: instruction.program_id_index,
            accounts: instruction.accounts.clone(),
            data: instruction.data.clone(),
        }
    }

    fn convert_account_keys(message: &Message) -> Vec<Pubkey> {
        message
            .account_keys
            .iter()
            .map(pubkey_from_spl_token)
            .collect()
    }

    #[test]
    fn test_parse_associated_token_deprecated() {
        let funder = Pubkey::new_unique();
        let wallet_address = Pubkey::new_unique();
        let mint = Pubkey::new_unique();
        let associated_account_address =
            get_associated_token_address(&convert_pubkey(wallet_address), &convert_pubkey(mint));
        #[allow(deprecated)]
        let create_ix = create_associated_token_account_deprecated(
            &convert_pubkey(funder),
            &convert_pubkey(wallet_address),
            &convert_pubkey(mint),
        );
        let message = Message::new(&[create_ix], None);
        let mut compiled_instruction = convert_compiled_instruction(&message.instructions[0]);
        assert_eq!(
            parse_associated_token(
                &compiled_instruction,
                &AccountKeys::new(&convert_account_keys(&message), None)
            )
            .unwrap(),
            ParsedInstructionEnum {
                instruction_type: "create".to_string(),
                info: json!({
                    "source": funder.to_string(),
                    "account": associated_account_address.to_string(),
                    "wallet": wallet_address.to_string(),
                    "mint": mint.to_string(),
                    "systemProgram": solana_sdk::system_program::id().to_string(),
                    "tokenProgram": spl_token::id().to_string(),
                    "rentSysvar": sysvar::rent::id().to_string(),
                })
            }
        );
        compiled_instruction.accounts.pop();
        assert!(parse_associated_token(
            &compiled_instruction,
            &AccountKeys::new(&convert_account_keys(&message), None)
        )
        .is_err());
    }

    #[test]
    fn test_parse_associated_token() {
        let funder = Pubkey::new_unique();
        let wallet_address = Pubkey::new_unique();
        let mint = Pubkey::new_unique();
        let associated_account_address =
            get_associated_token_address(&convert_pubkey(wallet_address), &convert_pubkey(mint));
        let create_ix = create_associated_token_account(
            &convert_pubkey(funder),
            &convert_pubkey(wallet_address),
            &convert_pubkey(mint),
        );
        let message = Message::new(&[create_ix], None);
        let mut compiled_instruction = convert_compiled_instruction(&message.instructions[0]);
        assert_eq!(
            parse_associated_token(
                &compiled_instruction,
                &AccountKeys::new(&convert_account_keys(&message), None)
            )
            .unwrap(),
            ParsedInstructionEnum {
                instruction_type: "create".to_string(),
                info: json!({
                    "source": funder.to_string(),
                    "account": associated_account_address.to_string(),
                    "wallet": wallet_address.to_string(),
                    "mint": mint.to_string(),
                    "systemProgram": solana_sdk::system_program::id().to_string(),
                    "tokenProgram": spl_token::id().to_string(),
                })
            }
        );
        compiled_instruction.accounts.pop();
        assert!(parse_associated_token(
            &compiled_instruction,
            &AccountKeys::new(&convert_account_keys(&message), None)
        )
        .is_err());
    }
}