lib.rs 17.6 KiB
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 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
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract 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.
//
// cargo-contract 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 cargo-contract.  If not, see <http://www.gnu.org/licenses/>.

//! Type definitions for creating and serializing metadata for smart contracts targeting
//! Substrate's contracts pallet.
//!
//! # Example
//!
//! ```
//! # use contract_metadata::*;
//! # use semver::Version;
//! # use url::Url;
//! # use serde_json::{Map, Value};
//!
//! 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([0u8; 32], language, compiler);
//! let contract = Contract::builder()
//!     .name("incrementer".to_string())
//!     .version(Version::new(2, 1, 0))
//!     .authors(vec!["Parity Technologies <[email protected]>".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();
//! // user defined raw json
//! let user_json: Map<String, Value> = Map::new();
//! let user = User::new(user_json);
//! // contract abi raw json generated by contract compilation
//! let abi_json: Map<String, Value> = Map::new();
//!
//! let metadata = ContractMetadata::new(source, contract, Some(user), abi_json);
//!
//! // serialize to json
//! let json = serde_json::to_value(&metadata).unwrap();
//! ```

use core::fmt::{Display, Formatter, Result as DisplayResult, Write};
use semver::Version;
use serde::{Serialize, Serializer};
use serde_json::{Map, Value};
use url::Url;

const METADATA_VERSION: &str = "0.1.0";

/// Smart contract metadata.
#[derive(Debug, Serialize)]
pub struct ContractMetadata {
    #[serde(rename = "metadataVersion")]
    metadata_version: semver::Version,
    source: Source,
    contract: Contract,
    #[serde(skip_serializing_if = "Option::is_none")]
    user: Option<User>,
    /// Raw JSON of the contract abi metadata, generated during contract compilation.
    #[serde(flatten)]
    abi: Map<String, Value>,
}

impl ContractMetadata {
    /// Construct new contract metadata.
    pub fn new(
        source: Source,
        contract: Contract,
        user: Option<User>,
        abi: Map<String, Value>,
    ) -> Self {
        let metadata_version = semver::Version::parse(METADATA_VERSION)
            .expect("METADATA_VERSION is a valid semver string");

        Self {
            metadata_version,
            source,
            contract,
            user,
            abi,
        }
    }
}

#[derive(Debug, Serialize)]
pub struct Source {
    #[serde(serialize_with = "serialize_as_byte_str")]
    hash: [u8; 32],
    language: SourceLanguage,
    compiler: SourceCompiler,
}

impl Source {
    /// Constructs a new InkProjectSource.
    pub fn new(hash: [u8; 32], language: SourceLanguage, compiler: SourceCompiler) -> Self {
        Source {
            hash,
            language,
            compiler,
        }
    }
}

/// The language and version in which a smart contract is written.
#[derive(Debug)]
pub struct SourceLanguage {
    language: Language,
    version: Version,
}

impl SourceLanguage {
    /// Constructs a new 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 Display for SourceLanguage {
    fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
        write!(f, "{} {}", self.language, self.version)
    }
}

/// The language in which the smart contract is written.
#[derive(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"),
        }
    }
}

/// A compiler used to compile a smart contract.
#[derive(Debug)]
pub struct SourceCompiler {
    compiler: Compiler,
    version: Version,
}

impl Display for SourceCompiler {
    fn fmt(&self, f: &mut Formatter<'_>) -> DisplayResult {
        write!(f, "{} {}", self.compiler, self.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 SourceCompiler {
    pub fn new(compiler: Compiler, version: Version) -> Self {
        SourceCompiler { compiler, version }
    }
}

/// Compilers used to compile a smart contract.
#[derive(Debug, 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"),
        }
    }
}

/// Metadata about a smart contract.
#[derive(Debug, Serialize)]
pub struct Contract {
    name: String,
    version: Version,
    authors: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    documentation: Option<Url>,
    #[serde(skip_serializing_if = "Option::is_none")]
    repository: Option<Url>,
    #[serde(skip_serializing_if = "Option::is_none")]
    homepage: Option<Url>,
    #[serde(skip_serializing_if = "Option::is_none")]
    license: Option<String>,
}

impl Contract {
    pub fn builder() -> ContractBuilder {
        ContractBuilder::default()
    }
}

