From 73cad3662bd91c0a0b3bc866ebcc77ce10d687a6 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 5 Aug 2020 10:45:42 +0100 Subject: [PATCH 01/17] Extract contract metadata to its own crate --- .gitlab-ci.yml | 2 +- Cargo.lock | 11 + Cargo.toml | 4 + metadata/Cargo.toml | 23 ++ metadata/LICENSE | 203 ++++++++++++++++++ metadata/README.md | 1 + .../metadata/contract.rs => metadata/lib.rs | 14 +- src/cmd/{metadata/mod.rs => metadata.rs} | 4 +- 8 files changed, 251 insertions(+), 11 deletions(-) create mode 100644 metadata/Cargo.toml create mode 100644 metadata/LICENSE create mode 100644 metadata/README.md rename src/cmd/metadata/contract.rs => metadata/lib.rs (95%) rename src/cmd/{metadata/mod.rs => metadata.rs} (99%) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b8d9c37f..2a957d10 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 8d358f37..c1b6aaba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -377,6 +377,7 @@ dependencies = [ "pretty_assertions", "pwasm-utils", "rustc_version", + "seal-contract-metadata", "semver 0.10.0", "serde", "serde_json", @@ -2521,6 +2522,16 @@ dependencies = [ "untrusted", ] +[[package]] +name = "seal-contract-metadata" +version = "0.1.0" +dependencies = [ + "semver 0.10.0", + "serde", + "serde_json", + "url 2.1.1", +] + [[package]] name = "semver" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 9a676db8..5bc61d35 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.4" cargo-xbuild = "0.5.32" rustc_version = "0.2.3" blake2 = "0.9.0" +seal-contract-metadata = { version = "0.1.0", path = "./metadata" } semver = { version = "0.10.0", features = ["serde"] } serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = "1.0" diff --git a/metadata/Cargo.toml b/metadata/Cargo.toml new file mode 100644 index 00000000..3358d682 --- /dev/null +++ b/metadata/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "seal-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/seal-contract-metadata" +homepage = "https://www.substrate.io/" +description = "Library defining metadata for SEAL smart contracts on substrate" +keywords = ["parity", "blockchain"] +include = ["Cargo.toml", "*.rs", "README.md", "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"] } diff --git a/metadata/LICENSE b/metadata/LICENSE new file mode 100644 index 00000000..6b0b1270 --- /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/README.md b/metadata/README.md new file mode 100644 index 00000000..044a4824 --- /dev/null +++ b/metadata/README.md @@ -0,0 +1 @@ +# todo diff --git a/src/cmd/metadata/contract.rs b/metadata/lib.rs similarity index 95% rename from src/cmd/metadata/contract.rs rename to metadata/lib.rs index dc273db0..eff67088 100644 --- a/src/cmd/metadata/contract.rs +++ b/metadata/lib.rs @@ -22,7 +22,7 @@ use url::Url; const METADATA_VERSION: &str = "0.1.0"; -/// An entire ink! project for metadata file generation purposes. +/// Smart contract metadata. #[derive(Debug, Serialize)] pub struct ContractMetadata { metadata_version: semver::Version, @@ -30,18 +30,18 @@ pub struct ContractMetadata { contract: Contract, #[serde(skip_serializing_if = "Option::is_none")] user: Option, - /// Raw JSON of the metadata generated by the ink! contract itself + /// Raw JSON of the contract abi metadata #[serde(flatten)] - ink: Map, + abi: Map, } impl ContractMetadata { - /// Construct new contract metadata + /// Construct new contract metadata. pub fn new( source: Source, contract: Contract, user: Option, - ink: Map, + abi: Map, ) -> Self { let metadata_version = semver::Version::parse(METADATA_VERSION) .expect("METADATA_VERSION is a valid semver string"); @@ -51,7 +51,7 @@ impl ContractMetadata { source, contract, user, - ink, + abi, } } } @@ -217,7 +217,7 @@ pub struct User { } impl User { - /// Constructs a new InkProjectUser + /// Constructs new user metadata. pub fn new(json: Map) -> Self { User { json } } diff --git a/src/cmd/metadata/mod.rs b/src/cmd/metadata.rs similarity index 99% rename from src/cmd/metadata/mod.rs rename to src/cmd/metadata.rs index 9a62dc04..04bbfafd 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 seal_contract_metadata::{ Compiler, Contract, ContractMetadata, Language, Source, SourceCompiler, SourceLanguage, User, }; use semver::Version; -- GitLab From 0f80cd5822072e2b522f5c56106253b3f37e2668 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 5 Aug 2020 11:41:51 +0100 Subject: [PATCH 02/17] Add json serialization test --- Cargo.lock | 1 + metadata/Cargo.toml | 5 ++- metadata/README.md | 1 - metadata/lib.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 88 insertions(+), 3 deletions(-) delete mode 100644 metadata/README.md diff --git a/Cargo.lock b/Cargo.lock index c1b6aaba..0d77c902 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2526,6 +2526,7 @@ dependencies = [ name = "seal-contract-metadata" version = "0.1.0" dependencies = [ + "pretty_assertions", "semver 0.10.0", "serde", "serde_json", diff --git a/metadata/Cargo.toml b/metadata/Cargo.toml index 3358d682..c2d5d1b5 100644 --- a/metadata/Cargo.toml +++ b/metadata/Cargo.toml @@ -11,7 +11,7 @@ documentation = "https://docs.rs/seal-contract-metadata" homepage = "https://www.substrate.io/" description = "Library defining metadata for SEAL smart contracts on substrate" keywords = ["parity", "blockchain"] -include = ["Cargo.toml", "*.rs", "README.md", "LICENSE"] +include = ["Cargo.toml", "*.rs", "LICENSE"] [lib] path = "lib.rs" @@ -21,3 +21,6 @@ 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/README.md b/metadata/README.md deleted file mode 100644 index 044a4824..00000000 --- a/metadata/README.md +++ /dev/null @@ -1 +0,0 @@ -# todo diff --git a/metadata/lib.rs b/metadata/lib.rs index eff67088..ef0e8793 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -30,7 +30,7 @@ pub struct ContractMetadata { contract: Contract, #[serde(skip_serializing_if = "Option::is_none")] user: Option, - /// Raw JSON of the contract abi metadata + /// Raw JSON of the contract abi metadata, generated during contract compilation. #[serde(flatten)] abi: Map, } @@ -239,3 +239,85 @@ where } serializer.serialize_str(&hex) } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[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::new( + "incrementer".to_string(), + Version::new(2, 1, 0), + vec!["Parity Technologies ".to_string()], + Some("increment a value".to_string()), + Some(Url::parse("http://docs.rs/").unwrap()), + Some(Url::parse("http://github.com/paritytech/ink/").unwrap()), + Some(Url::parse("http://example.com/").unwrap()), + Some("Apache-2.0".to_string()), + ); + 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! { + { + "metadata_version": "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); + } +} -- GitLab From 914adf9a8741c0fa4e2fd830d7ffee8080c967f9 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 5 Aug 2020 11:46:10 +0100 Subject: [PATCH 03/17] Add json test for excluding optional fields --- metadata/lib.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/metadata/lib.rs b/metadata/lib.rs index ef0e8793..8c9c967b 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -320,4 +320,55 @@ mod tests { 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::new( + "incrementer".to_string(), + Version::new(2, 1, 0), + vec!["Parity Technologies ".to_string()], + None, + None, + None, + None, + None, + ); + 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! { + { + "metadata_version": "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); + } } -- GitLab From 303879674e82e954600662f085f3d83dd3f00153 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 5 Aug 2020 12:13:23 +0100 Subject: [PATCH 04/17] Add doc tests and rename to contract-metadata --- Cargo.lock | 24 ++++++++++++------------ Cargo.toml | 2 +- metadata/Cargo.toml | 6 +++--- metadata/lib.rs | 36 ++++++++++++++++++++++++++++++++++++ src/cmd/metadata.rs | 2 +- 5 files changed, 53 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d77c902..f1fa982e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -367,6 +367,7 @@ dependencies = [ "cargo-xbuild", "cargo_metadata", "colored", + "contract-metadata", "env_logger", "futures 0.3.5", "heck", @@ -377,7 +378,6 @@ dependencies = [ "pretty_assertions", "pwasm-utils", "rustc_version", - "seal-contract-metadata", "semver 0.10.0", "serde", "serde_json", @@ -515,6 +515,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" @@ -2522,17 +2533,6 @@ dependencies = [ "untrusted", ] -[[package]] -name = "seal-contract-metadata" -version = "0.1.0" -dependencies = [ - "pretty_assertions", - "semver 0.10.0", - "serde", - "serde_json", - "url 2.1.1", -] - [[package]] name = "semver" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 5bc61d35..38ea039a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ toml = "0.5.4" cargo-xbuild = "0.5.32" rustc_version = "0.2.3" blake2 = "0.9.0" -seal-contract-metadata = { version = "0.1.0", path = "./metadata" } +contract-metadata = { version = "0.1.0", path = "./metadata" } semver = { version = "0.10.0", features = ["serde"] } serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = "1.0" diff --git a/metadata/Cargo.toml b/metadata/Cargo.toml index c2d5d1b5..36950c74 100644 --- a/metadata/Cargo.toml +++ b/metadata/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "seal-contract-metadata" +name = "contract-metadata" version = "0.1.0" authors = ["Parity Technologies "] edition = "2018" @@ -7,9 +7,9 @@ edition = "2018" license = "Apache-2.0" readme = "README.md" repository = "https://github.com/paritytech/cargo-contract" -documentation = "https://docs.rs/seal-contract-metadata" +documentation = "https://docs.rs/contract-metadata" homepage = "https://www.substrate.io/" -description = "Library defining metadata for SEAL smart contracts on substrate" +description = "Library defining metadata for smart contracts on substrate" keywords = ["parity", "blockchain"] include = ["Cargo.toml", "*.rs", "LICENSE"] diff --git a/metadata/lib.rs b/metadata/lib.rs index 8c9c967b..0f83d6ba 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -14,6 +14,42 @@ // 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::new( +//! "incrementer".to_string(), +//! Version::new(2, 1, 0), +//! vec!["Parity Technologies ".to_string()], +//! Some("increment a value".to_string()), +//! Some(Url::parse("http://!docs.rs/").unwrap()), +//! Some(Url::parse("http://!github.com/paritytech/ink/").unwrap()), +//! Some(Url::parse("http://!example.com/").unwrap()), +//! Some("Apache-2.0".to_string()), +//! ); +//! // 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}; diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 04bbfafd..35f38f16 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -21,7 +21,7 @@ use crate::{ UnstableFlags, Verbosity, }; use anyhow::Result; -use seal_contract_metadata::{ +use contract_metadata::{ Compiler, Contract, ContractMetadata, Language, Source, SourceCompiler, SourceLanguage, User, }; use semver::Version; -- GitLab From 4f214029c758c93ea50dcc2e7b102153eb759bb6 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Mon, 17 Aug 2020 09:53:30 +0100 Subject: [PATCH 05/17] Fmt --- metadata/lib.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 0f83d6ba..6c4500f9 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -285,7 +285,8 @@ mod tests { #[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 compiler = + SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap()); let source = Source::new([0u8; 32], language, compiler); let contract = Contract::new( "incrementer".to_string(), @@ -314,7 +315,10 @@ mod tests { "storage": {}, "types": [] } - }.as_object().unwrap().clone(); + } + .as_object() + .unwrap() + .clone(); let metadata = ContractMetadata::new(source, contract, Some(user), abi_json); let json = serde_json::to_value(&metadata).unwrap(); @@ -360,7 +364,8 @@ mod tests { #[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 compiler = + SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap()); let source = Source::new([0u8; 32], language, compiler); let contract = Contract::new( "incrementer".to_string(), @@ -378,7 +383,10 @@ mod tests { "storage": {}, "types": [] } - }.as_object().unwrap().clone(); + } + .as_object() + .unwrap() + .clone(); let metadata = ContractMetadata::new(source, contract, None, abi_json); let json = serde_json::to_value(&metadata).unwrap(); -- GitLab From 99c67755288a5421ce1c504e61467fcc4d176439 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Mon, 17 Aug 2020 10:16:55 +0100 Subject: [PATCH 06/17] Fix tests --- src/cmd/metadata.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 35f38f16..bb2a29db 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -173,12 +173,13 @@ pub(crate) fn execute( #[cfg(test)] mod tests { use crate::{ - cmd::{self, metadata::contract::*}, + cmd, crate_metadata::CrateMetadata, util::tests::with_tmp_dir, workspace::ManifestPath, UnstableFlags, }; + use contract_metadata::*; use blake2::digest::{Update as _, VariableOutput as _}; use serde_json::{Map, Value}; use std::{fmt::Write, fs}; -- GitLab From 1ec28e0a8ba8ff361f6a568e43d788304a1fa047 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Mon, 17 Aug 2020 10:18:56 +0100 Subject: [PATCH 07/17] Fmt --- src/cmd/metadata.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index bb2a29db..d2967aeb 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -173,14 +173,11 @@ pub(crate) fn execute( #[cfg(test)] mod tests { use crate::{ - cmd, - crate_metadata::CrateMetadata, - util::tests::with_tmp_dir, - workspace::ManifestPath, + cmd, crate_metadata::CrateMetadata, util::tests::with_tmp_dir, workspace::ManifestPath, UnstableFlags, }; - use contract_metadata::*; use blake2::digest::{Update as _, VariableOutput as _}; + use contract_metadata::*; use serde_json::{Map, Value}; use std::{fmt::Write, fs}; use toml::value; -- GitLab From ea01a8a540faa3c718e84d1bf3003db09315b5fb Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 19 Aug 2020 15:17:06 +0100 Subject: [PATCH 08/17] Builder API for contract metadata --- metadata/lib.rs | 196 ++++++++++++++++++++++++++++++++------------ src/cmd/metadata.rs | 21 ++--- 2 files changed, 156 insertions(+), 61 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 6c4500f9..1d3f101d 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -28,16 +28,17 @@ //! 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::new( -//! "incrementer".to_string(), -//! Version::new(2, 1, 0), -//! vec!["Parity Technologies ".to_string()], -//! Some("increment a value".to_string()), -//! Some(Url::parse("http://!docs.rs/").unwrap()), -//! Some(Url::parse("http://!github.com/paritytech/ink/").unwrap()), -//! Some(Url::parse("http://!example.com/").unwrap()), -//! Some("Apache-2.0".to_string()), -//! ); +//! let contract = Contract::builder() +//! .name("incrementer".to_string()) +//! .version(Version::new(2, 1, 0)) +//! .authors(vec!["Parity Technologies ".to_string()]) +//! .description(Some("increment a value".to_string())) +//! .documentation(Some(Url::parse("http:docs.rs/").unwrap())) +//! .repository(Some(Url::parse("http:github.com/paritytech/ink/").unwrap())) +//! .homepage(Some(Url::parse("http:example.com/").unwrap())) +//! .license(Some("Apache-2.0".to_string())) +//! .build() +//! .unwrap(); //! // user defined raw json //! let user_json: Map = Map::new(); //! let user = User::new(user_json); @@ -221,27 +222,8 @@ pub struct Contract { } 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, - } + pub fn builder() -> ContractBuilder { + ContractBuilder::default() } } @@ -259,6 +241,120 @@ impl User { } } +/// 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) + /// + /// Supplying an empty string will result in an `Err` when calling `build()` + pub fn name(&mut self, name: S) -> &mut Self + where + S: AsRef + { + self.name = Some(name.as_ref().to_string()); + self + } + + /// Set the contract version (required) + /// + /// Supplying the default version `0.0.0` will result in an `Err` when calling `build()` + pub fn version(&mut self, version: Version) -> &mut Self { + self.version = Some(version); + self + } + + /// Set the contract version (required) + /// + /// Supplying an empty list of authors will result in an `Err` when calling `build()` + pub fn authors(&mut self, authors: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + self.authors = Some(authors.into_iter().map(|s| s.as_ref().to_string()).collect()); + self + } + + /// Set the contract description (optional) + pub fn description(&mut self, description: Option) -> &mut Self + where + S: AsRef + { + self.description = description.map(|s| s.as_ref().to_string()); + self + } + + /// Set the contract documentation url (optional) + pub fn documentation(&mut self, documentation: Option) -> &mut Self { + self.documentation = documentation; + self + } + + /// Set the contract repository url (optional) + pub fn repository(&mut self, repository: Option) -> &mut Self { + self.repository = repository; + self + } + + /// Set the contract homepage url (optional) + pub fn homepage(&mut self, homepage: Option) -> &mut Self + { + self.homepage = homepage; + self + } + + /// Set the contract license (optional) + pub fn license(&mut self, license: Option) -> &mut Self + where + S: AsRef + { + self.license = license.map(|s| s.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)) + } + } +} + /// Serializes the given bytes as byte string. fn serialize_as_byte_str(bytes: &[u8], serializer: S) -> Result where @@ -288,16 +384,18 @@ mod tests { let compiler = SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap()); let source = Source::new([0u8; 32], language, compiler); - let contract = Contract::new( - "incrementer".to_string(), - Version::new(2, 1, 0), - vec!["Parity Technologies ".to_string()], - Some("increment a value".to_string()), - Some(Url::parse("http://docs.rs/").unwrap()), - Some(Url::parse("http://github.com/paritytech/ink/").unwrap()), - Some(Url::parse("http://example.com/").unwrap()), - Some("Apache-2.0".to_string()), - ); + let contract = Contract::builder() + .name("incrementer".to_string()) + .version(Version::new(2, 1, 0)) + .authors(vec!["Parity Technologies ".to_string()]) + .description(Some("increment a value".to_string())) + .documentation(Some(Url::parse("http://docs.rs/").unwrap())) + .repository(Some(Url::parse("http://github.com/paritytech/ink/").unwrap())) + .homepage(Some(Url::parse("http://example.com/").unwrap())) + .license(Some("Apache-2.0".to_string())) + .build() + .unwrap(); + let user_json = json! { { "more-user-provided-fields": [ @@ -367,16 +465,12 @@ mod tests { let compiler = SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap()); let source = Source::new([0u8; 32], language, compiler); - let contract = Contract::new( - "incrementer".to_string(), - Version::new(2, 1, 0), - vec!["Parity Technologies ".to_string()], - None, - None, - None, - None, - None, - ); + 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": {}, diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index d2967aeb..2206bd1e 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -116,16 +116,17 @@ impl GenerateMetadataCommand { }; // Required contract fields - let contract = Contract::new( - contract_name, - contract_version, - contract_authors, - description, - documentation, - repository, - homepage, - license, - ); + let contract = Contract::builder() + .name(contract_name) + .version(contract_version) + .authors(contract_authors) + .description(description) + .documentation(documentation) + .repository(repository) + .homepage(homepage) + .license(license) + .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); -- GitLab From 11c688f9b71fb539ecad796ca401820496a7980c Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 19 Aug 2020 16:06:29 +0100 Subject: [PATCH 09/17] Tests for builder pattern --- metadata/lib.rs | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 1d3f101d..32238514 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -256,8 +256,6 @@ pub struct ContractBuilder { impl ContractBuilder { /// Set the contract name (required) - /// - /// Supplying an empty string will result in an `Err` when calling `build()` pub fn name(&mut self, name: S) -> &mut Self where S: AsRef @@ -267,16 +265,12 @@ impl ContractBuilder { } /// Set the contract version (required) - /// - /// Supplying the default version `0.0.0` will result in an `Err` when calling `build()` pub fn version(&mut self, version: Version) -> &mut Self { self.version = Some(version); self } /// Set the contract version (required) - /// - /// Supplying an empty list of authors will result in an `Err` when calling `build()` pub fn authors(&mut self, authors: I) -> &mut Self where I: IntoIterator, @@ -350,7 +344,7 @@ impl ContractBuilder { if self.authors.is_none() { required.push("authors") } - Err(format!("Missing required non-default fields: {:?}", required)) + Err(format!("Missing required non-default fields: {}", required.join(", "))) } } } @@ -378,6 +372,41 @@ mod tests { 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)); -- GitLab From e55248a8f014f522be5a5ed7b3dc17e02b615e6a Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Wed, 19 Aug 2020 16:07:00 +0100 Subject: [PATCH 10/17] Fmt --- metadata/lib.rs | 51 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 32238514..4ba60462 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -258,7 +258,7 @@ impl ContractBuilder { /// Set the contract name (required) pub fn name(&mut self, name: S) -> &mut Self where - S: AsRef + S: AsRef, { self.name = Some(name.as_ref().to_string()); self @@ -276,14 +276,19 @@ impl ContractBuilder { I: IntoIterator, S: AsRef, { - self.authors = Some(authors.into_iter().map(|s| s.as_ref().to_string()).collect()); + self.authors = Some( + authors + .into_iter() + .map(|s| s.as_ref().to_string()) + .collect(), + ); self } /// Set the contract description (optional) pub fn description(&mut self, description: Option) -> &mut Self where - S: AsRef + S: AsRef, { self.description = description.map(|s| s.as_ref().to_string()); self @@ -302,16 +307,15 @@ impl ContractBuilder { } /// Set the contract homepage url (optional) - pub fn homepage(&mut self, homepage: Option) -> &mut Self - { + pub fn homepage(&mut self, homepage: Option) -> &mut Self { self.homepage = homepage; self } /// Set the contract license (optional) pub fn license(&mut self, license: Option) -> &mut Self - where - S: AsRef + where + S: AsRef, { self.license = license.map(|s| s.as_ref().to_string()); self @@ -323,7 +327,9 @@ impl ContractBuilder { pub fn build(&self) -> Result { let mut required = Vec::new(); - if let (Some(name), Some(version), Some(authors)) = (&self.name, &self.version, &self.authors) { + if let (Some(name), Some(version), Some(authors)) = + (&self.name, &self.version, &self.authors) + { Ok(Contract { name: name.to_string(), version: version.clone(), @@ -344,7 +350,10 @@ impl ContractBuilder { if self.authors.is_none() { required.push("authors") } - Err(format!("Missing required non-default fields: {}", required.join(", "))) + Err(format!( + "Missing required non-default fields: {}", + required.join(", ") + )) } } } @@ -380,7 +389,10 @@ mod tests { .authors(vec!["Parity Technologies ".to_string()]) .build(); - assert_eq!(missing_name.unwrap_err(), "Missing required non-default fields: name"); + assert_eq!( + missing_name.unwrap_err(), + "Missing required non-default fields: name" + ); let missing_version = Contract::builder() .name("incrementer".to_string()) @@ -388,7 +400,10 @@ mod tests { .authors(vec!["Parity Technologies ".to_string()]) .build(); - assert_eq!(missing_version.unwrap_err(), "Missing required non-default fields: version"); + assert_eq!( + missing_version.unwrap_err(), + "Missing required non-default fields: version" + ); let missing_authors = Contract::builder() .name("incrementer".to_string()) @@ -396,7 +411,10 @@ mod tests { // .authors(vec!["Parity Technologies ".to_string()]) .build(); - assert_eq!(missing_authors.unwrap_err(), "Missing required non-default fields: authors"); + assert_eq!( + missing_authors.unwrap_err(), + "Missing required non-default fields: authors" + ); let missing_all = Contract::builder() // .name("incrementer".to_string()) @@ -404,7 +422,10 @@ mod tests { // .authors(vec!["Parity Technologies ".to_string()]) .build(); - assert_eq!(missing_all.unwrap_err(), "Missing required non-default fields: name, version, authors"); + assert_eq!( + missing_all.unwrap_err(), + "Missing required non-default fields: name, version, authors" + ); } #[test] @@ -419,7 +440,9 @@ mod tests { .authors(vec!["Parity Technologies ".to_string()]) .description(Some("increment a value".to_string())) .documentation(Some(Url::parse("http://docs.rs/").unwrap())) - .repository(Some(Url::parse("http://github.com/paritytech/ink/").unwrap())) + .repository(Some( + Url::parse("http://github.com/paritytech/ink/").unwrap(), + )) .homepage(Some(Url::parse("http://example.com/").unwrap())) .license(Some("Apache-2.0".to_string())) .build() -- GitLab From 95f04f0876c42bfb12a05ebf3e8442f5d2d69aca Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 3 Sep 2020 10:40:55 +0100 Subject: [PATCH 11/17] Make metadata version camel case --- metadata/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 4ba60462..13f06975 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -62,6 +62,7 @@ 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, @@ -475,7 +476,7 @@ mod tests { let expected = json! { { - "metadata_version": "0.1.0", + "metadataVersion": "0.1.0", "source": { "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", "language": "ink! 2.1.0", @@ -539,7 +540,7 @@ mod tests { let expected = json! { { - "metadata_version": "0.1.0", + "metadataVersion": "0.1.0", "source": { "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", "language": "ink! 2.1.0", -- GitLab From 50b585b8da8856fe291d1936316729d64a99329b Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 11:48:07 +0100 Subject: [PATCH 12/17] Builder optional fields --- metadata/lib.rs | 57 ++++++++++++++++++++++++++++----------------- src/cmd/metadata.rs | 31 ++++++++++++++++++------ 2 files changed, 60 insertions(+), 28 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 13f06975..3c3c2acd 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -32,11 +32,11 @@ //! .name("incrementer".to_string()) //! .version(Version::new(2, 1, 0)) //! .authors(vec!["Parity Technologies ".to_string()]) -//! .description(Some("increment a value".to_string())) -//! .documentation(Some(Url::parse("http:docs.rs/").unwrap())) -//! .repository(Some(Url::parse("http:github.com/paritytech/ink/").unwrap())) -//! .homepage(Some(Url::parse("http:example.com/").unwrap())) -//! .license(Some("Apache-2.0".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 @@ -287,38 +287,53 @@ impl ContractBuilder { } /// Set the contract description (optional) - pub fn description(&mut self, description: Option) -> &mut Self + pub fn description(&mut self, description: S) -> &mut Self where S: AsRef, { - self.description = description.map(|s| s.as_ref().to_string()); + 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: Option) -> &mut Self { - self.documentation = documentation; + 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: Option) -> &mut Self { - self.repository = repository; + 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: Option) -> &mut Self { - self.homepage = homepage; + 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: Option) -> &mut Self + pub fn license(&mut self, license: S) -> &mut Self where S: AsRef, { - self.license = license.map(|s| s.as_ref().to_string()); + if self.license.is_some() { + panic!("license has already been set") + } + self.license = Some(license.as_ref().to_string()); self } @@ -439,13 +454,13 @@ mod tests { .name("incrementer".to_string()) .version(Version::new(2, 1, 0)) .authors(vec!["Parity Technologies ".to_string()]) - .description(Some("increment a value".to_string())) - .documentation(Some(Url::parse("http://docs.rs/").unwrap())) - .repository(Some( + .description("increment a value".to_string()) + .documentation(Url::parse("http://docs.rs/").unwrap()) + .repository( Url::parse("http://github.com/paritytech/ink/").unwrap(), - )) - .homepage(Some(Url::parse("http://example.com/").unwrap())) - .license(Some("Apache-2.0".to_string())) + ) + .homepage(Url::parse("http://example.com/").unwrap()) + .license("Apache-2.0".to_string()) .build() .unwrap(); diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 2206bd1e..396b2873 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -116,15 +116,32 @@ impl GenerateMetadataCommand { }; // Required contract fields - let contract = Contract::builder() + let mut builder = Contract::builder() .name(contract_name) .version(contract_version) - .authors(contract_authors) - .description(description) - .documentation(documentation) - .repository(repository) - .homepage(homepage) - .license(license) + .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))?; -- GitLab From aa955cfd24ac6ec72a364eda01798b481870a479 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 12:12:57 +0100 Subject: [PATCH 13/17] Check whether fields have not already been set --- metadata/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/metadata/lib.rs b/metadata/lib.rs index 3c3c2acd..8be73647 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -261,12 +261,18 @@ impl ContractBuilder { 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 } @@ -277,6 +283,9 @@ impl ContractBuilder { I: IntoIterator, S: AsRef, { + if self.authors.is_some() { + panic!("authors has already been set") + } self.authors = Some( authors .into_iter() -- GitLab From a49c0bb72c71c11355fbda6294f0dd3d05843ffc Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 12:16:23 +0100 Subject: [PATCH 14/17] Check at least one author --- metadata/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/metadata/lib.rs b/metadata/lib.rs index 8be73647..88f1f4be 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -286,6 +286,9 @@ impl ContractBuilder { if self.authors.is_some() { panic!("authors has already been set") } + if authors.into_iter().count() == 0 { + panic!("must have at least one author") + } self.authors = Some( authors .into_iter() -- GitLab From 6931945d6273453f8c21058f154276e0fb24e0ff Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 12:32:27 +0100 Subject: [PATCH 15/17] I really should check it compiles before pushing --- metadata/lib.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index 88f1f4be..fcb44c0a 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -286,15 +286,17 @@ impl ContractBuilder { if self.authors.is_some() { panic!("authors has already been set") } - if authors.into_iter().count() == 0 { + + 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 - .into_iter() - .map(|s| s.as_ref().to_string()) - .collect(), - ); + + self.authors = Some(authors); self } -- GitLab From 52306206319db24b0b976cd70be073ce0f02bd1f Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 12:33:21 +0100 Subject: [PATCH 16/17] Oh yeah and cargo fmt fml --- metadata/lib.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/metadata/lib.rs b/metadata/lib.rs index fcb44c0a..28507415 100644 --- a/metadata/lib.rs +++ b/metadata/lib.rs @@ -470,9 +470,7 @@ mod tests { .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(), - ) + .repository(Url::parse("http://github.com/paritytech/ink/").unwrap()) .homepage(Url::parse("http://example.com/").unwrap()) .license("Apache-2.0".to_string()) .build() -- GitLab From 3fe903595da1bb1bafcdd42839244f0debb0e225 Mon Sep 17 00:00:00 2001 From: Andrew Jones Date: Thu, 10 Sep 2020 14:40:36 +0100 Subject: [PATCH 17/17] Yeah --- src/cmd/metadata.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 396b2873..8b658d3f 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -116,29 +116,30 @@ impl GenerateMetadataCommand { }; // Required contract fields - let mut builder = Contract::builder() + let mut builder = Contract::builder(); + builder .name(contract_name) .version(contract_version) .authors(contract_authors); if let Some(description) = description { - builder.description(description) + builder.description(description); } if let Some(documentation) = documentation { - builder.documentation(documentation) + builder.documentation(documentation); } if let Some(repository) = repository { - builder.repository(repository) + builder.repository(repository); } if let Some(homepage) = homepage { - builder.homepage(homepage) + builder.homepage(homepage); } if let Some(license) = license { - builder.license(license) + builder.license(license); } let contract = builder -- GitLab