hacker-challenge/rewrite/src/persistence.rs
2024-09-29 13:16:14 +03:00

50 lines
1.5 KiB
Rust

use serde::{Deserialize, Serialize};
use solana_sdk::{pubkey::Pubkey, signature::keypair::Keypair};
use std::str::FromStr;
use tokio::{
fs::File,
io::{AsyncReadExt, AsyncWriteExt},
};
#[derive(Serialize, Deserialize)]
pub struct Data {
random: String,
keypair: String,
token: String,
}
impl Data {
pub async fn init_from(keypair: &Keypair, token: &Pubkey) -> Self {
use rand::{distributions::Alphanumeric, Rng};
let random_string: String =
rand::thread_rng().sample_iter(&Alphanumeric).take(128).map(char::from).collect();
Self {
random: random_string,
keypair: keypair.to_base58_string(),
token: token.to_string(),
}
}
pub async fn write(self, path: &str) -> Result<(), Box<dyn std::error::Error>> {
let serialized = serde_json::to_string(&self)?;
let mut file = File::create(path).await?;
file.write_all(serialized.as_bytes()).await?;
file.flush().await?;
Ok(())
}
pub async fn read(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
let mut file = File::open(path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
Ok(serde_json::from_str(&contents)?)
}
pub fn parse(self) -> (Keypair, Pubkey) {
let keypair = Keypair::from_base58_string(&self.keypair);
let pubkey = Pubkey::from_str(&self.token).unwrap();
(keypair, pubkey)
}
}