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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use solana_sdk::{
    clock::UnixTimestamp, instruction::CompiledInstruction, message::VersionedMessage,
};
use solana_transaction_status::{
    option_serializer::OptionSerializer, EncodedConfirmedTransactionWithStatusMeta,
    EncodedTransaction, EncodedTransactionWithStatusMeta, UiCompiledInstruction, UiInstruction,
    UiMessage, UiParsedInstruction, VersionedTransactionWithStatusMeta,
};

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ParsedTransaction {
    pub slot: u64,
    pub block_time: Option<UnixTimestamp>,
    pub instructions: Vec<ParsedInstruction>,
    pub inner_instructions: Vec<Vec<ParsedInnerInstruction>>,
    pub logs: Vec<String>,
    pub is_err: bool,
    pub signature: String,
    pub fee_payer: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ParsedInstruction {
    pub program_id: String,
    pub accounts: Vec<String>,
    pub data: Vec<u8>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ParsedInnerInstruction {
    pub parent_index: usize,
    pub instruction: ParsedInstruction,
}

pub fn parse_ui_compiled_instruction(
    c: &UiCompiledInstruction,
    account_keys: &[String],
) -> ParsedInstruction {
    ParsedInstruction {
        program_id: account_keys[c.program_id_index as usize].clone(),
        accounts: c
            .accounts
            .iter()
            .map(|i| account_keys[*i as usize].clone())
            .collect(),
        data: bs58::decode(c.data.clone()).into_vec().unwrap(),
    }
}

pub fn parse_ui_instruction(
    ui_instruction: &UiInstruction,
    account_keys: &[String],
) -> ParsedInstruction {
    match ui_instruction {
        UiInstruction::Compiled(c) => parse_ui_compiled_instruction(c, account_keys),
        UiInstruction::Parsed(p) => match p {
            UiParsedInstruction::PartiallyDecoded(pd) => ParsedInstruction {
                program_id: pd.program_id.clone(),
                accounts: pd.accounts.clone(),
                data: bs58::decode(&pd.data.clone()).into_vec().unwrap(),
            },
            _ => panic!("Unsupported instruction encoding"),
        },
    }
}

pub fn parse_compiled_instruction(
    instruction: &CompiledInstruction,
    account_keys: &[String],
) -> ParsedInstruction {
    ParsedInstruction {
        program_id: account_keys[instruction.program_id_index as usize].clone(),
        accounts: instruction
            .accounts
            .iter()
            .map(|i| account_keys[*i as usize].clone())
            .collect(),
        data: instruction.data.clone(),
    }
}

pub fn parse_ui_message(
    message: UiMessage,
    loaded_addresses: &[String],
) -> (Vec<String>, Vec<ParsedInstruction>) {
    match message {
        UiMessage::Parsed(p) => {
            let mut keys = p
                .account_keys
                .iter()
                .map(|k| k.pubkey.to_string())
                .collect::<Vec<String>>();
            keys.extend_from_slice(loaded_addresses);
            (
                keys.clone(),
                p.instructions
                    .iter()
                    .map(|i| parse_ui_instruction(i, &keys))
                    .collect::<Vec<ParsedInstruction>>(),
            )
        }
        UiMessage::Raw(r) => {
            let mut keys = r.account_keys.clone();
            keys.extend_from_slice(loaded_addresses);
            (
                keys.clone(),
                r.instructions
                    .iter()
                    .map(|i| parse_ui_compiled_instruction(i, &keys))
                    .collect::<Vec<ParsedInstruction>>(),
            )
        }
    }
}

pub fn parse_versioned_message(
    message: VersionedMessage,
    loaded_addresses: &[String],
) -> (Vec<String>, Vec<ParsedInstruction>) {
    let mut keys = message
        .static_account_keys()
        .into_iter()
        .map(|pk| pk.to_string())
        .collect_vec();
    keys.extend_from_slice(loaded_addresses);
    let instructions = message
        .instructions()
        .iter()
        .map(|i| parse_compiled_instruction(i, &keys))
        .collect_vec();
    (keys, instructions)
}

pub fn parse_transaction(tx: EncodedConfirmedTransactionWithStatusMeta) -> ParsedTransaction {
    let slot = tx.slot;
    let block_time = tx.block_time;

    let tx_meta = tx.transaction.meta.unwrap();
    let loaded_addresses = match tx_meta.loaded_addresses {
        OptionSerializer::Some(l) => [l.writable, l.readonly].concat(),
        _ => vec![],
    };

    let (keys, instructions, signature) = match tx.transaction.transaction {
        EncodedTransaction::Json(t) => {
            let (keys, instructions) = parse_ui_message(t.message, &loaded_addresses);
            let signature = t.signatures[0].to_string();
            (keys, instructions, signature)
        }
        _ => {
            let versioned_tx = tx
                .transaction
                .transaction
                .decode()
                .expect("Failed to decode transaction");
            let (keys, instructions) =
                parse_versioned_message(versioned_tx.message, &loaded_addresses);
            (keys, instructions, versioned_tx.signatures[0].to_string())
        }
    };

    let is_err = tx_meta.err.is_some();
    let logs = match tx_meta.log_messages {
        OptionSerializer::Some(l) => l,
        _ => vec![],
    };
    let inner_instructions = match tx_meta.inner_instructions {
        OptionSerializer::Some(inner) => inner
            .iter()
            .map(|ii| {
                ii.instructions
                    .iter()
                    .map(|i| ParsedInnerInstruction {
                        parent_index: ii.index as usize,
                        instruction: parse_ui_instruction(i, &keys),
                    })
                    .collect::<Vec<ParsedInnerInstruction>>()
            })
            .collect::<Vec<Vec<ParsedInnerInstruction>>>(),
        _ => vec![],
    };
    ParsedTransaction {
        slot,
        block_time,
        instructions,
        inner_instructions,
        logs,
        is_err,
        signature,
        fee_payer: keys[0].clone(),
    }
}

pub fn parse_versioned_transaction(
    slot: u64,
    block_time: Option<i64>,
    tx: VersionedTransactionWithStatusMeta,
) -> Option<ParsedTransaction> {
    let tx_meta = tx.meta;
    let is_err = tx_meta.status.is_err();
    if is_err {
        return None;
    }
    let loaded_addresses = [
        tx_meta.loaded_addresses.writable,
        tx_meta.loaded_addresses.readonly,
    ]
    .concat()
    .iter()
    .map(|x| x.to_string())
    .collect::<Vec<String>>();

    let (keys, instructions) =
        { parse_versioned_message(tx.transaction.message, loaded_addresses.as_slice()) };

    let logs = tx_meta.log_messages.unwrap_or_default();
    let inner_instructions = tx_meta
        .inner_instructions
        .unwrap_or_default()
        .iter()
        .map(|ii| {
            ii.instructions
                .iter()
                .map(|i| ParsedInnerInstruction {
                    parent_index: ii.index as usize,
                    instruction: parse_compiled_instruction(&i.instruction, &keys),
                })
                .collect::<Vec<ParsedInnerInstruction>>()
        })
        .collect::<Vec<Vec<ParsedInnerInstruction>>>();
    Some(ParsedTransaction {
        slot,
        signature: tx.transaction.signatures[0].to_string(),
        block_time,
        instructions,
        inner_instructions,
        logs,
        is_err,
        fee_payer: keys[0].clone(),
    })
}

pub fn parse_encoded_transaction_with_status_meta(
    slot: u64,
    block_time: Option<i64>,
    tx: EncodedTransactionWithStatusMeta,
) -> Option<ParsedTransaction> {
    let tx_meta = tx.meta?;
    let loaded_addresses = match tx_meta.loaded_addresses {
        OptionSerializer::Some(la) => [la.writable, la.readonly].concat(),
        _ => vec![],
    };

    let versioned_tx = tx.transaction.decode()?;
    let (keys, instructions) =
        { parse_versioned_message(versioned_tx.message, loaded_addresses.as_slice()) };

    let is_err = tx_meta.status.is_err();
    let logs = match tx_meta.log_messages {
        OptionSerializer::Some(lm) => lm,
        _ => vec![],
    };
    let inner_instructions = match tx_meta.inner_instructions {
        OptionSerializer::Some(inner_instructions) => inner_instructions
            .iter()
            .map(|ii| {
                ii.instructions
                    .iter()
                    .map(|i| ParsedInnerInstruction {
                        parent_index: ii.index as usize,
                        instruction: parse_ui_instruction(i, &keys),
                    })
                    .collect::<Vec<ParsedInnerInstruction>>()
            })
            .collect::<Vec<Vec<ParsedInnerInstruction>>>(),
        _ => vec![],
    };
    Some(ParsedTransaction {
        slot,
        signature: versioned_tx.signatures[0].to_string(),
        block_time,
        instructions,
        inner_instructions,
        logs,
        is_err,
        fee_payer: keys[0].clone(),
    })
}