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 9b93ff0
Show file tree
Hide file tree
Showing 15 changed files with 221 additions and 69 deletions.
12 changes: 12 additions & 0 deletions Cargo.lock

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

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
34 changes: 34 additions & 0 deletions pallets/proxy-bonding/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[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
sp-runtime.workspace = true
polimec-common.workspace = true
parity-scale-codec.workspace = true
scale-info.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",

]
29 changes: 29 additions & 0 deletions pallets/proxy-bonding/src/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::{AccountIdOf, Balance, Config, HoldReasonOf, Pallet};
use frame_support::traits::{
fungible,
tokens::{Fortitude, Precision, Preservation},
};
use polimec_common::ProvideAssetPrice;
use sp_runtime::traits::{AccountIdConversion, Get};

impl<T: Config> Pallet<T> {
pub fn bond_on_behalf_of(
account: T::AccountId,
bond_amount: Balance,
derivation_path: u32,
hold_reason: HoldReasonOf<T>,
) -> Result<(), &'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 fee = T::PriceProvider::get_decimals_aware_price()?;
//
// // 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)?;
// }
// T::BondingToken::transfer_and_hold(hold_reason, treasury.clone(), bonding_account.clone(), bond_amount, Precision::Exact, Preservation::Preserve, Fortitude::Polite)?;

Ok(())
}
}
83 changes: 83 additions & 0 deletions pallets/proxy-bonding/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#![cfg_attr(not(feature = "std"), no_std)]

pub use pallet::*;

mod functions;

#[frame_support::pallet]
pub mod pallet {
use frame_support::{
dispatch::DispatchResultWithPostInfo,
pallet_prelude::*,
traits::{fungible, fungibles},
DefaultNoBound,
};
use frame_system::{pallet_prelude::*, weights};
use polimec_common::ProvideAssetPrice;
use sp_runtime::{
traits::{CheckedAdd, One},
TypeId,
};
use frame_support::pallet_prelude::Weight;

pub type Balance = u128;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type HoldReasonOf<T> = <<T as Config>::FeeToken as fungibles::InspectHold<AccountIdOf<T>>>::Reason;
// pub type AssetId<T> = <<T as Config>::FeeToken as fungiles::Inspect<

/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

/// The pallet giving access to the bonding token
type BondingToken: fungible::Inspect<Self::AccountId, Balance = Balance>
+ fungible::Mutate<Self::AccountId, Balance = Balance>
+ fungible::MutateHold<Self::AccountId, Balance = Balance>;

/// The pallet giving access to fee-paying assets, like USDT
type FeeToken: fungibles::Inspect<Self::AccountId, Balance = Balance>
+ fungibles::Mutate<Self::AccountId, Balance = Balance>
+ fungibles::InspectHold<Self::AccountId, Balance = Balance>;

/// Method to get the price of an asset like USDT or PLMC. Likely to come from an oracle
type PriceProvider: ProvideAssetPrice<AssetId = u32>;

/// The account holding the tokens to be bonded. Normally the treasury
type Treasury: Get<Self::AccountId>;

/// The id type that can generate sub-accounts
type Id: Encode + Decode + TypeId;

/// The root id used to derive sub-accounts. These sub-accounts will be used to bond the tokens
type RootId: Get<Self::Id>;
}

#[pallet::pallet]
pub struct Pallet<T>(_);

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
Event1 { who: T::AccountId },
}

#[pallet::error]
pub enum Error<T> {
Error1,
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(Weight::zero())]
pub fn example_extrinsic(origin: OriginFor<T>) -> DispatchResult {
let _caller = ensure_signed(origin)?;
Ok(())
}
}
}
Loading

0 comments on commit 9b93ff0

Please sign in to comment.