-
Notifications
You must be signed in to change notification settings - Fork 25
/
lib.rs
233 lines (206 loc) · 6.26 KB
/
lib.rs
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_support::{decl_error, decl_event, decl_module, decl_storage, ensure};
use frame_system::{self as system, ensure_signed};
use node_primitives::RSymbol;
use sp_runtime::{
traits::{StaticLookup, Zero},
DispatchResult, RuntimeDebug,
};
use sp_std::convert::Infallible;
use sp_std::prelude::*;
pub mod traits;
pub trait Trait: system::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
}
decl_event!(
pub enum Event<T> where
<T as frame_system::Trait>::AccountId,
{
/// Transfer succeeded. \[from, to, symbol, value\]
Transfer(AccountId, AccountId, RSymbol, u128),
/// Some balance was deposited
Minted(AccountId, RSymbol, u128),
/// Some balance was burned
Burned(AccountId, RSymbol, u128),
}
);
decl_error! {
pub enum Error for Module<T: Trait> {
/// Account liquidity restrictions prevent withdrawal
LiquidityRestrictions,
/// Got an overflow after adding
Overflow,
/// Balance too low to send value
InsufficientBalance,
}
}
/// All balance information for an account.
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug)]
pub struct AccountLpData {
/// Non-reserved part of the balance.
pub free: u128,
}
decl_storage! {
trait Store for Module<T: Trait> as RDexBalances {
/// The total units issued in the system.
pub TotalIssuance get(fn total_issuance): map hasher(blake2_128_concat) RSymbol => u128;
/// NOTE: This is only used in the case that this module is used to store balances.
pub Account get(fn account):
double_map hasher(blake2_128_concat) RSymbol, hasher(blake2_128_concat) T::AccountId => Option<AccountLpData>;
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default;
/// Transfer some liquid free balance to another account.
#[weight = 195_000_000]
pub fn transfer(
origin,
dest: <T::Lookup as StaticLookup>::Source,
symbol: RSymbol,
value: u128
) {
let transactor = ensure_signed(origin)?;
let dest = T::Lookup::lookup(dest)?;
<Self as traits::Currency<_>>::transfer(&transactor, &dest, symbol, value)?;
}
}
}
impl<T: Trait> Module<T> {
pub fn mutate_account<R>(
who: &T::AccountId,
symbol: RSymbol,
f: impl FnOnce(&mut AccountLpData) -> R,
) -> R {
Self::try_mutate_account(who, symbol, |a| -> Result<R, Infallible> { Ok(f(a)) })
.expect("Error is infallible; qed")
}
/// Mutate an account to some new value
/// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that
/// the caller will do this.
fn try_mutate_account<R, E>(
who: &T::AccountId,
symbol: RSymbol,
f: impl FnOnce(&mut AccountLpData) -> Result<R, E>,
) -> Result<R, E> {
Account::<T>::try_mutate_exists(symbol, who, |maybe_value| {
let mut maybe_data = maybe_value.take().unwrap_or_default();
f(&mut maybe_data).map(|result| {
*maybe_value = Some(maybe_data);
result
})
})
.map(|result| result)
}
}
impl<T: Trait> traits::Currency<T::AccountId> for Module<T> {
fn free_balance(who: &T::AccountId, symbol: RSymbol) -> u128 {
if let Some(data) = <Account<T>>::get(symbol, &who) {
data.free
} else {
0
}
}
fn total_issuance(symbol: RSymbol) -> u128 {
<TotalIssuance>::get(symbol)
}
// Ensure that an account can withdraw from their free balance given any existing withdrawal
// restrictions like locks and vesting balance.
// Is a no-op if amount to be withdrawn is zero.
fn ensure_can_withdraw(
_who: &T::AccountId,
_symbol: RSymbol,
amount: u128,
new_balance: u128,
) -> DispatchResult {
if amount.is_zero() {
return Ok(());
}
ensure!(
new_balance >= Zero::zero(),
Error::<T>::LiquidityRestrictions
);
Ok(())
}
// Transfer some free balance from `transactor` to `dest`, respecting existence requirements.
// Is a no-op if value to be transferred is zero or the `transactor` is the same as `dest`.
fn transfer(
transactor: &T::AccountId,
dest: &T::AccountId,
symbol: RSymbol,
value: u128,
) -> DispatchResult {
if value.is_zero() || transactor == dest {
return Ok(());
}
Self::try_mutate_account(dest, symbol, |to_account_data| -> DispatchResult {
Self::try_mutate_account(transactor, symbol, |from_account_data| -> DispatchResult {
from_account_data.free = from_account_data
.free
.checked_sub(value)
.ok_or(Error::<T>::InsufficientBalance)?;
to_account_data.free = to_account_data
.free
.checked_add(value)
.ok_or(Error::<T>::Overflow)?;
Self::ensure_can_withdraw(transactor, symbol, value, from_account_data.free)?;
Ok(())
})
})?;
// Emit transfer event.
Self::deposit_event(RawEvent::Transfer(
transactor.clone(),
dest.clone(),
symbol.clone(),
value,
));
Ok(())
}
/// Deposit some `value` into the free balance of an existing target account `who`.
///
/// Is a no-op if the `value` to be deposited is zero.
fn mint(who: &T::AccountId, symbol: RSymbol, value: u128) -> DispatchResult {
if value.is_zero() {
return Ok(());
}
Self::try_mutate_account(who, symbol, |account_data| -> DispatchResult {
account_data.free = account_data
.free
.checked_add(value)
.ok_or(Error::<T>::Overflow)?;
Ok(())
})?;
<TotalIssuance>::mutate(symbol, |issued| {
*issued = issued
.checked_add(value)
.unwrap_or_else(|| u128::max_value())
});
// deposit into event.
Self::deposit_event(RawEvent::Minted(who.clone(), symbol.clone(), value));
Ok(())
}
/// Deposit some `value` into the free balance of an existing target account `who`.
///
/// Is a no-op if the `value` to be deposited is zero.
fn burn(who: &T::AccountId, symbol: RSymbol, value: u128) -> DispatchResult {
if value.is_zero() {
return Ok(());
}
Self::try_mutate_account(who, symbol, |account_data| -> DispatchResult {
account_data.free = account_data
.free
.checked_sub(value)
.ok_or(Error::<T>::InsufficientBalance)?;
Self::ensure_can_withdraw(who, symbol, value, account_data.free)?;
Ok(())
})?;
<TotalIssuance>::mutate(symbol, |issued| {
*issued = issued.checked_sub(value).unwrap_or_else(|| 0);
});
// withdraw from event.
Self::deposit_event(RawEvent::Burned(who.clone(), symbol.clone(), value));
Ok(())
}
}