Skip to content

Commit

Permalink
General Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
JuaniRios authored and lrazovic committed Feb 11, 2025
1 parent 5ac90e4 commit 15d9c00
Show file tree
Hide file tree
Showing 24 changed files with 794 additions and 1,149 deletions.
21 changes: 7 additions & 14 deletions pallets/funding/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,21 +542,14 @@ mod benchmarks {

// Storage
for (bid_params, price) in extrinsic_bids_post_bucketing.clone() {
let bid_filter = BidInfoFilter::<T> {
id: None,
project_id: Some(project_id),
bidder: Some(bidder.clone()),
status: Some(BidStatus::YetUnknown),
original_ct_amount: Some(bid_params.amount),
original_ct_usd_price: Some(price),
funding_asset: Some(AcceptedFundingAsset::USDT),
funding_asset_amount_locked: None,
mode: Some(bid_params.mode),
plmc_bond: None,
when: None,
};
Bids::<T>::iter_prefix_values((project_id,))
.find(|stored_bid| bid_filter.matches_bid(stored_bid))
.find(|stored_bid| {
stored_bid.bidder == bidder.clone() &&
stored_bid.original_ct_amount == bid_params.amount &&
stored_bid.original_ct_usd_price == price &&
stored_bid.funding_asset == AcceptedFundingAsset::USDT &&
stored_bid.mode == bid_params.mode
})
.expect("bid not found");
}
}
Expand Down
8 changes: 5 additions & 3 deletions pallets/funding/src/functions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ const QUERY_RESPONSE_TIME_WINDOW_BLOCKS: u32 = 20u32;
mod application;
#[path = "3_auction.rs"]
mod auction;
#[path = "7_ct_migration.rs"]
#[path = "6_ct_migration.rs"]
mod ct_migration;
#[path = "2_evaluation.rs"]
mod evaluation;
#[path = "5_funding_end.rs"]
#[path = "4_funding_end.rs"]
mod funding_end;
pub mod misc;
#[path = "6_settlement.rs"]
#[path = "5_settlement.rs"]
mod settlement;

pub mod runtime_api;
File renamed without changes.
106 changes: 1 addition & 105 deletions pallets/funding/src/instantiator/calculations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,6 @@ impl<
self.execute(|| T::FundingCurrency::minimum_balance(asset_id))
}

pub fn get_funding_asset_unit(&mut self, asset_id: AssetIdOf<T>) -> Balance {
self.execute(|| {
let decimals = T::FundingCurrency::decimals(asset_id);
10u128.pow(decimals as u32)
})
}

pub fn get_ct_account_deposit(&self) -> Balance {
<T as crate::Config>::ContributionTokenCurrency::deposit_required(One::one())
}

pub fn calculate_evaluation_plmc_spent(
&mut self,
evaluations: Vec<EvaluationParams<T>>,
Expand Down Expand Up @@ -72,7 +61,7 @@ impl<
while !amount_to_bid.is_zero() {
let bid_amount = if amount_to_bid <= bucket.amount_left { amount_to_bid } else { bucket.amount_left };
output.push((
BidParams::from((bid.bidder.clone(), bid.investor_type.clone(), bid_amount, bid.mode, bid.asset)),
BidParams::from((bid.bidder.clone(), bid.investor_type, bid_amount, bid.mode, bid.asset)),
bucket.current_price,
));
bucket.update(bid_amount);
Expand Down Expand Up @@ -170,18 +159,6 @@ impl<
output.merge_accounts(MergeOperation::Add)
}

pub fn calculate_auction_plmc_spent_post_wap(
&mut self,
bids: &Vec<BidParams<T>>,
project_metadata: ProjectMetadataOf<T>,
) -> Vec<UserToPLMCBalance<T>> {
let plmc_charged =
self.calculate_auction_plmc_charged_from_all_bids_made_or_with_bucket(bids, project_metadata.clone(), None);
let plmc_returned = self.calculate_auction_plmc_returned_from_all_bids_made(bids, project_metadata.clone());

plmc_charged.subtract_accounts(plmc_returned)
}

pub fn calculate_auction_funding_asset_charged_with_given_price(
&mut self,
bids: &Vec<BidParams<T>>,
Expand Down Expand Up @@ -273,45 +250,6 @@ impl<
output.merge_accounts(MergeOperation::Add)
}

pub fn calculate_auction_funding_asset_spent_post_wap(
&mut self,
bids: &Vec<BidParams<T>>,
project_metadata: ProjectMetadataOf<T>,
) -> Vec<UserToFundingAsset<T>> {
let funding_asset_charged = self.calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket(
bids,
project_metadata.clone(),
None,
);
let funding_asset_returned =
self.calculate_auction_funding_asset_returned_from_all_bids_made(bids, project_metadata.clone());

funding_asset_charged.subtract_accounts(funding_asset_returned)
}

/// Filters the bids that would be rejected after the auction ends.
pub fn filter_bids_after_auction(&self, bids: Vec<BidParams<T>>, total_cts: Balance) -> Vec<BidParams<T>> {
let mut filtered_bids: Vec<BidParams<T>> = Vec::new();
let sorted_bids = bids;
let mut total_cts_left = total_cts;
for bid in sorted_bids {
if total_cts_left >= bid.amount {
total_cts_left.saturating_reduce(bid.amount);
filtered_bids.push(bid);
} else if !total_cts_left.is_zero() {
filtered_bids.push(BidParams::from((
bid.bidder.clone(),
bid.investor_type,
total_cts_left,
bid.mode,
bid.asset,
)));
total_cts_left = Zero::zero();
}
}
filtered_bids
}

pub fn add_otm_fee_to(
&mut self,
balance: &mut Balance,
Expand Down Expand Up @@ -351,24 +289,6 @@ impl<
*balance += funding_asset_bond;
}

pub fn generic_map_merge_reduce<M: Clone, K: Ord + Clone, S: Clone>(
&self,
mappings: Vec<Vec<M>>,
key_extractor: impl Fn(&M) -> K,
initial_state: S,
merge_reduce: impl Fn(&M, S) -> S,
) -> Vec<(K, S)> {
let mut output = BTreeMap::new();
for mut map in mappings {
for item in map.drain(..) {
let key = key_extractor(&item);
let new_state = merge_reduce(&item, output.get(&key).cloned().unwrap_or(initial_state.clone()));
output.insert(key, new_state);
}
}
output.into_iter().collect()
}

/// Merge the given mappings into one mapping, where the values are merged using the given
/// merge operation.
///
Expand Down Expand Up @@ -604,23 +524,6 @@ impl<
balances
}

