-
Notifications
You must be signed in to change notification settings - Fork 79
/
lib.rs
561 lines (505 loc) · 18.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// This file is part of Bifrost.
// Copyright (C) Liebi Technologies PTE. LTD.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
pub use crate::pallet::*;
use bifrost_primitives::{
currency::{VGLMR, VMANTA, WETH},
traits::XcmDestWeightAndFeeHandler,
Balance, BalanceCmp, CurrencyId, DerivativeIndex, Price, PriceFeeder, TryConvertFrom,
XcmOperationType, BNC, DOT, GLMR, MANTA, VBNC, VDOT,
};
use bifrost_xcm_interface::{polkadot::RelaychainCall, traits::parachains, PolkadotXcmCall};
use core::convert::Into;
use cumulus_primitives_core::ParaId;
use frame_support::{
pallet_prelude::*,
traits::{
fungibles::Inspect,
tokens::{Fortitude, Preservation},
Get,
},
transactional,
weights::WeightMeter,
PalletId,
};
use frame_system::pallet_prelude::*;
use orml_traits::MultiCurrency;
use polkadot_parachain_primitives::primitives::Sibling;
use sp_arithmetic::traits::UniqueSaturatedInto;
use sp_runtime::{
traits::{AccountIdConversion, One},
BoundedVec,
};
use sp_std::{boxed::Box, cmp::Ordering, vec, vec::Vec};
pub use weights::WeightInfo;
use xcm::{prelude::Unlimited, v4::prelude::*};
use zenlink_protocol::{AssetId, ExportZenlink};
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod impls;
pub mod migrations;
mod mock;
mod mock_price;
mod tests;
pub mod weights;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type BalanceOf<T> = <<T as Config>::MultiCurrency as MultiCurrency<AccountIdOf<T>>>::Balance;
pub type RawCallName = BoundedVec<u8, ConstU32<32>>;
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum TargetChain {
AssetHub,
RelayChain,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use bifrost_primitives::{Balance, PriceFeeder};
use frame_support::traits::fungibles::Inspect;
#[pallet::config]
pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
/// Event
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
/// Handler for both NativeCurrency and MultiCurrency
type MultiCurrency: MultiCurrency<Self::AccountId, CurrencyId = CurrencyId, Balance = Balance>
+ Inspect<Self::AccountId, AssetId = CurrencyId, Balance = Balance>;
/// xcm transfer interface
type XcmRouter: SendXcm;
/// Zenlink interface
type DexOperator: ExportZenlink<Self::AccountId, AssetId>;
/// The oracle price feeder
type PriceFeeder: PriceFeeder;
/// The only origin that can set universal fee currency order list
type ControlOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Get the weight and fee for executing Xcm.
type XcmWeightAndFeeHandler: XcmDestWeightAndFeeHandler<CurrencyId, Balance>;
/// Get TreasuryAccount
#[pallet::constant]
type TreasuryAccount: Get<Self::AccountId>;
/// Maximum number of CurrencyId's to support handling fees.
#[pallet::constant]
type MaxFeeCurrencyOrderListLen: Get<u32>;
/// When this number is reached, the DOT is sent to AssetHub
#[pallet::constant]
type MinAssetHubExecutionFee: Get<BalanceOf<Self>>;
/// When this number is reached, the DOT is sent to Relaychain
#[pallet::constant]
type MinRelaychainExecutionFee: Get<BalanceOf<Self>>;
/// The currency id of the RelayChain
#[pallet::constant]
type RelaychainCurrencyId: Get<CurrencyId>;
#[pallet::constant]
type ParachainId: Get<ParaId>;
#[pallet::constant]
type PalletId: Get<PalletId>;
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_idle(_n: BlockNumberFor<T>, limit: Weight) -> Weight {
let mut weight = Weight::default();
if WeightMeter::with_limit(limit)
.try_consume(T::DbWeight::get().reads_writes(4, 2))
.is_err()
{
return weight;
}
weight += T::DbWeight::get().reads_writes(4, 2);
if Self::handle_fee().is_err() {
return weight;
}
weight += T::DbWeight::get().reads_writes(1, 2);
weight
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Transfer to another chain
TransferTo { from: T::AccountId, target_chain: TargetChain, amount: BalanceOf<T> },
/// Set user default fee currency
SetDefaultFeeCurrency { who: T::AccountId, currency_id: Option<CurrencyId> },
/// Set universal fee currency order list
SetFeeCurrencyList { currency_list: BoundedVec<CurrencyId, T::MaxFeeCurrencyOrderListLen> },
/// Set extra fee by call
SetExtraFee {
/// The raw call name to be set as the extra fee call.
raw_call_name: RawCallName,
/// currency_id, fee_amount, receiver
fee_info: Option<(CurrencyId, BalanceOf<T>, T::AccountId)>,
},
}
/// Universal fee currency order list for all users
#[pallet::storage]
pub type UniversalFeeCurrencyOrderList<T: Config> =
StorageValue<_, BoundedVec<CurrencyId, T::MaxFeeCurrencyOrderListLen>, ValueQuery>;
/// User default fee currency, if set, will be used as the first fee currency, and then use the
/// universal fee currency order list
#[pallet::storage]
pub type UserDefaultFeeCurrency<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, CurrencyId, OptionQuery>;
/// Extra fee by call
#[pallet::storage]
pub type ExtraFeeByCall<T: Config> = StorageMap<
_,
Twox64Concat,
RawCallName,
(CurrencyId, BalanceOf<T>, T::AccountId),
OptionQuery,
>;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::error]
pub enum Error<T> {
NotEnoughBalance,
ConversionError,
WeightAndFeeNotExist,
UnweighableMessage,
XcmExecutionFailed,
CurrencyNotSupport,
MaxCurrenciesReached,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Set user default fee currency
/// Parameters:
/// - `maybe_fee_currency`: The currency id to be set as the default fee currency.
/// If `None`, the user default fee currency will be removed.
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::set_user_default_fee_currency())]
pub fn set_user_default_fee_currency(
origin: OriginFor<T>,
currency_id: Option<CurrencyId>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
if let Some(fee_currency) = ¤cy_id {
UserDefaultFeeCurrency::<T>::insert(&who, fee_currency);
} else {
UserDefaultFeeCurrency::<T>::remove(&who);
}
Self::deposit_event(Event::<T>::SetDefaultFeeCurrency { who, currency_id });
Ok(())
}
/// Set universal fee currency order list
/// Parameters:
/// - `default_list`: The currency id list to be set as the universal fee currency order
/// list.
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::set_default_fee_currency_list())]
pub fn set_default_fee_currency_list(
origin: OriginFor<T>,
currency_list: BoundedVec<CurrencyId, T::MaxFeeCurrencyOrderListLen>,
) -> DispatchResult {
T::ControlOrigin::ensure_origin(origin)?;
UniversalFeeCurrencyOrderList::<T>::put(currency_list.clone());
Self::deposit_event(Event::<T>::SetFeeCurrencyList { currency_list });
Ok(())
}
/// Set universal fee currency order list
/// Parameters:
/// - `raw_call_name`: The raw call name to be set as the extra fee call.
/// - `fee_info`: The currency id, fee amount and receiver to be set as the extra fee.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::set_user_default_fee_currency())]
pub fn set_extra_fee(
origin: OriginFor<T>,
raw_call_name: RawCallName,
fee_info: Option<(CurrencyId, BalanceOf<T>, T::AccountId)>,
) -> DispatchResult {
T::ControlOrigin::ensure_origin(origin)?;
match fee_info.clone() {
Some(fee_info) => ExtraFeeByCall::<T>::insert(&raw_call_name, fee_info),
None => ExtraFeeByCall::<T>::remove(&raw_call_name),
};
Self::deposit_event(Event::<T>::SetExtraFee { raw_call_name, fee_info });
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
#[transactional]
fn handle_fee() -> DispatchResult {
let fee_receiver = Self::get_fee_receiver(1);
let fee_receiver_balance =
T::MultiCurrency::free_balance(T::RelaychainCurrencyId::get(), &fee_receiver);
if fee_receiver_balance >= T::MinAssetHubExecutionFee::get() {
T::MultiCurrency::withdraw(
T::RelaychainCurrencyId::get(),
&fee_receiver,
fee_receiver_balance,
)?;
let asset: Asset = Asset {
id: AssetId(Location::here()),
fun: Fungible(UniqueSaturatedInto::<u128>::unique_saturated_into(
fee_receiver_balance,
)),
};
let remote_call =
RelaychainCall::<BalanceOf<T>, AccountIdOf<T>, BlockNumberFor<T>>::XcmPallet(
PolkadotXcmCall::LimitedTeleportAssets(
Box::new(Location::new(0, [Parachain(parachains::Statemine::ID)]).into()),
Box::new(
Location::new(
0,
[AccountId32 {
network: None,
id: Sibling::from(T::ParachainId::get())
.into_account_truncating(),
}],
)
.into(),
),
Box::new(asset.into()),
0,
Unlimited,
),
)
.encode()
.into();
let (require_weight_at_most, xcm_fee) =
T::XcmWeightAndFeeHandler::get_operation_weight_and_fee(
T::RelaychainCurrencyId::get(),
XcmOperationType::TeleportAssets,
)
.ok_or(Error::<T>::WeightAndFeeNotExist)?;
let fee: Asset = Asset { id: AssetId(Location::here()), fun: Fungible(xcm_fee) };
let remote_xcm = Xcm(vec![
WithdrawAsset(fee.clone().into()),
BuyExecution { fees: fee.clone(), weight_limit: Unlimited },
Transact {
origin_kind: OriginKind::SovereignAccount,
require_weight_at_most,
call: remote_call,
},
DepositAsset {
assets: All.into(),
beneficiary: Location::new(0, [Parachain(T::ParachainId::get().into())]),
},
]);
let (ticket, _) =
T::XcmRouter::validate(&mut Some(Location::parent()), &mut Some(remote_xcm))
.map_err(|_| Error::<T>::UnweighableMessage)?;
T::XcmRouter::deliver(ticket).map_err(|_| Error::<T>::XcmExecutionFailed)?;
Self::deposit_event(Event::TransferTo {
from: fee_receiver,
target_chain: TargetChain::AssetHub,
amount: fee_receiver_balance,
});
}
let fee_receiver = Self::get_fee_receiver(0);
let fee_receiver_balance =
T::MultiCurrency::free_balance(T::RelaychainCurrencyId::get(), &fee_receiver);
if fee_receiver_balance >= T::MinRelaychainExecutionFee::get() {
T::MultiCurrency::withdraw(
T::RelaychainCurrencyId::get(),
&fee_receiver,
fee_receiver_balance,
)?;
Self::deposit_event(Event::TransferTo {
from: fee_receiver,
target_chain: TargetChain::RelayChain,
amount: fee_receiver_balance,
});
}
Ok(())
}
fn get_fee_receiver(index: DerivativeIndex) -> T::AccountId {
T::PalletId::get().into_sub_account_truncating(index)
}
/// Get user fee charge assets order
fn get_fee_currency_list(account_id: &T::AccountId) -> Vec<CurrencyId> {
// Get universal fee currency order list
let mut fee_currency_list: Vec<CurrencyId> =
UniversalFeeCurrencyOrderList::<T>::get().into_iter().collect();
// Get user default fee currency
if let Some(default_fee_currency) = UserDefaultFeeCurrency::<T>::get(&account_id) {
if let Some(index) = fee_currency_list.iter().position(|&c| c == default_fee_currency) {
fee_currency_list.remove(index);
}
let first_fee_currency_index = 0;
fee_currency_list.insert(first_fee_currency_index, default_fee_currency);
};
fee_currency_list
}
fn get_fee_currency_and_fee_amount(
who: &T::AccountId,
fee_amount: Balance,
) -> Result<(CurrencyId, Balance, Price, Price), Error<T>> {
let fee_currency_list = Self::get_fee_currency_list(who);
// charge the fee by the order of the above order list.
// first to check whether the user has the asset. If no, pass it. If yes, try to make
// transaction in the DEX in exchange for BNC
for currency_id in fee_currency_list {
// If it is mainnet currency
if currency_id == BNC {
if T::MultiCurrency::ensure_can_withdraw(currency_id, who, fee_amount).is_ok() {
return Ok((currency_id, fee_amount, Price::one(), Price::one()));
}
} else {
let (fee_amount, price_in, price_out) =
T::PriceFeeder::get_oracle_amount_by_currency_and_amount_in(
&BNC,
fee_amount,
¤cy_id,
)
.ok_or(Error::<T>::ConversionError)?;
if T::MultiCurrency::ensure_can_withdraw(currency_id, who, fee_amount).is_ok() {
return Ok((currency_id, fee_amount, price_in, price_out));
}
}
}
Err(Error::<T>::NotEnoughBalance)
}
fn charge_extra_fee(
who: &T::AccountId,
extra_fee_currency: CurrencyId,
extra_fee_amount: Balance,
extra_fee_receiver: &T::AccountId,
) -> Result<(), Error<T>> {
let fee_currency_list = Self::get_fee_currency_list(who);
// charge the fee by the order of the above order list.
// first to check whether the user has the asset. If no, pass it. If yes, try to make
// transaction in the DEX in exchange for BNC
let mut fee_info = None;
for currency_id in fee_currency_list {
// If it is mainnet currency
if currency_id == extra_fee_currency {
if T::MultiCurrency::ensure_can_withdraw(extra_fee_currency, who, extra_fee_amount)
.is_ok()
{
fee_info = Some((currency_id, extra_fee_amount));
break;
}
} else {
match Self::ensure_can_swap(who, currency_id, extra_fee_currency, extra_fee_amount)
{
Ok(amount_in) => {
fee_info = Some((currency_id, amount_in));
break;
},
Err(_) => {},
}
}
}
match fee_info {
Some((fee_currency, fee_amount)) =>
if fee_currency == extra_fee_currency {
T::MultiCurrency::transfer(fee_currency, who, extra_fee_receiver, fee_amount)
.map_err(|_| Error::<T>::NotEnoughBalance)?;
Ok(())
} else {
let from_asset_id = Self::get_currency_asset_id(fee_currency)?;
let to_asset_id = Self::get_currency_asset_id(extra_fee_currency)?;
let path = vec![from_asset_id, to_asset_id];
T::DexOperator::inner_swap_assets_for_exact_assets(
who,
extra_fee_amount,
fee_amount,
&path,
extra_fee_receiver,
)
.map_err(|_| Error::<T>::NotEnoughBalance)?;
Ok(())
},
None => Err(Error::<T>::ConversionError),
}
}
/// This function is for runtime-api to call
pub fn cal_fee_token_and_amount(
who: &T::AccountId,
fee: Balance,
_utx: &<T as frame_system::Config>::RuntimeCall,
) -> Result<(CurrencyId, Balance), Error<T>> {
let (fee_currency, fee_amount, _, _) = Self::get_fee_currency_and_fee_amount(who, fee)
.map_err(|_| Error::<T>::NotEnoughBalance)?;
Ok((fee_currency, fee_amount))
}
fn get_currency_asset_id(currency_id: CurrencyId) -> Result<AssetId, Error<T>> {
let asset_id: AssetId =
AssetId::try_convert_from(currency_id, T::ParachainId::get().into())
.map_err(|_| Error::<T>::ConversionError)?;
Ok(asset_id)
}
fn ensure_can_swap(
who: &T::AccountId,
from_currency: CurrencyId,
to_currency: CurrencyId,
amount_out: Balance,
) -> Result<Balance, Error<T>> {
// If it is other assets, go to exchange fee amount.
let from_asset_id =
Self::get_currency_asset_id(from_currency).map_err(|_| Error::<T>::ConversionError)?;
let to_asset_id =
Self::get_currency_asset_id(to_currency).map_err(|_| Error::<T>::ConversionError)?;
let path = vec![from_asset_id, to_asset_id];
match T::DexOperator::get_amount_in_by_path(amount_out, &path) {
Ok(amounts) => {
let amount_in = amounts[0];
T::MultiCurrency::ensure_can_withdraw(from_currency, who, amount_in)
.map_err(|_| Error::<T>::NotEnoughBalance)?;
Ok(amount_in)
},
Err(_) => Err(Error::<T>::NotEnoughBalance)?,
}
}
}
impl<T: Config> BalanceCmp<T::AccountId> for Pallet<T> {
type Error = Error<T>;
/// Compares the balance of a specific `currency` for a given `account` against an `amount`
/// while considering different currency precisions.
///
/// # Parameters
/// - `account`: The account ID whose balance will be checked.
/// - `currency`: The currency ID to be compared.
/// - `amount`: The amount to compare against the account's balance, with the precision
/// specified by `amount_precision`.
/// - `amount_precision`: The precision of the `amount` specified. If greater than 18, the
/// precision of the `currency` will be adjusted accordingly.
///
/// # Returns
/// - `Ok(std::cmp::Ordering)`: Returns the ordering result (`Less`, `Equal`, `Greater`) based
/// on the comparison between the adjusted balance and the adjusted amount.
/// - `Err(Error<T>)`: Returns an error if the currency is not supported.
fn cmp_with_precision(
account: &T::AccountId,
currency: &CurrencyId,
amount: u128,
amount_precision: u32,
) -> Result<Ordering, Error<T>> {
// Get the reducible balance for the specified account and currency.
let mut balance = T::MultiCurrency::reducible_balance(
*currency,
account,
Preservation::Preserve,
Fortitude::Polite,
);
// Define the standard precision as 18 decimal places.
let standard_precision: u32 = amount_precision.max(18);
// Adjust the amount to the standard precision.
let precision_offset = standard_precision.saturating_sub(amount_precision);
let adjust_precision = 10u128.pow(precision_offset);
let amount = amount.saturating_mul(adjust_precision);
// Adjust the balance based on currency type.
let balance_precision_offset = match *currency {
WETH | GLMR | VGLMR | MANTA | VMANTA => standard_precision.saturating_sub(18),
BNC | VBNC => standard_precision.saturating_sub(12),
DOT | VDOT => standard_precision.saturating_sub(10),
_ => return Err(Error::<T>::CurrencyNotSupport),
};
// Apply precision adjustment to balance.
balance = balance.saturating_mul(10u128.pow(balance_precision_offset));
// Compare the adjusted balance with the input amount.
Ok(balance.cmp(&amount))
}
}