feat: use rust_util
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
use std::{collections::HashMap, fs, fs::File};
|
||||
use rust_util::{SimpleError, XResult, simple_error};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use crate::{tx::Transaction, util::{SimpleError, XResult}};
|
||||
use crate::{tx::Transaction};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CreditContract {
|
||||
@@ -24,10 +25,10 @@ impl CreditContract {
|
||||
|
||||
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 Err(SimpleError::new(format!("Current user is not admin, {} vs {:?}", self.admin, tx.sender)).into())
|
||||
return simple_error!("Current user is not admin, {} vs {:?}", self.admin, tx.sender);
|
||||
}
|
||||
if self.issue_amount + credit > self.credit_limit {
|
||||
return Err(SimpleError::new(format!("Issue too much credit, current: {}, issue: {}, limit: {}", self.issue_amount, credit, self.credit_limit)).into());
|
||||
return simple_error!("Issue too much credit, current: {}, issue: {}, limit: {}", self.issue_amount, credit, self.credit_limit);
|
||||
}
|
||||
match self.credit.get_mut(receiver) {
|
||||
None => { self.credit.insert(receiver.to_owned(), credit); },
|
||||
@@ -39,7 +40,7 @@ impl CreditContract {
|
||||
|
||||
pub fn transfer(&mut self, tx: &Transaction, receiver: &str, credit: u32) -> XResult<()> {
|
||||
match self.credit.get_mut(tx.sender.as_ref().ok_or_else(|| SimpleError::new("Sender is not provided".into()))?) {
|
||||
None => return Err(SimpleError::new(format!("Have not enough credit: {:?}", tx.sender)).into()),
|
||||
None => return simple_error!("Have not enough credit: {:?}", tx.sender),
|
||||
Some(cr) => {
|
||||
if *cr >= credit {
|
||||
*cr -= credit;
|
||||
@@ -48,7 +49,7 @@ impl CreditContract {
|
||||
Some(receiver_credit) => *receiver_credit += credit,
|
||||
}
|
||||
} else {
|
||||
return Err(SimpleError::new(format!("Have not enough credit: {:?}", tx.sender)).into());
|
||||
return simple_error!("Have not enough credit: {:?}", tx.sender);
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -69,7 +70,7 @@ impl CreditContract {
|
||||
|
||||
pub fn save(name: &str, c: &CreditContract) -> XResult<()> {
|
||||
if let Ok(_) = File::open(name) {
|
||||
return Err(SimpleError::new(format!("File exists: {}", name)).into());
|
||||
return simple_error!("File exists: {}", name);
|
||||
}
|
||||
fs::write(name, serde_json::to_string(c)?.as_bytes())?;
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user