1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at info@botlabs.org

use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_runtime::AccountId32;

use crate::account::AccountId20;

#[derive(
	Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, TypeInfo, Serialize, Deserialize,
)]
pub enum LinkableAccountId {
	AccountId20(AccountId20),
	AccountId32(AccountId32),
}

impl From<AccountId20> for LinkableAccountId {
	fn from(account_id: AccountId20) -> Self {
		Self::AccountId20(account_id)
	}
}

impl From<AccountId32> for LinkableAccountId {
	fn from(account_id: AccountId32) -> Self {
		Self::AccountId32(account_id)
	}
}

impl From<[u8; 20]> for LinkableAccountId {
	fn from(account_id: [u8; 20]) -> Self {
		Self::AccountId20(account_id.into())
	}
}

impl From<[u8; 32]> for LinkableAccountId {
	fn from(account_id: [u8; 32]) -> Self {
		Self::AccountId32(account_id.into())
	}
}

impl AsRef<[u8]> for LinkableAccountId {
	fn as_ref(&self) -> &[u8] {
		match self {
			LinkableAccountId::AccountId20(value) => &value.0,
			LinkableAccountId::AccountId32(value) => value.as_ref(),
		}
	}
}

#[cfg(feature = "std")]
impl std::fmt::Display for LinkableAccountId {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::AccountId20(account_id) => write!(f, "{}", account_id),
			Self::AccountId32(account_id) => write!(f, "{}", account_id),
		}
	}
}

// Default implementation required by the DipDidOrigin origin type, only for
// benchmarks.
#[cfg(feature = "runtime-benchmarks")]
impl Default for LinkableAccountId {
	fn default() -> Self {
		AccountId32::new([0u8; 32]).into()
	}
}