/// Additional user defined metadata, can be any valid json.
#[derive(Debug, Serialize)]
pub struct User {
    #[serde(flatten)]
    json: Map<String, Value>,
}

impl User {
    /// Constructs new user metadata.
    pub fn new(json: Map<String, Value>) -> Self {
        User { json }
    }
}

/// Builder for contract metadata
#[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 {
    /// Set the contract name (required)
    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
    }

    /// Set the contract version (required)
    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
    }

    /// Set the contract version (required)
    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.len() == 0 {
            panic!("must have at least one author")
        }

        self.authors = Some(authors);
        self
    }

    /// Set the contract description (optional)
    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
    }

    /// Set the contract documentation url (optional)
    pub fn documentation(&mut self, documentation: Url) -> &mut Self {
        if self.documentation.is_some() {
            panic!("documentation is already set")
        }
        self.documentation = Some(documentation);
        self
    }

    /// Set the contract repository url (optional)
    pub fn repository(&mut self, repository: Url) -> &mut Self {
        if self.repository.is_some() {
            panic!("repository is already set")
        }
        self.repository = Some(repository);
        self
    }

    /// Set the contract homepage url (optional)
    pub fn homepage(&mut self, homepage: Url) -> &mut Self {
        if self.homepage.is_some() {
            panic!("homepage is already set")
        }
        self.homepage = Some(homepage);
        self
    }

    /// Set the contract license (optional)
    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
    }

    /// Finalize construction of the [`ContractMetadata`].
    ///
    /// Returns an `Err` if any required fields missing.
    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(", ")
            ))
        }
    }
}

/// Serializes the given bytes as byte string.
fn serialize_as_byte_str<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if bytes.is_empty() {
        // Return empty string without prepended `0x`.
        return serializer.serialize_str("");
    }
    let mut hex = String::with_capacity(bytes.len() * 2 + 2);
    write!(hex, "0x").expect("failed writing to string");
    for byte in bytes {
        write!(hex, "{:02x}", byte).expect("failed writing to string");
    }
    serializer.serialize_str(&hex)
}

#[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()
            // .name("incrementer".to_string())
            .version(Version::new(2, 1, 0))
            .authors(vec!["Parity Technologies <[email protected]>".to_string()])
            .build();

        assert_eq!(
            missing_name.unwrap_err(),
            "Missing required non-default fields: name"
        );

        let missing_version = Contract::builder()
            .name("incrementer".to_string())
            // .version(Version::new(2, 1, 0))
            .authors(vec!["Parity Technologies <[email protected]>".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))
            // .authors(vec!["Parity Technologies <[email protected]>".to_string()])
            .build();

        assert_eq!(
            missing_authors.unwrap_err(),
            "Missing required non-default fields: authors"
        );

        let missing_all = Contract::builder()
            // .name("incrementer".to_string())
            // .version(Version::new(2, 1, 0))
            // .authors(vec!["Parity Technologies <[email protected]>".to_string()])
            .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 source = Source::new([0u8; 32], language, compiler);
        let contract = Contract::builder()
            .name("incrementer".to_string())
            .version(Version::new(2, 1, 0))
            .authors(vec!["Parity Technologies <[email protected]>".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! {
            {
                "metadataVersion": "0.1.0",
                "source": {
                    "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
                    "language": "ink! 2.1.0",
                    "compiler": "rustc 1.46.0-nightly"
                },
                "contract": {
                    "name": "incrementer",
                    "version": "2.1.0",
                    "authors": [
                      "Parity Technologies <[email protected]>"
                    ],
                    "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"
                },
                // these fields are part of the flattened raw json for the contract ABI
                "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([0u8; 32], language, compiler);
        let contract = Contract::builder()
            .name("incrementer".to_string())
            .version(Version::new(2, 1, 0))
            .authors(vec!["Parity Technologies <[email protected]>".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! {
            {
                "metadataVersion": "0.1.0",
                "source": {
                    "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
                    "language": "ink! 2.1.0",
                    "compiler": "rustc 1.46.0-nightly"
                },
                "contract": {
                    "name": "incrementer",
                    "version": "2.1.0",
                    "authors": [
                      "Parity Technologies <[email protected]>"
                    ],
                },
                // these fields are part of the flattened raw json for the contract ABI
                "spec": {},
                "storage": {},
                "types": []
            }
        };

        assert_eq!(json, expected);
    }
}