feat: add name
This commit is contained in:
@@ -5,6 +5,7 @@ use crate::{tx::Transaction};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CreditContract {
|
||||
pub name: String,
|
||||
pub credit_limit: u32,
|
||||
pub issue_amount: u32,
|
||||
pub admin: String,
|
||||
@@ -14,15 +15,19 @@ pub struct CreditContract {
|
||||
impl CreditContract {
|
||||
pub fn new(tx: &Transaction, name: &str, credit_limit: u32) -> XResult<Self> {
|
||||
let c = Self {
|
||||
name: name.into(),
|
||||
credit_limit,
|
||||
issue_amount: 0,
|
||||
admin: tx.sender.clone().unwrap(),
|
||||
credit: HashMap::new(),
|
||||
};
|
||||
Self::save(name, &c)?;
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
pub fn load(name: &str) -> XResult<Self> {
|
||||
load_credit_contract(name)
|
||||
}
|
||||
|
||||
pub fn issue(&mut self, tx: &Transaction, receiver: &str, credit: u32) -> XResult<()> {
|
||||
if &self.admin != tx.sender.as_ref().ok_or_else(|| SimpleError::new("Sender is not provided".into()))? {
|
||||
return simple_error!("Current user is not admin, {} vs {:?}", self.admin, tx.sender);
|
||||
@@ -35,6 +40,7 @@ impl CreditContract {
|
||||
Some(cr) => *cr += credit,
|
||||
}
|
||||
self.issue_amount += credit;
|
||||
save_credit_contract(self)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -53,26 +59,32 @@ impl CreditContract {
|
||||
}
|
||||
},
|
||||
}
|
||||
save_credit_contract(self)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get(&self, _tx: &Transaction, account: &str) -> u32 {
|
||||
pub fn query(&self, _tx: &Transaction, account: &str) -> u32 {
|
||||
match self.credit.get(account) {
|
||||
None => 0,
|
||||
Some(receiver_credit) => *receiver_credit,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(name: &str) -> XResult<Self> {
|
||||
let json = fs::read_to_string(name)?;
|
||||
serde_json::from_str(&json).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
pub fn save(name: &str, c: &CreditContract) -> XResult<()> {
|
||||
if let Ok(_) = File::open(name) {
|
||||
return simple_error!("File exists: {}", name);
|
||||
}
|
||||
fs::write(name, serde_json::to_string(c)?.as_bytes())?;
|
||||
Ok(())
|
||||
pub fn query_all(&self, _tx: &Transaction) -> &HashMap<String, u32> {
|
||||
&self.credit
|
||||
}
|
||||
}
|
||||
|
||||
fn load_credit_contract(name: &str) -> XResult<CreditContract> {
|
||||
let json = fs::read_to_string(name)?;
|
||||
serde_json::from_str(&json).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn save_credit_contract(c: &CreditContract) -> XResult<()> {
|
||||
let name = &c.name;
|
||||
if let Ok(_) = File::open(name) {
|
||||
return simple_error!("File exists: {}", name);
|
||||
}
|
||||
fs::write(name, serde_json::to_string(c)?.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user