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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use super::scon::Value;
use crate::scon::Hex;
use anyhow::{
Context,
Result,
};
use scale::{
Decode,
Encode,
Output,
};
use scale_info::{
form::PortableForm,
IntoPortable,
Path,
TypeInfo,
};
use sp_core::crypto::{
AccountId32,
Ss58Codec,
};
use std::{
boxed::Box,
collections::HashMap,
convert::TryFrom,
str::FromStr,
};
#[derive(Default)]
pub struct EnvTypesTranscoder {
encoders: HashMap<u32, Box<dyn CustomTypeEncoder>>,
decoders: HashMap<u32, Box<dyn CustomTypeDecoder>>,
}
impl EnvTypesTranscoder {
pub fn new(
encoders: HashMap<u32, Box<dyn CustomTypeEncoder>>,
decoders: HashMap<u32, Box<dyn CustomTypeDecoder>>,
) -> Self {
Self { encoders, decoders }
}
pub fn try_encode<O>(
&self,
type_id: u32,
value: &Value,
output: &mut O,
) -> Result<bool>
where
O: Output,
{
match self.encoders.get(&type_id) {
Some(encoder) => {
tracing::debug!("Encoding type {:?} with custom encoder", type_id);
let encoded_env_type = encoder
.encode_value(value)
.context("Error encoding custom type")?;
output.write(&encoded_env_type);
Ok(true)
}
None => Ok(false),
}
}
pub fn try_decode(&self, type_id: u32, input: &mut &[u8]) -> Result<Option<Value>> {
match self.decoders.get(&type_id) {
Some(decoder) => {
tracing::debug!("Decoding type {:?} with custom decoder", type_id);
let decoded = decoder.decode_value(input)?;
Ok(Some(decoded))
}
None => {
tracing::debug!("No custom decoder found for type {:?}", type_id);
Ok(None)
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PathKey(Vec<String>);
impl PathKey {
pub fn from_type<T>() -> Self
where
T: TypeInfo,
{
let type_info = T::type_info();
let path = type_info
.path()
.clone()
.into_portable(&mut Default::default());
PathKey::from(&path)
}
}
impl From<&Path<PortableForm>> for PathKey {
fn from(path: &Path<PortableForm>) -> Self {
PathKey(path.segments().to_vec())
}
}
pub type TypesByPath = HashMap<PathKey, u32>;
pub trait CustomTypeEncoder: Send + Sync {
fn encode_value(&self, value: &Value) -> Result<Vec<u8>>;
}
pub trait CustomTypeDecoder: Send + Sync {
fn decode_value(&self, input: &mut &[u8]) -> Result<Value>;
}
#[derive(Clone)]
pub struct AccountId;
impl CustomTypeEncoder for AccountId {
fn encode_value(&self, value: &Value) -> Result<Vec<u8>> {
let account_id = match value {
Value::Literal(literal) => {
AccountId32::from_str(literal).map_err(|e| {
anyhow::anyhow!(
"Error parsing AccountId from literal `{}`: {}",
literal,
e
)
})?
}
Value::String(string) => {
AccountId32::from_str(string).map_err(|e| {
anyhow::anyhow!(
"Error parsing AccountId from string '{}': {}",
string,
e
)
})?
}
Value::Hex(hex) => {
AccountId32::try_from(hex.bytes()).map_err(|_| {
anyhow::anyhow!(
"Error converting hex bytes `{:?}` to AccountId",
hex.bytes()
)
})?
}
_ => {
return Err(anyhow::anyhow!(
"Expected a string or a literal for an AccountId"
))
}
};
Ok(account_id.encode())
}
}
impl CustomTypeDecoder for AccountId {
fn decode_value(&self, input: &mut &[u8]) -> Result<Value> {
let account_id = AccountId32::decode(input)?;
Ok(Value::Literal(account_id.to_ss58check()))
}
}
pub struct Hash;
impl CustomTypeDecoder for Hash {
fn decode_value(&self, input: &mut &[u8]) -> Result<Value> {
let hash = sp_core::H256::decode(input)?;
Ok(Value::Hex(Hex::from_str(&format!("{hash:?}"))?))
}
}