pub fn calculate_total_reward_for_evaluation(
&self,
evaluation: EvaluationInfoOf<T>,
reward_info: RewardInfo,
) -> Balance {
let early_reward_weight =
Perquintill::from_rational(evaluation.early_usd_amount, reward_info.early_evaluator_total_bonded_usd);
let normal_reward_weight = Perquintill::from_rational(
evaluation.late_usd_amount.saturating_add(evaluation.early_usd_amount),
reward_info.normal_evaluator_total_bonded_usd,
);
let early_evaluators_rewards = early_reward_weight * reward_info.early_evaluator_reward_pot;
let normal_evaluators_rewards = normal_reward_weight * reward_info.normal_evaluator_reward_pot;

early_evaluators_rewards.saturating_add(normal_evaluators_rewards)
}

// We assume a single bid can cover the whole first bucket. Make sure the ticket sizes allow this.
pub fn generate_bids_from_bucket(
&self,
Expand Down Expand Up @@ -677,13 +580,6 @@ impl<
bids
}

pub fn remainder_round_block(&self) -> BlockNumberFor<T> {
T::EvaluationRoundDuration::get() +
T::AuctionRoundDuration::get() +
T::CommunityRoundDuration::get() +
One::one()
}

#[cfg(feature = "std")]
pub fn eth_key_and_sig_from(
&mut self,
Expand Down
66 changes: 8 additions & 58 deletions pallets/funding/src/instantiator/chain_interactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,25 +107,6 @@ impl<
self.execute(|| <T as Config>::ContributionTokenCurrency::balance(project_id, &user))
}

pub fn get_all_free_plmc_balances(&mut self) -> Vec<UserToPLMCBalance<T>> {
let user_keys = self.execute(|| frame_system::Account::<T>::iter_keys().collect());
self.get_free_plmc_balances_for(user_keys)
}

pub fn get_all_reserved_plmc_balances(
&mut self,
reserve_type: <T as Config>::RuntimeHoldReason,
) -> Vec<UserToPLMCBalance<T>> {
let user_keys = self.execute(|| frame_system::Account::<T>::iter_keys().collect());
self.get_reserved_plmc_balances_for(user_keys, reserve_type)
}

pub fn get_all_free_funding_asset_balances(&mut self, asset_id: AssetIdOf<T>) -> Vec<UserToFundingAsset<T>> {
let user_keys =
self.execute(|| frame_system::Account::<T>::iter_keys().map(|a| (a, asset_id.clone())).collect());
self.get_free_funding_asset_balances_for(user_keys)
}

pub fn get_plmc_total_supply(&mut self) -> Balance {
self.execute(<T as Config>::NativeCurrency::total_issuance)
}
Expand Down Expand Up @@ -324,43 +305,11 @@ impl<
self.do_reserved_plmc_assertions(expected_reserved_plmc_balances, HoldReason::Evaluation.into());
}

pub fn finalized_bids_assertions(
&mut self,
project_id: ProjectId,
bid_expectations: Vec<BidInfoFilter<T>>,
expected_ct_sold: Balance,
) {
let project_metadata = self.get_project_metadata(project_id);
let project_details = self.get_project_details(project_id);
let project_bids = self.execute(|| Bids::<T>::iter_prefix_values((project_id,)).collect::<Vec<_>>());

for filter in bid_expectations {
let _found_bid = project_bids.iter().find(|bid| filter.matches_bid(bid)).unwrap();
}

// Remaining CTs are updated
assert_eq!(
project_details.remaining_contribution_tokens,
project_metadata.total_allocation_size - expected_ct_sold,
"Remaining CTs are incorrect"
);
}

