transaction_processor/
stake.rs

1use account::Account;
2use types::{ProcessError, ProcessResult};
3use utils::IfNotFound;
4
5pub fn place_stake(sender: &Account, amount: u64) -> ProcessResult<()> {
6    let new_stake = match sender.get_u64("stake").if_not_found(|| 0u64)?.checked_add(amount) {
7        Some(v) => v,
8        None => return Err(ProcessError::Overflow),
9    };
10
11    // PERL price is 0.2$USD; we require a minimum of 500$USD which is 2500 PERLs.
12    if new_stake < 2500 {
13        return Err(ProcessError::Custom("stake requires a minimum of 2500 PERLs".into()));
14    }
15
16    sender.set_u64(
17        "balance",
18        match sender.get_u64("balance").if_not_found(|| 0u64)?.checked_sub(amount)
19            {
20                Some(v) => v,
21                None => return Err(ProcessError::Custom("not enough balance".into())),
22            },
23    )?;
24
25    sender.set_u64(
26        "stake",
27        new_stake,
28    )?;
29
30    Ok(())
31}
32
33pub fn withdraw_stake(sender: &Account, amount: u64) -> ProcessResult<()> {
34    sender.set_u64(
35        "stake",
36        match sender.get_u64("stake").if_not_found(|| 0u64)?.checked_sub(amount)
37            {
38                Some(v) => v,
39                None => return Err(ProcessError::Custom("not enough stake".into())),
40            },
41    )?;
42
43    sender.set_u64(
44        "balance",
45        match sender.get_u64("balance").if_not_found(|| 0u64)?.checked_add(amount)
46            {
47                Some(v) => v,
48                None => return Err(ProcessError::Overflow),
49            },
50    )?;
51
52    Ok(())
53}