Skip to content

Commit

Permalink
one-token-model
Browse files Browse the repository at this point in the history
  • Loading branch information
JuaniRios committed Sep 10, 2024
1 parent 59222cb commit 6d96f7b
Show file tree
Hide file tree
Showing 19 changed files with 514 additions and 71 deletions.
18 changes: 18 additions & 0 deletions Cargo.lock

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

39 changes: 38 additions & 1 deletion integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -140,5 +140,42 @@ std = [
"xcm/std",
]
development-settings = [ "polimec-runtime/development-settings" ]
runtime-benchmarks = []
runtime-benchmarks = [
"asset-hub-polkadot-runtime/runtime-benchmarks",
"polkadot-runtime/runtime-benchmarks",
"penpal-runtime/runtime-benchmarks",
"pallet-democracy/runtime-benchmarks",
"pallet-dispenser/runtime-benchmarks",
"pallet-elections-phragmen/runtime-benchmarks",
"pallet-funding/runtime-benchmarks",
"pallet-linear-release/runtime-benchmarks",
"pallet-parachain-staking/runtime-benchmarks",
"polimec-receiver/runtime-benchmarks",
"polimec-common/runtime-benchmarks",
"polimec-common-test-utils/runtime-benchmarks",
"polimec-runtime/runtime-benchmarks",
"cumulus-primitives-core/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"orml-oracle/runtime-benchmarks",
"pallet-assets/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-collective/runtime-benchmarks",
"pallet-im-online/runtime-benchmarks",
"pallet-membership/runtime-benchmarks",
"pallet-message-queue/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
"pallet-xcm/runtime-benchmarks",
"parachains-common/runtime-benchmarks",
"polkadot-parachain-primitives/runtime-benchmarks",
"polkadot-primitives/runtime-benchmarks",
"polkadot-runtime-parachains/runtime-benchmarks",
"polkadot-service/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks"
]

7 changes: 2 additions & 5 deletions pallets/funding/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@
//! Benchmarking setup for Funding pallet
use super::*;
use crate::{
instantiator::*,
traits::{ProvideAssetPrice, SetPrices},
};
use crate::{instantiator::*, traits::SetPrices};
use frame_benchmarking::v2::*;
use frame_support::{
assert_ok,
Expand All @@ -35,7 +32,7 @@ use frame_support::{
};
use itertools::Itertools;
use parity_scale_codec::{Decode, Encode};
use polimec_common::{credentials::InvestorType, ReleaseSchedule, USD_DECIMALS, USD_UNIT};
use polimec_common::{credentials::InvestorType, ProvideAssetPrice, ReleaseSchedule, USD_DECIMALS, USD_UNIT};
use polimec_common_test_utils::{generate_did_from_account, get_mock_jwt_with_cid};
use sp_arithmetic::Percent;
use sp_core::H256;
Expand Down
2 changes: 1 addition & 1 deletion pallets/funding/src/functions/2_evaluation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[allow(clippy::wildcard_imports)]
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.
Expand Down
4 changes: 2 additions & 2 deletions pallets/funding/src/functions/misc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use sp_runtime::traits::CheckedAdd;

#[allow(clippy::wildcard_imports)]
use super::*;
use polimec_common::ProvideAssetPrice;
use sp_runtime::traits::CheckedAdd;

// Helper functions
// ATTENTION: if this is called directly, it will not be transactional
Expand Down
3 changes: 1 addition & 2 deletions pallets/funding/src/instantiator/calculations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
use super::*;
use core::cmp::Ordering;
use itertools::GroupBy;
use polimec_common::USD_DECIMALS;

use polimec_common::{ProvideAssetPrice, USD_DECIMALS};
impl<
T: Config + pallet_balances::Config<Balance = BalanceOf<T>>,
AllPalletsWithoutSystem: OnFinalize<BlockNumberFor<T>> + OnIdle<BlockNumberFor<T>> + OnInitialize<BlockNumberFor<T>>,
Expand Down
3 changes: 1 addition & 2 deletions pallets/funding/src/instantiator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ use crate::{
defaults::{bounded_name, bounded_symbol, default_evaluations, default_project_metadata, ipfs_hash},
CT_DECIMALS, CT_UNIT,
},
traits::ProvideAssetPrice,
*,
};
use core::cell::RefCell;
use itertools::Itertools;
use polimec_common::{USD_DECIMALS, USD_UNIT};
use polimec_common::{ProvideAssetPrice, USD_DECIMALS, USD_UNIT};
use sp_arithmetic::Percent;

