-
Notifications
You must be signed in to change notification settings - Fork 251
/
lib.rs
300 lines (254 loc) · 10.2 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#![cfg_attr(not(feature = "std"), no_std)]
use codec::FullCodec;
use orml_traits::{arithmetic::Signed, MultiCurrency, MultiCurrencyExtended, PriceProvider};
use paint_support::{decl_error, decl_event, decl_module, decl_storage, ensure, Parameter};
use rstd::{convert::TryInto, result};
use sr_primitives::{
traits::{CheckedAdd, CheckedSub, Convert, Member, SimpleArithmetic, Zero},
Fixed64,
};
use primitives::CurrencyId as CURRENCY_ID;
use support::RiskManager;
mod mock;
mod tests;
pub trait Trait: system::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type CurrencyId: From<u8> + Into<CurrencyIdOf<Self>> + Into<DebitCurrencyIdOf<Self>> + Parameter + Copy;
type Price: FullCodec + SimpleArithmetic + Member + Into<u64> + From<Self::Balance>;
type Balance: From<BalanceOf<Self>> + From<DebitBalanceOf<Self>> + Into<Self::Price> + Zero;
type Convert: Convert<(Self::CurrencyId, DebitBalanceOf<Self>), BalanceOf<Self>>;
type Currency: MultiCurrencyExtended<Self::AccountId>;
type DebitCurrency: MultiCurrencyExtended<Self::AccountId>;
type PriceSource: PriceProvider<Self::CurrencyId, Self::Price>;
type RiskManager: RiskManager<Self::AccountId, Self::CurrencyId, AmountOf<Self>, DebitAmountOf<Self>>;
}
type CurrencyIdOf<T> = <<T as Trait>::Currency as MultiCurrency<<T as system::Trait>::AccountId>>::CurrencyId;
type DebitCurrencyIdOf<T> = <<T as Trait>::DebitCurrency as MultiCurrency<<T as system::Trait>::AccountId>>::CurrencyId;
type BalanceOf<T> = <<T as Trait>::Currency as MultiCurrency<<T as system::Trait>::AccountId>>::Balance;
type DebitBalanceOf<T> = <<T as Trait>::DebitCurrency as MultiCurrency<<T as system::Trait>::AccountId>>::Balance;
type AmountOf<T> = <<T as Trait>::Currency as MultiCurrencyExtended<<T as system::Trait>::AccountId>>::Amount;
type DebitAmountOf<T> = <<T as Trait>::DebitCurrency as MultiCurrencyExtended<<T as system::Trait>::AccountId>>::Amount;
decl_storage! {
trait Store for Module<T: Trait> as Vaults {
pub Debits get(fn debits): double_map T::AccountId, blake2_256(T::CurrencyId) => DebitBalanceOf<T>;
pub Collaterals get(fn collaterals): double_map T::AccountId, blake2_256(T::CurrencyId) => BalanceOf<T>;
pub TotalDebits get(fn total_debits): map T::CurrencyId => DebitBalanceOf<T>;
pub TotalCollaterals get(fn total_collaterals): map T::CurrencyId => BalanceOf<T>;
}
}
decl_event!(
pub enum Event<T> where
<T as system::Trait>::AccountId,
<T as Trait>::CurrencyId,
DebitAmount = DebitAmountOf<T>,
Amount = AmountOf<T>,
{
/// Update Position success (account, currency_id, collaterals, debits)
UpdatePosition(AccountId, CurrencyId, Amount, DebitAmount),
/// Update collateral success (account, currency_id, collaterals, debits)
UpdateCollateral(AccountId, CurrencyId, Amount, DebitAmount),
/// Transfer vault (from, to)
TransferVault(AccountId, AccountId, CurrencyId),
}
);
decl_error! {
/// Error for vaults module.
pub enum Error {
DebitOverflow,
CollateralOverflow,
AmountIntoBalanceFailed,
BalanceIntoAmountFailed,
PositionWillUnsafe,
UpdateStableCoinFailed,
UpdateCollateralFailed,
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default;
}
}
impl<T: Trait> Module<T> {
pub fn collateral_ratio(who: T::AccountId, currency_id: T::CurrencyId) -> Option<Fixed64> {
// ensure debit and collateral exists
if (true, true)
!= (
!<Debits<T>>::exists(&who, currency_id),
!<Collaterals<T>>::exists(&who, currency_id),
) {
return None;
}
// get balance of collateral and debits
let collateral_balance: T::Balance = Self::collaterals(&who, currency_id).into();
let debit_balance: DebitBalanceOf<T> = Self::debits(&who, currency_id);
// get stable coin amount
let stable_balance: T::Balance = T::Convert::convert((currency_id, debit_balance)).into();
// ensure stable coin balance is not zero
if stable_balance.is_zero() {
return None;
}
// ensure collateral balance is not zero
if collateral_balance.is_zero() {
return None;
}
let ausd_currency_id = CURRENCY_ID::AUSD as u8;
// get prices and calc ratio of collateral
if let Some(price) = T::PriceSource::get_price(ausd_currency_id.into(), currency_id) {
// TODO: fix calculate
let result: T::Price = stable_balance.into() / (price * Into::<T::Price>::into(collateral_balance));
return Some(Fixed64::from_rational(1i64, result.into()));
}
None
}
// mutate collaterlas and debits, don't check position safe and don't mutate stable coin
pub fn update_collaterals_and_debits(
who: T::AccountId,
currency_id: T::CurrencyId,
collaterals: AmountOf<T>,
debits: DebitAmountOf<T>,
) -> result::Result<(), Error> {
// ensure mutate safe
Self::check_add_and_sub(&who, currency_id, collaterals, debits)?;
Self::update_collateral_and_debit(&who, currency_id, collaterals, debits)?;
Self::deposit_event(RawEvent::UpdateCollateral(who, currency_id, collaterals, debits));
Ok(())
}
// mulate collaterals and debits and then mulate stable coin
pub fn update_position(
who: T::AccountId,
currency_id: T::CurrencyId,
collaterals: AmountOf<T>,
debits: DebitAmountOf<T>,
) -> result::Result<(), Error> {
// ensure mutate safe
Self::check_add_and_sub(&who, currency_id, collaterals, debits)?;
// ensure cdp safe
T::RiskManager::check_position_adjustment(&who, currency_id, collaterals, debits)
.map_err(|_| Error::PositionWillUnsafe)?;
// update collateral asset
T::Currency::update_balance(Into::<CurrencyIdOf<T>>::into(currency_id), &who, -collaterals)
.map_err(|_| Error::UpdateCollateralFailed)?;
// updaet stable coin
T::DebitCurrency::update_balance(Into::<DebitCurrencyIdOf<T>>::into(currency_id), &who, debits)
.map_err(|_| Error::UpdateStableCoinFailed)?;
// mutate collaterals and debits
Self::update_collateral_and_debit(&who, currency_id, collaterals, debits)?;
Self::deposit_event(RawEvent::UpdatePosition(who, currency_id, collaterals, debits));
Ok(())
}
// transfer vault
pub fn transfer(from: T::AccountId, to: T::AccountId, currency_id: T::CurrencyId) -> result::Result<(), Error> {
// get `from` position data
let collateral: BalanceOf<T> = Self::collaterals(&from, currency_id);
let debit: DebitBalanceOf<T> = Self::debits(&from, currency_id);
// banlance -> amount
let collateral: AmountOf<T> =
TryInto::<AmountOf<T>>::try_into(collateral).map_err(|_| Error::BalanceIntoAmountFailed)?;
let debit: DebitAmountOf<T> =
TryInto::<DebitAmountOf<T>>::try_into(debit).map_err(|_| Error::BalanceIntoAmountFailed)?;
// ensure mutate safe
Self::check_add_and_sub(&from, currency_id, -collateral, -debit)?;
Self::check_add_and_sub(&to, currency_id, collateral, debit)?;
// ensure positions are safe after transfered
T::RiskManager::check_position_adjustment(&from, currency_id, -collateral, -debit)
.map_err(|_| Error::PositionWillUnsafe)?;
T::RiskManager::check_position_adjustment(&to, currency_id, collateral, debit)
.map_err(|_| Error::PositionWillUnsafe)?;
// execute transfer
Self::update_collateral_and_debit(&from, currency_id, -collateral, -debit)?;
Self::update_collateral_and_debit(&to, currency_id, collateral, debit)?;
Self::deposit_event(RawEvent::TransferVault(from, to, currency_id));
Ok(())
}
// ensure sum and sub will success when update
fn check_add_and_sub(
who: &T::AccountId,
currency_id: T::CurrencyId,
collaterals: AmountOf<T>,
debits: DebitAmountOf<T>,
) -> result::Result<(), Error> {
// judge collaterals and debits are negative or positive
let collaterals_balance =
TryInto::<BalanceOf<T>>::try_into(collaterals.abs()).map_err(|_| Error::AmountIntoBalanceFailed)?;
let debits_balance =
TryInto::<DebitBalanceOf<T>>::try_into(debits.abs()).map_err(|_| Error::AmountIntoBalanceFailed)?;
// check collaterals update
if collaterals.is_positive() {
ensure!(
Self::collaterals(who, currency_id)
.checked_add(&collaterals_balance)
.is_some(),
Error::CollateralOverflow
);
ensure!(
Self::total_collaterals(currency_id)
.checked_add(&collaterals_balance)
.is_some(),
Error::CollateralOverflow
);
} else {
ensure!(
Self::collaterals(who, currency_id)
.checked_sub(&collaterals_balance)
.is_some(),
Error::CollateralOverflow
);
ensure!(
Self::total_collaterals(currency_id)
.checked_sub(&collaterals_balance)
.is_some(),
Error::CollateralOverflow
);
}
// check collaterals update
if debits.is_positive() {
ensure!(
Self::debits(who, currency_id).checked_add(&debits_balance).is_some(),
Error::DebitOverflow
);
ensure!(
Self::total_debits(currency_id).checked_add(&debits_balance).is_some(),
Error::DebitOverflow
);
} else {
ensure!(
Self::debits(who, currency_id).checked_sub(&debits_balance).is_some(),
Error::DebitOverflow
);
ensure!(
Self::total_debits(currency_id).checked_sub(&debits_balance).is_some(),
Error::DebitOverflow
);
}
Ok(())
}
fn update_collateral_and_debit(
who: &T::AccountId,
currency_id: T::CurrencyId,
collaterals: AmountOf<T>,
debits: DebitAmountOf<T>,
) -> result::Result<(), Error> {
// judge collaterals and debits are negative or positive
let collaterals_balance =
TryInto::<BalanceOf<T>>::try_into(collaterals.abs()).map_err(|_| Error::AmountIntoBalanceFailed)?;
let debits_balance =
TryInto::<DebitBalanceOf<T>>::try_into(debits.abs()).map_err(|_| Error::AmountIntoBalanceFailed)?;
// updaet collaterals record
if collaterals.is_positive() {
<Collaterals<T>>::mutate(who, currency_id, |balance| *balance += collaterals_balance);
<TotalCollaterals<T>>::mutate(currency_id, |balance| *balance += collaterals_balance);
} else {
<Collaterals<T>>::mutate(who, currency_id, |balance| *balance -= collaterals_balance);
<TotalCollaterals<T>>::mutate(currency_id, |balance| *balance -= collaterals_balance);
}
// updaet debits record
if debits.is_positive() {
<Debits<T>>::mutate(who, currency_id, |balance| *balance += debits_balance);
<TotalDebits<T>>::mutate(currency_id, |balance| *balance += debits_balance);
} else {
<Debits<T>>::mutate(who, currency_id, |balance| *balance -= debits_balance);
<TotalDebits<T>>::mutate(currency_id, |balance| *balance -= debits_balance);
}
Ok(())
}
}