Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[AHM] Proxy migration #542

Merged
merged 2 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions integration-tests/ahm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub async fn remote_ext_test_setup<Block: sp_runtime::traits::Block>(

pub fn next_block_rc() {
let now = frame_system::Pallet::<polkadot_runtime::Runtime>::block_number();
log::info!(target: LOG_RC, "Next block: {:?}", now + 1);
log::debug!(target: LOG_RC, "Next block: {:?}", now + 1);
<polkadot_runtime::RcMigrator as frame_support::traits::OnFinalize<_>>::on_finalize(now);
frame_system::Pallet::<polkadot_runtime::Runtime>::set_block_number(now + 1);
frame_system::Pallet::<polkadot_runtime::Runtime>::reset_events();
Expand All @@ -67,7 +67,7 @@ pub fn next_block_rc() {

pub fn next_block_ah() {
let now = frame_system::Pallet::<asset_hub_polkadot_runtime::Runtime>::block_number();
log::info!(target: LOG_AH, "Next block: {:?}", now + 1);
log::debug!(target: LOG_AH, "Next block: {:?}", now + 1);
<asset_hub_polkadot_runtime::AhMigrator as frame_support::traits::OnFinalize<_>>::on_finalize(
now,
);
Expand Down
8 changes: 3 additions & 5 deletions integration-tests/ahm/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,8 @@ use frame_support::{pallet_prelude::*, traits::*, weights::WeightMeter};
use pallet_rc_migrator::{MigrationStage, RcMigrationStage};
use polkadot_primitives::InboundDownwardMessage;
use remote_externalities::RemoteExternalities;
use tokio::sync::mpsc::channel;

use asset_hub_polkadot_runtime::{Block as AssetHubBlock, Runtime as AssetHub};
use polkadot_runtime::{Block as PolkadotBlock, Runtime as Polkadot};
use polkadot_runtime::Runtime as Polkadot;

use super::mock::*;

Expand All @@ -61,9 +59,9 @@ async fn account_migration_works() {
dmps.extend(new_dmps);

if RcMigrationStage::<Polkadot>::get() ==
pallet_rc_migrator::MigrationStage::MultisigMigrationDone
pallet_rc_migrator::MigrationStage::ProxyMigrationDone
{
log::info!("Multisig migration done");
log::info!("Migration done");
break dmps;
}
}
Expand Down
4 changes: 4 additions & 0 deletions pallets/ah-migrator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pallet-balances = { workspace = true }
pallet-multisig = { workspace = true }
pallet-nomination-pools = { workspace = true }
pallet-preimage = { workspace = true }
pallet-proxy = { workspace = true }
pallet-rc-migrator = { workspace = true }
pallet-staking = { workspace = true }
pallet-state-trie-migration = { workspace = true }
Expand Down Expand Up @@ -44,6 +45,7 @@ std = [
"pallet-multisig/std",
"pallet-nomination-pools/std",
"pallet-preimage/std",
"pallet-proxy/std",
"pallet-rc-migrator/std",
"pallet-staking/std",
"pallet-state-trie-migration/std",
Expand All @@ -66,6 +68,7 @@ runtime-benchmarks = [
"pallet-multisig/runtime-benchmarks",
"pallet-nomination-pools/runtime-benchmarks",
"pallet-preimage/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-rc-migrator/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"pallet-state-trie-migration/runtime-benchmarks",
Expand All @@ -81,6 +84,7 @@ try-runtime = [
"pallet-multisig/try-runtime",
"pallet-nomination-pools/try-runtime",
"pallet-preimage/try-runtime",
"pallet-proxy/try-runtime",
"pallet-rc-migrator/try-runtime",
"pallet-staking/try-runtime",
"pallet-state-trie-migration/try-runtime",
Expand Down
66 changes: 63 additions & 3 deletions pallets/ah-migrator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,27 @@

pub mod account;
pub mod multisig;
pub mod proxy;
pub mod types;

pub use pallet::*;

use frame_support::{
pallet_prelude::*,
storage::{transactional::with_transaction_opaque_err, TransactionOutcome},
traits::{
fungible::{InspectFreeze, Mutate, MutateFreeze, MutateHold},
LockableCurrency, ReservableCurrency, WithdrawReasons as LockWithdrawReasons,
Defensive, LockableCurrency, ReservableCurrency, WithdrawReasons as LockWithdrawReasons,
},
};
use frame_system::pallet_prelude::*;
use pallet_balances::{AccountData, Reasons as LockReasons};
use pallet_rc_migrator::{accounts::Account as RcAccount, multisig::*};
use pallet_rc_migrator::{accounts::Account as RcAccount, multisig::*, proxy::*};
use sp_application_crypto::Ss58Codec;
use sp_runtime::{traits::Convert, AccountId32};
use sp_runtime::{
traits::{Convert, TryConvert},
AccountId32,
};
use sp_std::prelude::*;

/// The log target of this pallet.
Expand All @@ -65,6 +70,7 @@ pub mod pallet {
frame_system::Config<AccountData = AccountData<u128>, AccountId = AccountId32>
+ pallet_balances::Config<Balance = u128>
+ pallet_multisig::Config
+ pallet_proxy::Config
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
Expand All @@ -85,6 +91,15 @@ pub mod pallet {
type RcToAhHoldReason: Convert<Self::RcHoldReason, Self::RuntimeHoldReason>;
/// Relay Chain to Asset Hub Freeze Reasons mapping;
type RcToAhFreezeReason: Convert<Self::RcFreezeReason, Self::FreezeIdentifier>;
/// The abridged Relay Chain Proxy Type.
type RcProxyType: Parameter;
/// Convert a Relay Chain Proxy Type to a local AH one.
type RcToProxyType: TryConvert<Self::RcProxyType, <Self as pallet_proxy::Config>::ProxyType>;
/// Convert a Relay Chain Proxy Delay to a local AH one.
///
/// Note that we make a simplification here by assuming that both chains have the same block
// number type.
type RcToProxyDelay: TryConvert<BlockNumberFor<Self>, BlockNumberFor<Self>>;
}

#[pallet::error]
Expand All @@ -109,6 +124,30 @@ pub mod pallet {
/// How many multisigs failed to integrate.
count_bad: u32,
},
/// We received a batch of proxies that we are going to integrate.
ProxyProxiesBatchReceived {
/// How many proxies are in the batch.
count: u32,
},
/// We processed a batch of proxies that we received.
ProxyProxiesBatchProcessed {
/// How many proxies were successfully integrated.
count_good: u32,
/// How many proxies failed to integrate.
count_bad: u32,
},
/// We received a batch of proxy announcements that we are going to integrate.
ProxyAnnouncementsBatchReceived {
/// How many proxy announcements are in the batch.
count: u32,
},
/// We processed a batch of proxy announcements that we received.
ProxyAnnouncementsBatchProcessed {
/// How many proxy announcements were successfully integrated.
count_good: u32,
/// How many proxy announcements failed to integrate.
count_bad: u32,
},
}

#[pallet::pallet]
Expand Down Expand Up @@ -149,6 +188,27 @@ pub mod pallet {

Self::do_receive_multisigs(accounts).map_err(Into::into)
}

/// Receive proxies from the Relay Chain.
#[pallet::call_index(2)]
pub fn receive_proxy_proxies(
origin: OriginFor<T>,
proxies: Vec<RcProxyOf<T, T::RcProxyType>>,
) -> DispatchResult {
ensure_root(origin)?;

Self::do_receive_proxies(proxies).map_err(Into::into)
}

/// Receive proxy announcements from the Relay Chain.
#[pallet::call_index(3)]
pub fn receive_proxy_announcements(
origin: OriginFor<T>,
announcements: Vec<RcProxyAnnouncementOf<T>>,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_receive_proxy_announcements(announcements).map_err(Into::into)
}
}

#[pallet::hooks]
Expand Down
17 changes: 17 additions & 0 deletions pallets/ah-migrator/src/multisig.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{types::*, *};
use hex_literal::hex;

Expand Down
123 changes: 123 additions & 0 deletions pallets/ah-migrator/src/proxy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{types::*, *};
use sp_runtime::{traits::Zero, BoundedSlice};

impl<T: Config> Pallet<T> {
pub fn do_receive_proxies(proxies: Vec<RcProxyOf<T, T::RcProxyType>>) -> Result<(), Error<T>> {
Self::deposit_event(Event::ProxyProxiesBatchReceived { count: proxies.len() as u32 });
let (mut count_good, mut count_bad) = (0, 0);
log::info!(target: LOG_TARGET, "Integrating {} proxies", proxies.len());

for proxy in proxies {
match Self::do_receive_proxy(proxy) {
Ok(()) => count_good += 1,
Err(e) => {
count_bad += 1;
log::error!(target: LOG_TARGET, "Error while integrating proxy: {:?}", e);
},
}
}
Self::deposit_event(Event::ProxyProxiesBatchProcessed { count_good, count_bad });

Ok(())
}

/// Receive a single proxy and write it to storage.
pub fn do_receive_proxy(proxy: RcProxyOf<T, T::RcProxyType>) -> Result<(), Error<T>> {
log::debug!(target: LOG_TARGET, "Integrating proxy {}, deposit {:?}", proxy.delegator.to_ss58check(), proxy.deposit);

let max_proxies = <T as pallet_proxy::Config>::MaxProxies::get() as usize;
if proxy.proxies.len() > max_proxies {
log::error!(target: LOG_TARGET, "Truncating proxy list of {}", proxy.delegator.to_ss58check());
}

let proxies = proxy.proxies.into_iter().enumerate().filter_map(|(i, p)| {
let Ok(proxy_type) = T::RcToProxyType::try_convert(p.proxy_type) else {
// This is fine, eg. `Auction` proxy is not supported on AH
log::warn!(target: LOG_TARGET, "Dropping unsupported proxy at index {} for {}", i, proxy.delegator.to_ss58check());
return None;
};

let Ok(delay) = T::RcToProxyDelay::try_convert(p.delay).defensive() else {
return None;
};

Some(pallet_proxy::ProxyDefinition {
delegate: p.delegate,
delay: delay,
proxy_type,
})
})
.take(max_proxies)
.collect::<Vec<_>>();

let Ok(bounded_proxies) =
BoundedSlice::try_from(proxies.as_slice()).defensive_proof("unreachable")
else {
return Err(Error::TODO);
};

// The deposit was already taken by the account migration

// Add the proxies
pallet_proxy::Proxies::<T>::insert(proxy.delegator, (bounded_proxies, proxy.deposit));

Ok(())
}

pub fn do_receive_proxy_announcements(
announcements: Vec<RcProxyAnnouncementOf<T>>,
) -> Result<(), Error<T>> {
Self::deposit_event(Event::ProxyAnnouncementsBatchReceived {
count: announcements.len() as u32,
});

let (mut count_good, mut count_bad) = (0, 0);
log::info!(target: LOG_TARGET, "Integrating {} proxy announcements", announcements.len());

for announcement in announcements {
match Self::do_receive_proxy_announcement(announcement) {
Ok(()) => count_good += 1,
Err(e) => {
count_bad += 1;
log::error!(target: LOG_TARGET, "Error while integrating proxy announcement: {:?}", e);
},
}
}

Self::deposit_event(Event::ProxyAnnouncementsBatchProcessed { count_good, count_bad });

Ok(())
}

pub fn do_receive_proxy_announcement(
announcement: RcProxyAnnouncementOf<T>,
) -> Result<(), Error<T>> {
let missing = <T as pallet_proxy::Config>::Currency::unreserve(
&announcement.depositor,
announcement.deposit,
);

if !missing.is_zero() {
log::warn!(target: LOG_TARGET, "Could not unreserve full proxy announcement deposit for {}, missing {:?}", announcement.depositor.to_ss58check(), missing);
}

Ok(())
}
}
4 changes: 4 additions & 0 deletions pallets/rc-migrator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ sp-std = { workspace = true }
sp-io = { workspace = true }
pallet-balances = { workspace = true }
pallet-staking = { workspace = true }
pallet-proxy = { workspace = true }
pallet-multisig = { workspace = true }
polkadot-runtime-common = { workspace = true }
runtime-parachains = { workspace = true }
Expand All @@ -38,6 +39,7 @@ std = [
"log/std",
"pallet-balances/std",
"pallet-multisig/std",
"pallet-proxy/std",
"pallet-staking/std",
"polkadot-parachain-primitives/std",
"polkadot-runtime-common/std",
Expand All @@ -56,6 +58,7 @@ runtime-benchmarks = [
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-multisig/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"polkadot-parachain-primitives/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
Expand All @@ -67,6 +70,7 @@ try-runtime = [
"frame-system/try-runtime",
"pallet-balances/try-runtime",
"pallet-multisig/try-runtime",
"pallet-proxy/try-runtime",
"pallet-staking/try-runtime",
"polkadot-runtime-common/try-runtime",
"runtime-parachains/try-runtime",
Expand Down
Loading
Loading