odra_modules/cep18/
storage.rs1#![allow(missing_docs)]
2
3use odra::casper_types::bytesrepr::ToBytes;
4use odra::casper_types::U256;
5use odra::named_keys::{
6 base64_encoded_key_value_storage, compound_key_value_storage, single_value_storage
7};
8use odra::prelude::*;
9
10const ALLOWANCES_KEY: &str = "allowances";
11const BALANCES_KEY: &str = "balances";
12const NAME_KEY: &str = "name";
13const DECIMALS_KEY: &str = "decimals";
14const SYMBOL_KEY: &str = "symbol";
15const TOTAL_SUPPLY_KEY: &str = "total_supply";
16
17single_value_storage!(
18 Cep18NameStorage,
19 String,
20 NAME_KEY,
21 ExecutionError::KeyNotFound
22);
23single_value_storage!(
24 Cep18DecimalsStorage,
25 u8,
26 DECIMALS_KEY,
27 ExecutionError::KeyNotFound
28);
29single_value_storage!(
30 Cep18SymbolStorage,
31 String,
32 SYMBOL_KEY,
33 ExecutionError::KeyNotFound
34);
35single_value_storage!(
36 Cep18TotalSupplyStorage,
37 U256,
38 TOTAL_SUPPLY_KEY,
39 ExecutionError::KeyNotFound
40);
41impl Cep18TotalSupplyStorage {
42 pub fn add(&self, amount: U256) {
44 let total_supply = self.get();
45 let new_total_supply = total_supply
46 .checked_add(amount)
47 .unwrap_or_revert_with(&self.env(), ExecutionError::AdditionOverflow);
48 self.set(new_total_supply);
49 }
50
51 pub fn subtract(&self, amount: U256) {
53 let total_supply = self.get();
54 let new_total_supply = total_supply
55 .checked_sub(amount)
56 .unwrap_or_revert_with(&self.env(), ExecutionError::SubtractionOverflow);
57 self.set(new_total_supply);
58 }
59}
60base64_encoded_key_value_storage!(Cep18BalancesStorage, BALANCES_KEY, Address, U256);
61impl Cep18BalancesStorage {
62 pub fn add(&self, account: &Address, amount: U256) {
64 let balance = self.get(account).unwrap_or_default();
65 let new_balance = balance.checked_add(amount).unwrap_or_revert(self);
66 self.set(account, new_balance);
67 }
68
69 pub fn subtract(&self, account: &Address, amount: U256) {
71 let balance = self.get(account).unwrap_or_default();
72 let new_balance = balance
73 .checked_sub(amount)
74 .unwrap_or_revert_with(self, ExecutionError::SubtractionOverflow);
75 self.set(account, new_balance);
76 }
77}
78compound_key_value_storage!(Cep18AllowancesStorage, ALLOWANCES_KEY, Address, U256);
79impl Cep18AllowancesStorage {
80 pub fn add(&self, owner: &Address, spender: &Address, amount: U256) {
82 let allowance = self.get_or_default(owner, spender);
83 let new_allowance = allowance
84 .checked_add(amount)
85 .unwrap_or_revert_with(&self.env(), ExecutionError::AdditionOverflow);
86 self.set(owner, spender, new_allowance);
87 }
88
89 pub fn subtract(&self, owner: &Address, spender: &Address, amount: U256) {
91 let allowance = self.get_or_default(owner, spender);
92 let new_allowance = allowance
93 .checked_sub(amount)
94 .unwrap_or_revert_with(&self.env(), ExecutionError::AdditionOverflow);
95 self.set(owner, spender, new_allowance);
96 }
97}