pub fn assert_plmc_free_balance(&mut self, account_id: AccountIdOf<T>, expected_balance: Balance) {
let real_balance = self.get_free_plmc_balance_for(account_id.clone());
assert_eq!(real_balance, expected_balance, "Unexpected PLMC balance for user {:?}", account_id);
}

pub fn assert_plmc_held_balance(
&mut self,
account_id: AccountIdOf<T>,
expected_balance: Balance,
hold_reason: <T as Config>::RuntimeHoldReason,
) {
let real_balance = self.get_reserved_plmc_balance_for(account_id.clone(), hold_reason);
assert_eq!(real_balance, expected_balance, "Unexpected PLMC balance for user {:?}", account_id);
}

pub fn assert_funding_asset_free_balance(
&mut self,
account_id: AccountIdOf<T>,
Expand Down Expand Up @@ -465,6 +414,12 @@ impl<
self.mint_funding_asset_to(necessary_funding_assets);
}

pub fn mint_necessary_tokens_for_evaluations(&mut self, evaluations: Vec<EvaluationParams<T>>) {
let plmc_required = self.calculate_evaluation_plmc_spent(evaluations.clone());
self.mint_plmc_ed_if_required(plmc_required.accounts());
self.mint_plmc_to(plmc_required);
}

pub fn bid_for_users(&mut self, project_id: ProjectId, bids: Vec<BidParams<T>>) -> DispatchResultWithPostInfo {
let project_policy = self.get_project_metadata(project_id).policy_ipfs_cid.unwrap();

Expand Down Expand Up @@ -514,10 +469,6 @@ impl<
self.execute(|| Bids::<T>::iter_prefix_values((project_id,)).collect())
}

pub fn get_bid(&mut self, bid_id: u32) -> BidInfoOf<T> {
self.execute(|| Bids::<T>::iter_values().find(|bid| bid.id == bid_id).unwrap())
}

// Used to check all the USDT/USDC/DOT was paid to the issuer funding account
pub fn assert_total_funding_paid_out(&mut self, project_id: ProjectId, bids: Vec<BidInfoOf<T>>) {
let project_metadata = self.get_project_metadata(project_id);
Expand Down Expand Up @@ -805,9 +756,7 @@ impl<

let status = self.go_to_next_state(project_id);

if status == ProjectStatus::FundingSuccessful {
self.test_ct_not_created_for(project_id);
} else if status == ProjectStatus::FundingFailed {
if status == ProjectStatus::FundingSuccessful || status == ProjectStatus::FundingFailed {
self.test_ct_not_created_for(project_id);
} else {
panic!("Project should be in FundingSuccessful or FundingFailed status");
Expand All @@ -834,6 +783,7 @@ impl<
);

assert!(matches!(self.go_to_next_state(project_id), ProjectStatus::SettlementStarted(_)));
self.test_ct_created_for(project_id);

self.settle_project(project_id, mark_as_settled);

Expand Down
45 changes: 0 additions & 45 deletions pallets/funding/src/instantiator/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,6 @@ macro_rules! assert_close_enough {
};
}

#[macro_export]
macro_rules! call_and_is_ok {
($inst: expr, $( $call: expr ),* ) => {
$inst.execute(|| {
$(
let result = $call;
assert!(result.is_ok(), "Call failed: {:?}", result);
)*
})
};
}
#[macro_export]
macro_rules! find_event {
($runtime:ty, $pattern:pat, $($field_name:ident == $field_value:expr),+) => {
Expand All @@ -77,37 +66,3 @@ macro_rules! find_event {
}
};
}

#[macro_export]
macro_rules! extract_from_event {
($env: expr, $pattern:pat, $field:ident) => {
$env.execute(|| {
let events = System::events();

events.iter().find_map(|event_record| {
if let frame_system::EventRecord { event: RuntimeEvent::PolimecFunding($pattern), .. } = event_record {
Some($field.clone())
} else {
None
}
})
})
};
}

#[macro_export]
macro_rules! define_names {
($($name:ident: $id:expr, $label:expr);* $(;)?) => {
$(
pub const $name: AccountId = $id;
)*

pub fn names() -> std::collections::HashMap<AccountId, &'static str> {
let mut names = std::collections::HashMap::new();
$(
names.insert($name, $label);
)*
names
}
};
}
2 changes: 1 addition & 1 deletion pallets/funding/src/instantiator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use frame_support::{
metadata::Inspect as MetadataInspect, roles::Inspect as RolesInspect, Inspect as FungiblesInspect,
Mutate as FungiblesMutate,
},
AccountTouch, Get, OnFinalize, OnIdle, OnInitialize,
Get, OnFinalize, OnIdle, OnInitialize,
},
weights::Weight,
Parameter,
Expand Down
Loading

0 comments on commit 15d9c00

Please sign in to comment.