1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use cosmwasm_std::{Addr, Decimal, StdError, StdResult, Storage};
use cw_storage_plus::Item;
pub struct Slashers<'a>(Item<'a, Vec<Addr>>);
impl<'a> Slashers<'a> {
pub const fn new(storage_key: &'a str) -> Self {
Slashers(Item::new(storage_key))
}
pub fn instantiate(&self, storage: &mut dyn Storage) -> StdResult<()> {
self.0.save(storage, &vec![])
}
pub fn add_slasher(&self, storage: &mut dyn Storage, addr: Addr) -> Result<(), SlasherError> {
let mut slashers = self.0.load(storage)?;
if !slashers.iter().any(|h| h == &addr) {
slashers.push(addr);
} else {
return Err(SlasherError::SlasherAlreadyRegistered(addr.to_string()));
}
Ok(self.0.save(storage, &slashers)?)
}
pub fn remove_slasher(
&self,
storage: &mut dyn Storage,
addr: Addr,
) -> Result<(), SlasherError> {
let mut slashers = self.0.load(storage)?;
if let Some(p) = slashers.iter().position(|x| x == &addr) {
slashers.remove(p);
} else {
return Err(SlasherError::SlasherNotRegistered(addr.to_string()));
}
Ok(self.0.save(storage, &slashers)?)
}
pub fn is_slasher(&self, storage: &dyn Storage, addr: &Addr) -> StdResult<bool> {
let slashers = self.0.load(storage)?;
Ok(slashers.contains(addr))
}
pub fn list_slashers(&self, storage: &dyn Storage) -> StdResult<Vec<String>> {
let slashers = self.0.load(storage)?;
Ok(slashers.into_iter().map(String::from).collect())
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum SlashMsg {
AddSlasher { addr: String },
RemoveSlasher { addr: String },
Slash { addr: String, portion: Decimal },
}
#[derive(Error, Debug, PartialEq)]
pub enum SlasherError {
#[error("{0}")]
Std(#[from] StdError),
#[error("Given address already registered as a hook")]
SlasherAlreadyRegistered(String),
#[error("Given address not registered as a hook")]
SlasherNotRegistered(String),
#[error("Invalid portion {0}, must be (0, 1]")]
InvalidPortion(Decimal),
}
pub fn validate_portion(portion: Decimal) -> Result<(), SlasherError> {
match portion.is_zero() || portion > Decimal::one() {
true => Err(SlasherError::InvalidPortion(portion)),
false => Ok(()),
}
}