use std::io::Write;
use flate2::write::ZlibEncoder;
use solana_idl::Idl;
use solana_sdk::pubkey::Pubkey;
use crate::errors::ChainparserResult;
#[rustfmt::skip]
const DISCRIMINATOR: [u8; 8] = [
0x18, 0x46, 0x62, 0xbf,
0x3a, 0x90, 0x7b, 0x9e,
];
pub fn encode_idl_account(
program_id: &Pubkey,
idl: &Idl,
) -> ChainparserResult<Vec<u8>> {
let json = serde_json::to_vec(idl)?;
let pubkey_vec = program_id.to_bytes().to_vec();
let data_len_bytes = (json.len() as u32).to_le_bytes().to_vec();
let zipped = zip_bytes(&json)?;
let full_vec =
[DISCRIMINATOR.to_vec(), pubkey_vec, data_len_bytes, zipped].concat();
Ok(full_vec)
}
pub fn encode_idl(idl: &Idl) -> ChainparserResult<Vec<u8>> {
let json = serde_json::to_vec(idl)?;
zip_bytes(&json)
}
pub fn encode_idl_account_json(
program_id: &Pubkey,
idl_json: &str,
) -> ChainparserResult<Vec<u8>> {
let json_bytes = idl_json.as_bytes();
let pubkey_vec = program_id.to_bytes().to_vec();
let data_len_bytes = (json_bytes.len() as u32).to_le_bytes().to_vec();
let zipped = zip_bytes(idl_json.as_bytes())?;
let full_vec =
[DISCRIMINATOR.to_vec(), pubkey_vec, data_len_bytes, zipped].concat();
Ok(full_vec)
}
fn zip_bytes(bytes: &[u8]) -> ChainparserResult<Vec<u8>> {
let mut encoder =
ZlibEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(bytes)?;
Ok(encoder.finish()?)
}