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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
mod byte_str;
use semver::Version;
use serde::{de, Deserialize, Serialize, Serializer};
use serde_json::{Map, Value};
use std::{
fmt::{Display, Formatter, Result as DisplayResult},
str::FromStr,
};
use url::Url;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ContractMetadata {
pub source: Source,
pub contract: Contract,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<User>,
#[serde(flatten)]
pub abi: Map<String, Value>,
}
impl ContractMetadata {
pub fn new(
source: Source,
contract: Contract,
user: Option<User>,
abi: Map<String, Value>,
) -> Self {
Self {
source,
contract,
user,
abi,
}
}
pub fn remove_source_wasm_attribute(&mut self) {
self.source.wasm = None;
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CodeHash(
#[serde(
serialize_with = "byte_str::serialize_as_byte_str",
deserialize_with = "byte_str::deserialize_from_byte_str_array"
)]
pub [u8; 32],
);
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Source {
pub hash: CodeHash,
pub language: SourceLanguage,
pub compiler: SourceCompiler,
#[serde(skip_serializing_if = "Option::is_none")]
pub wasm: Option<SourceWasm>,
}
impl Source {
pub fn new(
wasm: Option<SourceWasm>,
hash: CodeHash,
language: SourceLanguage,
compiler: SourceCompiler,
) -> Self {
Source {
hash,
language,
compiler,
wasm,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SourceWasm(
#[serde(
serialize_with = "byte_str::serialize_as_byte_str",
deserialize_with = "byte_str::deserialize_from_byte_str"
)]
pub Vec<u8>,
);
impl SourceWasm {
pub fn new(wasm: Vec<u8>) -> Self {
SourceWasm(wasm)
}
}
impl Display for SourceWasm {
fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
write!(f, "0x").expect("failed writing to string");
for byte in &self.0 {
write!(f, "{:02x}", byte).expect("failed writing to string");
}
write!(f, "")
}
}
#[derive(Clone, Debug)]
pub struct SourceLanguage {
pub language: Language,
pub version: Version,
}
impl SourceLanguage {
pub fn new(language: Language, version: Version) -> Self {
SourceLanguage { language, version }
}
}
impl Serialize for SourceLanguage {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for SourceLanguage {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
FromStr::from_str(&s).map_err(de::Error::custom)
}
}
impl Display for SourceLanguage {
fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
write!(f, "{} {}", self.language, self.version)
}
}
impl FromStr for SourceLanguage {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split_whitespace();
let language = parts
.next()
.ok_or_else(|| {
format!(
"SourceLanguage: Expected format '<language> <version>', got '{}'",
s
)
})
.and_then(FromStr::from_str)?;
let version = parts
.next()
.ok_or_else(|| {
format!(
"SourceLanguage: Expected format '<language> <version>', got '{}'",
s
)
})
.and_then(|v| {
<Version as FromStr>::from_str(v)
.map_err(|e| format!("Error parsing version {}", e))
})?;
Ok(Self { language, version })
}
}
#[derive(Clone, Debug)]
pub enum Language {
Ink,
Solidity,
AssemblyScript,
}
impl Display for Language {
fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
match self {
Self::Ink => write!(f, "ink!"),
Self::Solidity => write!(f, "Solidity"),
Self::AssemblyScript => write!(f, "AssemblyScript"),
}
}
}
impl FromStr for Language {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ink!" => Ok(Self::Ink),
"Solidity" => Ok(Self::Solidity),
"AssemblyScript" => Ok(Self::AssemblyScript),
_ => Err(format!("Invalid language '{}'", s)),
}
}
}
#[derive(Clone, Debug)]
pub struct SourceCompiler {
pub compiler: Compiler,
pub version: Version,
}
impl Display for SourceCompiler {
fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
write!(f, "{} {}", self.compiler, self.version)
}
}
impl FromStr for SourceCompiler {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split_whitespace();
let compiler = parts
.next()
.ok_or_else(|| {
format!(
"SourceCompiler: Expected format '<compiler> <version>', got '{}'",
s
)
})
.and_then(FromStr::from_str)?;
let version = parts
.next()
.ok_or_else(|| {
format!(
"SourceCompiler: Expected format '<compiler> <version>', got '{}'",
s
)
})
.and_then(|v| {
<Version as FromStr>::from_str(v)
.map_err(|e| format!("Error parsing version {}", e))
})?;
Ok(Self { compiler, version })
}
}
impl Serialize for SourceCompiler {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for SourceCompiler {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
FromStr::from_str(&s).map_err(de::Error::custom)
}
}
impl SourceCompiler {
pub fn new(compiler: Compiler, version: Version) -> Self {
SourceCompiler { compiler, version }
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Compiler {
RustC,
Solang,
}
impl Display for Compiler {
fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
match self {
Self::RustC => write!(f, "rustc"),
Self::Solang => write!(f, "solang"),
}
}
}
impl FromStr for Compiler {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"rustc" => Ok(Self::RustC),
"solang" => Ok(Self::Solang),
_ => Err(format!("Invalid compiler '{}'", s)),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Contract {
pub name: String,
pub version: Version,
pub authors: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub documentation: Option<Url>,
#[serde(skip_serializing_if = "Option::is_none")]
pub repository: Option<Url>,
#[serde(skip_serializing_if = "Option::is_none")]
pub homepage: Option<Url>,
#[serde(skip_serializing_if = "Option::is_none")]
pub license: Option<String>,
}
impl Contract {
pub fn builder() -> ContractBuilder {
ContractBuilder::default()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct User {
#[serde(flatten)]
pub json: Map<String, Value>,
}
impl User {
pub fn new(json: Map<String, Value>) -> Self {
User { json }
}
}
#[derive(Default)]
pub struct ContractBuilder {
name: Option<String>,
version: Option<Version>,
authors: Option<Vec<String>>,
description: Option<String>,
documentation: Option<Url>,
repository: Option<Url>,
homepage: Option<Url>,
license: Option<String>,
}
impl ContractBuilder {
pub fn name<S>(&mut self, name: S) -> &mut Self
where
S: AsRef<str>,
{
if self.name.is_some() {
panic!("name has already been set")
}
self.name = Some(name.as_ref().to_string());
self
}
pub fn version(&mut self, version: Version) -> &mut Self {
if self.version.is_some() {
panic!("version has already been set")
}
self.version = Some(version);
self
}
pub fn authors<I, S>(&mut self, authors: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
if self.authors.is_some() {
panic!("authors has already been set")
}
let authors = authors
.into_iter()
.map(|s| s.as_ref().to_string())
.collect::<Vec<_>>();
if authors.is_empty() {
panic!("must have at least one author")
}
self.authors = Some(authors);
self
}
pub fn description<S>(&mut self, description: S) -> &mut Self
where
S: AsRef<str>,
{
if self.description.is_some() {
panic!("description has already been set")
}
self.description = Some(description.as_ref().to_string());
self
}
pub fn documentation(&mut self, documentation: Url) -> &mut Self {
if self.documentation.is_some() {
panic!("documentation is already set")
}
self.documentation = Some(documentation);
self
}
pub fn repository(&mut self, repository: Url) -> &mut Self {
if self.repository.is_some() {
panic!("repository is already set")
}
self.repository = Some(repository);
self
}
pub fn homepage(&mut self, homepage: Url) -> &mut Self {
if self.homepage.is_some() {
panic!("homepage is already set")
}
self.homepage = Some(homepage);
self
}
pub fn license<S>(&mut self, license: S) -> &mut Self
where
S: AsRef<str>,
{
if self.license.is_some() {
panic!("license has already been set")
}
self.license = Some(license.as_ref().to_string());
self
}
pub fn build(&self) -> Result<Contract, String> {
let mut required = Vec::new();
if let (Some(name), Some(version), Some(authors)) =
(&self.name, &self.version, &self.authors)
{
Ok(Contract {
name: name.to_string(),
version: version.clone(),
authors: authors.to_vec(),
description: self.description.clone(),
documentation: self.documentation.clone(),
repository: self.repository.clone(),
homepage: self.homepage.clone(),
license: self.license.clone(),
})
} else {
if self.name.is_none() {
required.push("name");
}
if self.version.is_none() {
required.push("version")
}
if self.authors.is_none() {
required.push("authors")
}
Err(format!(
"Missing required non-default fields: {}",
required.join(", ")
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn builder_fails_with_missing_required_fields() {
let missing_name = Contract::builder()
.version(Version::new(2, 1, 0))
.authors(vec!["Parity Technologies <admin@parity.io>".to_string()])
.build();
assert_eq!(
missing_name.unwrap_err(),
"Missing required non-default fields: name"
);
let missing_version = Contract::builder()
.name("incrementer".to_string())
.authors(vec!["Parity Technologies <admin@parity.io>".to_string()])
.build();
assert_eq!(
missing_version.unwrap_err(),
"Missing required non-default fields: version"
);
let missing_authors = Contract::builder()
.name("incrementer".to_string())
.version(Version::new(2, 1, 0))
.build();
assert_eq!(
missing_authors.unwrap_err(),
"Missing required non-default fields: authors"
);
let missing_all = Contract::builder()
.build();
assert_eq!(
missing_all.unwrap_err(),
"Missing required non-default fields: name, version, authors"
);
}
#[test]
fn json_with_optional_fields() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let wasm = SourceWasm::new(vec![0u8, 1u8, 2u8]);
let source = Source::new(Some(wasm), CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
.name("incrementer".to_string())
.version(Version::new(2, 1, 0))
.authors(vec!["Parity Technologies <admin@parity.io>".to_string()])
.description("increment a value".to_string())
.documentation(Url::parse("http://docs.rs/").unwrap())
.repository(Url::parse("http://github.com/paritytech/ink/").unwrap())
.homepage(Url::parse("http://example.com/").unwrap())
.license("Apache-2.0".to_string())
.build()
.unwrap();
let user_json = json! {
{
"more-user-provided-fields": [
"and",
"their",
"values"
],
"some-user-provided-field": "and-its-value"
}
};
let user = User::new(user_json.as_object().unwrap().clone());
let abi_json = json! {
{
"spec": {},
"storage": {},
"types": []
}
}
.as_object()
.unwrap()
.clone();
let metadata = ContractMetadata::new(source, contract, Some(user), abi_json);
let json = serde_json::to_value(&metadata).unwrap();
let expected = json! {
{
"source": {
"hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"language": "ink! 2.1.0",
"compiler": "rustc 1.46.0-nightly",
"wasm": "0x000102"
},
"contract": {
"name": "incrementer",
"version": "2.1.0",
"authors": [
"Parity Technologies <admin@parity.io>"
],
"description": "increment a value",
"documentation": "http://docs.rs/",
"repository": "http://github.com/paritytech/ink/",
"homepage": "http://example.com/",
"license": "Apache-2.0",
},
"user": {
"more-user-provided-fields": [
"and",
"their",
"values"
],
"some-user-provided-field": "and-its-value"
},
"spec": {},
"storage": {},
"types": []
}
};
assert_eq!(json, expected);
}
#[test]
fn json_excludes_optional_fields() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let source = Source::new(None, CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
.name("incrementer".to_string())
.version(Version::new(2, 1, 0))
.authors(vec!["Parity Technologies <admin@parity.io>".to_string()])
.build()
.unwrap();
let abi_json = json! {
{
"spec": {},
"storage": {},
"types": []
}
}
.as_object()
.unwrap()
.clone();
let metadata = ContractMetadata::new(source, contract, None, abi_json);
let json = serde_json::to_value(&metadata).unwrap();
let expected = json! {
{
"contract": {
"name": "incrementer",
"version": "2.1.0",
"authors": [
"Parity Technologies <admin@parity.io>"
],
},
"source": {
"hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"language": "ink! 2.1.0",
"compiler": "rustc 1.46.0-nightly"
},
"spec": {},
"storage": {},
"types": []
}
};
assert_eq!(json, expected);
}
#[test]
fn decoding_works() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let wasm = SourceWasm::new(vec![0u8, 1u8, 2u8]);
let source = Source::new(Some(wasm), CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
.name("incrementer".to_string())
.version(Version::new(2, 1, 0))
.authors(vec!["Parity Technologies <admin@parity.io>".to_string()])
.description("increment a value".to_string())
.documentation(Url::parse("http://docs.rs/").unwrap())
.repository(Url::parse("http://github.com/paritytech/ink/").unwrap())
.homepage(Url::parse("http://example.com/").unwrap())
.license("Apache-2.0".to_string())
.build()
.unwrap();
let user_json = json! {
{
"more-user-provided-fields": [
"and",
"their",
"values"
],
"some-user-provided-field": "and-its-value"
}
};
let user = User::new(user_json.as_object().unwrap().clone());
let abi_json = json! {
{
"spec": {},
"storage": {},
"types": []
}
}
.as_object()
.unwrap()
.clone();
let metadata = ContractMetadata::new(source, contract, Some(user), abi_json);
let json = serde_json::to_value(&metadata).unwrap();
let decoded = serde_json::from_value::<ContractMetadata>(json);
assert!(decoded.is_ok())
}
}