Newer
Older
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright 2021 Axiom-Team
//
// This file is part of Substrate-Libre-Currency.
//
// Substrate-Libre-Currency is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Substrate-Libre-Currency 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use anyhow::{anyhow, bail, Context, Result};
use codec::Decode;
use scale_info::form::PortableForm;
use std::{
fs::File,
io::{Read, Write},
};
const CALLS_DOC_FILEPATH: &str = "docs/api/runtime-calls.md";
type RuntimeCalls = Vec<Pallet>;
enum CallCategory {
Disabled,
Inherent,
OtherOrigin,
Root,
Sudo,
User,
}
impl CallCategory {
fn is(pallet_name: &str, call_name: &str) -> Self {
match (pallet_name, call_name) {
("System", "remark" | "remark_with_event") => Self::Disabled,
("System", _) => Self::Root,
("Babe", "report_equivocation_unsigned") => Self::Inherent,
("Babe", "plan_config_change") => Self::Root,
("Timestamp", _) => Self::Inherent,
("Balances", "set_balance" | "force_transfer" | "force_unreserve") => Self::Root,
("AuthorityMembers", "prune_account_id_of" | "remove_member") => Self::Root,
("Authorship", _) => Self::Inherent,
("Session", _) => Self::Disabled,
("Grandpa", "report_equivocation_unsigned") => Self::Inherent,
("Grandpa", "note_stalled") => Self::Root,
("UpgradeOrigin", "dispatch_as_root") => Self::OtherOrigin,
("ImOnline", _) => Self::Inherent,
("Sudo", _) => Self::Sudo,
(
"Identity",
"remove_identity" | "prune_item_identities_names" | "prune_item_identity_index_of",
) => Self::Root,
("Membership", "force_request_membership") => Self::Root,
("Membership", "claim_membership" | "revoke_membership") => Self::Disabled,
("Cert", "force_add_cert" | "del_cert" | "remove_all_certs_received_by") => Self::Root,
("SmithsMembership", "force_request_membership") => Self::Root,
("SmithsMembership", "claim_membership") => Self::Disabled,
("SmithsCert", "force_add_cert" | "del_cert" | "remove_all_certs_received_by") => {
Self::Root
}
("SmithsCollective", "set_members" | "disapprove_proposal") => Self::Root,
("Utility", "dispatch_as") => Self::Root,
_ => Self::User,
}
}
fn is_root(pallet_name: &str, call_name: &str) -> bool {
if let Self::Root = Self::is(pallet_name, call_name) {
true
} else {
false
}
}
fn is_user(pallet_name: &str, call_name: &str) -> bool {
if let Self::User = Self::is(pallet_name, call_name) {
true
} else {
false
}
}
}
#[derive(Clone)]
struct Pallet {
index: u8,
name: String,
calls: Vec<Call>,
}
impl Pallet {
fn new(
index: u8,
name: String,
scale_type_def: &scale_info::TypeDef<PortableForm>,
) -> Result<Self> {
if let scale_info::TypeDef::Variant(calls_enum) = scale_type_def {
Ok(Self {
index,
name,
calls: calls_enum.variants().iter().map(Into::into).collect(),
})
} else {
bail!("Invalid metadata")
}
}
}
#[derive(Clone)]
struct Call {
docs: Vec<String>,
index: u8,
name: String,
params: Vec<CallParam>,
}
impl From<&scale_info::Variant<PortableForm>> for Call {
fn from(variant: &scale_info::Variant<PortableForm>) -> Self {
Self {
docs: variant.docs().to_vec(),
index: variant.index(),
name: variant.name().to_owned(),
params: variant.fields().iter().map(Into::into).collect(),
}
}
}
#[derive(Clone)]
struct CallParam {
docs: Vec<String>,
name: String,
type_name: String,
}
impl From<&scale_info::Field<PortableForm>> for CallParam {
fn from(field: &scale_info::Field<PortableForm>) -> Self {
Self {
docs: field.docs().to_vec(),
name: field.name().cloned().unwrap_or_default(),
type_name: field.type_name().cloned().unwrap_or_default(),
}
}
}
pub(super) fn gen_calls_doc() -> Result<()> {
// Read metadata
let mut file = std::fs::File::open("resources/metadata.scale")
.with_context(|| "Failed to open metadata file")?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)
.with_context(|| "Failed to read metadata file")?;
let metadata = frame_metadata::RuntimeMetadataPrefixed::decode(&mut &bytes[..])
.with_context(|| "Failed to decode metadata")?;
println!("Metadata successfully loaded!");
let runtime_calls = if let frame_metadata::RuntimeMetadata::V14(metadata_v14) = metadata.1 {
get_calls_from_metadata_v14(metadata_v14)?
} else {
bail!("unsuported metadata version")
};
let output = print_runtime_calls(runtime_calls);
let mut file = File::create(CALLS_DOC_FILEPATH)
.with_context(|| format!("Failed to create file '{}'", CALLS_DOC_FILEPATH))?;
file.write_all(output.as_bytes())
.with_context(|| format!("Failed to write to file '{}'", CALLS_DOC_FILEPATH))?;
Ok(())
}
fn get_calls_from_metadata_v14(
metadata_v14: frame_metadata::v14::RuntimeMetadataV14,
) -> Result<RuntimeCalls> {
println!("Number of pallets: {}", metadata_v14.pallets.len());
let mut pallets = Vec::new();
for pallet in metadata_v14.pallets {
if let Some(calls) = pallet.calls {
if let Some(calls_type) = metadata_v14.types.resolve(calls.ty.id()) {
let pallet = Pallet::new(pallet.index, pallet.name.clone(), calls_type.type_def())?;
let calls_len = pallet.calls.len();
println!("{}: {} ({} calls)", pallet.index, pallet.name, calls_len);
pallets.push(pallet);
} else {
bail!("Invalid metadata")
}
} else {
println!("{}: {} (0 calls)", pallet.index, pallet.name);
}
}
Ok(pallets)
}
fn print_runtime_calls(pallets: RuntimeCalls) -> String {
let mut user_calls_counter = 0;
let user_calls_pallets: RuntimeCalls = pallets
.iter()
.cloned()
.filter_map(|mut pallet| {
let pallet_name = pallet.name.clone();
pallet
.calls
.retain(|call| CallCategory::is_user(&pallet_name, &call.name));
if pallet.calls.is_empty() {
None
} else {
user_calls_counter += pallet.calls.len();
Some(pallet)
}
})
.collect();
let mut root_calls_counter = 0;
let root_calls_pallets: RuntimeCalls = pallets
.iter()
.cloned()
.filter_map(|mut pallet| {
let pallet_name = pallet.name.clone();
pallet
.calls
.retain(|call| CallCategory::is_root(&pallet_name, &call.name));
if pallet.calls.is_empty() {
None
} else {
root_calls_counter += pallet.calls.len();
Some(pallet)
}
})
.collect();
let mut output = String::new();
output.push_str("# Runtime calls\n\n");
output.push_str("Calls are categorized according to the dispatch origin they require:\n\n");
output.push_str(
r#"1. User calls: the dispatch origin for this kind of call must be Signed by
the transactor. This is the only call category that can be submitted with an extrinsic.
"#,
);
output.push_str(
r#"1. Root calls: This kind of call requires a special origin that can only be invoked
through on-chain governance mechanisms.
"#,
);
output.push_str(
r#"1. Inherent calls: This kind of call is invoked by the author of the block itself
(usually automatically by the node).
"#,
);
output.push_str("\n\n## User calls\n\n");
output.push_str(&print_calls_category(
user_calls_counter,
"user",
user_calls_pallets,
));
output.push_str("\n\n## Root calls\n\n");
output.push_str(&print_calls_category(
root_calls_counter,
"root",
root_calls_pallets,
));
output
}
fn print_calls_category(calls_counter: usize, category_name: &str, pallets: Vec<Pallet>) -> String {
let mut output = String::new();
output.push_str(&format!(
"There are **{}** {} calls organized in **{}** pallets.\n",
calls_counter,
category_name,
pallets.len()
));
for pallet in pallets {
output.push_str(&format!("\n### {}: {}\n\n", pallet.index, pallet.name));
for call in pallet.calls {
output.push_str(&format!(
"<details><summary>{}: {}({})</summary>\n<p>\n\n{}</p>\n</details>\n\n",
call.index,
call.name,
print_call_params(&call.params),
print_call_details(&call),
));
}
}
output
}
fn print_call_details(call: &Call) -> String {
let mut output = String::new();
output.push_str(&format!("### Index\n\n`{}`\n\n", call.index));
output.push_str(&format!(
"### Documentation\n\n{}\n\n",
call.docs
.iter()
.take_while(|line| !line.starts_with("# <weight>"))
.cloned()
.collect::<Vec<_>>()
.join("\n")
));
if !call.params.is_empty() {
output.push_str("### Types of parameters\n\n```rust\n");
output.push_str(
&call
.params
.iter()
.map(|param| format!("{}: {}", param.name, param.type_name))
.collect::<Vec<_>>()
.join(",\n"),
);
output.push_str("\n```\n\n");
}
output
}
fn print_call_params(call_params: &[CallParam]) -> String {
call_params
.iter()
.map(|param| param.name.clone())
.collect::<Vec<_>>()
.join(", ")
}