Skip to content

Commit

Permalink
otm_funding_tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JuaniRios committed Sep 19, 2024
1 parent 59622fb commit 1dc36c2
Show file tree
Hide file tree
Showing 17 changed files with 499 additions and 152 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

14 changes: 9 additions & 5 deletions pallets/funding/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1040,11 +1040,15 @@ mod benchmarks {

let price = inst.get_project_details(project_id).weighted_average_price.unwrap();

let contributions =
vec![
ContributionParams::new(contributor.clone(), (50 * CT_UNIT).into(), ParticipationMode::Normal(1u8), AcceptedFundingAsset::USDT);
x as usize + 1
];
let contributions = vec![
ContributionParams::new(
contributor.clone(),
(50 * CT_UNIT).into(),
ParticipationMode::Normal(1u8),
AcceptedFundingAsset::USDT
);
x as usize + 1
];

let plmc = inst.calculate_contributed_plmc_spent(contributions.clone(), price, false);
let usdt = inst.calculate_contributed_funding_asset_spent(contributions.clone(), price);
Expand Down
40 changes: 27 additions & 13 deletions pallets/funding/src/functions/6_settlement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,11 @@ impl<T: Config> Pallet<T> {

if outcome == FundingOutcome::Failure {
// Release the held PLMC bond
Self::unbond_participation_with_mode(contribution.contributor.clone(), contribution.plmc_bond, contribution.mode)?;
Self::unbond_participation_with_mode(
contribution.contributor.clone(),
contribution.plmc_bond,
contribution.mode,
)?;

Self::release_funding_asset(
project_id,
Expand All @@ -254,7 +258,6 @@ impl<T: Config> Pallet<T> {
contribution.funding_asset,
)?;
} else {

let ct_vesting_duration = Self::set_bond_release_with_mode(
contribution.contributor.clone(),
contribution.plmc_bond,
Expand All @@ -280,7 +283,7 @@ impl<T: Config> Pallet<T> {
contribution.id,
ParticipationType::Contribution,
contribution.ct_amount,
ct_vesting_duration
ct_vesting_duration,
)?;

final_ct_amount = contribution.ct_amount;
Expand Down Expand Up @@ -355,7 +358,11 @@ impl<T: Config> Pallet<T> {
Ok(())
}

fn unbond_participation_with_mode(participant: AccountIdOf<T>, plmc_amount: Balance, mode: ParticipationMode) -> DispatchResult {
fn unbond_participation_with_mode(
participant: AccountIdOf<T>,
plmc_amount: Balance,
mode: ParticipationMode,
) -> DispatchResult {
match mode {
ParticipationMode::OTM => todo!(),
ParticipationMode::Normal(_) => Self::release_participation_bond_for(&participant, plmc_amount),
Expand All @@ -371,22 +378,29 @@ impl<T: Config> Pallet<T> {
Ok(())
}

fn set_bond_release_with_mode(participant: AccountIdOf<T>, plmc_amount: Balance, mode: ParticipationMode, funding_end_block: BlockNumberFor<T>) -> Result<BlockNumberFor<T>, DispatchError> {
fn set_bond_release_with_mode(
participant: AccountIdOf<T>,
plmc_amount: Balance,
mode: ParticipationMode,
funding_end_block: BlockNumberFor<T>,
) -> Result<BlockNumberFor<T>, DispatchError> {
let multiplier = mode.multiplier().try_into().map_err(|_| Error::<T>::ImpossibleState)?;
match mode {
ParticipationMode::OTM => todo!(),
ParticipationMode::Normal(_) => Self::set_release_schedule_for(&participant, plmc_amount, multiplier, funding_end_block),
ParticipationMode::Normal(_) =>
Self::set_release_schedule_for(&participant, plmc_amount, multiplier, funding_end_block),
}
}

fn set_release_schedule_for(participant: &AccountIdOf<T>, plmc_amount: Balance, multiplier: MultiplierOf<T>, funding_end_block: BlockNumberFor<T>) -> Result<BlockNumberFor<T>, DispatchError> {
fn set_release_schedule_for(
participant: &AccountIdOf<T>,
plmc_amount: Balance,
multiplier: MultiplierOf<T>,
funding_end_block: BlockNumberFor<T>,
) -> Result<BlockNumberFor<T>, DispatchError> {
// Calculate the vesting info and add the release schedule
let vesting_info = Self::calculate_vesting_info(
participant,
multiplier,
plmc_amount,
)
.map_err(|_| Error::<T>::BadMath)?;
let vesting_info =
Self::calculate_vesting_info(participant, multiplier, plmc_amount).map_err(|_| Error::<T>::BadMath)?;

if vesting_info.duration == 1u32.into() {
Self::release_participation_bond_for(participant, vesting_info.total_amount)?;
Expand Down
29 changes: 25 additions & 4 deletions pallets/funding/src/instantiator/calculations.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#[allow(clippy::wildcard_imports)]
use super::*;
use crate::{Multiplier, MultiplierOf, ParticipationMode};
use core::cmp::Ordering;
use itertools::GroupBy;
use polimec_common::{ProvideAssetPrice, USD_DECIMALS};
use crate::{Multiplier, MultiplierOf, ParticipationMode};

impl<
T: Config,
Expand All @@ -15,6 +15,10 @@ impl<
T::ExistentialDeposit::get()
}

pub fn get_funding_asset_ed(&mut self, asset_id: AssetIdOf<T>) -> Balance {
self.execute(|| T::FundingCurrency::minimum_balance(asset_id))
}

pub fn get_ct_account_deposit(&self) -> Balance {
<T as crate::Config>::ContributionTokenCurrency::deposit_required(One::one())
}
Expand Down Expand Up @@ -433,7 +437,14 @@ impl<
.unwrap()
});
let usd_ticket_size = token_usd_price.saturating_mul_int(cont.amount);
let funding_asset_spent = funding_asset_usd_price.reciprocal().unwrap().saturating_mul_int(usd_ticket_size);
let mut funding_asset_spent =
funding_asset_usd_price.reciprocal().unwrap().saturating_mul_int(usd_ticket_size);
if cont.mode == ParticipationMode::OTM {
let multiplier: MultiplierOf<T> = cont.mode.multiplier().try_into().ok().unwrap();
let plmc_bond = multiplier.calculate_bonding_requirement::<T>(usd_ticket_size).unwrap();
let otm_fee = <pallet_proxy_bonding::Pallet<T>>::calculate_fee(plmc_bond, funding_asset_id).unwrap();
funding_asset_spent += otm_fee;
}
output.push(UserToFundingAsset::new(cont.contributor, funding_asset_spent, cont.asset.id()));
}
output
Expand Down Expand Up @@ -595,7 +606,12 @@ impl<
let ticket_size = Percent::from_percent(weight) * usd_amount;
let token_amount = final_price.reciprocal().unwrap().saturating_mul_int(ticket_size);

ContributionParams::new(bidder, token_amount, ParticipationMode::Normal(multiplier), AcceptedFundingAsset::USDT)
ContributionParams::new(
bidder,
token_amount,
ParticipationMode::Normal(multiplier),
AcceptedFundingAsset::USDT,
)
})
.collect()
}
Expand All @@ -616,7 +632,12 @@ impl<
zip(zip(weights, contributors), multipliers)
.map(|((weight, contributor), multiplier)| {
let token_amount = Percent::from_percent(weight) * total_ct_bought;
ContributionParams::new(contributor, token_amount, ParticipationMode::Normal(multiplier), AcceptedFundingAsset::USDT)
ContributionParams::new(
contributor,
token_amount,
ParticipationMode::Normal(multiplier),
AcceptedFundingAsset::USDT,
)
})
.collect()
}
Expand Down
28 changes: 14 additions & 14 deletions pallets/funding/src/instantiator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ use sp_arithmetic::Percent;
fn dry_run_wap() {
let mut inst = tests::MockInstantiator::new(Some(RefCell::new(new_test_ext())));

const ADAM: u32 = 60;
const TOM: u32 = 61;
const SOFIA: u32 = 62;
const FRED: u32 = 63;
const ANNA: u32 = 64;
const DAMIAN: u32 = 65;
const ADAM: AccountIdOf<TestRuntime> = 60;
const TOM: AccountIdOf<TestRuntime> = 61;
const SOFIA: AccountIdOf<TestRuntime> = 62;
const FRED: AccountIdOf<TestRuntime> = 63;
const ANNA: AccountIdOf<TestRuntime> = 64;
const DAMIAN: AccountIdOf<TestRuntime> = 65;

let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN];

Expand Down Expand Up @@ -50,7 +50,7 @@ fn dry_run_wap() {
phantom: Default::default(),
},
participation_currencies: vec![AcceptedFundingAsset::USDT].try_into().unwrap(),
funding_destination_account: 0u32,
funding_destination_account: 0,
policy_ipfs_cid: Some(metadata_hash),
};

Expand Down Expand Up @@ -98,12 +98,12 @@ fn dry_run_wap() {
fn find_bucket_for_wap() {
let mut inst = tests::MockInstantiator::new(Some(RefCell::new(new_test_ext())));

const ADAM: u32 = 60;
const TOM: u32 = 61;
const SOFIA: u32 = 62;
const FRED: u32 = 63;
const ANNA: u32 = 64;
const DAMIAN: u32 = 65;
const ADAM: AccountIdOf<TestRuntime> = 60;
const TOM: AccountIdOf<TestRuntime> = 61;
const SOFIA: AccountIdOf<TestRuntime> = 62;
const FRED: AccountIdOf<TestRuntime> = 63;
const ANNA: AccountIdOf<TestRuntime> = 64;
const DAMIAN: AccountIdOf<TestRuntime> = 65;

let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN];

Expand Down Expand Up @@ -132,7 +132,7 @@ fn find_bucket_for_wap() {
phantom: Default::default(),
},
participation_currencies: vec![AcceptedFundingAsset::USDT].try_into().unwrap(),
funding_destination_account: 0u32,
funding_destination_account: 0,
policy_ipfs_cid: Some(metadata_hash),
};

Expand Down
23 changes: 9 additions & 14 deletions pallets/funding/src/instantiator/types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[allow(clippy::wildcard_imports)]
use super::*;
use frame_support::{Deserialize, Serialize};
use crate::ParticipationMode;
use frame_support::{Deserialize, Serialize};

pub type RuntimeOriginOf<T> = <T as frame_system::Config>::RuntimeOrigin;
pub struct BoxToFunction(pub Box<dyn FnOnce()>);
Expand Down Expand Up @@ -321,27 +321,22 @@ pub struct ContributionParams<T: Config> {
pub asset: AcceptedFundingAsset,
}
impl<T: Config> ContributionParams<T> {
pub fn new(contributor: AccountIdOf<T>, amount: Balance, mode: ParticipationMode, asset: AcceptedFundingAsset) -> Self {
pub fn new(
contributor: AccountIdOf<T>,
amount: Balance,
mode: ParticipationMode,
asset: AcceptedFundingAsset,
) -> Self {
Self { contributor, amount, mode, asset }
}

pub fn new_with_defaults(contributor: AccountIdOf<T>, amount: Balance) -> Self {
Self {
contributor,
amount,
mode: ParticipationMode::Normal(1u8),
asset: AcceptedFundingAsset::USDT,
}
Self { contributor, amount, mode: ParticipationMode::Normal(1u8), asset: AcceptedFundingAsset::USDT }
}
}
impl<T: Config> From<(AccountIdOf<T>, Balance)> for ContributionParams<T> {
fn from((contributor, amount): (AccountIdOf<T>, Balance)) -> Self {
Self {
contributor,
amount,
mode: ParticipationMode::Normal(1u8),
asset: AcceptedFundingAsset::USDT,
}
Self { contributor, amount, mode: ParticipationMode::Normal(1u8), asset: AcceptedFundingAsset::USDT }
}
}
impl<T: Config> From<(AccountIdOf<T>, Balance, ParticipationMode)> for ContributionParams<T> {
Expand Down
3 changes: 1 addition & 2 deletions pallets/funding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ pub type ProjectDetailsOf<T> = ProjectDetails<AccountIdOf<T>, Did, BlockNumberFo
pub type EvaluationInfoOf<T> = EvaluationInfo<u32, Did, ProjectId, AccountIdOf<T>, BlockNumberFor<T>>;
pub type BidInfoOf<T> = BidInfo<ProjectId, Did, PriceOf<T>, AccountIdOf<T>, BlockNumberFor<T>, MultiplierOf<T>>;

pub type ContributionInfoOf<T> =
ContributionInfo<u32, Did, ProjectId, AccountIdOf<T>, BlockNumberFor<T>>;
pub type ContributionInfoOf<T> = ContributionInfo<u32, Did, ProjectId, AccountIdOf<T>, BlockNumberFor<T>>;

pub type BucketOf<T> = Bucket<PriceOf<T>>;
pub type WeightInfoOf<T> = <T as Config>::WeightInfo;
Expand Down
26 changes: 14 additions & 12 deletions pallets/funding/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub const MILLI_PLMC: Balance = PLMC / 10u128.pow(3);
pub const MICRO_PLMC: Balance = PLMC / 10u128.pow(6);
pub const EXISTENTIAL_DEPOSIT: Balance = 10 * MILLI_PLMC;
pub type Block = frame_system::mocking::MockBlock<TestRuntime>;
pub type AccountId = u32;
pub type AccountId = u64;
pub type BlockNumber = u64;
pub type Identifier = u32;
pub type Price = FixedU128;
Expand All @@ -71,7 +71,7 @@ pub const fn free_deposit() -> Balance {

pub struct SignedToAccountIndex<RuntimeOrigin, AccountId, Network>(PhantomData<(RuntimeOrigin, AccountId, Network)>);

impl<RuntimeOrigin: OriginTrait + Clone, AccountId: Into<u32>, Network: Get<Option<NetworkId>>>
impl<RuntimeOrigin: OriginTrait + Clone, AccountId: Into<u64>, Network: Get<Option<NetworkId>>>
TryConvert<RuntimeOrigin, Location> for SignedToAccountIndex<RuntimeOrigin, AccountId, Network>
where
RuntimeOrigin::PalletsOrigin:
Expand All @@ -80,7 +80,7 @@ where
fn try_convert(o: RuntimeOrigin) -> Result<Location, RuntimeOrigin> {
o.try_with_caller(|caller| match caller.try_into() {
Ok(SystemRawOrigin::Signed(who)) =>
Ok(Junction::AccountIndex64 { network: Network::get(), index: Into::<u32>::into(who).into() }.into()),
Ok(Junction::AccountIndex64 { network: Network::get(), index: Into::<u64>::into(who).into() }.into()),
Ok(other) => Err(other.into()),
Err(other) => Err(other),
})
Expand Down Expand Up @@ -296,7 +296,7 @@ parameter_types! {
pub const CommunityRoundDuration: BlockNumber = 18u64;
pub const RemainderRoundDuration: BlockNumber = 6u64;

pub const FundingPalletId: PalletId = PalletId(*b"py/cfund");
pub const FundingPalletId: PalletId = PalletId(*b"plmc-fun");
pub FeeBrackets: Vec<(Percent, Balance)> = vec![
(Percent::from_percent(10), 1_000_000 * USD_UNIT),
(Percent::from_percent(8), 4_000_000 * USD_UNIT),
Expand Down Expand Up @@ -353,14 +353,14 @@ pub struct DummyConverter;
impl sp_runtime::traits::Convert<AccountId, [u8; 32]> for DummyConverter {
fn convert(a: AccountId) -> [u8; 32] {
let mut account: [u8; 32] = [0u8; 32];
account[0..4].copy_from_slice(a.to_le_bytes().as_slice());
account[0..8].copy_from_slice(a.to_le_bytes().as_slice());
account
}
}
impl ConvertBack<AccountId, [u8; 32]> for DummyConverter {
fn convert_back(bytes: [u8; 32]) -> AccountId {
let account: [u8; 4] = bytes[0..3].try_into().unwrap();
u32::from_le_bytes(account)
let account: [u8; 8] = bytes[0..7].try_into().unwrap();
u64::from_le_bytes(account)
}
}
thread_local! {
Expand Down Expand Up @@ -437,7 +437,7 @@ impl Config for TestRuntime {

parameter_types! {
pub const FeePercentage: Perbill = Perbill::from_percent(5);
pub const FeeRecipient: AccountId = 80085u32;
pub const FeeRecipient: AccountId = 80085;
pub const RootId: PalletId = PalletId(*b"treasury");
}
impl pallet_proxy_bonding::Config for TestRuntime {
Expand Down Expand Up @@ -482,27 +482,29 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
balances: vec![
(<TestRuntime as Config>::PalletId::get().into_account_truncating(), ed),
(<TestRuntime as Config>::ContributionTreasury::get(), ed),
(<TestRuntime as Config>::BlockchainOperationTreasury::get(), ed),
/// Treasury account needs PLMC for the One Token Model participations
(<TestRuntime as Config>::BlockchainOperationTreasury::get(), 1_000_000 * PLMC),
],
},
foreign_assets: ForeignAssetsConfig {
assets: vec![
(
AcceptedFundingAsset::USDT.id(),
<TestRuntime as Config>::PalletId::get().into_account_truncating(),
false,
// asset is sufficient, i.e. participants can hold only this asset to participate with OTM
true,
10,
),
(
AcceptedFundingAsset::USDC.id(),
<TestRuntime as Config>::PalletId::get().into_account_truncating(),
false,
true,
10,
),
(
AcceptedFundingAsset::DOT.id(),
<TestRuntime as Config>::PalletId::get().into_account_truncating(),
false,
true,
10,
),
],
Expand Down
2 changes: 1 addition & 1 deletion pallets/funding/src/tests/2_evaluation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ mod evaluate_extrinsic {
let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext())));
let project_metadata = default_project_metadata(ISSUER_1);
let evaluations = (0u32..<TestRuntime as Config>::MaxEvaluationsPerProject::get())
.map(|i| UserToUSDBalance::<TestRuntime>::new(i as u32 + 420u32, (100u128 * CT_UNIT).into()))
.map(|i| UserToUSDBalance::<TestRuntime>::new(i as u64 + 420, (100u128 * CT_UNIT).into()))
.collect_vec();
let failing_evaluation = UserToUSDBalance::new(EVALUATOR_1, 1000 * CT_UNIT);

Expand Down
Loading

0 comments on commit 1dc36c2

Please sign in to comment.