Skip to content

Commit

Permalink
refactor: Drop tranche multiLocation (#1340)
Browse files Browse the repository at this point in the history
* Drop Tranche location

We make it just `None` since having a MultiLocation for Tranche tokens
implies they are XCM-transferrable when in fact we have specific Xcm
configs in place to forbid tranche tokens transfers. Tranche tokens are
only transferrable through Centrifuge Connectors, which guarantee the
permissioned-nature of tranche tokens are respected.

* centrifuge: Add TrancheLocationMigration

* centrifuge: Extend Executive with TrancheLocationMigration

* centrifuge: Add migrations

* altair: Add migrations

* dev: Add migrations

* pool-system: Drop unused deps

* Use log instead of expect
  • Loading branch information
NunoAlexandre authored May 17, 2023
1 parent 0be3e2f commit 9239998
Show file tree
Hide file tree
Showing 15 changed files with 150 additions and 91 deletions.
3 changes: 2 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion pallets/pool-registry/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ impl pallet_pool_system::Config for Test {
type NAV = FakeNav;
type PalletId = PoolPalletId;
type PalletIndex = PoolPalletIndex;
type ParachainId = ParachainInfo;
type Permission = PermissionsMock;
type PoolCreateOrigin = EnsureSigned<u64>;
type PoolCurrency = PoolCurrency;
Expand Down
11 changes: 3 additions & 8 deletions pallets/pool-system/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,16 @@ sp-arithmetic = { git = "https://github.com/paritytech/substrate", default-featu
sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.37" }
sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.37" }

orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.37" }
pallet-permissions = { path = "../../pallets/permissions", default-features = false }
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.37" }
xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.37" }

# Benchmarking dependencies - optional
frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.37" }
orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, optional = true, branch = "polkadot-v0.9.37" }
pallet-investments = { path = "../../pallets/investments", default-features = false, optional = true }

[dev-dependencies]
cfg-test-utils = { path = "../../libs/test-utils", default-features = true }
orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.37" }
orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = true, branch = "polkadot-v0.9.37" }
pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = true, branch = "polkadot-v0.9.37" }
pallet-investments = { path = "../../pallets/investments", default-features = true }
Expand All @@ -48,6 +47,7 @@ parachain-info = { git = "https://github.com/paritytech/cumulus", default-featur
rand = "0.8.5"
sp-core = { git = "https://github.com/paritytech/substrate", default-features = true, branch = "polkadot-v0.9.37" }
sp-io = { git = "https://github.com/paritytech/substrate", default-features = true, branch = "polkadot-v0.9.37" }
xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.37" }

[features]
default = ["std"]
Expand All @@ -63,7 +63,6 @@ runtime-benchmarks = [
"pallet-investments/runtime-benchmarks",
"pallet-permissions/runtime-benchmarks",
"xcm/runtime-benchmarks",
"polkadot-parachain/runtime-benchmarks",
"orml-asset-registry/runtime-benchmarks",
]
std = [
Expand All @@ -81,9 +80,6 @@ std = [
"cfg-types/std",
"cfg-primitives/std",
"pallet-permissions/std",
"polkadot-parachain/std",
"orml-asset-registry/std",
"xcm/std",
"frame-benchmarking/std",
"serde/std",
]
Expand All @@ -94,7 +90,6 @@ try-runtime = [
"lazy_static/spin_no_std",
"cfg-types/try-runtime",
"frame-system/try-runtime",
"orml-asset-registry/try-runtime",
"pallet-permissions/try-runtime",
"pallet-timestamp/try-runtime",
]
11 changes: 2 additions & 9 deletions pallets/pool-system/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,8 @@ impl<T: Config> PoolMutate<T::AccountId, T::PoolId> for Pallet<T> {
None => return Err(Error::<T>::MetadataForCurrencyNotFound.into()),
};

let parachain_id = T::ParachainId::get();

let metadata = tranche.create_asset_metadata(
decimals,
parachain_id,
T::PalletIndex::get(),
token_name.to_vec(),
token_symbol.to_vec(),
);
let metadata =
tranche.create_asset_metadata(decimals, token_name.to_vec(), token_symbol.to_vec());

T::AssetRegistry::register_asset(Some(tranche.currency.into()), metadata)
.map_err(|_| Error::<T>::FailedToRegisterTrancheMetadata)?;
Expand Down
4 changes: 0 additions & 4 deletions pallets/pool-system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ use orml_traits::{
Change,
};
pub use pallet::*;
use polkadot_parachain::primitives::Id as ParachainId;
use pool_types::{
PoolChanges, PoolDepositInfo, PoolDetails, PoolEssence, PoolLocator, ScheduledUpdateDetails,
};
Expand Down Expand Up @@ -275,9 +274,6 @@ pub mod pallet {
CustomMetadata = CustomMetadata,
>;

#[pallet::constant]
type ParachainId: Get<ParachainId>;

type Currency: ReservableCurrency<Self::AccountId, Balance = Self::Balance>;

type Tokens: Mutate<Self::AccountId>
Expand Down
1 change: 0 additions & 1 deletion pallets/pool-system/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,6 @@ impl Config for Runtime {
type NAV = FakeNav;
type PalletId = PoolPalletId;
type PalletIndex = PoolPalletIndex;
type ParachainId = ParachainInfo;
type Permission = Permissions;
type PoolCreateOrigin = EnsureSigned<u64>;
type PoolCurrency = PoolCurrency;
Expand Down
22 changes: 4 additions & 18 deletions pallets/pool-system/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,10 @@ use cfg_types::{
use frame_support::{assert_err, assert_noop, assert_ok};
use orml_traits::asset_registry::{AssetMetadata, Inspect};
use rand::Rng;
use sp_core::{storage::StateVersion, Encode};
use sp_core::storage::StateVersion;
use sp_runtime::{
traits::{ConstU32, One, Zero},
FixedPointNumber, Perquintill, TokenError, WeakBoundedVec,
};
use xcm::{
latest::MultiLocation,
prelude::{GeneralKey, PalletInstance, Parachain, X3},
VersionedMultiLocation,
traits::{One, Zero},
FixedPointNumber, Perquintill, TokenError,
};

use crate::{
Expand Down Expand Up @@ -2311,8 +2306,6 @@ fn create_tranche_token_metadata() {

let pool = Pool::<Runtime>::get(3).unwrap();
let tranche_currency = pool.tranches.tranches[0].currency;
let tranche_id =
WeakBoundedVec::<u8, ConstU32<32>>::force_from(tranche_currency.encode(), None);

assert_eq!(
<Runtime as Config>::AssetRegistry::metadata(&tranche_currency.into()).unwrap(),
Expand All @@ -2321,14 +2314,7 @@ fn create_tranche_token_metadata() {
name: "SuperToken".into(),
symbol: "ST".into(),
existential_deposit: 0,
location: Some(VersionedMultiLocation::V1(MultiLocation {
parents: 1,
interior: X3(
Parachain(MockParachainId::get()),
PalletInstance(PoolPalletIndex::get()),
GeneralKey(tranche_id)
),
})),
location: None,
additional: CustomMetadata {
mintable: false,
permissioned: true,
Expand Down
44 changes: 6 additions & 38 deletions pallets/pool-system/src/tranches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,20 @@ use frame_support::{
dispatch::DispatchResult,
ensure,
sp_runtime::ArithmeticError,
traits::{fungibles::Inspect, Get},
traits::{fungibles::Inspect, Get, Len},
Blake2_128, BoundedVec, Parameter, RuntimeDebug, StorageHasher,
};
use orml_traits::asset_registry::AssetMetadata;
use polkadot_parachain::primitives::Id as ParachainId;
use rev_slice::{RevSlice, SliceExt};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_arithmetic::traits::{checked_pow, BaseArithmetic, Unsigned};
use sp_runtime::{
traits::{ConstU32, Member, One, Zero},
DispatchError, FixedPointNumber, FixedPointOperand, Perquintill, WeakBoundedVec,
traits::{Member, One, Zero},
DispatchError, FixedPointNumber, FixedPointOperand, Perquintill,
};
use sp_std::{marker::PhantomData, ops::Deref, vec::Vec};
use xcm::{
latest::MultiLocation,
prelude::{GeneralKey, PalletInstance, Parachain, X3},
VersionedMultiLocation,
};

/// Type that indicates the seniority of a tranche
pub type Seniority = u32;
Expand Down Expand Up @@ -236,8 +230,6 @@ where
pub fn create_asset_metadata(
&self,
decimals: u32,
parachain_id: ParachainId,
pallet_index: u8,
token_name: Vec<u8>,
token_symbol: Vec<u8>,
) -> AssetMetadata<Balance, CustomMetadata>
Expand All @@ -246,22 +238,12 @@ where
Currency: Encode,
CustomMetadata: Parameter + Member + TypeInfo,
{
let tranche_id =
WeakBoundedVec::<u8, ConstU32<32>>::force_from(self.currency.encode(), None);

AssetMetadata {
decimals,
name: token_name,
symbol: token_symbol,
existential_deposit: Zero::zero(),
location: Some(VersionedMultiLocation::V1(MultiLocation {
parents: 1,
interior: X3(
Parachain(parachain_id.into()),
PalletInstance(pallet_index),
GeneralKey(tranche_id),
),
})),
location: None,
additional: CustomMetadata {
mintable: false,
permissioned: true,
Expand Down Expand Up @@ -1854,27 +1836,13 @@ pub mod test {
let decimals: u32 = 10;
let name: Vec<u8> = "Glimmer".into();
let symbol: Vec<u8> = "GLMR".into();
let asset_metadata = tranche.create_asset_metadata(
decimals,
// fake parachain id
ParachainId::from(42),
// fake pallet index
42u8,
name,
symbol,
);
let asset_metadata = tranche.create_asset_metadata(decimals, name, symbol);

assert_eq!(asset_metadata.existential_deposit, 0);
assert_eq!(asset_metadata.name[..], [71, 108, 105, 109, 109, 101, 114]);
assert_eq!(asset_metadata.symbol[..], [71, 76, 77, 82]);
assert_eq!(asset_metadata.decimals, decimals);
assert!(match asset_metadata.location {
Some(VersionedMultiLocation::V1(xcm::v1::MultiLocation {
parents: 1,
interior: X3(Parachain(42), PalletInstance(42), GeneralKey(_)),
})) => true,
_ => false,
})
assert_eq!(asset_metadata.location, None);
}
}

Expand Down
1 change: 1 addition & 0 deletions runtime/altair/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/centrifuge/centrifuge-chain"
# third-party dependencies
codec = { package = "parity-scale-codec", version = "3.0", default-features = false, features = ["derive"] }
hex-literal = { version = "0.3.4", optional = true }
log = { version = "0.4.17", default-features = false }
scale-info = { version = "2.3.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.119", optional = true }
static_assertions = "1.1.0"
Expand Down
3 changes: 1 addition & 2 deletions runtime/altair/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,6 @@ impl pallet_pool_system::Config for Runtime {
type NAV = Loans;
type PalletId = PoolPalletId;
type PalletIndex = PoolPalletIndex;
type ParachainId = ParachainInfo;
type Permission = Permissions;
type PoolCreateOrigin = EnsureRoot<AccountId>;
type PoolCurrency = PoolCurrency;
Expand Down Expand Up @@ -1560,7 +1559,7 @@ pub type Executive = frame_executive::Executive<
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
crate::migrations::UpgradeAltair1027,
migrations::UpgradeAltair1027,
>;

#[cfg(not(feature = "disable-runtime-api"))]
Expand Down
64 changes: 63 additions & 1 deletion runtime/altair/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

use crate::{AccountId, BlockRewards, ExistentialDeposit, NativeToken, Runtime};
use cfg_types::tokens::CurrencyId;
use frame_support::{traits::OnRuntimeUpgrade, weights::Weight};

use crate::{AccountId, BlockRewards, ExistentialDeposit, NativeToken, OrmlAssetRegistry, Runtime};

pub type UpgradeAltair1027 = (
pallet_loans_ref::migrations::v1::Migration<Runtime>,
Expand All @@ -26,6 +29,7 @@ pub type UpgradeAltair1027 = (
NativeToken,
ExistentialDeposit,
>,
asset_registry::TrancheLocationMigration,
);

mod init_block_rewards {
Expand Down Expand Up @@ -145,3 +149,61 @@ mod session_key_migration {
}
}
}

mod asset_registry {
use super::*;

/// This migration sets the AssetMetadata.location of all the Tranche tokens
/// registered in the AssetRegistry to `None`.
pub struct TrancheLocationMigration;

impl OnRuntimeUpgrade for TrancheLocationMigration {
fn on_runtime_upgrade() -> Weight {
for (asset_id, metadata) in orml_asset_registry::Metadata::<Runtime>::iter() {
if matches!(asset_id, CurrencyId::Tranche(_, _)) && metadata.location.is_some() {
match OrmlAssetRegistry::do_update_asset(
asset_id,
// decimals
None,
// name
None,
// symbol
None,
// existential_deposit
None,
// location: we do set it to `None`
Some(None),
// additional
None,
) {
Err(e) => log::error!("TrancheLocationMigration: Failed to update asset with underlying error: {:?}", e),
_ => continue,
}
}
}

// todo(nuno): not sure how to build this properly,
// setting it to a conservative value for now.
Weight::from_ref_time(200_000_000)
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<sp_std::vec::Vec<u8>, &'static str> {
Ok(Default::default())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_: sp_std::vec::Vec<u8>) -> Result<(), &'static str> {
for (asset_id, metadata) in orml_asset_registry::Metadata::<Runtime>::iter() {
if matches!(asset_id, CurrencyId::Tranche(_, _)) {
frame_support::ensure!(
metadata.location.is_none(),
"A tranche token's location is not None"
)
}
}

Ok(())
}
}
}
1 change: 1 addition & 0 deletions runtime/centrifuge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/centrifuge/centrifuge-chain"
# third-party dependencies
codec = { package = "parity-scale-codec", version = "3.0", default-features = false, features = ["derive"] }
hex-literal = { version = "0.3.4", optional = true }
log = { version = "0.4.17", default-features = false }
scale-info = { version = "2.3.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.119", optional = true }
static_assertions = "1.1.0"
Expand Down
3 changes: 1 addition & 2 deletions runtime/centrifuge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1379,7 +1379,6 @@ impl pallet_pool_system::Config for Runtime {
type NAV = Loans;
type PalletId = PoolPalletId;
type PalletIndex = PoolPalletIndex;
type ParachainId = ParachainInfo;
type Permission = Permissions;
type PoolCreateOrigin = EnsureRoot<AccountId>;
type PoolCurrency = PoolCurrency;
Expand Down Expand Up @@ -1734,7 +1733,7 @@ pub type Executive = frame_executive::Executive<
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
crate::migrations::UpgradeCentrifuge1019,
migrations::UpgradeCentrifuge1019,
>;

#[cfg(not(feature = "disable-runtime-api"))]
Expand Down
Loading

0 comments on commit 9239998

Please sign in to comment.