difftreelog
fix(preimage-execution) introduce weight expectation + adjust benchmarks + new tests
in: master
6 files changed
pallets/maintenance/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/maintenance/src/benchmarking.rs
+++ b/pallets/maintenance/src/benchmarking.rs
@@ -19,7 +19,7 @@
use frame_benchmarking::benchmarks;
use frame_system::{Call as RuntimeCall, RawOrigin};
-use frame_support::{ensure, traits::StorePreimage};
+use frame_support::{ensure, pallet_prelude::Weight, traits::StorePreimage};
use codec::Encode;
use sp_std::vec;
@@ -40,7 +40,7 @@
execute_preimage {
let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();
let hash = T::Preimages::note(call_hash.into())?;
- }: _(RawOrigin::Root, hash)
+ }: _(RawOrigin::Root, hash, None, Weight::from_parts(100000000000, 100000000000))
verify {
}
}
pallets/maintenance/src/lib.rsdiffbeforeafterboth--- a/pallets/maintenance/src/lib.rs
+++ b/pallets/maintenance/src/lib.rs
@@ -104,30 +104,48 @@
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]
- pub fn execute_preimage(_origin: OriginFor<T>, _hash: H256) -> DispatchResult {
- #[cfg(feature = "preimage")]
- {
- let origin = _origin;
- let hash = _hash;
+ pub fn execute_preimage(
+ origin: OriginFor<T>,
+ hash: H256,
+ preimage_length: Option<u32>,
+ weight_bound: Weight,
+ ) -> DispatchResultWithPostInfo {
+ use codec::Decode;
- ensure_root(origin)?;
+ ensure_root(origin)?;
- let len = T::Preimages::len(&hash).ok_or(DispatchError::Unavailable)?;
- let bounded = T::Preimages::pick::<<T as Config>::RuntimeCall>(hash, len);
- let (call, _) =
- T::Preimages::realize(&bounded).map_err(|_| DispatchError::Unavailable)?;
+ let data = T::Preimages::fetch(&hash, preimage_length)?;
+ weight_bound.set_proof_size(
+ weight_bound
+ .proof_size()
+ .checked_sub(
+ data.len()
+ .try_into()
+ .map_err(|_| DispatchError::Corruption)?,
+ )
+ .ok_or(DispatchError::Exhausted)?,
+ );
- let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {
- Ok(_) => Ok(()),
- Err(error_and_info) => Err(error_and_info.error),
- };
+ let call = <T as Config>::RuntimeCall::decode(&mut &data[..])
+ .map_err(|_| DispatchError::Corruption)?;
- result
- }
+ ensure!(
+ call.get_dispatch_info().weight.all_lte(weight_bound),
+ DispatchError::Exhausted
+ );
- #[cfg(not(feature = "preimage"))]
- {
- Err(DispatchError::Unavailable)
+ match call.dispatch(frame_system::RawOrigin::Root.into()) {
+ Ok(post_info) => Ok(PostDispatchInfo {
+ actual_weight: post_info.actual_weight,
+ pays_fee: Pays::No,
+ }),
+ Err(error_and_info) => Err(DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: error_and_info.post_info.actual_weight,
+ pays_fee: Pays::No,
+ },
+ error: error_and_info.error,
+ }),
}
}
}
runtime/common/config/pallets/preimage.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/preimage.rs
+++ b/runtime/common/config/pallets/preimage.rs
@@ -20,8 +20,7 @@
use up_common::constants::*;
parameter_types! {
- pub PreimageBaseDeposit: Balance = 1000 * UNIQUE; // deposit(2, 64);
- // pub PreimageByteDeposit: Balance = 1 * CENTIUNIQUE; // deposit(0, 1);
+ pub PreimageBaseDeposit: Balance = 1000 * UNIQUE;
}
impl pallet_preimage::Config for Runtime {
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -565,9 +565,6 @@
#[cfg(feature = "collator-selection")]
list_benchmark!(list, extra, pallet_identity, Identity);
- #[cfg(feature = "preimage")]
- list_benchmark!(list, extra, pallet_preimage, Preimage);
-
#[cfg(feature = "foreign-assets")]
list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);
@@ -631,9 +628,6 @@
#[cfg(feature = "collator-selection")]
add_benchmark!(params, batches, pallet_identity, Identity);
-
- #[cfg(feature = "preimage")]
- add_benchmark!(params, batches, pallet_preimage, Preimage);
#[cfg(feature = "foreign-assets")]
add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);
tests/src/maintenance.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -18,6 +18,7 @@
import {ApiPromise} from '@polkadot/api';
import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
import {itEth} from './eth/util';
+import {UniqueHelper} from './util/playgrounds/unique';
async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
return (await api.query.maintenance.enabled()).toJSON() as boolean;
@@ -280,6 +281,13 @@
describe('Preimage Execution', () => {
let preimageHash: string;
+ async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {
+ const result = await helper.preimage.notePreimage(bob, preimage);
+ const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
+ const preimageHash = events[0].event.data[0].toHuman();
+ return preimageHash;
+ }
+
before(async function() {
await usingPlaygrounds(async (helper) => {
requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);
@@ -298,15 +306,14 @@
},
]);
const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();
- const result = await helper.preimage.notePreimage(bob, preimage);
- const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
- preimageHash = events[0].event.data[0].toHuman();
+ preimageHash = await notePreimage(helper, preimage);
});
});
itSub('Successfully executes call in a preimage', async ({helper}) => {
- const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [preimageHash]))
- .to.be.fulfilled;
+ const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 10000000000, proofSize: 10000000000},
+ ])).to.be.fulfilled;
// preimage is executed, and an appropriate event is present
const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');
@@ -316,17 +323,37 @@
expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');
});
+ itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {
+ const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);
+
+ const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [
+ {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,
+ ]).method.toHex();
+ const preimageHash = await notePreimage(helper, preimage);
+
+ await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
+ ])).to.be.rejectedWith(/balances\.InsufficientBalance/);
+ });
+
itSub('Does not allow preimage execution with non-root', async ({helper}) => {
- await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [preimageHash]))
- .to.be.rejectedWith(/BadOrigin/);
+ await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
+ ])).to.be.rejectedWith(/BadOrigin/);
});
itSub('Does not allow execution of non-existent preimages', async ({helper}) => {
await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
- '0x1010101010101010101010101010101010101010101010101010101010101010',
+ '0x1010101010101010101010101010101010101010101010101010101010101010', null, {refTime: 100000000000, proofSize: 100000000000},
])).to.be.rejectedWith(/Unavailable/);
});
+ itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {
+ await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
+ preimageHash, null, {refTime: 1000, proofSize: 1000},
+ ])).to.be.rejectedWith(/Exhausted/);
+ });
+
after(async function() {
await usingPlaygrounds(async (helper) => {
if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;
tests/src/util/identitySetter.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.03//4// Pulls identities and sub-identities from a chain and then makes a preimage to later force upload them into another.5// Only changed or previously non-existent data are inserted.6//7// Usage: `yarn setIdentities [relay WS URL] [parachain WS URL] [user key]8// Example: `yarn setIdentities wss://polkadot-rpc.dwellir.com ws://localhost:9944 escape pattern miracle train sudden cart adapt embark wedding alien lamp mesh`910import {encodeAddress} from '@polkadot/keyring';11import {IKeyringPair} from '@polkadot/types/types';12import {usingPlaygrounds, Pallets} from './index';13import {ChainHelperBase} from './playgrounds/unique';1415const relayUrl = process.argv[2] ?? 'ws://localhost:9844';16const paraUrl = process.argv[3] ?? 'ws://localhost:9944';17const key = process.argv.length > 4 ? process.argv.slice(4).join(' ') : '//Alice';1819export function extractAccountId(key: any): string {20 return (key as any).toHuman()[0];21}2223export function extractIdentityInfo(value: any): object {24 const heart = (value as any).unwrap();25 const identity = heart.toJSON();26 identity.judgements = heart.judgements.toHuman();27 return identity;28}2930export function extractIdentity(key: any, value: any): [string, any] {31 return [extractAccountId(key), extractIdentityInfo(value)];32}3334export async function getIdentities(helper: ChainHelperBase, noneCasePredicate?: (key: any, value: any) => void) {35 const identities: [string, any][] = [];36 for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {37 const value = v as any;38 if (value.isNone) {39 if (noneCasePredicate) noneCasePredicate(key, value);40 continue;41 }42 identities.push(extractIdentity(key, value));43 }44 return identities;45}4647// whether the existing chain data is more important than the coming48function isCurrentChainDataPriority(helper: ChainHelperBase, currentChainId: number | undefined, relayChainId: number) {49 if (!currentChainId) return false;50 // information has come from local chain, and is automatically superior51 if (currentChainId == helper.chain.getChainProperties().ss58Format) return true;52 // the lower the id, the more important it is (Polkadot has ss58 prefix = 0, Kusama has ss58 prefix = 2)53 return currentChainId < relayChainId;54}5556// construct an object with all data necessary for insertion from storage query results57export function constructSubInfo(identityAccount: string, subQuery: any, supers: any[], ss58?: number): [string, any] {58 const deposit = subQuery.toJSON()[0];59 const subIdentities = subQuery.toHuman()[1];60 subIdentities.map((sub: string) => supers.find((sup: any) => sup[0] === sub));6162 return [63 encodeAddress(identityAccount, ss58), [64 deposit,65 subIdentities.map((sub: string): [string, object] | null => {66 const sup = supers.find((sup: any) => sup[0] === sub);67 if (!sup) {68 console.error(`Error: Could not find info on super for \nsub-identity account\t${sub} of \nsuper account \t\t${identityAccount}, skipping.`);69 return null;70 }71 return [encodeAddress(sub, ss58), sup[1].toJSON()[1]];72 }).filter((x: any) => x),73 ],74 ];75}7677export async function getSubs(helper: ChainHelperBase) {78 return (await helper.getApi().query.identity.subsOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);79}8081export async function getSupers(helper: ChainHelperBase) {82 return (await helper.getApi().query.identity.superOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);83}8485async function uploadPreimage(helper: ChainHelperBase, preimageMaker: IKeyringPair, preimage: string) {86 try {87 await helper.executeExtrinsic(preimageMaker, 'api.tx.preimage.notePreimage', [preimage]);88 } catch(e: any) {89 if (e.message.includes('AlreadyNoted')) {90 console.warn('Warning: The same preimage already exists on the chain. Nothing was uploaded.');91 } else {92 console.error(e);93 }94 }95}9697// The utility for pulling identity and sub-identity data98const forceInsertIdentities = async (): Promise<void> => {99 let relaySS58Prefix = 0;100 const identitiesOnRelay: any[] = [];101 const subsOnRelay: any[] = [];102 const identitiesToRemove: string[] = [];103 await usingPlaygrounds(async helper => {104 try {105 relaySS58Prefix = helper.chain.getChainProperties().ss58Format;106 // iterate over every identity107 for(const [key, value] of await getIdentities(helper, (key, _value) => identitiesToRemove.push((key as any).toHuman()[0]))) {108 // if any of the judgements resulted in a good confirmed outcome, keep this identity109 let knownGood = false, reasonable = false;110 for (const [_id, judgement] of value.judgements) {111 if (judgement == 'KnownGood') knownGood = true;112 if (judgement == 'Reasonable') reasonable = true;113 }114 if (!(reasonable || knownGood)) continue;115 // replace the registrator id with the relay chain's ss58 format116 value.judgements = [[helper.chain.getChainProperties().ss58Format, knownGood ? 'KnownGood' : 'Reasonable']];117 identitiesOnRelay.push([key, value]);118 }119120 const sublessIdentities = [...identitiesOnRelay];121 const supersOfSubs = await getSupers(helper);122123 // iterate over every sub-identity124 for(const [key, value] of await getSubs(helper)) {125 // only get subs of the identities interesting to us126 const identityIndex = sublessIdentities.findIndex((x: any) => x[0] == key);127 if (identityIndex == -1) continue;128 sublessIdentities.splice(identityIndex, 1);129 subsOnRelay.push(constructSubInfo(key, value, supersOfSubs));130 }131132 // mark the rest of sub-identities for deletion with empty arrays133 /*for(const [account, _identity] of sublessIdentities) {134 subsOnRelay.push([account, ['0', []]]);135 }*/136 } catch (error) {137 console.error(error);138 throw Error('Error during fetching identities');139 }140 }, relayUrl);141142 await usingPlaygrounds(async (helper, privateKey) => {143 if (helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) console.error('pallet-identity is not included in parachain.');144 if (helper.fetchMissingPalletNames([Pallets.Preimage]).length != 0) console.error('pallet-preimage is not included in parachain.');145146 try {147 const preimageMaker = await privateKey(key);148 const ss58Format = helper.chain.getChainProperties().ss58Format;149 const paraIdentities = await getIdentities(helper);150 const identitiesToAdd: any[] = [];151 const paraAccountsRegistrators: {[name: string]: number} = {};152153 // cross-reference every account for changes154 for (const [key, value] of identitiesOnRelay) {155 const encodedKey = encodeAddress(key, ss58Format);156157 // only update if the identity info does not exist or is changed158 const identity = paraIdentities.find(i => i[0] === encodedKey);159 if (identity) {160 const registratorId = identity[1].judgements[0][0];161 paraAccountsRegistrators[encodedKey] = registratorId;162 if (isCurrentChainDataPriority(helper, registratorId, value.judgements[0][0])163 || JSON.stringify(value.info) === JSON.stringify(identity[1].info)) {164 continue;165 }166 }167168 identitiesToAdd.push([key, value]);169 // exercise caution - in case we have an identity and the realy doesn't, it might mean one of two things:170 // 1) it was deleted on the relay;171 // 2) it is our own identity, we don't want to delete it.172 // identitiesToRemove.push((key as any).toHuman()[0]);173 }174175 console.log(identitiesToAdd[0][1]);176177 if (identitiesToRemove.length != 0)178 await uploadPreimage(179 helper,180 preimageMaker,181 helper.constructApiCall('api.tx.identity.forceRemoveIdentities', [identitiesToRemove]).method.toHex(),182 );183 if (identitiesToAdd.length != 0)184 await uploadPreimage(185 helper,186 preimageMaker,187 helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex(),188 );189190 console.log(`Tried to push ${identitiesToAdd.length} identities`191 + ` and found ${identitiesToRemove.length} identities for potential removal.`192 + ` Currently there are ${(awaithelper.getApi().query.identity.identityOf.keys()).length} identities on the chain.`);193194 // fill sub-identities195 const paraSubs = await getSubs(helper);196 const supersOfSubs = await getSupers(helper);197 const subsToUpdate: any[] = [];198199 for (const [key, value] of subsOnRelay) {200 const encodedKey = encodeAddress(key, ss58Format);201 const sub = paraSubs.find(i => i[0] === encodedKey);202 if (sub) {203 // only update if the sub-identity info does not exist or is changed204 if (isCurrentChainDataPriority(helper, paraAccountsRegistrators[encodedKey], relaySS58Prefix)205 || JSON.stringify(value) === JSON.stringify(constructSubInfo(sub[0], sub[1], supersOfSubs)[1])) {206 continue;207 }208 } else if (value[1].length == 0)209 continue;210211 subsToUpdate.push([key, value]);212 }213214 if (subsToUpdate.length != 0)215 await uploadPreimage(216 helper,217 preimageMaker,218 helper.constructApiCall('api.tx.identity.forceSetSubs', [subsToUpdate]).method.toHex(),219 );220221 console.log(`Also tried to push ${subsToUpdate.length} identities with their sub-identities.`222 + ` Currently there are ${(awaithelper.getApi().query.identity.subsOf.keys()).length} identities with subs.`);223 } catch (error) {224 console.error(error);225 throw Error('Error during setting identities');226 }227 }, paraUrl);228};229230if (process.argv[1] === module.filename)231 forceInsertIdentities().catch(() => process.exit(1));1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.03//4// Pulls identities and sub-identities from a chain and then makes a preimage to later force upload them into another.5// Only changed or previously non-existent data are inserted.6//7// Usage: `yarn setIdentities [relay WS URL] [parachain WS URL] [user key]8// Example: `yarn setIdentities wss://polkadot-rpc.dwellir.com ws://localhost:9944 escape pattern miracle train sudden cart adapt embark wedding alien lamp mesh`910import {encodeAddress} from '@polkadot/keyring';11import {IKeyringPair} from '@polkadot/types/types';12import {usingPlaygrounds, Pallets} from './index';13import {ChainHelperBase} from './playgrounds/unique';1415const relayUrl = process.argv[2] ?? 'ws://localhost:9844';16const paraUrl = process.argv[3] ?? 'ws://localhost:9944';17const key = process.argv.length > 4 ? process.argv.slice(4).join(' ') : '//Alice';1819export function extractAccountId(key: any): string {20 return (key as any).toHuman()[0];21}2223export function extractIdentityInfo(value: any): object {24 const heart = (value as any).unwrap();25 const identity = heart.toJSON();26 identity.judgements = heart.judgements.toHuman();27 return identity;28}2930export function extractIdentity(key: any, value: any): [string, any] {31 return [extractAccountId(key), extractIdentityInfo(value)];32}3334export async function getIdentities(helper: ChainHelperBase, noneCasePredicate?: (key: any, value: any) => void) {35 const identities: [string, any][] = [];36 for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {37 const value = v as any;38 if (value.isNone) {39 if (noneCasePredicate) noneCasePredicate(key, value);40 continue;41 }42 identities.push(extractIdentity(key, value));43 }44 return identities;45}4647// whether the existing chain data is more important than the coming48function isCurrentChainDataPriority(helper: ChainHelperBase, currentChainId: number | undefined, relayChainId: number) {49 if (!currentChainId) return false;50 // information has come from local chain, and is automatically superior51 if (currentChainId == helper.chain.getChainProperties().ss58Format) return true;52 // the lower the id, the more important it is (Polkadot has ss58 prefix = 0, Kusama has ss58 prefix = 2)53 return currentChainId < relayChainId;54}5556// construct an object with all data necessary for insertion from storage query results57export function constructSubInfo(identityAccount: string, subQuery: any, supers: any[], ss58?: number): [string, any] {58 const deposit = subQuery.toJSON()[0];59 const subIdentities = subQuery.toHuman()[1];60 subIdentities.map((sub: string) => supers.find((sup: any) => sup[0] === sub));6162 return [63 encodeAddress(identityAccount, ss58), [64 deposit,65 subIdentities.map((sub: string): [string, object] | null => {66 const sup = supers.find((sup: any) => sup[0] === sub);67 if (!sup) {68 console.error(`Error: Could not find info on super for \nsub-identity account\t${sub} of \nsuper account \t\t${identityAccount}, skipping.`);69 return null;70 }71 return [encodeAddress(sub, ss58), sup[1].toJSON()[1]];72 }).filter((x: any) => x),73 ],74 ];75}7677export async function getSubs(helper: ChainHelperBase) {78 return (await helper.getApi().query.identity.subsOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);79}8081export async function getSupers(helper: ChainHelperBase) {82 return (await helper.getApi().query.identity.superOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);83}8485async function uploadPreimage(helper: ChainHelperBase, preimageMaker: IKeyringPair, preimage: string) {86 try {87 await helper.executeExtrinsic(preimageMaker, 'api.tx.preimage.notePreimage', [preimage]);88 } catch(e: any) {89 if (e.message.includes('AlreadyNoted')) {90 console.warn('Warning: The same preimage already exists on the chain. Nothing was uploaded.');91 } else {92 console.error(e);93 }94 }95}9697// The utility for pulling identity and sub-identity data98const forceInsertIdentities = async (): Promise<void> => {99 let relaySS58Prefix = 0;100 const identitiesOnRelay: any[] = [];101 const subsOnRelay: any[] = [];102 const identitiesToRemove: string[] = [];103 await usingPlaygrounds(async helper => {104 try {105 relaySS58Prefix = helper.chain.getChainProperties().ss58Format;106 // iterate over every identity107 for(const [key, value] of await getIdentities(helper, (key, _value) => identitiesToRemove.push((key as any).toHuman()[0]))) {108 // if any of the judgements resulted in a good confirmed outcome, keep this identity109 let knownGood = false, reasonable = false;110 for (const [_id, judgement] of value.judgements) {111 if (judgement == 'KnownGood') knownGood = true;112 if (judgement == 'Reasonable') reasonable = true;113 }114 if (!(reasonable || knownGood)) continue;115 // replace the registrator id with the relay chain's ss58 format116 value.judgements = [[helper.chain.getChainProperties().ss58Format, knownGood ? 'KnownGood' : 'Reasonable']];117 identitiesOnRelay.push([key, value]);118 }119120 const sublessIdentities = [...identitiesOnRelay];121 const supersOfSubs = await getSupers(helper);122123 // iterate over every sub-identity124 for(const [key, value] of await getSubs(helper)) {125 // only get subs of the identities interesting to us126 const identityIndex = sublessIdentities.findIndex((x: any) => x[0] == key);127 if (identityIndex == -1) continue;128 sublessIdentities.splice(identityIndex, 1);129 subsOnRelay.push(constructSubInfo(key, value, supersOfSubs));130 }131132 // mark the rest of sub-identities for deletion with empty arrays133 /*for(const [account, _identity] of sublessIdentities) {134 subsOnRelay.push([account, ['0', []]]);135 }*/136 } catch (error) {137 console.error(error);138 throw Error('Error during fetching identities');139 }140 }, relayUrl);141142 await usingPlaygrounds(async (helper, privateKey) => {143 if (helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) console.error('pallet-identity is not included in parachain.');144 if (helper.fetchMissingPalletNames([Pallets.Preimage]).length != 0) console.error('pallet-preimage is not included in parachain.');145146 try {147 const preimageMaker = await privateKey(key);148 const ss58Format = helper.chain.getChainProperties().ss58Format;149 const paraIdentities = await getIdentities(helper);150 const identitiesToAdd: any[] = [];151 const paraAccountsRegistrators: {[name: string]: number} = {};152153 // cross-reference every account for changes154 for (const [key, value] of identitiesOnRelay) {155 const encodedKey = encodeAddress(key, ss58Format);156157 // only update if the identity info does not exist or is changed158 const identity = paraIdentities.find(i => i[0] === encodedKey);159 if (identity) {160 const registratorId = identity[1].judgements[0][0];161 paraAccountsRegistrators[encodedKey] = registratorId;162 if (isCurrentChainDataPriority(helper, registratorId, value.judgements[0][0])163 || JSON.stringify(value.info) === JSON.stringify(identity[1].info)) {164 continue;165 }166 }167168 identitiesToAdd.push([key, value]);169 // exercise caution - in case we have an identity and the realy doesn't, it might mean one of two things:170 // 1) it was deleted on the relay;171 // 2) it is our own identity, we don't want to delete it.172 // identitiesToRemove.push((key as any).toHuman()[0]);173 }174175 if (identitiesToRemove.length != 0)176 await uploadPreimage(177 helper,178 preimageMaker,179 helper.constructApiCall('api.tx.identity.forceRemoveIdentities', [identitiesToRemove]).method.toHex(),180 );181 if (identitiesToAdd.length != 0)182 await uploadPreimage(183 helper,184 preimageMaker,185 helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex(),186 );187188 console.log(`Tried to push ${identitiesToAdd.length} identities`189 + ` and found ${identitiesToRemove.length} identities for potential removal.`190 + ` Currently there are ${(awaithelper.getApi().query.identity.identityOf.keys()).length} identities on the chain.`);191192 // fill sub-identities193 const paraSubs = await getSubs(helper);194 const supersOfSubs = await getSupers(helper);195 const subsToUpdate: any[] = [];196197 for (const [key, value] of subsOnRelay) {198 const encodedKey = encodeAddress(key, ss58Format);199 const sub = paraSubs.find(i => i[0] === encodedKey);200 if (sub) {201 // only update if the sub-identity info does not exist or is changed202 if (isCurrentChainDataPriority(helper, paraAccountsRegistrators[encodedKey], relaySS58Prefix)203 || JSON.stringify(value) === JSON.stringify(constructSubInfo(sub[0], sub[1], supersOfSubs)[1])) {204 continue;205 }206 } else if (value[1].length == 0)207 continue;208209 subsToUpdate.push([key, value]);210 }211212 if (subsToUpdate.length != 0)213 await uploadPreimage(214 helper,215 preimageMaker,216 helper.constructApiCall('api.tx.identity.forceSetSubs', [subsToUpdate]).method.toHex(),217 );218219 console.log(`Also tried to push ${subsToUpdate.length} identities with their sub-identities.`220 + ` Currently there are ${(awaithelper.getApi().query.identity.subsOf.keys()).length} identities with subs.`);221 } catch (error) {222 console.error(error);223 throw Error('Error during setting identities');224 }225 }, paraUrl);226};227228if (process.argv[1] === module.filename)229 forceInsertIdentities().catch(() => process.exit(1));