Skip to main content

titan_api_types/common/
instruction.rs

1//! Contains type definitions for Solana Instructions and account metadata.
2//!
3//! These types are based on those from the [`solana_instruction`] crate, but using more efficient
4//! serialization of binary data by default.
5//!
6//! Conversions between these types and the solana SDK types can be enabled via the
7//! `solana-instruction-convert` feature.
8//!
9//! [`solana_instruction`]: https://crates.io/crates/solana-instruction
10
11use super::pubkey::Pubkey;
12
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15
16/// Contains metadata for a single account read or written to by a program during instruction
17/// execution.
18///
19/// See [`solana_instruction::AccountMeta`] for more information.
20#[repr(C)]
21#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
22#[derive(Debug, Default, PartialEq, Eq, Clone)]
23pub struct AccountMeta {
24    /// The account's public key.
25    ///
26    /// When serialized, encoded to a field named "p" for space efficiency.
27    #[cfg_attr(feature = "serde", serde(rename = "p"))]
28    pub pubkey: Pubkey,
29    /// True if an instruction requires a transaction signature matching this account's `pubkey`.
30    ///
31    /// When serialized, encoded to a field named "s" for space efficiency.
32    #[cfg_attr(feature = "serde", serde(rename = "s"))]
33    pub is_signer: bool,
34    /// True if the account data or metadata may be mutated during program execution.
35    ///
36    /// When serialized, encoded to a field named "w" for space efficiency.
37    #[cfg_attr(feature = "serde", serde(rename = "w"))]
38    pub is_writable: bool,
39}
40
41impl AccountMeta {
42    /// Constructs metatdata for a writable account.
43    pub fn new(pubkey: Pubkey, is_signer: bool) -> Self {
44        Self {
45            pubkey,
46            is_signer,
47            is_writable: true,
48        }
49    }
50
51    /// Constructs metadata for a readable account.
52    pub fn new_readonly(pubkey: Pubkey, is_signer: bool) -> Self {
53        Self {
54            pubkey,
55            is_signer,
56            is_writable: false,
57        }
58    }
59}
60
61/// Contains account lookup table metadata
62///
63/// See [`solana_instruction::AccountMeta`] for more information.
64#[repr(C)]
65#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
66#[derive(Debug, Default, PartialEq, Eq, Clone)]
67pub struct AddressLookupTableAccount {
68    /// The address lookup tables public key.
69    ///
70    /// When serialized, encoded to a field named "p" for space efficiency.
71    #[cfg_attr(feature = "serde", serde(rename = "p"))]
72    pub key: Pubkey,
73    /// List of addresses which the address lookup table has coverage for.
74    ///
75    /// When serialized, encoded to a field named "a" for space efficiency.
76    #[cfg_attr(feature = "serde", serde(rename = "a"))]
77    pub addresses: Vec<Pubkey>,
78}
79
80#[cfg(feature = "solana-alt-account-convert-v2")]
81impl From<solana_message_v2::AddressLookupTableAccount> for AddressLookupTableAccount {
82    #[inline]
83    fn from(value: solana_message_v2::AddressLookupTableAccount) -> Self {
84        Self {
85            key: value.key.into(),
86            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
87        }
88    }
89}
90
91#[cfg(feature = "solana-alt-account-convert-v2")]
92impl From<AddressLookupTableAccount> for solana_message_v2::AddressLookupTableAccount {
93    #[inline]
94    fn from(value: AddressLookupTableAccount) -> Self {
95        Self {
96            key: value.key.into(),
97            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
98        }
99    }
100}
101
102#[cfg(feature = "solana-alt-account-convert-v3")]
103impl From<solana_message_v3::AddressLookupTableAccount> for AddressLookupTableAccount {
104    #[inline]
105    fn from(value: solana_message_v3::AddressLookupTableAccount) -> Self {
106        Self {
107            key: value.key.into(),
108            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
109        }
110    }
111}
112
113#[cfg(feature = "solana-alt-account-convert-v3")]
114impl From<AddressLookupTableAccount> for solana_message_v3::AddressLookupTableAccount {
115    #[inline]
116    fn from(value: AddressLookupTableAccount) -> Self {
117        Self {
118            key: value.key.into(),
119            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
120        }
121    }
122}
123
124#[cfg(feature = "solana-alt-account-convert-v4")]
125impl From<solana_message_v4::AddressLookupTableAccount> for AddressLookupTableAccount {
126    #[inline]
127    fn from(value: solana_message_v4::AddressLookupTableAccount) -> Self {
128        Self {
129            key: value.key.into(),
130            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
131        }
132    }
133}
134
135#[cfg(feature = "solana-alt-account-convert-v4")]
136impl From<AddressLookupTableAccount> for solana_message_v4::AddressLookupTableAccount {
137    #[inline]
138    fn from(value: AddressLookupTableAccount) -> Self {
139        Self {
140            key: value.key.into(),
141            addresses: value.addresses.into_iter().map(|key| key.into()).collect(),
142        }
143    }
144}
145
146#[cfg(feature = "solana-instruction-convert-v2")]
147impl From<solana_instruction_v2::AccountMeta> for AccountMeta {
148    #[inline]
149    fn from(value: solana_instruction_v2::AccountMeta) -> Self {
150        Self {
151            pubkey: value.pubkey.into(),
152            is_signer: value.is_signer,
153            is_writable: value.is_writable,
154        }
155    }
156}
157
158#[cfg(feature = "solana-instruction-convert-v2")]
159impl From<AccountMeta> for solana_instruction_v2::AccountMeta {
160    #[inline]
161    fn from(value: AccountMeta) -> Self {
162        Self {
163            pubkey: value.pubkey.into(),
164            is_signer: value.is_signer,
165            is_writable: value.is_writable,
166        }
167    }
168}
169
170#[cfg(feature = "solana-instruction-convert-v3")]
171impl From<solana_instruction_v3::AccountMeta> for AccountMeta {
172    #[inline]
173    fn from(value: solana_instruction_v3::AccountMeta) -> Self {
174        Self {
175            pubkey: value.pubkey.into(),
176            is_signer: value.is_signer,
177            is_writable: value.is_writable,
178        }
179    }
180}
181
182#[cfg(feature = "solana-instruction-convert-v3")]
183impl From<AccountMeta> for solana_instruction_v3::AccountMeta {
184    #[inline]
185    fn from(value: AccountMeta) -> Self {
186        Self {
187            pubkey: value.pubkey.into(),
188            is_signer: value.is_signer,
189            is_writable: value.is_writable,
190        }
191    }
192}
193
194/// A directive for a single invocation of a Solana program.
195///
196/// See [`solana_instruction::Instruction`] for more information.
197#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
198#[derive(Debug, PartialEq, Eq, Clone)]
199pub struct Instruction {
200    /// Pubkey of the program that executes this transaction.
201    ///
202    /// When serialized, encoded to a field named "p" for space efficiency.
203    #[cfg_attr(feature = "serde", serde(rename = "p"))]
204    pub program_id: Pubkey,
205    /// Metadata describing accounts that should be passed to the program.
206    ///
207    /// When serialized, encoded to a field named "a" for space efficiency.
208    #[cfg_attr(feature = "serde", serde(rename = "a"))]
209    pub accounts: Vec<AccountMeta>,
210    /// Opaque data passed to the program for its own interpretation.
211    ///
212    /// When serialized, encoded to a field named "d" for space efficiency.
213    #[cfg_attr(feature = "serde", serde(with = "data_bytes", rename = "d"))]
214    pub data: Vec<u8>,
215}
216
217#[cfg(feature = "serde")]
218mod data_bytes {
219    use serde::Serialize;
220
221    #[cfg(feature = "serde-instruction-human-base64")]
222    use base64::{
223        alphabet,
224        engine::{
225            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
226            DecodePaddingMode,
227        },
228        Engine,
229    };
230    use serde::{de::Visitor, Deserializer, Serializer};
231    #[cfg(feature = "serde-instruction-human-base64")]
232    const CONFIG: GeneralPurposeConfig = GeneralPurposeConfig::new()
233        .with_encode_padding(false)
234        .with_decode_padding_mode(DecodePaddingMode::Indifferent);
235    #[cfg(feature = "serde-instruction-human-base64")]
236    const ENGINE: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, CONFIG);
237
238    struct BinaryVisitor;
239
240    impl<'de> Visitor<'de> for BinaryVisitor {
241        type Value = Vec<u8>;
242        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
243            formatter.write_str("binary data")
244        }
245
246        #[cfg(feature = "serde-instruction-human-base64")]
247        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
248        where
249            E: serde::de::Error,
250        {
251            ENGINE.decode(v).map_err(E::custom)
252        }
253
254        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
255        where
256            E: serde::de::Error,
257        {
258            Ok(Vec::from(v))
259        }
260
261        fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
262        where
263            E: serde::de::Error,
264        {
265            Ok(v)
266        }
267
268        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
269        where
270            A: serde::de::SeqAccess<'de>,
271        {
272            let mut data = Vec::with_capacity(seq.size_hint().unwrap_or(0));
273            while let Some(elem) = seq.next_element()? {
274                data.push(elem);
275            }
276            Ok(data)
277        }
278    }
279
280    pub fn serialize<S, T>(value: T, serializer: S) -> Result<S::Ok, S::Error>
281    where
282        S: Serializer,
283        T: AsRef<[u8]>,
284    {
285        #[cfg(feature = "serde-instruction-human-base64")]
286        if serializer.is_human_readable() {
287            let b64_str = ENGINE.encode(value);
288            return b64_str.serialize(serializer);
289        }
290
291        serde_bytes::serialize(value.as_ref(), serializer)
292    }
293
294    /// Deserializes the value from binary, array of u8s, or a Base64 string, with or without padding.
295    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
296    where
297        D: Deserializer<'de>,
298    {
299        deserializer.deserialize_any(BinaryVisitor)
300    }
301}
302
303#[cfg(feature = "solana-instruction-convert-v2")]
304impl From<solana_instruction_v2::Instruction> for Instruction {
305    fn from(value: solana_instruction_v2::Instruction) -> Self {
306        Self {
307            program_id: value.program_id.into(),
308            accounts: value.accounts.into_iter().map(Into::into).collect(),
309            data: value.data,
310        }
311    }
312}
313
314#[cfg(feature = "solana-instruction-convert-v2")]
315impl From<Instruction> for solana_instruction_v2::Instruction {
316    fn from(value: Instruction) -> Self {
317        Self {
318            program_id: value.program_id.into(),
319            accounts: value.accounts.into_iter().map(Into::into).collect(),
320            data: value.data,
321        }
322    }
323}
324
325#[cfg(feature = "solana-instruction-convert-v3")]
326impl From<solana_instruction_v3::Instruction> for Instruction {
327    fn from(value: solana_instruction_v3::Instruction) -> Self {
328        Self {
329            program_id: value.program_id.into(),
330            accounts: value.accounts.into_iter().map(Into::into).collect(),
331            data: value.data,
332        }
333    }
334}
335
336#[cfg(feature = "solana-instruction-convert-v3")]
337impl From<Instruction> for solana_instruction_v3::Instruction {
338    fn from(value: Instruction) -> Self {
339        Self {
340            program_id: value.program_id.into(),
341            accounts: value.accounts.into_iter().map(Into::into).collect(),
342            data: value.data,
343        }
344    }
345}
346
347#[cfg(test)]
348mod test {
349    use super::AccountMeta;
350    use crate::common::pubkey::{Pubkey, PUBKEY_BYTES};
351    use rmpv::Value;
352
353    const SOL_ADDR_BYTES: [u8; PUBKEY_BYTES] = [
354        6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57, 220,
355        26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0,
356    ];
357    const SOL_PUBKEY: Pubkey = Pubkey::new_from_array(SOL_ADDR_BYTES);
358    const SOL_ADDR_BASE58: &str = "So11111111111111111111111111111111111111111";
359
360    #[cfg(feature = "serde")]
361    #[test]
362    fn test_accountmeta_serialize_messagepack_unnamed() {
363        // Should encode to a fixarray with length 3 (0x93) with the elements:
364        // - bin8 with 32 bytes of data (0xc4 0x20 <data>)
365        // - bool false (0xc2)
366        // - bool true (0xc3)
367        let account = AccountMeta {
368            pubkey: SOL_PUBKEY,
369            is_signer: false,
370            is_writable: true,
371        };
372
373        let encoded = rmp_serde::encode::to_vec(&account).expect("should encode via messagepack");
374        assert_eq!(encoded.len(), 37);
375        assert_eq!(encoded[0], 0x93_u8); // fixarray with length 3
376        assert_eq!(encoded[1..3], [0xc4_u8, 32_u8]); // bin8 with length 32
377        assert_eq!(encoded[3..35], SOL_ADDR_BYTES); // pubkey data
378        assert_eq!(encoded[35], 0xc2_u8); // bool false
379        assert_eq!(encoded[36], 0xc3_u8); // bool true
380    }
381
382    #[cfg(feature = "serde")]
383    #[test]
384    fn test_accountmeta_deserialize_messagepack_unnamed() {
385        let expected = AccountMeta {
386            pubkey: SOL_PUBKEY,
387            is_signer: false,
388            is_writable: true,
389        };
390        let encoded: [u8; 37] = [
391            0x93, // fixarray len=3
392            0xc4, 32, // bin8 len=32
393            // 32 bytes of data
394            6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57,
395            220, 26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0, 0xc2, // bool false
396            0xc3, // bool true
397        ];
398
399        let decoded = rmp_serde::decode::from_slice::<AccountMeta>(&encoded)
400            .expect("should decode via messagepack");
401        assert_eq!(decoded, expected);
402    }
403
404    // Test to see if decoding will ignore extra fields while decoding if new optional fields are
405    // added in the future.
406    // The unnamed encoding fails due to requiring the lengths to match exactly
407    #[cfg(feature = "serde")]
408    #[test]
409    fn test_accountmeta_deserialize_messagepack_extra_field_unnamed() {
410        let encoded: [u8; 38] = [
411            0x94, // fixarray len=4
412            0xc4, 32, // bin8 len=32
413            // 32 bytes of data
414            6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57,
415            220, 26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0, 0xc2, // bool false
416            0xc3, // bool true
417            0xc0, // nil
418        ];
419
420        let decoded = rmp_serde::decode::from_slice::<AccountMeta>(&encoded)
421            .expect_err("should fail to decode");
422        match decoded {
423            rmp_serde::decode::Error::LengthMismatch(_) => (),
424            other => panic!("unexpected error: {}", other),
425        }
426    }
427
428    #[cfg(feature = "serde")]
429    #[test]
430    fn test_accountmeta_serialize_messagepack_named() {
431        // Should encode to a fixmap with length 3 (0x83) with the elements:
432        // - fixstr len=1 (0xa1) followed by "p"
433        // - bin8 with 32 bytes of data (0xc4 0x20 <data>)
434        // - fixstr len=1 (0xa1) data "s"
435        // - bool false (0xc2)
436        // - fixstr len=1 (0xa1) data "w"
437        // - bool true (0xc3)
438        //
439        // total len = 43
440        let account = AccountMeta {
441            pubkey: SOL_PUBKEY,
442            is_signer: false,
443            is_writable: true,
444        };
445
446        let encoded =
447            rmp_serde::encode::to_vec_named(&account).expect("should encode via messagepack");
448        assert_eq!(encoded.len(), 43);
449        assert_eq!(encoded[0], 0x83_u8); // fixmap with length 3
450        assert_eq!(encoded[1..3], [0xa1_u8, 0x70_u8]); // fixstr len=1, data="p"
451        assert_eq!(encoded[3..5], [0xc4_u8, 32_u8]); // bin8 with length 32
452        assert_eq!(encoded[5..37], SOL_ADDR_BYTES); // pubkey data
453        assert_eq!(encoded[37..39], [0xa1_u8, 0x73_u8]); // fixstr len=1, data="s"
454        assert_eq!(encoded[39], 0xc2_u8); // bool false
455        assert_eq!(encoded[40..42], [0xa1_u8, 0x77_u8]); // fixstr len=1, data="w"
456        assert_eq!(encoded[42], 0xc3_u8); // bool true
457    }
458
459    #[cfg(feature = "serde")]
460    #[test]
461    fn test_accountmeta_deserialize_messagepack_named() {
462        let expected = AccountMeta {
463            pubkey: SOL_PUBKEY,
464            is_signer: false,
465            is_writable: true,
466        };
467        let encoded: [u8; 43] = [
468            0x83, // fixmap len=3
469            0xa1, 0x70, // fixstr "p"
470            0xc4, 32, // bin8 len=32
471            6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57,
472            220, 26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0, // 32 bytes of data
473            0xa1, 0x73, // fixstr "s"
474            0xc2, // bool false
475            0xa1, 0x77, // fixstr "w"
476            0xc3, // bool true
477        ];
478
479        let decoded = rmp_serde::decode::from_slice::<AccountMeta>(&encoded)
480            .expect("should decode via messagepack");
481        assert_eq!(decoded, expected);
482    }
483
484    #[cfg(feature = "serde")]
485    #[test]
486    fn test_accountmeta_deserialize_messagepack_extra_field_named() {
487        let expected = AccountMeta {
488            pubkey: SOL_PUBKEY,
489            is_signer: false,
490            is_writable: true,
491        };
492        let encoded: [u8; 46] = [
493            0x84, // fixmap len=4
494            0xa1, 0x70, // fixstr "p"
495            0xc4, 32, // bin8 len=32
496            6, 155, 136, 87, 254, 171, 129, 132, 251, 104, 127, 99, 70, 24, 192, 53, 218, 196, 57,
497            220, 26, 235, 59, 85, 152, 160, 240, 0, 0, 0, 0, 0, // 32 bytes of data
498            0xa1, 0x73, // fixstr "s"
499            0xc2, // bool false
500            0xa1, 0x77, // fixstr "w"
501            0xc3, // bool true
502            0xa1, 0x65, // fixstr "e" for extra
503            0xc0, // nil
504        ];
505
506        let decoded = rmp_serde::decode::from_slice::<AccountMeta>(&encoded)
507            .expect("should decode via messagepack");
508        assert_eq!(decoded, expected);
509    }
510
511    #[cfg(feature = "serde")]
512    #[test]
513    fn test_instruction_messagepack_roundtrip() {
514        let instruction = super::Instruction {
515            program_id: SOL_PUBKEY,
516            accounts: Vec::new(),
517            data: Vec::from([104, 101, 108, 108, 111]), // hello
518        };
519        let expected_msgpack = Value::Map(vec![
520            (
521                Value::String("p".into()),
522                Value::Binary(Vec::from(SOL_ADDR_BYTES)),
523            ),
524            (Value::String("a".into()), Value::Array(vec![])),
525            (
526                Value::String("d".into()),
527                Value::Binary(vec![104, 101, 108, 108, 111]),
528            ),
529        ]);
530
531        let encoded_instruction =
532            rmp_serde::to_vec_named(&instruction).expect("should encode to messagepack");
533        let encoded_expected =
534            rmp_serde::to_vec_named(&expected_msgpack).expect("should encode to messagepack");
535        assert_eq!(encoded_instruction, encoded_expected);
536
537        let decoded: super::Instruction =
538            rmp_serde::from_slice(&encoded_expected).expect("should decode from messagepack");
539        assert_eq!(decoded, instruction);
540    }
541
542    #[cfg(feature = "serde-instruction-human-base64")]
543    #[test]
544    fn test_instruction_json_human() {
545        let instruction = super::Instruction {
546            program_id: SOL_PUBKEY,
547            accounts: Vec::new(),
548            data: Vec::from([104, 101, 108, 108, 111]), // hello
549        };
550        let expected_json = serde_json::json!({
551            "p": SOL_ADDR_BASE58,
552            "a": [],
553            "d": "aGVsbG8",
554        });
555        let encoded_value = serde_json::to_value(&instruction).expect("should encode to JSON");
556        assert_eq!(encoded_value, expected_json);
557
558        let decoded: super::Instruction =
559            serde_json::from_value(expected_json).expect("should decoded from JSON");
560        assert_eq!(decoded, instruction);
561    }
562
563    #[cfg(feature = "serde")]
564    #[test]
565    fn test_instruction_decode_json_nonhuman() {
566        use super::Instruction;
567        let instruction = Instruction {
568            program_id: SOL_PUBKEY,
569            accounts: Vec::new(),
570            data: Vec::from([104, 101, 108, 108, 111]), // hello
571        };
572        let json_data = serde_json::json!({
573            "p": SOL_ADDR_BYTES,
574            "a": [],
575            "d": [104, 101, 108, 108, 111]
576        });
577
578        let decoded: Instruction =
579            serde_json::from_value(json_data).expect("should decode from JSON");
580        assert_eq!(decoded, instruction);
581    }
582}