Skip to content

Commit

Permalink
blockdeep review changes
Browse files Browse the repository at this point in the history
  • Loading branch information
JuaniRios committed Oct 14, 2024
1 parent e9408f0 commit b80f3f4
Show file tree
Hide file tree
Showing 16 changed files with 237 additions and 324 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 6 additions & 7 deletions pallets/funding/src/functions/1_application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use super::*;

impl<T: Config> Pallet<T> {
fn project_validation(
project_metadata: ProjectMetadataOf<T>,
project_metadata: &ProjectMetadataOf<T>,
issuer: AccountIdOf<T>,
did: Did,
) -> Result<(ProjectMetadataOf<T>, ProjectDetailsOf<T>, BucketOf<T>), DispatchError> {
) -> Result<(ProjectDetailsOf<T>, BucketOf<T>), DispatchError> {
if let Err(error) = project_metadata.is_valid() {
let pallet_error = match error {
MetadataError::PriceTooLow => Error::<T>::PriceTooLow,
Expand Down Expand Up @@ -51,7 +51,7 @@ impl<T: Config> Pallet<T> {

let bucket: BucketOf<T> = Self::create_bucket_from_metadata(&project_metadata)?;

Ok((project_metadata, project_details, bucket))
Ok((project_details, bucket))
}

#[transactional]
Expand All @@ -67,8 +67,7 @@ impl<T: Config> Pallet<T> {
// * Validity checks *
ensure!(maybe_active_project.is_none(), Error::<T>::HasActiveProject);

let (project_metadata, project_details, bucket) =
Self::project_validation(project_metadata, issuer.clone(), did.clone())?;
let (project_details, bucket) = Self::project_validation(&project_metadata, issuer.clone(), did.clone())?;

// Each project needs an escrow system account to temporarily hold the USDT/USDC. We need to create it by depositing `ED` amount of PLMC into it.
// This should be paid by the issuer.
Expand Down Expand Up @@ -109,8 +108,8 @@ impl<T: Config> Pallet<T> {
ensure!(!project_details.is_frozen, Error::<T>::ProjectIsFrozen);

// * Calculate new variables *
let (new_project_metadata, project_details, bucket) =
Self::project_validation(new_project_metadata, issuer.clone(), project_details.issuer_did.clone())?;
let (project_details, bucket) =
Self::project_validation(&new_project_metadata, issuer.clone(), project_details.issuer_did.clone())?;

// * Update storage *
ProjectsMetadata::<T>::insert(project_id, new_project_metadata.clone());
Expand Down
51 changes: 3 additions & 48 deletions pallets/funding/src/functions/2_evaluation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,6 @@
use super::*;
use polimec_common::ProvideAssetPrice;
impl<T: Config> Pallet<T> {
/// Called by user extrinsic
/// Starts the evaluation round of a project. It needs to be called by the project issuer.
///
/// # Arguments
/// * `project_id` - The id of the project to start the evaluation round for.
///
/// # Storage access
/// * [`ProjectsDetails`] - Checking and updating the round status, transition points and freezing the project.
///
/// # Success path
/// The project information is found, its round status was in Application round, and It's not yet frozen.
/// The pertinent project info is updated on the storage, and the project is scheduled for automatic transition by on_initialize.
///
/// # Next step
/// Users will pond PLMC for this project, and when the time comes, the project will be transitioned
/// to the next round by `on_initialize` using [`do_evaluation_end`](Self::do_end_evaluation(project_id))
#[transactional]
pub fn do_start_evaluation(caller: AccountIdOf<T>, project_id: ProjectId) -> DispatchResult {
// * Get variables *
Expand All @@ -43,34 +27,6 @@ impl<T: Config> Pallet<T> {
)
}

/// Called automatically by on_initialize.
/// Ends the evaluation round, and sets the current round to `AuctionInitializePeriod` if it
/// reached enough PLMC bonding, or to `FundingFailed` if it didn't.
///
/// # Arguments
/// * `project_id` - The id of the project to end the evaluation round for.
///
/// # Storage access
/// * [`ProjectsDetails`] - Checking the round status and transition points for validity, and updating
/// the round status and transition points in case of success or failure of the evaluation.
/// * [`Evaluations`] - Checking that the threshold for PLMC bonded was reached, to decide
/// whether the project failed or succeeded.
///
/// # Possible paths
/// * Project achieves its evaluation goal. >=10% of the target funding was reached through bonding,
/// so the project is transitioned to the [`AuctionInitializePeriod`](ProjectStatus::AuctionInitializePeriod) round. The project information
/// is updated with the new transition points and round status.
///
/// * Project doesn't reach the evaluation goal - <10% of the target funding was reached
/// through bonding, so the project is transitioned to the `FundingFailed` round. The project
/// information is updated with the new rounds status and it is scheduled for automatic unbonding.
///
/// # Next step
/// * Bonding achieved - The issuer calls an extrinsic within the set period to initialize the
/// auction round. `auction` is called
///
/// * Bonding failed - `on_idle` at some point checks for failed evaluation projects, and
/// unbonds the evaluators funds.
#[transactional]
pub fn do_end_evaluation(project_id: ProjectId) -> DispatchResult {
// * Get variables *
Expand Down Expand Up @@ -110,7 +66,6 @@ impl<T: Config> Pallet<T> {
}
}

// Note: usd_amount needs to have the same amount of decimals as PLMC, so when multiplied by the plmc-usd price, it gives us the PLMC amount with the decimals we wanted.
#[transactional]
pub fn do_evaluate(
evaluator: &AccountIdOf<T>,
Expand Down Expand Up @@ -175,10 +130,10 @@ impl<T: Config> Pallet<T> {
T::NativeCurrency::hold(&HoldReason::Evaluation.into(), evaluator, plmc_bond)?;
Evaluations::<T>::insert((project_id, evaluator, evaluation_id), new_evaluation);
NextEvaluationId::<T>::set(evaluation_id.saturating_add(One::one()));
evaluation_round_info.total_bonded_usd += usd_amount;
evaluation_round_info.total_bonded_plmc += plmc_bond;
evaluation_round_info.total_bonded_usd = evaluation_round_info.total_bonded_usd.saturating_add(usd_amount);
evaluation_round_info.total_bonded_plmc = evaluation_round_info.total_bonded_plmc.saturating_add(plmc_bond);
ProjectsDetails::<T>::insert(project_id, project_details);
EvaluationCounts::<T>::mutate(project_id, |c| *c += 1);
EvaluationCounts::<T>::mutate(project_id, |c| *c = c.saturating_add(1));

// * Emit events *
Self::deposit_event(Event::Evaluation {
Expand Down
20 changes: 3 additions & 17 deletions pallets/funding/src/functions/3_auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
use super::*;

impl<T: Config> Pallet<T> {
/// Decides which bids are accepted and which are rejected.
/// Deletes and refunds the rejected ones, and prepares the project for the WAP calculation the next block
#[transactional]
pub fn do_end_auction(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
Expand Down Expand Up @@ -45,18 +43,6 @@ impl<T: Config> Pallet<T> {
}
}

/// Bid for a project in the bidding stage.
///
/// # Arguments
/// * `bidder` - The account that is bidding
/// * `project_id` - The project to bid for
/// * `amount` - The amount of tokens that the bidder wants to buy
/// * `multiplier` - Used for calculating how much PLMC needs to be bonded to spend this much money (in USD)
///
/// # Storage access
/// * [`ProjectsDetails`] - Check that the project is in the bidding stage
/// * [`BiddingBonds`] - Update the storage with the bidder's PLMC bond for that bid
/// * [`Bids`] - Check previous bids by that user, and update the storage with the new bid
#[transactional]
pub fn do_bid(params: DoBidParams<T>) -> DispatchResultWithPostInfo {
// * Get variables *
Expand Down Expand Up @@ -148,7 +134,7 @@ impl<T: Config> Pallet<T> {
};
Self::do_perform_bid(perform_params)?;

perform_bid_calls += 1;
perform_bid_calls = perform_bid_calls.saturating_add(1);

// Update the current bucket and reduce the amount to bid by the amount we just bid
current_bucket.update(ct_amount);
Expand Down Expand Up @@ -217,8 +203,8 @@ impl<T: Config> Pallet<T> {

Bids::<T>::insert((project_id, bidder.clone(), bid_id), &new_bid);
NextBidId::<T>::set(bid_id.saturating_add(One::one()));
BidCounts::<T>::mutate(project_id, |c| *c += 1);
AuctionBoughtUSD::<T>::mutate((project_id, did), |amount| *amount += ticket_size);
BidCounts::<T>::mutate(project_id, |c| *c = c.saturating_add(1));
AuctionBoughtUSD::<T>::mutate((project_id, did), |amount| *amount = amount.saturating_add(ticket_size));

Self::deposit_event(Event::Bid {
project_id,
Expand Down
11 changes: 1 addition & 10 deletions pallets/funding/src/functions/4_contribution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,6 @@
use super::*;

impl<T: Config> Pallet<T> {
/// Buy tokens in the Community Round at the price set in the Bidding Round
///
/// # Arguments
/// * contributor: The account that is buying the tokens
/// * project_id: The identifier of the project
/// * token_amount: The amount of contribution tokens the contributor tries to buy. Tokens
/// are limited by the total amount of tokens available in the Community Round.
/// * multiplier: Decides how much PLMC bonding is required for buying that amount of tokens
/// * asset: The asset used for the contribution
#[transactional]
pub fn do_contribute(params: DoContributeParams<T>) -> DispatchResultWithPostInfo {
let DoContributeParams {
Expand Down Expand Up @@ -139,7 +130,7 @@ impl<T: Config> Pallet<T> {

Contributions::<T>::insert((project_id, contributor.clone(), contribution_id), &new_contribution);
NextContributionId::<T>::set(contribution_id.saturating_add(One::one()));
ContributionBoughtUSD::<T>::mutate((project_id, did), |amount| *amount += ticket_size);
ContributionBoughtUSD::<T>::mutate((project_id, did), |amount| *amount = amount.saturating_add(ticket_size));

project_details.funding_amount_reached_usd.saturating_accrue(new_contribution.usd_contribution_amount);
ProjectsDetails::<T>::insert(project_id, project_details);
Expand Down
29 changes: 0 additions & 29 deletions pallets/funding/src/functions/5_funding_end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,6 @@
use super::*;

impl<T: Config> Pallet<T> {
/// Called automatically by on_initialize
/// Ends the project funding, and calculates if the project was successfully funded or not.
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, the current block is after the remainder funding end period.
/// Update the project information with the new round status.
///
/// # Success Path
/// The validity checks pass, and either of 2 paths happen:
///
/// * Project achieves its funding target - the project info is set to a successful funding state,
/// and the contribution token asset class is created with the same id as the project.
///
/// * Project doesn't achieve its funding target - the project info is set to an unsuccessful funding state.
///
/// # Next step
/// If **successful**, bidders can claim:
/// * Contribution tokens with [`vested_contribution_token_bid_mint_for`](Self::vested_contribution_token_bid_mint_for)
/// * Bonded plmc with [`vested_plmc_bid_unbond_for`](Self::vested_plmc_bid_unbond_for)
///
/// And contributors can claim:
/// * Contribution tokens with [`vested_contribution_token_purchase_mint_for`](Self::vested_contribution_token_purchase_mint_for)
/// * Bonded plmc with [`vested_plmc_purchase_unbond_for`](Self::vested_plmc_purchase_unbond_for)
///
/// If **unsuccessful**, users every user should have their PLMC vesting unbonded.
#[transactional]
pub fn do_end_funding(project_id: ProjectId) -> DispatchResult {
// * Get variables *
Expand Down
98 changes: 25 additions & 73 deletions pallets/funding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,6 @@ pub mod pallet {
+ OnIdle<BlockNumberFor<Self>>
+ OnInitialize<BlockNumberFor<Self>>;

// TODO: our local BlockNumber should be removed once we move onto using Moment for time tracking
/// BlockNumber used for PLMC vesting durations on this chain, and CT vesting durations on funded chains.
type BlockNumber: IsType<BlockNumberFor<Self>> + Into<u64>;

Expand Down Expand Up @@ -484,33 +483,15 @@ pub mod pallet {
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// A project was created.
ProjectCreated {
project_id: ProjectId,
issuer: T::AccountId,
metadata: ProjectMetadataOf<T>,
},
ProjectCreated { project_id: ProjectId, issuer: T::AccountId, metadata: ProjectMetadataOf<T> },
/// An issuer removed the project before the evaluation started
ProjectRemoved {
project_id: ProjectId,
issuer: T::AccountId,
},
ProjectRemoved { project_id: ProjectId, issuer: T::AccountId },
/// The metadata of a project was modified.
MetadataEdited {
project_id: ProjectId,
metadata: ProjectMetadataOf<T>,
},
MetadataEdited { project_id: ProjectId, metadata: ProjectMetadataOf<T> },
/// Project transitioned to a new phase.
ProjectPhaseTransition {
project_id: ProjectId,
phase: ProjectStatus<BlockNumberFor<T>>,
},
ProjectPhaseTransition { project_id: ProjectId, phase: ProjectStatus<BlockNumberFor<T>> },
/// A `bonder` bonded an `amount` of PLMC for `project_id`.
Evaluation {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
plmc_amount: Balance,
},
Evaluation { project_id: ProjectId, evaluator: AccountIdOf<T>, id: u32, plmc_amount: Balance },
/// A bid was made for a project
Bid {
project_id: ProjectId,
Expand All @@ -534,72 +515,43 @@ pub mod pallet {
plmc_bond: Balance,
mode: ParticipationMode,
},
BidRefunded {
project_id: ProjectId,
account: AccountIdOf<T>,
bid_id: u32,
plmc_amount: Balance,
funding_asset: AcceptedFundingAsset,
funding_amount: Balance,
},
/// An evaluation was settled. PLMC has been unbonded with either a CT reward or a PLMC slash depending on the project outcome.
EvaluationSettled {
project_id: ProjectId,
account: AccountIdOf<T>,
id: u32,
ct_rewarded: Balance,
plmc_released: Balance,
},
/// A bid was settled. On Funding Success the PLMC has been unbonded/locked with a vesting schedule and the funding assets have been transferred to the issuer.
/// Some funds and PLMC might have been returned to the bidder if they paid a higher price than the final CT price.
/// If Funding Failed, the PLMC has been unbonded and the funds have been returned to the bidder.
BidSettled {
project_id: ProjectId,
account: AccountIdOf<T>,
id: u32,
final_ct_amount: Balance,
final_ct_usd_price: PriceOf<T>,
},
ContributionSettled {
project_id: ProjectId,
account: AccountIdOf<T>,
id: u32,
ct_amount: Balance,
},
PalletMigrationStarted {
project_id: ProjectId,
para_id: ParaId,
},
/// A contribution was settled. On Funding Success the PLMC has been unbonded/locked with a vesting schedule and the funding assets have been transferred to the issuer.
/// If Funding Failed, the PLMC has been unbonded and the funds have been returned to the contributor.
ContributionSettled { project_id: ProjectId, account: AccountIdOf<T>, id: u32, ct_amount: Balance },
/// Issuer started the CT migration to mainnet tokens using the pallet migration method
PalletMigrationStarted { project_id: ProjectId, para_id: ParaId },
/// A channel was accepted from a parachain to Polimec belonging to a project. A request has been sent to the relay for a Polimec->project channel
HrmpChannelAccepted {
project_id: ProjectId,
para_id: ParaId,
},
HrmpChannelAccepted { project_id: ProjectId, para_id: ParaId },
/// A channel was established from Polimec to a project. The relay has notified us of their acceptance of our request
HrmpChannelEstablished {
project_id: ProjectId,
para_id: ParaId,
},
HrmpChannelEstablished { project_id: ProjectId, para_id: ParaId },
/// Started a migration readiness check
MigrationReadinessCheckStarted {
project_id: ProjectId,
caller: T::AccountId,
},
MigrationCheckResponseAccepted {
project_id: ProjectId,
query_id: QueryId,
response: Response,
},
MigrationCheckResponseRejected {
project_id: ProjectId,
query_id: QueryId,
response: Response,
},
MigrationStatusUpdated {
project_id: ProjectId,
account: AccountIdOf<T>,
status: MigrationStatus,
},

CTMigrationFinished {
project_id: ProjectId,
},
MigrationReadinessCheckStarted { project_id: ProjectId, caller: T::AccountId },
/// Migration readiness check was accepted
MigrationCheckResponseAccepted { project_id: ProjectId, query_id: QueryId, response: Response },
/// Migration readiness check was rejected
MigrationCheckResponseRejected { project_id: ProjectId, query_id: QueryId, response: Response },
/// A user's CT migrations status was updated
MigrationStatusUpdated { project_id: ProjectId, account: AccountIdOf<T>, status: MigrationStatus },
/// The CT migration of a project has been completed. All CTs were converted to mainnet tokens.
CTMigrationFinished { project_id: ProjectId },
}

#[pallet::error]
Expand Down
Loading

0 comments on commit b80f3f4

Please sign in to comment.