Skip to content

Commit

Permalink
Final commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ntn-x2 committed Nov 6, 2024
1 parent ba6e25b commit 7af6831
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 18 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion runtime-api/unique-linking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ version = { workspace = true }
[dependencies]
# External dependencies
parity-scale-codec = { workspace = true }
scale-info = { workspace = true }

# Substrate dependencies
sp-api = { workspace = true }
sp-std = { workspace = true }

[features]
default = ["std"]
std = ["parity-scale-codec/std", "sp-api/std", "sp-std/std"]
std = ["parity-scale-codec/std", "scale-info/std", "sp-api/std", "sp-std/std"]
28 changes: 21 additions & 7 deletions runtime-api/unique-linking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,43 @@
#![cfg_attr(not(feature = "std"), no_std)]

use parity_scale_codec::{Codec, Decode, Encode};
use scale_info::TypeInfo;
use sp_std::vec::Vec;

#[derive(Encode, Decode)]
#[derive(Encode, Decode, TypeInfo)]
pub struct AddressResult<Address, Extra> {
address: Address,
extra: Option<Extra>,
}

#[derive(Encode, Decode)]
impl<Address, Extra> AddressResult<Address, Extra> {
pub const fn new(address: Address, extra: Option<Extra>) -> Self {
Self { address, extra }
}
}

#[derive(Encode, Decode, TypeInfo)]
pub struct NameResult<Name, Extra> {
name: Name,
extra: Option<Extra>,
}

impl<Name, Extra> NameResult<Name, Extra> {
pub const fn new(name: Name, extra: Option<Extra>) -> Self {
Self { name, extra }
}
}

sp_api::decl_runtime_apis! {
pub trait UniqueLookup<Address, Name, Extra> where
pub trait UniqueLookup<Address, Name, Extra, Error> where
Address: Codec,
Name: Codec,
Extra: Codec,
Error: Codec,
{
fn address_for_name(name: Name) -> Option<AddressResult<Address, Extra>>;
fn batch_address_for_name(names: Vec<Name>) -> Vec<Option<AddressResult<Address, Extra>>>;
fn name_for_address(address: Address) -> Option<NameResult<Name, Extra>>;
fn batch_name_for_address(addresses: Vec<Address>) -> Vec<Option<NameResult<Name, Extra>>>;
fn address_for_name(name: Name) -> Result<Option<AddressResult<Address, Extra>>, Error>;
fn batch_address_for_name(names: Vec<Name>) -> Result<Vec<Option<AddressResult<Address, Extra>>>, Error>;
fn name_for_address(address: Address) -> Result<Option<NameResult<Name, Extra>>, Error>;
fn batch_name_for_address(addresses: Vec<Address>) -> Result<Vec<Option<NameResult<Name, Extra>>>, Error>;
}
}
5 changes: 5 additions & 0 deletions runtimes/common/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,8 @@ use scale_info::TypeInfo;
pub enum PublicCredentialsApiError {
InvalidSubjectId,
}

#[derive(Encode, Decode, TypeInfo)]
pub enum UniqueLinkingApiError {
Internal,
}
2 changes: 2 additions & 0 deletions runtimes/peregrine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ kilt-runtime-api-public-credentials = { workspace = true }
kilt-runtime-api-staking = { workspace = true }
pallet-asset-switch-runtime-api = { workspace = true }
pallet-transaction-payment-rpc-runtime-api = { workspace = true }
unique-linking-runtime-api = { workspace = true }

