diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b8d9c37f90d39494ba6547a5eb55e95c48b007cc..2a957d10c070865148a960f8cffd65e61ee7fbc7 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -74,7 +74,7 @@ test: stage: test <<: *docker-env script: - - cargo test --verbose --all-features + - cargo test --verbose --all --all-features #### stage: build (default features) diff --git a/Cargo.lock b/Cargo.lock index 782079f360717e8d714324fe94642dfe34de6654..2dbcfe354bc30e90e5dacd9ef4781d2b9e8cdf05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -366,6 +366,7 @@ dependencies = [ "cargo-xbuild", "cargo_metadata 0.11.1", "colored", + "contract-metadata", "env_logger", "futures 0.3.5", "heck", @@ -524,6 +525,17 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" +[[package]] +name = "contract-metadata" +version = "0.1.0" +dependencies = [ + "pretty_assertions", + "semver 0.10.0", + "serde", + "serde_json", + "url 2.1.1", +] + [[package]] name = "crc32fast" version = "1.2.0" diff --git a/Cargo.toml b/Cargo.toml index 5c2bb0a9b9dcf88b2e4b7e8731de91f13f8fdfba..29c00d248aa69521a49ed07754bb78412c4f027e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,6 @@ +[workspace] +members = [".", "metadata"] + [package] name = "cargo-contract" version = "0.7.0" @@ -32,6 +35,7 @@ toml = "0.5.6" cargo-xbuild = "0.6.0" rustc_version = "0.2.3" blake2 = "0.9.0" +contract-metadata = { version = "0.1.0", path = "./metadata" } semver = { version = "0.10.0", features = ["serde"] } serde = { version = "1.0.115", default-features = false, features = ["derive"] } serde_json = "1.0.57" diff --git a/metadata/Cargo.toml b/metadata/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..36950c7482cdddaff91b67eadcf2076149c5389e --- /dev/null +++ b/metadata/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "contract-metadata" +version = "0.1.0" +authors = ["Parity Technologies "] +edition = "2018" + +license = "Apache-2.0" +readme = "README.md" +repository = "https://github.com/paritytech/cargo-contract" +documentation = "https://docs.rs/contract-metadata" +homepage = "https://www.substrate.io/" +description = "Library defining metadata for smart contracts on substrate" +keywords = ["parity", "blockchain"] +include = ["Cargo.toml", "*.rs", "LICENSE"] + +[lib] +path = "lib.rs" + +[dependencies] +semver = { version = "0.10.0", features = ["serde"] } +serde = { version = "1.0", default-features = false, features = ["derive"] } +serde_json = "1.0" +url = { version = "2.1.1", features = ["serde"] } + +[dev-dependencies] +pretty_assertions = "0.6.1" diff --git a/metadata/LICENSE b/metadata/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6b0b1270ff0ca8f03867efcd09ba6ddb6392b1e1 --- /dev/null +++ b/metadata/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/metadata/lib.rs b/metadata/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..285074151fe4ec5b97836b98b2785a529b75f427 --- /dev/null +++ b/metadata/lib.rs @@ -0,0 +1,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 . + +//! 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 ".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 = Map::new(); +//! let user = User::new(user_json); +//! // contract abi raw json generated by contract compilation +//! let abi_json: Map = 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, + /// Raw JSON of the contract abi metadata, generated during contract compilation. + #[serde(flatten)] + abi: Map, +} + +impl ContractMetadata { + /// Construct new contract metadata. + pub fn new( + source: Source, + contract: Contract, + user: Option, + abi: Map, + ) -> 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(&self, serializer: S) -> Result + 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(&self, serializer: S) -> Result + 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, + #[serde(skip_serializing_if = "Option::is_none")] + description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + documentation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + repository: Option, + #[serde(skip_serializing_if = "Option::is_none")] + homepage: Option, + #[serde(skip_serializing_if = "Option::is_none")] + license: Option, +} + +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, +} + +impl User { + /// Constructs new user metadata. + pub fn new(json: Map) -> Self { + User { json } + } +} + +/// Builder for contract metadata +#[derive(Default)] +pub struct ContractBuilder { + name: Option, + version: Option, + authors: Option>, + description: Option, + documentation: Option, + repository: Option, + homepage: Option, + license: Option, +} + +impl ContractBuilder { + /// Set the contract name (required) + pub fn name(&mut self, name: S) -> &mut Self + where + S: AsRef, + { + 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(&mut self, authors: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + if self.authors.is_some() { + panic!("authors has already been set") + } + + let authors = authors + .into_iter() + .map(|s| s.as_ref().to_string()) + .collect::>(); + + if authors.len() == 0 { + panic!("must have at least one author") + } + + self.authors = Some(authors); + self + } + + /// Set the contract description (optional) + pub fn description(&mut self, description: S) -> &mut Self + where + S: AsRef, + { + 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(&mut self, license: S) -> &mut Self + where + S: AsRef, + { + 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 { + 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(bytes: &[u8], serializer: S) -> Result +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 ".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 ".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 ".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 ".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 ".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 " + ], + "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 ".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 " + ], + }, + // these fields are part of the flattened raw json for the contract ABI + "spec": {}, + "storage": {}, + "types": [] + } + }; + + assert_eq!(json, expected); + } +} diff --git a/src/cmd/metadata/mod.rs b/src/cmd/metadata.rs similarity index 93% rename from src/cmd/metadata/mod.rs rename to src/cmd/metadata.rs index 9a62dc0464f3357744e6d53f321ef2e85e35c038..8b658d3fe33139a9cc5c04a19fa76de5b9ce019e 100644 --- a/src/cmd/metadata/mod.rs +++ b/src/cmd/metadata.rs @@ -14,8 +14,6 @@ // You should have received a copy of the GNU General Public License // along with cargo-contract. If not, see . -mod contract; - use crate::{ crate_metadata::CrateMetadata, util, @@ -23,7 +21,7 @@ use crate::{ UnstableFlags, Verbosity, }; use anyhow::Result; -use contract::{ +use contract_metadata::{ Compiler, Contract, ContractMetadata, Language, Source, SourceCompiler, SourceLanguage, User, }; use semver::Version; @@ -118,16 +116,35 @@ impl GenerateMetadataCommand { }; // Required contract fields - let contract = Contract::new( - contract_name, - contract_version, - contract_authors, - description, - documentation, - repository, - homepage, - license, - ); + let mut builder = Contract::builder(); + builder + .name(contract_name) + .version(contract_version) + .authors(contract_authors); + + if let Some(description) = description { + builder.description(description); + } + + if let Some(documentation) = documentation { + builder.documentation(documentation); + } + + if let Some(repository) = repository { + builder.repository(repository); + } + + if let Some(homepage) = homepage { + builder.homepage(homepage); + } + + if let Some(license) = license { + builder.license(license); + } + + let contract = builder + .build() + .map_err(|err| anyhow::anyhow!("Invalid contract metadata builder state: {}", err))?; // user defined metadata let user = self.crate_metadata.user.clone().map(User::new); @@ -175,13 +192,11 @@ pub(crate) fn execute( #[cfg(test)] mod tests { use crate::{ - cmd::{self, metadata::contract::*}, - crate_metadata::CrateMetadata, - util::tests::with_tmp_dir, - workspace::ManifestPath, + cmd, crate_metadata::CrateMetadata, util::tests::with_tmp_dir, workspace::ManifestPath, UnstableFlags, }; use blake2::digest::{Update as _, VariableOutput as _}; + use contract_metadata::*; use serde_json::{Map, Value}; use std::{fmt::Write, fs}; use toml::value; diff --git a/src/cmd/metadata/contract.rs b/src/cmd/metadata/contract.rs deleted file mode 100644 index dc273db09df6f5ba5fc429b9dd2d5eeb32190052..0000000000000000000000000000000000000000 --- a/src/cmd/metadata/contract.rs +++ /dev/null @@ -1,241 +0,0 @@ -// 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 . - -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"; - -/// An entire ink! project for metadata file generation purposes. -#[derive(Debug, Serialize)] -pub struct ContractMetadata { - metadata_version: semver::Version, - source: Source, - contract: Contract, - #[serde(skip_serializing_if = "Option::is_none")] - user: Option, - /// Raw JSON of the metadata generated by the ink! contract itself - #[serde(flatten)] - ink: Map, -} - -impl ContractMetadata { - /// Construct new contract metadata - pub fn new( - source: Source, - contract: Contract, - user: Option, - ink: Map, - ) -> Self { - let metadata_version = semver::Version::parse(METADATA_VERSION) - .expect("METADATA_VERSION is a valid semver string"); - - Self { - metadata_version, - source, - contract, - user, - ink, - } - } -} - -#[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(&self, serializer: S) -> Result - 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(&self, serializer: S) -> Result - 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, - #[serde(skip_serializing_if = "Option::is_none")] - description: Option, - #[serde(skip_serializing_if = "Option::is_none")] - documentation: Option, - #[serde(skip_serializing_if = "Option::is_none")] - repository: Option, - #[serde(skip_serializing_if = "Option::is_none")] - homepage: Option, - #[serde(skip_serializing_if = "Option::is_none")] - license: Option, -} - -impl Contract { - /// Constructs a new Contract. - pub fn new( - name: String, - version: Version, - authors: Vec, - description: Option, - documentation: Option, - repository: Option, - homepage: Option, - license: Option, - ) -> Self { - Contract { - name, - version, - authors, - description, - documentation, - repository, - homepage, - license, - } - } -} - -/// Additional user defined metadata, can be any valid json. -#[derive(Debug, Serialize)] -pub struct User { - #[serde(flatten)] - json: Map, -} - -impl User { - /// Constructs a new InkProjectUser - pub fn new(json: Map) -> Self { - User { json } - } -} - -/// Serializes the given bytes as byte string. -fn serialize_as_byte_str(bytes: &[u8], serializer: S) -> Result -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) -}