Skip to content

Commit

Permalink
wip parachain utils
Browse files Browse the repository at this point in the history
  • Loading branch information
seunlanlege committed Feb 3, 2022
1 parent adc2b1a commit 7ad33f5
Show file tree
Hide file tree
Showing 19 changed files with 182 additions and 214 deletions.
25 changes: 10 additions & 15 deletions frame/assets-registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ pub mod pallet {
let local_admin = <LocalAdmin<T>>::get();
let foreign_admin = <ForeignAdmin<T>>::get();
match current_candidate_status {
None => {
None =>
if Some(who) == local_admin {
<AssetsMappingCandidates<T>>::insert(
(local_asset_id, foreign_asset_id),
Expand All @@ -303,20 +303,17 @@ pub mod pallet {
(local_asset_id, foreign_asset_id),
CandidateStatus::ForeignAdminApproved,
);
}
},
Some(CandidateStatus::LocalAdminApproved) => {
},
Some(CandidateStatus::LocalAdminApproved) =>
if Some(who) == foreign_admin {
Self::set_location(local_asset_id, foreign_asset_id.clone())?;
<AssetsMappingCandidates<T>>::remove((local_asset_id, foreign_asset_id));
}
},
Some(CandidateStatus::ForeignAdminApproved) => {
},
Some(CandidateStatus::ForeignAdminApproved) =>
if Some(who) == local_admin {
Self::set_location(local_asset_id, foreign_asset_id.clone())?;
<AssetsMappingCandidates<T>>::remove((local_asset_id, foreign_asset_id));
}
},
},
};
Ok(().into())
}
Expand All @@ -327,9 +324,8 @@ pub mod pallet {
type Success = T::AccountId;
fn try_origin(o: T::Origin) -> Result<Self::Success, T::Origin> {
o.into().and_then(|o| match (o, LocalAdmin::<T>::try_get()) {
(frame_system::RawOrigin::Signed(ref who), Ok(ref f)) if who == f => {
Ok(who.clone())
},
(frame_system::RawOrigin::Signed(ref who), Ok(ref f)) if who == f =>
Ok(who.clone()),
(r, _) => Err(T::Origin::from(r)),
})
}
Expand All @@ -346,9 +342,8 @@ pub mod pallet {
type Success = T::AccountId;
fn try_origin(o: T::Origin) -> Result<Self::Success, T::Origin> {
o.into().and_then(|o| match (o, ForeignAdmin::<T>::try_get()) {
(frame_system::RawOrigin::Signed(ref who), Ok(ref f)) if who == f => {
Ok(who.clone())
},
(frame_system::RawOrigin::Signed(ref who), Ok(ref f)) if who == f =>
Ok(who.clone()),
(r, _) => Err(T::Origin::from(r)),
})
}
Expand Down
11 changes: 5 additions & 6 deletions frame/bonded-finance/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,10 @@ pub mod pallet {
// Continue on admin origin
(_, Ok(_)) => {},
// Only issuer is allowed
(Ok(account), _) => {
(Ok(account), _) =>
if issuer != account {
return Err(DispatchError::BadOrigin);
}
},
return Err(DispatchError::BadOrigin)
},
_ => return Err(DispatchError::BadOrigin),
};
let offer_account = Self::account_id(offer_id);
Expand Down Expand Up @@ -327,8 +326,8 @@ pub mod pallet {
Error::<T>::OfferCompleted
);
ensure!(
nb_of_bonds > BalanceOf::<T>::zero()
&& nb_of_bonds <= offer.nb_of_bonds,
nb_of_bonds > BalanceOf::<T>::zero() &&
nb_of_bonds <= offer.nb_of_bonds,
Error::<T>::InvalidNumberOfBonds
);
// can't overflow, subsumed by `offer.valid()` in
Expand Down
5 changes: 2 additions & 3 deletions frame/call-filter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,8 @@ pub mod pallet {
BoundedVec::try_from(pallet_name.as_bytes().to_vec()),
BoundedVec::try_from(function_name.as_bytes().to_vec()),
) {
(Ok(pallet_name), Ok(function_name)) => {
DisabledCalls::<T>::contains_key(CallFilterEntry { pallet_name, function_name })
},
(Ok(pallet_name), Ok(function_name)) =>
DisabledCalls::<T>::contains_key(CallFilterEntry { pallet_name, function_name }),
_ => false,
}
}
Expand Down
4 changes: 2 additions & 2 deletions frame/composable-traits/src/call_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct CallFilterEntry<S: Get<u32>> {

impl<S: Get<u32>> CallFilterEntry<S> {
pub fn valid(&self) -> bool {
sp_std::str::from_utf8(&self.pallet_name).is_ok()
&& sp_std::str::from_utf8(&self.function_name).is_ok()
sp_std::str::from_utf8(&self.pallet_name).is_ok() &&
sp_std::str::from_utf8(&self.function_name).is_ok()
}
}
2 changes: 1 addition & 1 deletion frame/composable-traits/src/lending/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl<LiquidationStrategyId, Asset: Eq> Validate<MarketModelValid>
{
fn validate(self) -> Result<Self, &'static str> {
if self.updatable.collateral_factor < MoreThanOneFixedU128::one() {
return Err("collateral factor must be >=1");
return Err("collateral factor must be >=1")
}

let interest_rate_model =
Expand Down
21 changes: 9 additions & 12 deletions frame/crowdloan-rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,10 @@ pub mod pallet {
// The user should have claimed the upfront payment + the vested
// amount until this window point.
let vested_reward = reward.total - upfront_payment;
upfront_payment
+ (vested_reward
.saturating_mul(T::Convert::convert(vesting_window))
/ T::Convert::convert(reward.vesting_period))
upfront_payment +
(vested_reward
.saturating_mul(T::Convert::convert(vesting_window)) /
T::Convert::convert(reward.vesting_period))
}
};
let available_to_claim = should_have_claimed - reward.claimed;
Expand Down Expand Up @@ -453,8 +453,7 @@ pub mod pallet {
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::associate { reward_account, proof } = call {
if Associations::<T>::get(reward_account).is_some() {
return InvalidTransaction::Custom(ValidityError::AlreadyAssociated as u8)
.into();
return InvalidTransaction::Custom(ValidityError::AlreadyAssociated as u8).into()
}
let remote_account =
get_remote_account::<T>(proof.clone(), reward_account, T::Prefix::get())
Expand All @@ -465,14 +464,12 @@ pub mod pallet {
})?;
match Rewards::<T>::get(remote_account.clone()) {
None => InvalidTransaction::Custom(ValidityError::NoReward as u8).into(),
Some(reward) if reward.total.is_zero() => {
InvalidTransaction::Custom(ValidityError::NoReward as u8).into()
},
Some(_) => {
Some(reward) if reward.total.is_zero() =>
InvalidTransaction::Custom(ValidityError::NoReward as u8).into(),
Some(_) =>
ValidTransaction::with_tag_prefix("CrowdloanRewardsAssociationCheck")
.and_provides(remote_account)
.build()
},
.build(),
}
} else {
Err(InvalidTransaction::Call.into())
Expand Down
2 changes: 1 addition & 1 deletion frame/crowdloan-rewards/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl<'de> frame_support::Deserialize<'de> for EthereumAddress {
if s.len() != 40 {
return Err(frame_support::serde::de::Error::custom(
"Bad length of Ethereum address (should be 42 including '0x')",
));
))
}
let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s)
.map_err(|e| frame_support::serde::de::Error::custom(format!("{:?}", e)))?;
Expand Down
26 changes: 13 additions & 13 deletions frame/curve-amm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,7 @@ pub mod pallet {
let n = FixedU128::saturating_from_integer(u128::try_from(xp_f.len()).ok()?);
let sum = xp_f.iter().try_fold(zero, |s, x| s.checked_add(x))?;
if sum == zero {
return Some(zero);
return Some(zero)
}
let mut d = sum;

Expand All @@ -895,10 +895,10 @@ pub mod pallet {

if d > d_prev {
if d.checked_sub(&d_prev)? <= prec {
return Some(d);
return Some(d)
}
} else if d_prev.checked_sub(&d)? <= prec {
return Some(d);
return Some(d)
}
}
None
Expand Down Expand Up @@ -934,14 +934,14 @@ pub mod pallet {

// Same coin
if i == j {
return None;
return None
}
// j above n
if j >= xp_f.len() {
return None;
return None
}
if i >= xp_f.len() {
return None;
return None
}
let d_f = Self::get_d(xp_f, ann_f)?;
let mut c = d_f;
Expand All @@ -957,7 +957,7 @@ pub mod pallet {
} else if k != j {
x_k = *xp_k;
} else {
continue;
continue
}
// s = s + x_k
s = s.checked_add(&x_k)?;
Expand Down Expand Up @@ -987,10 +987,10 @@ pub mod pallet {
// Equality with the specified precision
if y > y_prev {
if y.checked_sub(&y_prev)? <= prec {
return Some(y);
return Some(y)
}
} else if y_prev.checked_sub(&y)? <= prec {
return Some(y);
return Some(y)
}
}

Expand Down Expand Up @@ -1022,15 +1022,15 @@ pub mod pallet {
let n = FixedU128::try_from(xp_f.len() as u128).ok()?;

if i >= xp_f.len() {
return None;
return None
}

let mut c = d_f;
let mut s = zero;

for (k, xp_k) in xp_f.iter().enumerate() {
if k == i {
continue;
continue
}

let x = xp_k;
Expand All @@ -1056,10 +1056,10 @@ pub mod pallet {
// Equality with the specified precision
if y > y_prev {
if y.checked_sub(&y_prev)? <= prec {
return Some(y);
return Some(y)
}
} else if y_prev.checked_sub(&y)? <= prec {
return Some(y);
return Some(y)
}
}

Expand Down
13 changes: 6 additions & 7 deletions frame/democracy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,7 @@ pub mod pallet {
if let Some((e_proposal_id, _)) = <NextExternal<T>>::get() {
ensure!(id == e_proposal_id, Error::<T>::ProposalMissing);
} else {
return Err(Error::<T>::NoProposal.into());
return Err(Error::<T>::NoProposal.into())
}

let mut existing_vetoers =
Expand Down Expand Up @@ -1222,9 +1222,8 @@ pub mod pallet {

let (provider, deposit, since, expiry) = <Preimages<T>>::get(&id)
.and_then(|m| match m {
PreimageStatus::Available { provider, deposit, since, expiry, .. } => {
Some((provider, deposit, since, expiry))
},
PreimageStatus::Available { provider, deposit, since, expiry, .. } =>
Some((provider, deposit, since, expiry)),
_ => None,
})
.ok_or(Error::<T>::PreimageMissing)?;
Expand Down Expand Up @@ -1985,8 +1984,8 @@ impl<T: Config> Pallet<T> {
// of unbaked referendum is bounded by this number. In case those number have changed in a
// runtime upgrade the formula should be adjusted but the bound should still be sensible.
<LowestUnbaked<T>>::mutate(|ref_index| {
while *ref_index < last
&& Self::referendum_info(*ref_index)
while *ref_index < last &&
Self::referendum_info(*ref_index)
.map_or(true, |info| matches!(info, ReferendumInfo::Finished { .. }))
{
*ref_index += 1
Expand Down Expand Up @@ -2056,7 +2055,7 @@ impl<T: Config> Pallet<T> {
Ok(0) => return Err(Error::<T>::PreimageMissing.into()),
_ => {
sp_runtime::print("Failed to decode `PreimageStatus` variant");
return Err(Error::<T>::PreimageMissing.into());
return Err(Error::<T>::PreimageMissing.into())
},
}

Expand Down
34 changes: 17 additions & 17 deletions frame/lending/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,17 +259,17 @@ pub mod pallet {
let one_read = T::DbWeight::get().reads(1);
weight += u64::from(call_counters.now) * <T as Config>::WeightInfo::now();
weight += u64::from(call_counters.read_markets) * one_read;
weight += u64::from(call_counters.accrue_interest)
* <T as Config>::WeightInfo::accrue_interest();
weight += u64::from(call_counters.accrue_interest) *
<T as Config>::WeightInfo::accrue_interest();
weight += u64::from(call_counters.account_id) * <T as Config>::WeightInfo::account_id();
weight += u64::from(call_counters.available_funds)
* <T as Config>::WeightInfo::available_funds();
weight += u64::from(call_counters.handle_withdrawable)
* <T as Config>::WeightInfo::handle_withdrawable();
weight += u64::from(call_counters.handle_depositable)
* <T as Config>::WeightInfo::handle_depositable();
weight += u64::from(call_counters.handle_must_liquidate)
* <T as Config>::WeightInfo::handle_must_liquidate();
weight += u64::from(call_counters.available_funds) *
<T as Config>::WeightInfo::available_funds();
weight += u64::from(call_counters.handle_withdrawable) *
<T as Config>::WeightInfo::handle_withdrawable();
weight += u64::from(call_counters.handle_depositable) *
<T as Config>::WeightInfo::handle_depositable();
weight += u64::from(call_counters.handle_must_liquidate) *
<T as Config>::WeightInfo::handle_must_liquidate();
weight
}

Expand All @@ -278,7 +278,7 @@ pub mod pallet {
let signer = Signer::<T, <T as Config>::AuthorityId>::all_accounts();
if !signer.can_sign() {
log::warn!("No signer");
return;
return
}
for (market_id, account, _) in DebtIndex::<T>::iter() {
let results = signer.send_signed_transaction(|_account| Call::liquidate {
Expand Down Expand Up @@ -996,8 +996,8 @@ pub mod pallet {
let existing_borrow_share =
Percent::from_rational(existing_borrow_amount, total_borrow_amount);
let new_borrow_share = Percent::from_rational(amount_to_borrow, total_borrow_amount);
Ok((market_index * new_borrow_share.into())
+ (account_interest_index * existing_borrow_share.into()))
Ok((market_index * new_borrow_share.into()) +
(account_interest_index * existing_borrow_share.into()))
}

fn can_borrow(
Expand All @@ -1010,7 +1010,7 @@ pub mod pallet {
let latest_borrow_timestamp = BorrowTimestamp::<T>::get(market_id, debt_owner);
if let Some(time) = latest_borrow_timestamp {
if time >= Self::last_block_timestamp() {
return Err(Error::<T>::InvalidTimestampOnBorrowRequest.into());
return Err(Error::<T>::InvalidTimestampOnBorrowRequest.into())
}
}

Expand Down Expand Up @@ -1558,8 +1558,8 @@ pub mod pallet {

let market_account = Self::account_id(market_id);
ensure!(
<T as Config>::MultiCurrency::can_deposit(market.collateral, account, amount)
== DepositConsequence::Success,
<T as Config>::MultiCurrency::can_deposit(market.collateral, account, amount) ==
DepositConsequence::Success,
Error::<T>::TransferFailed
);
ensure!(
Expand Down Expand Up @@ -1602,7 +1602,7 @@ pub mod pallet {
account_interest_index: ZeroToOneFixedU128,
) -> Result<Option<u64>, DispatchError> {
if principal.is_zero() {
return Ok(None);
return Ok(None)
}
let principal = LiftedFixedBalance::saturating_from_integer(principal.into());
let balance = principal
Expand Down
Loading

0 comments on commit 7ad33f5

Please sign in to comment.