#[test]
Expand Down
3 changes: 2 additions & 1 deletion pallets/funding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,15 @@ pub const PLMC_DECIMALS: u8 = 10;
pub mod pallet {
#[allow(clippy::wildcard_imports)]
use super::*;
use crate::traits::{BondingRequirementCalculation, ProvideAssetPrice, VestingDurationCalculation};
use crate::traits::{BondingRequirementCalculation, VestingDurationCalculation};
use core::ops::RangeInclusive;
use frame_support::{
pallet_prelude::*,
storage::KeyPrefixIterator,
traits::{OnFinalize, OnIdle, OnInitialize},
};
use frame_system::pallet_prelude::*;
use polimec_common::ProvideAssetPrice;
use sp_arithmetic::Percent;
use sp_runtime::{
traits::{Convert, ConvertBack, Get},
Expand Down
7 changes: 3 additions & 4 deletions pallets/funding/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@
use super::*;
use crate as pallet_funding;
use crate::{
runtime_api::{ExtrinsicHelpers, Leaderboards, ProjectInformation, ProjectParticipationIds, UserInformation},
traits::ProvideAssetPrice,
use crate::runtime_api::{
ExtrinsicHelpers, Leaderboards, ProjectInformation, ProjectParticipationIds, UserInformation,
};
use core::ops::RangeInclusive;
use frame_support::{
Expand All @@ -34,7 +33,7 @@ use frame_support::{
};
use frame_system as system;
use frame_system::{EnsureRoot, RawOrigin as SystemRawOrigin};
use polimec_common::{credentials::EnsureInvestor, DummyXcmSender, USD_UNIT};
use polimec_common::{credentials::EnsureInvestor, DummyXcmSender, ProvideAssetPrice, USD_UNIT};
use polkadot_parachain_primitives::primitives::Sibling;
use sp_arithmetic::Percent;
use sp_core::H256;
Expand Down
3 changes: 1 addition & 2 deletions pallets/funding/src/runtime_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ use alloc::collections::BTreeMap;
use frame_support::traits::fungibles::{metadata::Inspect as MetadataInspect, Inspect, InspectEnumerable};
use itertools::Itertools;
use parity_scale_codec::{Decode, Encode};
use polimec_common::USD_DECIMALS;
use polimec_common::{ProvideAssetPrice, USD_DECIMALS};
use scale_info::TypeInfo;
use sp_runtime::traits::Zero;

#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)]
pub struct ProjectParticipationIds<T: Config> {
account: AccountIdOf<T>,
Expand Down
7 changes: 2 additions & 5 deletions pallets/funding/src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use super::*;
use crate::{
instantiator::*,
mock::*,
traits::{ProvideAssetPrice, VestingDurationCalculation},
CurrencyMetadata, Error, ProjectMetadata, TicketSize,
instantiator::*, mock::*, traits::VestingDurationCalculation, CurrencyMetadata, Error, ProjectMetadata, TicketSize,
};
use defaults::*;
use frame_support::{
Expand All @@ -15,7 +12,7 @@ use frame_support::{
};
use itertools::Itertools;
use parachains_common::DAYS;
use polimec_common::{ReleaseSchedule, USD_DECIMALS, USD_UNIT};
use polimec_common::{ProvideAssetPrice, ReleaseSchedule, USD_DECIMALS, USD_UNIT};
use polimec_common_test_utils::{generate_did_from_account, get_mock_jwt_with_cid};
use sp_arithmetic::{traits::Zero, Percent, Perquintill};
use sp_runtime::TokenError;
Expand Down
44 changes: 0 additions & 44 deletions pallets/funding/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,50 +31,6 @@ pub trait VestingDurationCalculation {
fn calculate_vesting_duration<T: Config>(&self) -> BlockNumberFor<T>;
}

pub trait ProvideAssetPrice {
type AssetId;
type Price: FixedPointNumber;
fn get_price(asset_id: Self::AssetId) -> Option<Self::Price>;

/// Prices define the relationship between USD/Asset. When to and from that asset, we need to be aware that they might
/// have different decimals. This function calculates the relationship having in mind the decimals. For example:
/// if the price is 2.5, our underlying USD unit has 6 decimals, and the asset has 8 decimals, the price will be
/// calculated like so: `(2.5USD * 10^6) / (1 * 10^8) = 0.025`. And so if we want to convert 20 of the asset to USD,
/// we would do `0.025(USD/Asset)FixedPointNumber * 20_000_000_00(Asset)u128 = 50_000_000` which is 50 USD with 6 decimals
fn calculate_decimals_aware_price(
original_price: Self::Price,
usd_decimals: u8,
asset_decimals: u8,
) -> Option<Self::Price> {
let usd_unit = 10u128.checked_pow(usd_decimals.into())?;
let usd_price_with_decimals = original_price.checked_mul_int(usd_unit)?;
let asset_unit = 10u128.checked_pow(asset_decimals.into())?;

Self::Price::checked_from_rational(usd_price_with_decimals, asset_unit)
}

fn convert_back_to_normal_price(
decimals_aware_price: Self::Price,
usd_decimals: u8,
asset_decimals: u8,
) -> Option<Self::Price> {
let abs_diff: u32 = asset_decimals.abs_diff(usd_decimals).into();
let abs_diff_unit = 10u128.checked_pow(abs_diff)?;
// We are pretty sure this is going to be representable because the number size is not the size of the asset decimals, but the difference between the asset and usd decimals
let abs_diff_fixed = Self::Price::checked_from_rational(abs_diff_unit, 1)?;
if usd_decimals > asset_decimals {
decimals_aware_price.checked_div(&abs_diff_fixed)
} else {
decimals_aware_price.checked_mul(&abs_diff_fixed)
}
}

fn get_decimals_aware_price(asset_id: Self::AssetId, usd_decimals: u8, asset_decimals: u8) -> Option<Self::Price> {
let original_price = Self::get_price(asset_id)?;
Self::calculate_decimals_aware_price(original_price, usd_decimals, asset_decimals)
}
}

pub trait DoRemainingOperation<T: Config> {
fn has_remaining_operations(&self) -> bool;

Expand Down
62 changes: 62 additions & 0 deletions pallets/proxy-bonding/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
[package]
name = "proxy-bonding"
authors.workspace = true
documentation.workspace = true
edition.workspace = true
homepage.workspace = true
license-file.workspace = true
readme.workspace = true
repository.workspace = true
version.workspace = true

[lints]
workspace = true

[dependencies]
frame-system.workspace = true
frame-support.workspace = true
frame-benchmarking = { workspace = true, optional = true }
sp-runtime.workspace = true
polimec-common.workspace = true
parity-scale-codec.workspace = true
scale-info.workspace = true

[dev-dependencies]
sp-io.workspace = true
pallet-linear-release.workspace = true
pallet-balances.workspace = true
pallet-assets.workspace = true


[features]
default = ["std"]

std = [
"frame-system/std",
"frame-support/std",
"sp-runtime/std",
"polimec-common/std",
"parity-scale-codec/std",
"scale-info/std",
"frame-benchmarking?/std",

"sp-io/std",
"pallet-linear-release/std",
"pallet-balances/std",
"pallet-assets/std"
]

try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
"polimec-common/try-runtime"
]

runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"polimec-common/runtime-benchmarks"
]
69 changes: 69 additions & 0 deletions pallets/proxy-bonding/src/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use crate::{AccountIdOf, AssetId, BalanceOf, Config, HoldReasonOf, Pallet};
use frame_support::traits::{
fungible,
fungible::{Inspect, Mutate, MutateHold},
fungibles,
fungibles::Mutate as FungiblesMutate,
tokens::{Fortitude, Precision, Preservation},
};
use polimec_common::ProvideAssetPrice;
use sp_runtime::{
traits::{AccountIdConversion, CheckedMul, Get},
FixedPointNumber,
};

impl<T: Config> Pallet<T> {
pub fn bond_on_behalf_of(
account: T::AccountId,
bond_amount: BalanceOf<T>,
fee_asset: AssetId,
derivation_path: u32,
hold_reason: HoldReasonOf<T>,
) -> Result<AccountIdOf<T>, &'static str> {
let treasury = T::Treasury::get();
let bonding_account: AccountIdOf<T> = T::RootId::get().into_sub_account_truncating(derivation_path);
let existential_deposit = <T::BondingToken as fungible::Inspect<T::AccountId>>::minimum_balance();

let bonding_token_price = T::PriceProvider::get_decimals_aware_price(
T::BondingTokenId::get(),
T::UsdDecimals::get(),
T::BondingTokenDecimals::get(),
)
.ok_or("Price not available")?;

let fee_asset_decimals = <T::FeeToken as fungibles::metadata::Inspect<AccountIdOf<T>>>::decimals(fee_asset);
let fee_token_price =
T::PriceProvider::get_decimals_aware_price(fee_asset, T::UsdDecimals::get(), fee_asset_decimals)
.ok_or("Price not available")?;

let bonded_in_usd = bonding_token_price.saturating_mul_int(bond_amount);
let fee_in_usd = T::FeePercentage::get() * bonded_in_usd;
let fee_in_fee_asset =
fee_token_price.reciprocal().ok_or("Price not available")?.saturating_mul_int(fee_in_usd);

// Pay the fee from the user to the treasury
T::FeeToken::transfer(fee_asset, &account, &treasury, fee_in_fee_asset, Preservation::Preserve)?;

// Ensure the sub-account has an ED by the treasury. This will be refunded after all the tokens are unlocked
if T::BondingToken::balance(&bonding_account) < existential_deposit {
T::BondingToken::transfer(
&treasury.clone(),
&bonding_account,
existential_deposit,
Preservation::Preserve,
)?;
}
// Bond the PLMC on behalf of the user
T::BondingToken::transfer_and_hold(
&hold_reason,
&treasury.clone(),
&bonding_account.clone(),
bond_amount,
Precision::Exact,
Preservation::Preserve,
Fortitude::Polite,
)?;

Ok(bonding_account)
}
}
Loading

0 comments on commit 6d96f7b

Please sign in to comment.