gear_subxt/utils/
multi_address.rs

1// Copyright 2019-2023 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5//! The "default" Substrate/Polkadot Address type. This is used in codegen, as well as signing related bits.
6//! This doesn't contain much functionality itself, but is easy to convert to/from an `sp_runtime::MultiAddress`
7//! for instance, to gain functionality without forcing a dependency on Substrate crates here.
8
9use codec::{Decode, Encode};
10
11/// A multi-format address wrapper for on-chain accounts. This is a simplified version of Substrate's
12/// `sp_runtime::MultiAddress`. To obtain more functionality, convert this into that type (this conversion
13/// functionality is provided via `From` impls if the `substrate-compat` feature is enabled).
14#[derive(
15    Clone,
16    Eq,
17    PartialEq,
18    Ord,
19    PartialOrd,
20    Encode,
21    Decode,
22    Debug,
23    scale_encode::EncodeAsType,
24    scale_decode::DecodeAsType,
25)]
26pub enum MultiAddress<AccountId, AccountIndex> {
27    /// It's an account ID (pubkey).
28    Id(AccountId),
29    /// It's an account index.
30    Index(#[codec(compact)] AccountIndex),
31    /// It's some arbitrary raw bytes.
32    Raw(Vec<u8>),
33    /// It's a 32 byte representation.
34    Address32([u8; 32]),
35    /// Its a 20 byte representation.
36    Address20([u8; 20]),
37}
38
39impl<AccountId, AccountIndex> From<AccountId> for MultiAddress<AccountId, AccountIndex> {
40    fn from(a: AccountId) -> Self {
41        Self::Id(a)
42    }
43}
44
45// Improve compat with the substrate version if we're using those crates:
46#[cfg(feature = "substrate-compat")]
47mod substrate_impls {
48    use super::{super::AccountId32, *};
49
50    impl<N> From<sp_runtime::AccountId32> for MultiAddress<AccountId32, N> {
51        fn from(value: sp_runtime::AccountId32) -> Self {
52            let val: AccountId32 = value.into();
53            val.into()
54        }
55    }
56
57    impl<Id, N> From<sp_runtime::MultiAddress<Id, N>> for MultiAddress<AccountId32, N>
58    where
59        Id: Into<AccountId32>,
60    {
61        fn from(value: sp_runtime::MultiAddress<Id, N>) -> Self {
62            match value {
63                sp_runtime::MultiAddress::Id(v) => Self::Id(v.into()),
64                sp_runtime::MultiAddress::Index(v) => Self::Index(v),
65                sp_runtime::MultiAddress::Raw(v) => Self::Raw(v),
66                sp_runtime::MultiAddress::Address32(v) => Self::Address32(v),
67                sp_runtime::MultiAddress::Address20(v) => Self::Address20(v),
68            }
69        }
70    }
71}