# KILT pallets & primitives
attestation = { workspace = true }
Expand Down Expand Up @@ -247,6 +248,7 @@ std = [
"sp-transaction-pool/std",
"sp-version/std",
"sp-weights/std",
"unique-linking-runtime-api/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
Expand Down
57 changes: 52 additions & 5 deletions runtimes/peregrine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,11 @@ use xcm_builder::{FungiblesAdapter, NoChecking};

use delegation::DelegationAc;
use kilt_support::traits::ItemFilter;
use pallet_did_lookup::linkable_account::LinkableAccountId;
use pallet_did_lookup::{linkable_account::LinkableAccountId, ConnectionRecord};
use pallet_web3_names::web3_name::Web3NameOwnership;
pub use parachain_staking::InflationInfo;
pub use public_credentials;
use unique_linking_runtime_api::{AddressResult, NameResult};

use runtime_common::{
asset_switch::{runtime_api::Error as AssetSwitchApiError, EnsureRootAsTreasury},
Expand All @@ -71,12 +73,12 @@ use runtime_common::{
RELAY_CHAIN_SLOT_DURATION_MILLIS, SLOT_DURATION, UNINCLUDED_SEGMENT_CAPACITY,
},
dip::merkle::{CompleteMerkleProof, DidMerkleProofOf, DidMerkleRootGenerator},
errors::PublicCredentialsApiError,
errors::{PublicCredentialsApiError, UniqueLinkingApiError},
fees::{ToAuthorCredit, WeightToFee},
pallet_id,
xcm_config::RelayOrigin,
AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, DotName,
FeeSplit, Hash, Header, Nonce, SendDustAndFeesToTreasury, Signature, SlowAdjustingFeeUpdate,
AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, FeeSplit,
Hash, Header, Nonce, SendDustAndFeesToTreasury, Signature, SlowAdjustingFeeUpdate,
};

use crate::xcm_config::{LocationToAccountIdConverter, UniversalLocation, XcmRouter};
Expand Down Expand Up @@ -738,6 +740,8 @@ impl pallet_web3_names::Config for Runtime {
type BalanceMigrationManager = Migration;
}

pub type DotName = runtime_common::DotName<{ constants::dot_names::MIN_LENGTH }, { constants::dot_names::MAX_LENGTH }>;

type DotNamesDeployment = pallet_web3_names::Instance2;
impl pallet_web3_names::Config<DotNamesDeployment> for Runtime {
type BalanceMigrationManager = ();
Expand All @@ -750,7 +754,7 @@ impl pallet_web3_names::Config<DotNamesDeployment> for Runtime {
type OwnerOrigin = did::EnsureDidOrigin<DidIdentifier, AccountId>;
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type Web3Name = DotName<{ Self::MinNameLength::get() }, { Self::MaxNameLength::get() }>;
type Web3Name = DotName;
type Web3NameOwner = DidIdentifier;
// TODO: Change
type WeightInfo = ();
Expand Down Expand Up @@ -1754,6 +1758,49 @@ impl_runtime_apis! {
}
}

impl unique_linking_runtime_api::UniqueLookup<Block, LinkableAccountId, DotName, DidIdentifier, UniqueLinkingApiError> for Runtime {
fn address_for_name(name: DotName) -> Result<Option<AddressResult<LinkableAccountId, DidIdentifier>>, UniqueLinkingApiError> {
let Some(Web3NameOwnership { owner, .. }) = DotNames::owner(name) else {
return Ok(None);
};

let (first_account, second_account) = {
let mut owner_linked_accounts = pallet_did_lookup::ConnectedAccounts::<Runtime, UniqueLinkingDeployment>::iter_key_prefix(&owner);
(owner_linked_accounts.next(), owner_linked_accounts.next())
};
let linked_account = match (first_account, second_account) {
(Some(_), Some(_)) => Err(UniqueLinkingApiError::Internal),
(first, _) => Ok(first)
}?;

let Some(account) = linked_account else {
return Ok(None);
};

Ok(Some(AddressResult::new(account, Some(owner))))
}

fn batch_address_for_name(names: Vec<DotName>) -> Result<Vec<Option<AddressResult<LinkableAccountId, DidIdentifier>>>, UniqueLinkingApiError> {
names.into_iter().map(Self::address_for_name).collect::<Result<Vec<_>, _>>()
}

fn name_for_address(address: LinkableAccountId) -> Result<Option<NameResult<DotName, DidIdentifier>>, UniqueLinkingApiError> {
let Some(ConnectionRecord { did, .. }) = UniqueLinking::connected_dids(address) else {
return Ok(None);
};

let Some(name) = DotNames::names(&did) else {
return Ok(None);
};

Ok(Some(NameResult::new(name, Some(did))))
}

fn batch_name_for_address(addresses: Vec<LinkableAccountId>) -> Result<Vec<Option<NameResult<DotName, DidIdentifier>>>, UniqueLinkingApiError> {
addresses.into_iter().map(Self::name_for_address).collect::<Result<Vec<_>, _>>()
}
}

#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Expand Down
2 changes: 2 additions & 0 deletions runtimes/spiritnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ kilt-runtime-api-public-credentials = { workspace = true }
kilt-runtime-api-staking = { workspace = true }
pallet-asset-switch-runtime-api = { workspace = true }
pallet-transaction-payment-rpc-runtime-api = { workspace = true }
unique-linking-runtime-api = { workspace = true }

# KILT pallets & primitives
attestation = { workspace = true }
Expand Down Expand Up @@ -246,6 +247,7 @@ std = [
"sp-transaction-pool/std",
"sp-version/std",
"sp-weights/std",
"unique-linking-runtime-api/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
Expand Down
57 changes: 52 additions & 5 deletions runtimes/spiritnet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,11 @@ use xcm_builder::{FungiblesAdapter, NoChecking};

use delegation::DelegationAc;
use kilt_support::traits::ItemFilter;
use pallet_did_lookup::linkable_account::LinkableAccountId;
use pallet_did_lookup::{linkable_account::LinkableAccountId, ConnectionRecord};
use pallet_web3_names::web3_name::Web3NameOwnership;
pub use parachain_staking::InflationInfo;
pub use public_credentials;
use unique_linking_runtime_api::{AddressResult, NameResult};

use runtime_common::{
asset_switch::{runtime_api::Error as AssetSwitchApiError, EnsureRootAsTreasury},
Expand All @@ -71,12 +73,12 @@ use runtime_common::{
RELAY_CHAIN_SLOT_DURATION_MILLIS, SLOT_DURATION, UNINCLUDED_SEGMENT_CAPACITY,
},
dip::merkle::{CompleteMerkleProof, DidMerkleProofOf, DidMerkleRootGenerator},
errors::PublicCredentialsApiError,
errors::{PublicCredentialsApiError, UniqueLinkingApiError},
fees::{ToAuthorCredit, WeightToFee},
pallet_id,
xcm_config::RelayOrigin,
AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, DotName,
FeeSplit, Hash, Header, Nonce, SendDustAndFeesToTreasury, Signature, SlowAdjustingFeeUpdate,
AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, FeeSplit,
Hash, Header, Nonce, SendDustAndFeesToTreasury, Signature, SlowAdjustingFeeUpdate,
};

use crate::xcm_config::{LocationToAccountIdConverter, UniversalLocation, XcmRouter};
Expand Down Expand Up @@ -731,6 +733,8 @@ impl pallet_web3_names::Config for Runtime {
type BalanceMigrationManager = Migration;
}

pub type DotName = runtime_common::DotName<{ constants::dot_names::MIN_LENGTH }, { constants::dot_names::MAX_LENGTH }>;

type DotNamesDeployment = pallet_web3_names::Instance2;
impl pallet_web3_names::Config<DotNamesDeployment> for Runtime {
type BalanceMigrationManager = ();
Expand All @@ -743,7 +747,7 @@ impl pallet_web3_names::Config<DotNamesDeployment> for Runtime {
type OwnerOrigin = did::EnsureDidOrigin<DidIdentifier, AccountId>;
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type Web3Name = DotName<{ Self::MinNameLength::get() }, { Self::MaxNameLength::get() }>;
type Web3Name = DotName;
type Web3NameOwner = DidIdentifier;
// TODO: Change
type WeightInfo = ();
Expand Down Expand Up @@ -1744,6 +1748,49 @@ impl_runtime_apis! {
}
}

impl unique_linking_runtime_api::UniqueLookup<Block, LinkableAccountId, DotName, DidIdentifier, UniqueLinkingApiError> for Runtime {
fn address_for_name(name: DotName) -> Result<Option<AddressResult<LinkableAccountId, DidIdentifier>>, UniqueLinkingApiError> {
let Some(Web3NameOwnership { owner, .. }) = DotNames::owner(name) else {
return Ok(None);
};

let (first_account, second_account) = {
let mut owner_linked_accounts = pallet_did_lookup::ConnectedAccounts::<Runtime, UniqueLinkingDeployment>::iter_key_prefix(&owner);
(owner_linked_accounts.next(), owner_linked_accounts.next())
};
let linked_account = match (first_account, second_account) {
(Some(_), Some(_)) => Err(UniqueLinkingApiError::Internal),
(first, _) => Ok(first)
}?;

let Some(account) = linked_account else {
return Ok(None);
};

Ok(Some(AddressResult::new(account, Some(owner))))
}

fn batch_address_for_name(names: Vec<DotName>) -> Result<Vec<Option<AddressResult<LinkableAccountId, DidIdentifier>>>, UniqueLinkingApiError> {
names.into_iter().map(Self::address_for_name).collect::<Result<Vec<_>, _>>()
}

fn name_for_address(address: LinkableAccountId) -> Result<Option<NameResult<DotName, DidIdentifier>>, UniqueLinkingApiError> {
let Some(ConnectionRecord { did, .. }) = UniqueLinking::connected_dids(address) else {
return Ok(None);
};

let Some(name) = DotNames::names(&did) else {
return Ok(None);
};

Ok(Some(NameResult::new(name, Some(did))))
}

fn batch_name_for_address(addresses: Vec<LinkableAccountId>) -> Result<Vec<Option<NameResult<DotName, DidIdentifier>>>, UniqueLinkingApiError> {
addresses.into_iter().map(Self::name_for_address).collect::<Result<Vec<_>, _>>()
}
}

#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Expand Down

0 comments on commit 7af6831

Please sign in to comment.