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 20, 2024
1 parent 0d71a49 commit 7675e65
Show file tree
Hide file tree
Showing 18 changed files with 772 additions and 69 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.

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
2 changes: 2 additions & 0 deletions pallets/funding/src/functions/misc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[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,
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 @@ -151,7 +151,7 @@ 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::*,
Expand All @@ -160,6 +160,7 @@ pub mod pallet {
};
use frame_system::pallet_prelude::*;
use on_slash_vesting::OnSlash;
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
63 changes: 63 additions & 0 deletions pallets/proxy-bonding/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
[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
serde = { version = "1.0.204", features = ["derive"] }

[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"
]
112 changes: 112 additions & 0 deletions pallets/proxy-bonding/src/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use frame_support::ensure;
use crate::{AccountIdOf, AssetId, BalanceOf, Config, Pallet, ReleaseType, Releases};
use frame_support::traits::{
fungible,
fungible::{Inspect, Mutate, MutateHold},
fungibles,
fungibles::Mutate as FungiblesMutate,
tokens::{Fortitude, Precision, Preservation},
};
use frame_system::pallet_prelude::BlockNumberFor;
use polimec_common::ProvideAssetPrice;
use sp_runtime::{
traits::{AccountIdConversion, Get},
FixedPointNumber,
};

impl<T: Config> Pallet<T> {
/// Calculate the USD fee in `fee_asset` for bonding `bond_amount` of the native token.
/// e.g. if the fee is 1%, native token PLMC, fee_asset USDT, bond_amount 1000 PLMC, PLMC price 0.5USD, USDT price 1USD,
/// Then the calculated fee would be 1% * 1000 * 0.5 = 5USD, which is 5 USDT at a price of 1USD.
pub fn calculate_fee(bond_amount: BalanceOf<T>, fee_asset: AssetId) -> Result<BalanceOf<T>, &'static str> {
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);

Ok(fee_in_fee_asset)
}

/// Put some tokens on hold from the treasury into a sub-account, on behalf of a user.
/// User pays a fee for this functionality, which can be later refunded.
pub fn bond_on_behalf_of(
derivation_path: u32,
account: T::AccountId,
bond_amount: BalanceOf<T>,
fee_asset: AssetId,
hold_reason: T::RuntimeHoldReason,
) -> 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_in_fee_asset = Self::calculate_fee(bond_amount, fee_asset)?;

// Pay the fee from the user to the bonding account. It awaits either a full transfer to the T::FeeRecipient, or a refund to each user
T::FeeToken::transfer(fee_asset, &account, &bonding_account, 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.into(),
&treasury.clone(),
&bonding_account.clone(),
bond_amount,
Precision::Exact,
Preservation::Preserve,
Fortitude::Polite,
)?;

Ok(())
}

/// Set the block for which we can release the bonds of a sub-account, and transfer it back to the treasury.
pub fn set_release_type(
derivation_path: u32,
hold_reason: T::RuntimeHoldReason,
release_type: ReleaseType<BlockNumberFor<T>>,
) {
Releases::<T>::insert(derivation_path, hold_reason, release_type);
}

/// Refund the fee paid by a user to lock up some treasury tokens. It is this function's caller responsibility to ensure that the fee is not refunded twice.
pub fn refund_fee(
derivation_path: u32,
hold_reason: T::RuntimeHoldReason,
account: &T::AccountId,
bond_amount: BalanceOf<T>,
fee_asset: AssetId,
) -> Result<(), DispatchError> {
let bonding_account: AccountIdOf<T> = T::RootId::get().into_sub_account_truncating(derivation_path);
let fee_in_fee_asset = Self::calculate_fee(bond_amount, fee_asset)?;
let release_type = Releases::<T>::get(derivation_path, hold_reason).ok_or("Release type not found")?;

ensure!(release_type == ReleaseType::Refunded, "Need to set this derivation path / hold reason as `Refunded`");

// We know this fee token account is existing thanks to the provider reference of the ED of the native asset, so we can fully move all the funds.
// FYI same cannot be said of the `account`. We assume they only hold the fee token so their fee asset balance must not go below the min_balance.
T::FeeToken::transfer(fee_asset, &bonding_account, account, fee_in_fee_asset, Preservation::Expendable)?;

Ok(())
}
}
Loading

0 comments on commit 7675e65

Please sign in to comment.