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 0cae26c
Show file tree
Hide file tree
Showing 15 changed files with 204 additions and 56 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

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

5 changes: 3 additions & 2 deletions pallets/funding/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
use super::*;
use crate::{
instantiator::*,
traits::{ProvideAssetPrice, SetPrices},
traits::{SetPrices},

};
use frame_benchmarking::v2::*;
use frame_support::{
Expand All @@ -35,7 +36,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, ReleaseSchedule, USD_DECIMALS, USD_UNIT, ProvideAssetPrice};
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
2 changes: 1 addition & 1 deletion pallets/funding/src/functions/misc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use sp_runtime::traits::CheckedAdd;

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

Expand Down
2 changes: 1 addition & 1 deletion pallets/funding/src/instantiator/calculations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use super::*;
use core::cmp::Ordering;
use itertools::GroupBy;
use polimec_common::USD_DECIMALS;

use polimec_common::ProvideAssetPrice;
impl<
T: Config + pallet_balances::Config<Balance = BalanceOf<T>>,
AllPalletsWithoutSystem: OnFinalize<BlockNumberFor<T>> + OnIdle<BlockNumberFor<T>> + OnInitialize<BlockNumberFor<T>>,
Expand Down
2 changes: 1 addition & 1 deletion pallets/funding/src/instantiator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use crate::{
defaults::{bounded_name, bounded_symbol, default_evaluations, default_project_metadata, ipfs_hash},
CT_DECIMALS, CT_UNIT,
},
traits::ProvideAssetPrice,
*,
};
use polimec_common::ProvideAssetPrice;
use core::cell::RefCell;
use itertools::Itertools;
use polimec_common::{USD_DECIMALS, USD_UNIT};
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,13 +197,14 @@ 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 polimec_common::ProvideAssetPrice;
use frame_system::pallet_prelude::*;
use sp_arithmetic::Percent;
use sp_runtime::{
Expand Down
3 changes: 1 addition & 2 deletions pallets/funding/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use super::*;
use crate as pallet_funding;
use crate::{
runtime_api::{ExtrinsicHelpers, Leaderboards, ProjectInformation, ProjectParticipationIds, UserInformation},
traits::ProvideAssetPrice,
};
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, USD_UNIT, ProvideAssetPrice};
use polkadot_parachain_primitives::primitives::Sibling;
use sp_arithmetic::Percent;
use sp_core::H256;
Expand Down
2 changes: 1 addition & 1 deletion pallets/funding/src/runtime_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use parity_scale_codec::{Decode, Encode};
use polimec_common::USD_DECIMALS;
use scale_info::TypeInfo;
use sp_runtime::traits::Zero;

use polimec_common::ProvideAssetPrice;
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)]
pub struct ProjectParticipationIds<T: Config> {
account: AccountIdOf<T>,
Expand Down
4 changes: 2 additions & 2 deletions pallets/funding/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::*;
use crate::{
instantiator::*,
mock::*,
traits::{ProvideAssetPrice, VestingDurationCalculation},
traits::{VestingDurationCalculation},
CurrencyMetadata, Error, ProjectMetadata, TicketSize,
};
use defaults::*;
Expand All @@ -15,7 +15,7 @@ use frame_support::{
};
use itertools::Itertools;
use parachains_common::DAYS;
use polimec_common::{ReleaseSchedule, USD_DECIMALS, USD_UNIT};
use polimec_common::{ReleaseSchedule, USD_DECIMALS, USD_UNIT, ProvideAssetPrice};
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
43 changes: 0 additions & 43 deletions pallets/funding/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,49 +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
19 changes: 19 additions & 0 deletions pallets/proxy-bonding/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[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
10 changes: 10 additions & 0 deletions pallets/proxy-bonding/src/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use crate::pallet::{Pallet, Config};

impl<T: Config> Pallet<T> {

pub fn bond_on_behalf_of(account: T::AccountId, amount: T::Balance) -> Result<(), &'static str> {
let bond = T::NativeToken::hold(account.clone(), amount)?;
T::NativeToken::transfer(account, T::ProxyBonding::account_id(), bond)?;
Ok(())
}
}
104 changes: 104 additions & 0 deletions pallets/proxy-bonding/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
mod functions;

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


type Balance = u128;

/// 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>;

/// A type representing the weights required by the dispatchables of this pallet.
type WeightInfo: crate::weights::WeightInfo;

/// The pallet giving access to this chain's native token
type NativeToken: fungible::Inspect<Self::AccountId, Balance=Balance> + fungible::MutateHold<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, Price = Self::Price>;
}

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

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// We usually use passive tense for events.
SomethingStored { block_number: BlockNumberFor<T>, who: T::AccountId },
}

#[pallet::error]
pub enum Error<T> {
/// Error names should be descriptive.
NoneValue,
/// Errors should have helpful documentation associated with them.
StorageOverflow,
}

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

#[pallet::call]
impl<T: Config> Pallet<T> {
/// An example dispatchable that takes a singles value as a parameter, writes the value to
/// storage and emits an event. This function must be dispatched by a signed extrinsic.
#[pallet::call_index(0)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn do_something(origin: OriginFor<T>, bn: u32) -> DispatchResultWithPostInfo {
// Check that the extrinsic was signed and get the signer.
// This function will return an error if the extrinsic is not signed.
// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_origin/index.html>
let who = ensure_signed(origin)?;

// Convert the u32 into a block number. This is possible because the set of trait bounds
// defined in [`frame_system::Config::BlockNumber`].
let block_number: BlockNumberFor<T> = bn.into();

// Update storage.
<Something<T>>::put(CompositeStruct { block_number });

// Emit an event.
Self::deposit_event(Event::SomethingStored { block_number, who });

// Return a successful [`DispatchResultWithPostInfo`] or [`DispatchResult`].
Ok(().into())
}

/// An example dispatchable that may throw a custom error.
#[pallet::call_index(1)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))]
pub fn cause_error(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let _who = ensure_signed(origin)?;

// Read a value from storage.
match <Something<T>>::get() {
// Return an error if the value has not been set.
None => Err(Error::<T>::NoneValue)?,
Some(mut old) => {
// Increment the value read from storage; will error in the event of overflow.
old.block_number = old
.block_number
.checked_add(&One::one())
// ^^ equivalent is to:
// .checked_add(&1u32.into())
// both of which build a `One` instance for the type `BlockNumber`.
.ok_or(Error::<T>::StorageOverflow)?;
// Update the value in storage with the incremented result.
<Something<T>>::put(old);
// Explore how you can rewrite this using
// [`frame_support::storage::StorageValue::mutate`].
Ok(().into())
},
}
}
}
}
49 changes: 48 additions & 1 deletion polimec-common/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{pallet_prelude::*, traits::tokens::fungible};
use sp_runtime::RuntimeDebug;
use sp_runtime::{FixedPointNumber, RuntimeDebug};
use sp_std::prelude::*;
use sp_runtime::traits::CheckedDiv;
pub use xcm::v4::{opaque::Xcm, Assets, Location, QueryId, SendError, SendResult, SendXcm, XcmHash};
use sp_runtime::traits::CheckedMul;

pub mod credentials;

Expand Down Expand Up @@ -235,3 +237,48 @@ impl SendXcm for DummyXcmSender {
Ok([0u8; 32])
}
}


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)
}
}

0 comments on commit 0cae26c

Please sign in to comment.