diff --git a/Cargo.lock b/Cargo.lock index 5fb111ff8..de7d2f4a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4595,6 +4595,35 @@ dependencies = [ "vending-factory", ] +[[package]] +name = "vending-minter-featured" +version = "3.5.0" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-storage-plus 1.1.0", + "cw-utils 1.0.1", + "cw2 1.1.0", + "cw721 0.18.0", + "cw721-base 0.18.0", + "rand_core 0.6.4", + "rand_xoshiro", + "schemars", + "semver", + "serde", + "sg-std", + "sg-whitelist", + "sg1", + "sg2", + "sg4", + "sg721", + "sha2 0.10.7", + "shuffle", + "thiserror", + "url", + "vending-factory", +] + [[package]] name = "vending-minter-merkle-wl" version = "3.5.0" diff --git a/contracts/minters/vending-minter-featured/.cargo/config b/contracts/minters/vending-minter-featured/.cargo/config new file mode 100644 index 000000000..ab407a024 --- /dev/null +++ b/contracts/minters/vending-minter-featured/.cargo/config @@ -0,0 +1,4 @@ +[alias] +wasm = "build --release --lib --target wasm32-unknown-unknown" +unit-test = "test --lib" +schema = "run --example schema" diff --git a/contracts/minters/vending-minter-featured/.editorconfig b/contracts/minters/vending-minter-featured/.editorconfig new file mode 100644 index 000000000..3d36f20b1 --- /dev/null +++ b/contracts/minters/vending-minter-featured/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.rs] +indent_size = 4 diff --git a/contracts/minters/vending-minter-featured/.gitignore b/contracts/minters/vending-minter-featured/.gitignore new file mode 100644 index 000000000..dfdaaa6bc --- /dev/null +++ b/contracts/minters/vending-minter-featured/.gitignore @@ -0,0 +1,15 @@ +# Build results +/target + +# Cargo+Git helper file (https://github.com/rust-lang/cargo/blob/0.44.1/src/cargo/sources/git/utils.rs#L320-L327) +.cargo-ok + +# Text file backups +**/*.rs.bk + +# macOS +.DS_Store + +# IDEs +*.iml +.idea diff --git a/contracts/minters/vending-minter-featured/Cargo.toml b/contracts/minters/vending-minter-featured/Cargo.toml new file mode 100644 index 000000000..1324b42c9 --- /dev/null +++ b/contracts/minters/vending-minter-featured/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "vending-minter-featured" +authors = ["Jake Hartnell ", "Shane Vitarana "] +description = "Stargaze vending minter contract" +version = { workspace = true } +edition = { workspace = true } +homepage = { workspace = true } +repository = { workspace = true } +license = { workspace = true } + +exclude = [ + # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. + "contract.wasm", + "hash.txt", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +# for more explicit tests, cargo test --features=backtraces +backtraces = ["cosmwasm-std/backtraces"] +# use library feature to disable all instantiate/execute/query exports +library = [] + +[dependencies] +cosmwasm-schema = { workspace = true } +cosmwasm-std = { workspace = true } +cw2 = { workspace = true } +cw721 = { workspace = true } +cw721-base = { workspace = true, features = ["library"] } +cw-storage-plus = { workspace = true } +cw-utils = { workspace = true } +rand_core = { version = "0.6.4", default-features = false } +rand_xoshiro = { version = "0.6.0", default-features = false } +schemars = { workspace = true } +serde = { workspace = true } +sha2 = { workspace = true } +shuffle = { git = "https://github.com/webmaster128/shuffle", branch = "rm-getrandom", version = "0.1.7" } +sg1 = { workspace = true } +sg2 = { workspace = true } +sg4 = { workspace = true } +sg721 = { workspace = true } +sg-std = { workspace = true } +sg-whitelist = { workspace = true, features = ["library"] } +thiserror = { workspace = true } +url = { workspace = true } +vending-factory = { workspace = true, features = ["library"] } +semver = { workspace = true } diff --git a/contracts/minters/vending-minter-featured/LICENSE b/contracts/minters/vending-minter-featured/LICENSE new file mode 100644 index 000000000..1520ce81b --- /dev/null +++ b/contracts/minters/vending-minter-featured/LICENSE @@ -0,0 +1,202 @@ + + 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 2022 Public Awesome + + 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/contracts/minters/vending-minter-featured/README.md b/contracts/minters/vending-minter-featured/README.md new file mode 100644 index 000000000..3b7d1380c --- /dev/null +++ b/contracts/minters/vending-minter-featured/README.md @@ -0,0 +1,5 @@ +# Stargaze Vending Minter Contract + +A minter that best works for generated art collections. It's designed for collections stored on IPFS that have a base URI root. + +Mints are in random order. The entire collection is shuffled on instantiation. Each mint triggers a smaller "baby" shuffle. At any time, a `Shuffle {}` function can be called to add a time element to the random mint. diff --git a/contracts/minters/vending-minter-featured/examples/schema.rs b/contracts/minters/vending-minter-featured/examples/schema.rs new file mode 100644 index 000000000..e2326007a --- /dev/null +++ b/contracts/minters/vending-minter-featured/examples/schema.rs @@ -0,0 +1,29 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use sg4::StatusResponse; +use vending_minter_featured::msg::{ + ConfigResponse, ExecuteMsg, InstantiateMsg, MintCountResponse, MintPriceResponse, + MintableNumTokensResponse, QueryMsg, StartTimeResponse, +}; +use vending_minter_featured::state::Config; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(Config), &out_dir); + export_schema(&schema_for!(ConfigResponse), &out_dir); + export_schema(&schema_for!(MintableNumTokensResponse), &out_dir); + export_schema(&schema_for!(MintCountResponse), &out_dir); + export_schema(&schema_for!(StartTimeResponse), &out_dir); + export_schema(&schema_for!(MintPriceResponse), &out_dir); + export_schema(&schema_for!(StatusResponse), &out_dir); +} diff --git a/contracts/minters/vending-minter-featured/rustfmt.toml b/contracts/minters/vending-minter-featured/rustfmt.toml new file mode 100644 index 000000000..79d13fd0a --- /dev/null +++ b/contracts/minters/vending-minter-featured/rustfmt.toml @@ -0,0 +1,14 @@ +# stable +newline_style = "Unix" +hard_tabs = false +tab_spaces = 4 + +# unstable... should we require `rustup run nightly cargo fmt` ? +# or just update the style guide when they are stable? +#fn_single_line = true +#format_code_in_doc_comments = true +#overflow_delimited_expr = true +#reorder_impl_items = true +#struct_field_align_threshold = 20 +#struct_lit_single_line = true +#report_todo = "Always" diff --git a/contracts/minters/vending-minter-featured/schema/config_response.json b/contracts/minters/vending-minter-featured/schema/config_response.json new file mode 100644 index 000000000..7b69be083 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/config_response.json @@ -0,0 +1,101 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ConfigResponse", + "type": "object", + "required": [ + "admin", + "base_token_uri", + "factory", + "mint_price", + "num_tokens", + "per_address_limit", + "sg721_address", + "sg721_code_id", + "start_time" + ], + "properties": { + "admin": { + "type": "string" + }, + "base_token_uri": { + "type": "string" + }, + "discount_price": { + "anyOf": [ + { + "$ref": "#/definitions/Coin" + }, + { + "type": "null" + } + ] + }, + "factory": { + "type": "string" + }, + "mint_price": { + "$ref": "#/definitions/Coin" + }, + "num_tokens": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "per_address_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "sg721_address": { + "type": "string" + }, + "sg721_code_id": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "start_time": { + "$ref": "#/definitions/Timestamp" + }, + "whitelist": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false, + "definitions": { + "Coin": { + "type": "object", + "required": [ + "amount", + "denom" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "denom": { + "type": "string" + } + } + }, + "Timestamp": { + "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", + "allOf": [ + { + "$ref": "#/definitions/Uint64" + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + }, + "Uint64": { + "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/minters/vending-minter-featured/schema/execute_msg.json b/contracts/minters/vending-minter-featured/schema/execute_msg.json new file mode 100644 index 000000000..a6044d1ab --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/execute_msg.json @@ -0,0 +1,255 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ExecuteMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "mint" + ], + "properties": { + "mint": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "set_whitelist" + ], + "properties": { + "set_whitelist": { + "type": "object", + "required": [ + "whitelist" + ], + "properties": { + "whitelist": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "purge" + ], + "properties": { + "purge": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "update_mint_price" + ], + "properties": { + "update_mint_price": { + "type": "object", + "required": [ + "price" + ], + "properties": { + "price": { + "type": "integer", + "format": "uint128", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "update_start_time" + ], + "properties": { + "update_start_time": { + "$ref": "#/definitions/Timestamp" + } + }, + "additionalProperties": false + }, + { + "description": "Runs custom checks against TradingStartTime on VendingMinter, then updates by calling sg721-base", + "type": "object", + "required": [ + "update_start_trading_time" + ], + "properties": { + "update_start_trading_time": { + "anyOf": [ + { + "$ref": "#/definitions/Timestamp" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "update_per_address_limit" + ], + "properties": { + "update_per_address_limit": { + "type": "object", + "required": [ + "per_address_limit" + ], + "properties": { + "per_address_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "mint_to" + ], + "properties": { + "mint_to": { + "type": "object", + "required": [ + "recipient" + ], + "properties": { + "recipient": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "mint_for" + ], + "properties": { + "mint_for": { + "type": "object", + "required": [ + "recipient", + "token_id" + ], + "properties": { + "recipient": { + "type": "string" + }, + "token_id": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "shuffle" + ], + "properties": { + "shuffle": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "burn_remaining" + ], + "properties": { + "burn_remaining": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "update_discount_price" + ], + "properties": { + "update_discount_price": { + "type": "object", + "required": [ + "price" + ], + "properties": { + "price": { + "type": "integer", + "format": "uint128", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "remove_discount_price" + ], + "properties": { + "remove_discount_price": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + } + ], + "definitions": { + "Timestamp": { + "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", + "allOf": [ + { + "$ref": "#/definitions/Uint64" + } + ] + }, + "Uint64": { + "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/minters/vending-minter-featured/schema/instantiate_msg.json b/contracts/minters/vending-minter-featured/schema/instantiate_msg.json new file mode 100644 index 000000000..e36b41465 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/instantiate_msg.json @@ -0,0 +1,298 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "InstantiateMsg", + "type": "object", + "required": [ + "create_msg", + "params" + ], + "properties": { + "create_msg": { + "$ref": "#/definitions/CreateMinterMsg_for_VendingMinterInitMsgExtension" + }, + "params": { + "$ref": "#/definitions/MinterParams_for_ParamsExtension" + } + }, + "additionalProperties": false, + "definitions": { + "Coin": { + "type": "object", + "required": [ + "amount", + "denom" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "denom": { + "type": "string" + } + } + }, + "CollectionInfo_for_RoyaltyInfoResponse": { + "type": "object", + "required": [ + "creator", + "description", + "image" + ], + "properties": { + "creator": { + "type": "string" + }, + "description": { + "type": "string" + }, + "explicit_content": { + "type": [ + "boolean", + "null" + ] + }, + "external_link": { + "type": [ + "string", + "null" + ] + }, + "image": { + "type": "string" + }, + "royalty_info": { + "anyOf": [ + { + "$ref": "#/definitions/RoyaltyInfoResponse" + }, + { + "type": "null" + } + ] + }, + "start_trading_time": { + "anyOf": [ + { + "$ref": "#/definitions/Timestamp" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "CollectionParams": { + "type": "object", + "required": [ + "code_id", + "info", + "name", + "symbol" + ], + "properties": { + "code_id": { + "description": "The collection code id", + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "info": { + "$ref": "#/definitions/CollectionInfo_for_RoyaltyInfoResponse" + }, + "name": { + "type": "string" + }, + "symbol": { + "type": "string" + } + }, + "additionalProperties": false + }, + "CreateMinterMsg_for_VendingMinterInitMsgExtension": { + "type": "object", + "required": [ + "collection_params", + "init_msg" + ], + "properties": { + "collection_params": { + "$ref": "#/definitions/CollectionParams" + }, + "init_msg": { + "$ref": "#/definitions/VendingMinterInitMsgExtension" + } + }, + "additionalProperties": false + }, + "Decimal": { + "description": "A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18)", + "type": "string" + }, + "MinterParams_for_ParamsExtension": { + "description": "Common params for all minters used for storage", + "type": "object", + "required": [ + "allowed_sg721_code_ids", + "code_id", + "creation_fee", + "extension", + "frozen", + "max_trading_offset_secs", + "min_mint_price", + "mint_fee_bps" + ], + "properties": { + "allowed_sg721_code_ids": { + "type": "array", + "items": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + } + }, + "code_id": { + "description": "The minter code id", + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "creation_fee": { + "$ref": "#/definitions/Coin" + }, + "extension": { + "$ref": "#/definitions/ParamsExtension" + }, + "frozen": { + "type": "boolean" + }, + "max_trading_offset_secs": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "min_mint_price": { + "$ref": "#/definitions/Coin" + }, + "mint_fee_bps": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + } + }, + "additionalProperties": false + }, + "ParamsExtension": { + "description": "Parameters common to all vending minters, as determined by governance", + "type": "object", + "required": [ + "airdrop_mint_fee_bps", + "airdrop_mint_price", + "max_per_address_limit", + "max_token_limit", + "shuffle_fee" + ], + "properties": { + "airdrop_mint_fee_bps": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "airdrop_mint_price": { + "$ref": "#/definitions/Coin" + }, + "max_per_address_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "max_token_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "shuffle_fee": { + "$ref": "#/definitions/Coin" + } + }, + "additionalProperties": false + }, + "RoyaltyInfoResponse": { + "type": "object", + "required": [ + "payment_address", + "share" + ], + "properties": { + "payment_address": { + "type": "string" + }, + "share": { + "$ref": "#/definitions/Decimal" + } + }, + "additionalProperties": false + }, + "Timestamp": { + "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", + "allOf": [ + { + "$ref": "#/definitions/Uint64" + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + }, + "Uint64": { + "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", + "type": "string" + }, + "VendingMinterInitMsgExtension": { + "type": "object", + "required": [ + "base_token_uri", + "mint_price", + "num_tokens", + "per_address_limit", + "start_time" + ], + "properties": { + "base_token_uri": { + "type": "string" + }, + "mint_price": { + "$ref": "#/definitions/Coin" + }, + "num_tokens": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "payment_address": { + "type": [ + "string", + "null" + ] + }, + "per_address_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "start_time": { + "$ref": "#/definitions/Timestamp" + }, + "whitelist": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + } + } +} diff --git a/contracts/minters/vending-minter-featured/schema/mint_count_response.json b/contracts/minters/vending-minter-featured/schema/mint_count_response.json new file mode 100644 index 000000000..8cb578300 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/mint_count_response.json @@ -0,0 +1,20 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MintCountResponse", + "type": "object", + "required": [ + "address", + "count" + ], + "properties": { + "address": { + "type": "string" + }, + "count": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false +} diff --git a/contracts/minters/vending-minter-featured/schema/mint_price_response.json b/contracts/minters/vending-minter-featured/schema/mint_price_response.json new file mode 100644 index 000000000..e6857d00b --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/mint_price_response.json @@ -0,0 +1,63 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MintPriceResponse", + "type": "object", + "required": [ + "airdrop_price", + "current_price", + "public_price" + ], + "properties": { + "airdrop_price": { + "$ref": "#/definitions/Coin" + }, + "current_price": { + "$ref": "#/definitions/Coin" + }, + "discount_price": { + "anyOf": [ + { + "$ref": "#/definitions/Coin" + }, + { + "type": "null" + } + ] + }, + "public_price": { + "$ref": "#/definitions/Coin" + }, + "whitelist_price": { + "anyOf": [ + { + "$ref": "#/definitions/Coin" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false, + "definitions": { + "Coin": { + "type": "object", + "required": [ + "amount", + "denom" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "denom": { + "type": "string" + } + } + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/minters/vending-minter-featured/schema/mintable_num_tokens_response.json b/contracts/minters/vending-minter-featured/schema/mintable_num_tokens_response.json new file mode 100644 index 000000000..8b80aa85b --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/mintable_num_tokens_response.json @@ -0,0 +1,16 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MintableNumTokensResponse", + "type": "object", + "required": [ + "count" + ], + "properties": { + "count": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + } + }, + "additionalProperties": false +} diff --git a/contracts/minters/vending-minter-featured/schema/minter_config_for__config_extension.json b/contracts/minters/vending-minter-featured/schema/minter_config_for__config_extension.json new file mode 100644 index 000000000..0556ef225 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/minter_config_for__config_extension.json @@ -0,0 +1,128 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MinterConfig_for_ConfigExtension", + "description": "Saved in every minter", + "type": "object", + "required": [ + "collection_code_id", + "extension", + "factory", + "mint_price" + ], + "properties": { + "collection_code_id": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "extension": { + "$ref": "#/definitions/ConfigExtension" + }, + "factory": { + "$ref": "#/definitions/Addr" + }, + "mint_price": { + "$ref": "#/definitions/Coin" + } + }, + "additionalProperties": false, + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + }, + "Coin": { + "type": "object", + "required": [ + "amount", + "denom" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "denom": { + "type": "string" + } + } + }, + "ConfigExtension": { + "type": "object", + "required": [ + "admin", + "base_token_uri", + "num_tokens", + "per_address_limit", + "start_time" + ], + "properties": { + "admin": { + "$ref": "#/definitions/Addr" + }, + "base_token_uri": { + "type": "string" + }, + "discount_price": { + "anyOf": [ + { + "$ref": "#/definitions/Coin" + }, + { + "type": "null" + } + ] + }, + "num_tokens": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "payment_address": { + "anyOf": [ + { + "$ref": "#/definitions/Addr" + }, + { + "type": "null" + } + ] + }, + "per_address_limit": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "start_time": { + "$ref": "#/definitions/Timestamp" + }, + "whitelist": { + "anyOf": [ + { + "$ref": "#/definitions/Addr" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "Timestamp": { + "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", + "allOf": [ + { + "$ref": "#/definitions/Uint64" + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + }, + "Uint64": { + "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/minters/vending-minter-featured/schema/query_msg.json b/contracts/minters/vending-minter-featured/schema/query_msg.json new file mode 100644 index 000000000..56821a1c8 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/query_msg.json @@ -0,0 +1,92 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "QueryMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "config" + ], + "properties": { + "config": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "mintable_num_tokens" + ], + "properties": { + "mintable_num_tokens": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "start_time" + ], + "properties": { + "start_time": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "mint_price" + ], + "properties": { + "mint_price": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "mint_count" + ], + "properties": { + "mint_count": { + "type": "object", + "required": [ + "address" + ], + "properties": { + "address": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "status" + ], + "properties": { + "status": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] +} diff --git a/contracts/minters/vending-minter-featured/schema/start_time_response.json b/contracts/minters/vending-minter-featured/schema/start_time_response.json new file mode 100644 index 000000000..40a03518d --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/start_time_response.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "StartTimeResponse", + "type": "object", + "required": [ + "start_time" + ], + "properties": { + "start_time": { + "type": "string" + } + }, + "additionalProperties": false +} diff --git a/contracts/minters/vending-minter-featured/schema/status_response.json b/contracts/minters/vending-minter-featured/schema/status_response.json new file mode 100644 index 000000000..dfcf3dc33 --- /dev/null +++ b/contracts/minters/vending-minter-featured/schema/status_response.json @@ -0,0 +1,36 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "StatusResponse", + "type": "object", + "required": [ + "status" + ], + "properties": { + "status": { + "$ref": "#/definitions/Status" + } + }, + "additionalProperties": false, + "definitions": { + "Status": { + "type": "object", + "required": [ + "is_blocked", + "is_explicit", + "is_verified" + ], + "properties": { + "is_blocked": { + "type": "boolean" + }, + "is_explicit": { + "type": "boolean" + }, + "is_verified": { + "type": "boolean" + } + }, + "additionalProperties": false + } + } +} diff --git a/contracts/minters/vending-minter-featured/src/contract.rs b/contracts/minters/vending-minter-featured/src/contract.rs new file mode 100644 index 000000000..af707827e --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/contract.rs @@ -0,0 +1,1254 @@ +use crate::error::ContractError; +use crate::msg::{ + ConfigResponse, ExecuteMsg, MintCountResponse, MintPriceResponse, MintableNumTokensResponse, + QueryMsg, StartTimeResponse, +}; +use crate::state::{ + Config, ConfigExtension, CONFIG, MINTABLE_NUM_TOKENS, MINTABLE_TOKEN_POSITIONS, MINTER_ADDRS, + SG721_ADDRESS, STATUS, +}; +use crate::validation::{check_dynamic_per_address_limit, get_three_percent_of_tokens}; +#[cfg(not(feature = "library"))] +use cosmwasm_std::entry_point; +use cosmwasm_std::{ + coin, ensure, to_binary, Addr, BankMsg, Binary, Coin, CosmosMsg, Decimal, Deps, DepsMut, Empty, + Env, Event, MessageInfo, Order, Reply, ReplyOn, StdError, StdResult, Timestamp, Uint128, + WasmMsg, +}; +use cw2::set_contract_version; +use cw721_base::Extension; +use cw_utils::{may_pay, maybe_addr, nonpayable, parse_reply_instantiate_data}; +use rand_core::{RngCore, SeedableRng}; +use rand_xoshiro::Xoshiro128PlusPlus; +use semver::Version; +use sg1::checked_fair_burn; +use sg2::query::Sg2QueryMsg; +use sg4::{MinterConfig, Status, StatusResponse, SudoMsg}; +use sg721::{ExecuteMsg as Sg721ExecuteMsg, InstantiateMsg as Sg721InstantiateMsg}; +use sg_std::{StargazeMsgWrapper, GENESIS_MINT_START_TIME}; +use sg_whitelist::msg::{ + ConfigResponse as WhitelistConfigResponse, HasMemberResponse, QueryMsg as WhitelistQueryMsg, +}; +use sha2::{Digest, Sha256}; +use shuffle::{fy::FisherYates, shuffler::Shuffler}; +use std::convert::TryInto; +use url::Url; +use vending_factory::msg::{ParamsResponse, VendingMinterCreateMsg}; +use vending_factory::state::VendingMinterParams; + +pub type Response = cosmwasm_std::Response; +pub type SubMsg = cosmwasm_std::SubMsg; + +pub struct TokenPositionMapping { + pub position: u32, + pub token_id: u32, +} + +// version info for migration info +const CONTRACT_NAME: &str = "crates.io:sg-minter"; +const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +const INSTANTIATE_SG721_REPLY_ID: u64 = 1; + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: VendingMinterCreateMsg, +) -> Result { + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + + let factory = info.sender.clone(); + + // Make sure the sender is the factory contract + // This will fail if the sender cannot parse a response from the factory contract + let factory_response: ParamsResponse = deps + .querier + .query_wasm_smart(factory.clone(), &Sg2QueryMsg::Params {})?; + let factory_params = factory_response.params; + + // set default status so it can be queried without failing + STATUS.save(deps.storage, &Status::default())?; + + if !check_dynamic_per_address_limit( + msg.init_msg.per_address_limit, + msg.init_msg.num_tokens, + factory_params.extension.max_per_address_limit, + )? { + return Err(ContractError::InvalidPerAddressLimit { + max: display_max_mintable_tokens( + msg.init_msg.per_address_limit, + msg.init_msg.num_tokens, + factory_params.extension.max_per_address_limit, + )?, + min: 1, + got: msg.init_msg.per_address_limit, + }); + } + + // sanitize base token uri + let mut base_token_uri = msg.init_msg.base_token_uri.trim().to_string(); + // Token URI must be a valid URL (ipfs, https, etc.) + let parsed_token_uri = + Url::parse(&base_token_uri).map_err(|_| ContractError::InvalidBaseTokenURI {})?; + base_token_uri = parsed_token_uri.to_string(); + + let genesis_time = Timestamp::from_nanos(GENESIS_MINT_START_TIME); + // If start time is before genesis time return error + if msg.init_msg.start_time < genesis_time { + return Err(ContractError::BeforeGenesisTime {}); + } + + // If current time is beyond the provided start time return error + if env.block.time > msg.init_msg.start_time { + return Err(ContractError::InvalidStartTime( + msg.init_msg.start_time, + env.block.time, + )); + } + + // Validate address for the optional whitelist contract + let whitelist_addr = msg + .init_msg + .whitelist + .and_then(|w| deps.api.addr_validate(w.as_str()).ok()); + + if let Some(wl) = whitelist_addr.clone() { + // check the whitelist exists + let res: WhitelistConfigResponse = deps + .querier + .query_wasm_smart(wl, &WhitelistQueryMsg::Config {})?; + if res.is_active { + return Err(ContractError::WhitelistAlreadyStarted {}); + } + } + + // Use default start trading time if not provided + let mut collection_info = msg.collection_params.info.clone(); + let offset = factory_params.max_trading_offset_secs; + let default_start_time_with_offset = msg.init_msg.start_time.plus_seconds(offset); + if let Some(start_trading_time) = msg.collection_params.info.start_trading_time { + // If trading start time > start_time + offset, return error + if start_trading_time > default_start_time_with_offset { + return Err(ContractError::InvalidStartTradingTime( + start_trading_time, + default_start_time_with_offset, + )); + } + } + let start_trading_time = msg + .collection_params + .info + .start_trading_time + .or(Some(default_start_time_with_offset)); + collection_info.start_trading_time = start_trading_time; + + let config = Config { + factory: factory.clone(), + collection_code_id: msg.collection_params.code_id, + extension: ConfigExtension { + admin: deps + .api + .addr_validate(&msg.collection_params.info.creator)?, + payment_address: maybe_addr(deps.api, msg.init_msg.payment_address)?, + base_token_uri, + num_tokens: msg.init_msg.num_tokens, + per_address_limit: msg.init_msg.per_address_limit, + whitelist: whitelist_addr, + start_time: msg.init_msg.start_time, + discount_price: None, + }, + mint_price: msg.init_msg.mint_price, + }; + + CONFIG.save(deps.storage, &config)?; + MINTABLE_NUM_TOKENS.save(deps.storage, &msg.init_msg.num_tokens)?; + + let token_ids = random_token_list( + &env, + deps.api + .addr_validate(&msg.collection_params.info.creator)?, + (1..=msg.init_msg.num_tokens).collect::>(), + )?; + // Save mintable token ids map + let mut token_position = 1; + for token_id in token_ids { + MINTABLE_TOKEN_POSITIONS.save(deps.storage, token_position, &token_id)?; + token_position += 1; + } + + // Submessage to instantiate sg721 contract + let submsg = SubMsg { + msg: WasmMsg::Instantiate { + code_id: msg.collection_params.code_id, + msg: to_binary(&Sg721InstantiateMsg { + name: msg.collection_params.name.clone(), + symbol: msg.collection_params.symbol, + minter: env.contract.address.to_string(), + collection_info, + })?, + funds: info.funds, + admin: Some(config.extension.admin.to_string()), + label: format!("SG721-{}", msg.collection_params.name.trim()), + } + .into(), + id: INSTANTIATE_SG721_REPLY_ID, + gas_limit: None, + reply_on: ReplyOn::Success, + }; + + Ok(Response::new() + .add_attribute("action", "instantiate") + .add_attribute("contract_name", CONTRACT_NAME) + .add_attribute("contract_version", CONTRACT_VERSION) + .add_attribute("sender", factory) + .add_submessage(submsg)) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::Mint {} => execute_mint_sender(deps, env, info), + ExecuteMsg::Purge {} => execute_purge(deps, env, info), + ExecuteMsg::UpdateMintPrice { price } => execute_update_mint_price(deps, env, info, price), + ExecuteMsg::UpdateStartTime(time) => execute_update_start_time(deps, env, info, time), + ExecuteMsg::UpdateStartTradingTime(time) => { + execute_update_start_trading_time(deps, env, info, time) + } + ExecuteMsg::UpdatePerAddressLimit { per_address_limit } => { + execute_update_per_address_limit(deps, env, info, per_address_limit) + } + ExecuteMsg::MintTo { recipient } => execute_mint_to(deps, env, info, recipient), + ExecuteMsg::MintFor { + token_id, + recipient, + } => execute_mint_for(deps, env, info, token_id, recipient), + ExecuteMsg::SetWhitelist { whitelist } => { + execute_set_whitelist(deps, env, info, &whitelist) + } + ExecuteMsg::Shuffle {} => execute_shuffle(deps, env, info), + ExecuteMsg::BurnRemaining {} => execute_burn_remaining(deps, env, info), + ExecuteMsg::UpdateDiscountPrice { price } => { + execute_update_discount_price(deps, env, info, price) + } + ExecuteMsg::RemoveDiscountPrice {} => execute_remove_discount_price(deps, info), + } +} + +pub fn execute_update_discount_price( + deps: DepsMut, + env: Env, + info: MessageInfo, + price: u128, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + if env.block.time < config.extension.start_time { + return Err(ContractError::BeforeMintStartTime {}); + } + + // discount price can't be greater than unit price + if price > config.mint_price.amount.u128() { + return Err(ContractError::UpdatedMintPriceTooHigh { + allowed: config.mint_price.amount.u128(), + updated: price, + }); + } + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.clone().factory, &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + if factory_params.min_mint_price.amount.u128() > price { + return Err(ContractError::InsufficientMintPrice { + expected: factory_params.min_mint_price.amount.u128(), + got: price, + }); + } + + config.extension.discount_price = Some(coin(price, config.mint_price.denom.clone())); + CONFIG.save(deps.storage, &config)?; + + Ok(Response::new() + .add_attribute("action", "update_discount_price") + .add_attribute("sender", info.sender) + .add_attribute("discount_price", price.to_string())) +} + +pub fn execute_remove_discount_price( + deps: DepsMut, + info: MessageInfo, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + config.extension.discount_price = None; + CONFIG.save(deps.storage, &config)?; + + Ok(Response::new() + .add_attribute("action", "remove_discount_price") + .add_attribute("sender", info.sender)) +} + +// Purge frees data after a mint is sold out +// Anyone can purge +pub fn execute_purge( + deps: DepsMut, + env: Env, + info: MessageInfo, +) -> Result { + nonpayable(&info)?; + // check mint sold out + let mintable_num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + if mintable_num_tokens != 0 { + return Err(ContractError::NotSoldOut {}); + } + + let keys = MINTER_ADDRS + .keys(deps.storage, None, None, Order::Ascending) + .collect::>(); + for key in keys { + MINTER_ADDRS.remove(deps.storage, &key?); + } + + Ok(Response::new() + .add_attribute("action", "purge") + .add_attribute("contract", env.contract.address.to_string()) + .add_attribute("sender", info.sender)) +} + +// Anyone can pay to shuffle at any time +// Introduces another source of randomness to minting +// There's a fee because this action is expensive. +pub fn execute_shuffle( + deps: DepsMut, + env: Env, + info: MessageInfo, +) -> Result { + let mut res = Response::new(); + + let config = CONFIG.load(deps.storage)?; + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory, &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + // Check exact shuffle fee payment included in message + checked_fair_burn( + &info, + factory_params.extension.shuffle_fee.amount.u128(), + None, + &mut res, + )?; + + // Check not sold out + let mintable_num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + if mintable_num_tokens == 0 { + return Err(ContractError::SoldOut {}); + } + + // get positions and token_ids, then randomize token_ids and reassign positions + let mut positions = vec![]; + let mut token_ids = vec![]; + for mapping in MINTABLE_TOKEN_POSITIONS.range(deps.storage, None, None, Order::Ascending) { + let (position, token_id) = mapping?; + positions.push(position); + token_ids.push(token_id); + } + let randomized_token_ids = random_token_list(&env, info.sender.clone(), token_ids.clone())?; + for (i, position) in positions.iter().enumerate() { + MINTABLE_TOKEN_POSITIONS.save(deps.storage, *position, &randomized_token_ids[i])?; + } + + Ok(res + .add_attribute("action", "shuffle") + .add_attribute("sender", info.sender)) +} + +pub fn execute_set_whitelist( + deps: DepsMut, + env: Env, + info: MessageInfo, + whitelist: &str, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + let MinterConfig { + factory, + extension: + ConfigExtension { + whitelist: existing_whitelist, + admin, + start_time, + .. + }, + .. + } = config.clone(); + ensure!( + admin == info.sender, + ContractError::Unauthorized("Sender is not an admin".to_owned()) + ); + + ensure!( + env.block.time < start_time, + ContractError::AlreadyStarted {} + ); + + if let Some(wl) = existing_whitelist { + let res: WhitelistConfigResponse = deps + .querier + .query_wasm_smart(wl, &WhitelistQueryMsg::Config {})?; + + ensure!(!res.is_active, ContractError::WhitelistAlreadyStarted {}); + } + + let new_wl = deps.api.addr_validate(whitelist)?; + config.extension.whitelist = Some(new_wl.clone()); + // check that the new whitelist exists + let WhitelistConfigResponse { + is_active: wl_is_active, + mint_price: wl_mint_price, + .. + } = deps + .querier + .query_wasm_smart(new_wl, &WhitelistQueryMsg::Config {})?; + + ensure!(!wl_is_active, ContractError::WhitelistAlreadyStarted {}); + + ensure!( + wl_mint_price.denom == config.mint_price.denom, + ContractError::InvalidDenom { + expected: config.mint_price.denom, + got: wl_mint_price.denom, + } + ); + + // Whitelist could be free, while factory minimum is not + let ParamsResponse { + params: + VendingMinterParams { + min_mint_price: factory_min_mint_price, + .. + }, + } = deps + .querier + .query_wasm_smart(factory, &Sg2QueryMsg::Params {})?; + + ensure!( + factory_min_mint_price.amount <= wl_mint_price.amount, + ContractError::InsufficientWhitelistMintPrice { + expected: factory_min_mint_price.amount.into(), + got: wl_mint_price.amount.into(), + } + ); + + // Whitelist denom should match factory mint denom + ensure!( + factory_min_mint_price.denom == wl_mint_price.denom, + ContractError::InvalidDenom { + expected: factory_min_mint_price.denom, + got: wl_mint_price.denom, + } + ); + + CONFIG.save(deps.storage, &config)?; + + Ok(Response::default() + .add_attribute("action", "set_whitelist") + .add_attribute("whitelist", whitelist.to_string())) +} + +pub fn execute_mint_sender( + deps: DepsMut, + env: Env, + info: MessageInfo, +) -> Result { + let config = CONFIG.load(deps.storage)?; + let action = "mint_sender"; + + // If there is no active whitelist right now, check public mint + // Check if after start_time + if is_public_mint(deps.as_ref(), &info)? && (env.block.time < config.extension.start_time) { + return Err(ContractError::BeforeMintStartTime {}); + } + + // Check if already minted max per address limit + let mint_count = mint_count(deps.as_ref(), &info)?; + if mint_count >= config.extension.per_address_limit { + return Err(ContractError::MaxPerAddressLimitExceeded {}); + } + + _execute_mint(deps, env, info, action, false, None, None) +} + +// Check if a whitelist exists and not ended +// Sender has to be whitelisted to mint +fn is_public_mint(deps: Deps, info: &MessageInfo) -> Result { + let config = CONFIG.load(deps.storage)?; + + // If there is no whitelist, there's only a public mint + if config.extension.whitelist.is_none() { + return Ok(true); + } + + let whitelist = config.extension.whitelist.unwrap(); + + let wl_config: WhitelistConfigResponse = deps + .querier + .query_wasm_smart(whitelist.clone(), &WhitelistQueryMsg::Config {})?; + + if !wl_config.is_active { + return Ok(true); + } + + let res: HasMemberResponse = deps.querier.query_wasm_smart( + whitelist, + &WhitelistQueryMsg::HasMember { + member: info.sender.to_string(), + }, + )?; + if !res.has_member { + return Err(ContractError::NotWhitelisted { + addr: info.sender.to_string(), + }); + } + + // Check wl per address limit + let mint_count = mint_count(deps, info)?; + if mint_count >= wl_config.per_address_limit { + return Err(ContractError::MaxPerAddressLimitExceeded {}); + } + + Ok(false) +} + +pub fn execute_mint_to( + deps: DepsMut, + env: Env, + info: MessageInfo, + recipient: String, +) -> Result { + let recipient = deps.api.addr_validate(&recipient)?; + let config = CONFIG.load(deps.storage)?; + let action = "mint_to"; + + // Check only admin + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + + _execute_mint(deps, env, info, action, true, Some(recipient), None) +} + +pub fn execute_mint_for( + deps: DepsMut, + env: Env, + info: MessageInfo, + token_id: u32, + recipient: String, +) -> Result { + let recipient = deps.api.addr_validate(&recipient)?; + let config = CONFIG.load(deps.storage)?; + let action = "mint_for"; + + // Check only admin + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + + _execute_mint( + deps, + env, + info, + action, + true, + Some(recipient), + Some(token_id), + ) +} + +// Generalize checks and mint message creation +// mint -> _execute_mint(recipient: None, token_id: None) +// mint_to(recipient: "friend") -> _execute_mint(Some(recipient), token_id: None) +// mint_for(recipient: "friend2", token_id: 420) -> _execute_mint(recipient, token_id) +fn _execute_mint( + deps: DepsMut, + env: Env, + info: MessageInfo, + action: &str, + is_admin: bool, + recipient: Option, + token_id: Option, +) -> Result { + let mintable_num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + if mintable_num_tokens == 0 { + return Err(ContractError::SoldOut {}); + } + + let config = CONFIG.load(deps.storage)?; + + if let Some(token_id) = token_id { + if token_id == 0 || token_id > config.extension.num_tokens { + return Err(ContractError::InvalidTokenId {}); + } + } + + let sg721_address = SG721_ADDRESS.load(deps.storage)?; + + let recipient_addr = match recipient { + Some(some_recipient) => some_recipient, + None => info.sender.clone(), + }; + + let mint_price: Coin = mint_price(deps.as_ref(), is_admin)?; + // Exact payment only accepted + let payment = may_pay(&info, &mint_price.denom)?; + if payment != mint_price.amount { + return Err(ContractError::IncorrectPaymentAmount( + coin(payment.u128(), &config.mint_price.denom), + mint_price, + )); + } + + let mut res = Response::new(); + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory, &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + // Create network fee msgs + let mint_fee = if is_admin { + Decimal::bps(factory_params.extension.airdrop_mint_fee_bps) + } else { + Decimal::bps(factory_params.mint_fee_bps) + }; + + let network_fee = mint_price.amount * mint_fee; + + // send non-native fees to community pool + let pa_dao = "stars159t8e03zlmgyekmdrpxnyf70rdky28v553kj53zsapqadaunt4wsmn5m3l".to_string(); + + if !network_fee.is_zero() { + res = res.add_message(BankMsg::Send { + to_address: pa_dao.to_string(), + amount: vec![coin(network_fee.u128(), mint_price.denom.clone())], + }); + } + + let mintable_token_mapping = match token_id { + Some(token_id) => { + // set position to invalid value, iterate to find matching token_id + // if token_id not found, token_id is already sold, position is unchanged and throw err + // otherwise return position and token_id + let mut position = 0; + for res in MINTABLE_TOKEN_POSITIONS.range(deps.storage, None, None, Order::Ascending) { + let (pos, id) = res?; + if id == token_id { + position = pos; + break; + } + } + if position == 0 { + return Err(ContractError::TokenIdAlreadySold { token_id }); + } + TokenPositionMapping { position, token_id } + } + None => random_mintable_token_mapping(deps.as_ref(), env, info.sender.clone())?, + }; + + // Create mint msgs + let mint_msg = Sg721ExecuteMsg::::Mint { + token_id: mintable_token_mapping.token_id.to_string(), + owner: recipient_addr.to_string(), + token_uri: Some(format!( + "{}/{}", + config.extension.base_token_uri, mintable_token_mapping.token_id + )), + extension: None, + }; + let msg = CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: sg721_address.to_string(), + msg: to_binary(&mint_msg)?, + funds: vec![], + }); + res = res.add_message(msg); + + // Remove mintable token position from map + MINTABLE_TOKEN_POSITIONS.remove(deps.storage, mintable_token_mapping.position); + let mintable_num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + // Decrement mintable num tokens + MINTABLE_NUM_TOKENS.save(deps.storage, &(mintable_num_tokens - 1))?; + // Save the new mint count for the sender's address + let new_mint_count = mint_count(deps.as_ref(), &info)? + 1; + MINTER_ADDRS.save(deps.storage, &info.sender, &new_mint_count)?; + + let seller_amount = if !is_admin { + let amount = mint_price.amount - network_fee; + let payment_address = config.extension.payment_address; + let seller = config.extension.admin; + // Sending 0 coins fails, so only send if amount is non-zero + if !amount.is_zero() { + let msg = BankMsg::Send { + to_address: payment_address.unwrap_or(seller).to_string(), + amount: vec![coin(amount.u128(), mint_price.clone().denom)], + }; + res = res.add_message(msg); + } + amount + } else { + Uint128::zero() + }; + + Ok(res + .add_attribute("action", action) + .add_attribute("sender", info.sender) + .add_attribute("recipient", recipient_addr) + .add_attribute("token_id", mintable_token_mapping.token_id.to_string()) + .add_attribute( + "network_fee", + coin(network_fee.u128(), mint_price.clone().denom).to_string(), + ) + .add_attribute("mint_price", mint_price.to_string()) + .add_attribute( + "seller_amount", + coin(seller_amount.u128(), mint_price.denom).to_string(), + )) +} + +fn random_token_list( + env: &Env, + sender: Addr, + mut tokens: Vec, +) -> Result, ContractError> { + let tx_index = if let Some(tx) = &env.transaction { + tx.index + } else { + 0 + }; + let sha256 = Sha256::digest( + format!("{}{}{}{}", sender, env.block.height, tokens.len(), tx_index).into_bytes(), + ); + // Cut first 16 bytes from 32 byte value + let randomness: [u8; 16] = sha256.to_vec()[0..16].try_into().unwrap(); + let mut rng = Xoshiro128PlusPlus::from_seed(randomness); + let mut shuffler = FisherYates::default(); + shuffler + .shuffle(&mut tokens, &mut rng) + .map_err(StdError::generic_err)?; + Ok(tokens) +} + +// Does a baby shuffle, picking a token_id from the first or last 50 mintable positions. +fn random_mintable_token_mapping( + deps: Deps, + env: Env, + sender: Addr, +) -> Result { + let num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + let tx_index = if let Some(tx) = &env.transaction { + tx.index + } else { + 0 + }; + let sha256 = Sha256::digest( + format!("{}{}{}{}", sender, num_tokens, env.block.height, tx_index).into_bytes(), + ); + // Cut first 16 bytes from 32 byte value + let randomness: [u8; 16] = sha256.to_vec()[0..16].try_into().unwrap(); + + let mut rng = Xoshiro128PlusPlus::from_seed(randomness); + + let r = rng.next_u32(); + + let order = match r % 2 { + 1 => Order::Descending, + _ => Order::Ascending, + }; + let mut rem = 50; + if rem > num_tokens { + rem = num_tokens; + } + let n = r % rem; + let position = MINTABLE_TOKEN_POSITIONS + .keys(deps.storage, None, None, order) + .skip(n as usize) + .take(1) + .collect::>>()?[0]; + + let token_id = MINTABLE_TOKEN_POSITIONS.load(deps.storage, position)?; + Ok(TokenPositionMapping { position, token_id }) +} + +pub fn execute_update_mint_price( + deps: DepsMut, + env: Env, + info: MessageInfo, + price: u128, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + // If current time is after the stored start time, only allow lowering price + if env.block.time >= config.extension.start_time && price >= config.mint_price.amount.u128() { + return Err(ContractError::UpdatedMintPriceTooHigh { + allowed: config.mint_price.amount.u128(), + updated: price, + }); + } + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.clone().factory, &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + if factory_params.min_mint_price.amount.u128() > price { + return Err(ContractError::InsufficientMintPrice { + expected: factory_params.min_mint_price.amount.u128(), + got: price, + }); + } + + config.mint_price = coin(price, config.mint_price.denom); + CONFIG.save(deps.storage, &config)?; + Ok(Response::new() + .add_attribute("action", "update_mint_price") + .add_attribute("sender", info.sender) + .add_attribute("mint_price", price.to_string())) +} + +pub fn execute_update_start_time( + deps: DepsMut, + env: Env, + info: MessageInfo, + start_time: Timestamp, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + // If current time is after the stored start time return error + if env.block.time >= config.extension.start_time { + return Err(ContractError::AlreadyStarted {}); + } + + // If current time already passed the new start_time return error + if env.block.time > start_time { + return Err(ContractError::InvalidStartTime(start_time, env.block.time)); + } + + let genesis_start_time = Timestamp::from_nanos(GENESIS_MINT_START_TIME); + // If the new start_time is before genesis start time return error + if start_time < genesis_start_time { + return Err(ContractError::BeforeGenesisTime {}); + } + + config.extension.start_time = start_time; + CONFIG.save(deps.storage, &config)?; + Ok(Response::new() + .add_attribute("action", "update_start_time") + .add_attribute("sender", info.sender) + .add_attribute("start_time", start_time.to_string())) +} + +pub fn execute_update_start_trading_time( + deps: DepsMut, + env: Env, + info: MessageInfo, + start_time: Option, +) -> Result { + nonpayable(&info)?; + let config = CONFIG.load(deps.storage)?; + let sg721_contract_addr = SG721_ADDRESS.load(deps.storage)?; + + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + + // add custom rules here + let factory_params: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory.clone(), &Sg2QueryMsg::Params {})?; + let default_start_time_with_offset = config + .extension + .start_time + .plus_seconds(factory_params.params.max_trading_offset_secs); + + if let Some(start_trading_time) = start_time { + if env.block.time > start_trading_time { + return Err(ContractError::InvalidStartTradingTime( + env.block.time, + start_trading_time, + )); + } + // If new start_trading_time > old start time + offset , return error + if start_trading_time > default_start_time_with_offset { + return Err(ContractError::InvalidStartTradingTime( + start_trading_time, + default_start_time_with_offset, + )); + } + } + + // execute sg721 contract + let msg = WasmMsg::Execute { + contract_addr: sg721_contract_addr.to_string(), + msg: to_binary(&Sg721ExecuteMsg::::UpdateStartTradingTime( + start_time, + ))?, + funds: vec![], + }; + + Ok(Response::new() + .add_attribute("action", "update_start_trading_time") + .add_attribute("sender", info.sender) + .add_message(msg)) +} + +pub fn execute_update_per_address_limit( + deps: DepsMut, + _env: Env, + info: MessageInfo, + per_address_limit: u32, +) -> Result { + nonpayable(&info)?; + let mut config = CONFIG.load(deps.storage)?; + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory.clone(), &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + if per_address_limit == 0 || per_address_limit > factory_params.extension.max_per_address_limit + { + return Err(ContractError::InvalidPerAddressLimit { + max: factory_params.extension.max_per_address_limit, + min: 1, + got: per_address_limit, + }); + } + + if !check_dynamic_per_address_limit( + per_address_limit, + config.extension.num_tokens, + factory_params.extension.max_per_address_limit, + )? { + return Err(ContractError::InvalidPerAddressLimit { + max: display_max_mintable_tokens( + per_address_limit, + config.extension.num_tokens, + factory_params.extension.max_per_address_limit, + )?, + min: 1, + got: per_address_limit, + }); + } + + config.extension.per_address_limit = per_address_limit; + CONFIG.save(deps.storage, &config)?; + Ok(Response::new() + .add_attribute("action", "update_per_address_limit") + .add_attribute("sender", info.sender) + .add_attribute("limit", per_address_limit.to_string())) +} + +pub fn execute_burn_remaining( + deps: DepsMut, + env: Env, + info: MessageInfo, +) -> Result { + nonpayable(&info)?; + let config = CONFIG.load(deps.storage)?; + // Check only admin + if info.sender != config.extension.admin { + return Err(ContractError::Unauthorized( + "Sender is not an admin".to_owned(), + )); + } + + // check mint not sold out + let mintable_num_tokens = MINTABLE_NUM_TOKENS.load(deps.storage)?; + if mintable_num_tokens == 0 { + return Err(ContractError::SoldOut {}); + } + + let keys = MINTABLE_TOKEN_POSITIONS + .keys(deps.storage, None, None, Order::Ascending) + .collect::>(); + let mut total: u32 = 0; + for key in keys { + total += 1; + MINTABLE_TOKEN_POSITIONS.remove(deps.storage, key?); + } + // Decrement mintable num tokens + MINTABLE_NUM_TOKENS.save(deps.storage, &(mintable_num_tokens - total))?; + + let event = Event::new("burn-remaining") + .add_attribute("sender", info.sender) + .add_attribute("tokens_burned", total.to_string()) + .add_attribute("minter", env.contract.address.to_string()); + Ok(Response::new().add_event(event)) +} + +// if admin_no_fee => no fee, +// else if in whitelist => whitelist price +// else => config unit price +pub fn mint_price(deps: Deps, is_admin: bool) -> Result { + let config = CONFIG.load(deps.storage)?; + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory, &Sg2QueryMsg::Params {})?; + let factory_params = factory.params; + + if is_admin { + return Ok(coin( + factory_params.extension.airdrop_mint_price.amount.u128(), + factory_params.extension.airdrop_mint_price.denom, + )); + } + + if config.extension.whitelist.is_none() { + let price = config.extension.discount_price.unwrap_or(config.mint_price); + return Ok(price); + } + + let whitelist = config.extension.whitelist.unwrap(); + + let wl_config: WhitelistConfigResponse = deps + .querier + .query_wasm_smart(whitelist, &WhitelistQueryMsg::Config {})?; + + if wl_config.is_active { + Ok(wl_config.mint_price) + } else { + let price = config.extension.discount_price.unwrap_or(config.mint_price); + Ok(price) + } +} + +fn mint_count(deps: Deps, info: &MessageInfo) -> Result { + let mint_count = (MINTER_ADDRS.key(&info.sender).may_load(deps.storage)?).unwrap_or(0); + Ok(mint_count) +} + +pub fn display_max_mintable_tokens( + per_address_limit: u32, + num_tokens: u32, + max_per_address_limit: u32, +) -> Result { + if per_address_limit > max_per_address_limit { + return Ok(max_per_address_limit); + } + if num_tokens < 100 { + return Ok(3_u32); + } + let three_percent = get_three_percent_of_tokens(num_tokens)?.u128(); + Ok(three_percent as u32) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn sudo(deps: DepsMut, _env: Env, msg: SudoMsg) -> Result { + match msg { + SudoMsg::UpdateStatus { + is_verified, + is_blocked, + is_explicit, + } => update_status(deps, is_verified, is_blocked, is_explicit) + .map_err(|_| ContractError::UpdateStatus {}), + } +} + +/// Only governance can update contract params +pub fn update_status( + deps: DepsMut, + is_verified: bool, + is_blocked: bool, + is_explicit: bool, +) -> StdResult { + let mut status = STATUS.load(deps.storage)?; + status.is_verified = is_verified; + status.is_blocked = is_blocked; + status.is_explicit = is_explicit; + STATUS.save(deps.storage, &status)?; + + Ok(Response::new().add_attribute("action", "sudo_update_status")) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { + match msg { + QueryMsg::Config {} => to_binary(&query_config(deps)?), + QueryMsg::Status {} => to_binary(&query_status(deps)?), + QueryMsg::StartTime {} => to_binary(&query_start_time(deps)?), + QueryMsg::MintableNumTokens {} => to_binary(&query_mintable_num_tokens(deps)?), + QueryMsg::MintPrice {} => to_binary(&query_mint_price(deps)?), + QueryMsg::MintCount { address } => to_binary(&query_mint_count(deps, address)?), + } +} + +fn query_config(deps: Deps) -> StdResult { + let config = CONFIG.load(deps.storage)?; + let sg721_address = SG721_ADDRESS.load(deps.storage)?; + + Ok(ConfigResponse { + admin: config.extension.admin.to_string(), + base_token_uri: config.extension.base_token_uri, + sg721_address: sg721_address.to_string(), + sg721_code_id: config.collection_code_id, + num_tokens: config.extension.num_tokens, + start_time: config.extension.start_time, + mint_price: config.mint_price, + per_address_limit: config.extension.per_address_limit, + whitelist: config.extension.whitelist.map(|w| w.to_string()), + factory: config.factory.to_string(), + discount_price: config.extension.discount_price, + }) +} + +pub fn query_status(deps: Deps) -> StdResult { + let status = STATUS.load(deps.storage)?; + + Ok(StatusResponse { status }) +} + +fn query_mint_count(deps: Deps, address: String) -> StdResult { + let addr = deps.api.addr_validate(&address)?; + let mint_count = (MINTER_ADDRS.key(&addr).may_load(deps.storage)?).unwrap_or(0); + Ok(MintCountResponse { + address: addr.to_string(), + count: mint_count, + }) +} + +fn query_start_time(deps: Deps) -> StdResult { + let config = CONFIG.load(deps.storage)?; + Ok(StartTimeResponse { + start_time: config.extension.start_time.to_string(), + }) +} + +fn query_mintable_num_tokens(deps: Deps) -> StdResult { + let count = MINTABLE_NUM_TOKENS.load(deps.storage)?; + Ok(MintableNumTokensResponse { count }) +} + +fn query_mint_price(deps: Deps) -> StdResult { + let config = CONFIG.load(deps.storage)?; + + let factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory, &Sg2QueryMsg::Params {})?; + + let factory_params = factory.params; + + let current_price = mint_price(deps, false)?; + let public_price = config.mint_price.clone(); + let whitelist_price: Option = if let Some(whitelist) = config.extension.whitelist { + let wl_config: WhitelistConfigResponse = deps + .querier + .query_wasm_smart(whitelist, &WhitelistQueryMsg::Config {})?; + Some(wl_config.mint_price) + } else { + None + }; + let airdrop_price = coin( + factory_params.extension.airdrop_mint_price.amount.u128(), + config.mint_price.denom, + ); + let discount_price = config.extension.discount_price; + Ok(MintPriceResponse { + public_price, + airdrop_price, + whitelist_price, + current_price, + discount_price, + }) +} + +// Reply callback triggered from cw721 contract instantiation +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result { + if msg.id != INSTANTIATE_SG721_REPLY_ID { + return Err(ContractError::InvalidReplyID {}); + } + + let reply = parse_reply_instantiate_data(msg); + match reply { + Ok(res) => { + let sg721_address = res.contract_address; + SG721_ADDRESS.save(deps.storage, &Addr::unchecked(sg721_address.clone()))?; + Ok(Response::default() + .add_attribute("action", "instantiate_sg721_reply") + .add_attribute("sg721_address", sg721_address)) + } + Err(_) => Err(ContractError::InstantiateSg721Error {}), + } +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn migrate(deps: DepsMut, _env: Env, _msg: Empty) -> Result { + let current_version = cw2::get_contract_version(deps.storage)?; + if current_version.contract != CONTRACT_NAME { + return Err(StdError::generic_err("Cannot upgrade to a different contract").into()); + } + let version: Version = current_version + .version + .parse() + .map_err(|_| StdError::generic_err("Invalid contract version"))?; + let new_version: Version = CONTRACT_VERSION + .parse() + .map_err(|_| StdError::generic_err("Invalid contract version"))?; + + if version > new_version { + return Err(StdError::generic_err("Cannot upgrade to a previous contract version").into()); + } + // if same version return + if version == new_version { + return Ok(Response::new()); + } + + // set new contract version + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + let event = Event::new("migrate") + .add_attribute("from_name", current_version.contract) + .add_attribute("from_version", current_version.version) + .add_attribute("to_name", CONTRACT_NAME) + .add_attribute("to_version", CONTRACT_VERSION); + Ok(Response::new().add_event(event)) +} diff --git a/contracts/minters/vending-minter-featured/src/error.rs b/contracts/minters/vending-minter-featured/src/error.rs new file mode 100644 index 000000000..5defd6e75 --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/error.rs @@ -0,0 +1,106 @@ +use cosmwasm_std::{Coin, StdError, Timestamp}; +use cw_utils::PaymentError; +use sg1::FeeError; +use thiserror::Error; +use url::ParseError; +#[derive(Error, Debug, PartialEq)] +pub enum ContractError { + #[error("{0}")] + Std(#[from] StdError), + + #[error("{0}")] + Payment(#[from] PaymentError), + + #[error("{0}")] + ParseError(#[from] ParseError), + + #[error("{0}")] + Fee(#[from] FeeError), + + #[error("Unauthorized: {0}")] + Unauthorized(String), + + #[error("UpdateStatus")] + UpdateStatus {}, + + #[error("Invalid reply ID")] + InvalidReplyID {}, + + #[error("Not enough funds sent")] + NotEnoughFunds {}, + + #[error("TooManyCoins")] + TooManyCoins {}, + + #[error("IncorrectPaymentAmount {0} != {1}")] + IncorrectPaymentAmount(Coin, Coin), + + #[error("InvalidNumTokens {max}, min: 1")] + InvalidNumTokens { max: u32, min: u32 }, + + #[error("Sold out")] + SoldOut {}, + + #[error("Not sold out")] + NotSoldOut {}, + + #[error("InvalidDenom {expected} got {got}")] + InvalidDenom { expected: String, got: String }, + + #[error("Minimum network mint price {expected} got {got}")] + InsufficientMintPrice { expected: u128, got: u128 }, + + #[error("Minimum whitelist mint price {expected} got {got}")] + InsufficientWhitelistMintPrice { expected: u128, got: u128 }, + + #[error("Update price {updated} higher than allowed price {allowed}")] + UpdatedMintPriceTooHigh { allowed: u128, updated: u128 }, + + #[error("Invalid address {addr}")] + InvalidAddress { addr: String }, + + #[error("Invalid token id")] + InvalidTokenId {}, + + #[error("AlreadyStarted")] + AlreadyStarted {}, + + #[error("BeforeGenesisTime")] + BeforeGenesisTime {}, + + #[error("WhitelistAlreadyStarted")] + WhitelistAlreadyStarted {}, + + #[error("InvalidStartTime {0} < {1}")] + InvalidStartTime(Timestamp, Timestamp), + + #[error("InvalidStartTradingTime {0} > {1}")] + InvalidStartTradingTime(Timestamp, Timestamp), + + #[error("Instantiate sg721 error")] + InstantiateSg721Error {}, + + #[error("Invalid base token URI (must be an IPFS URI)")] + InvalidBaseTokenURI {}, + + #[error("address not on whitelist: {addr}")] + NotWhitelisted { addr: String }, + + #[error("Minting has not started yet")] + BeforeMintStartTime {}, + + #[error("Invalid minting limit per address. max: {max}, min: 1, got: {got}")] + InvalidPerAddressLimit { max: u32, min: u32, got: u32 }, + + #[error("Max minting limit per address exceeded")] + MaxPerAddressLimitExceeded {}, + + #[error("Token id: {token_id} already sold")] + TokenIdAlreadySold { token_id: u32 }, + + #[error("NoEnvTransactionIndex")] + NoEnvTransactionIndex {}, + + #[error("Multiply Fraction Error")] + CheckedMultiplyFractionError {}, +} diff --git a/contracts/minters/vending-minter-featured/src/helpers.rs b/contracts/minters/vending-minter-featured/src/helpers.rs new file mode 100644 index 000000000..173587cb6 --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/helpers.rs @@ -0,0 +1,62 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{ + to_binary, Addr, Coin, ContractInfoResponse, CustomQuery, Querier, QuerierWrapper, StdResult, + WasmMsg, WasmQuery, +}; +use sg_std::CosmosMsg; + +use crate::msg::{ConfigResponse, ExecuteMsg, QueryMsg}; + +/// MinterContract is a wrapper around Addr that provides a lot of helpers +/// for working with this. +#[cw_serde] +pub struct MinterContract(pub Addr); + +impl MinterContract { + pub fn addr(&self) -> Addr { + self.0.clone() + } + + pub fn call>(&self, msg: T) -> StdResult { + let msg = to_binary(&msg.into())?; + Ok(WasmMsg::Execute { + contract_addr: self.addr().into(), + msg, + funds: vec![], + } + .into()) + } + + pub fn call_with_funds>( + &self, + msg: T, + funds: Coin, + ) -> StdResult { + let msg = to_binary(&msg.into())?; + Ok(WasmMsg::Execute { + contract_addr: self.addr().into(), + msg, + funds: vec![funds], + } + .into()) + } + + pub fn contract_info(&self, querier: &Q) -> StdResult + where + Q: Querier, + T: Into, + CQ: CustomQuery, + { + let query = WasmQuery::ContractInfo { + contract_addr: self.addr().into(), + } + .into(); + let res: ContractInfoResponse = QuerierWrapper::::new(querier).query(&query)?; + Ok(res) + } + + pub fn config(&self, querier: &QuerierWrapper) -> StdResult { + let res: ConfigResponse = querier.query_wasm_smart(self.addr(), &QueryMsg::Config {})?; + Ok(res) + } +} diff --git a/contracts/minters/vending-minter-featured/src/lib.rs b/contracts/minters/vending-minter-featured/src/lib.rs new file mode 100644 index 000000000..e061fa43c --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/lib.rs @@ -0,0 +1,9 @@ +pub mod contract; +mod error; +pub mod msg; + +pub mod state; +pub use crate::error::ContractError; + +pub mod helpers; +pub mod validation; diff --git a/contracts/minters/vending-minter-featured/src/msg.rs b/contracts/minters/vending-minter-featured/src/msg.rs new file mode 100644 index 000000000..d4d9f0358 --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/msg.rs @@ -0,0 +1,90 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Coin, Timestamp}; +use vending_factory::{msg::VendingMinterCreateMsg, state::VendingMinterParams}; + +#[cw_serde] +pub struct InstantiateMsg { + pub create_msg: VendingMinterCreateMsg, + pub params: VendingMinterParams, +} + +#[cw_serde] +pub enum ExecuteMsg { + Mint {}, + SetWhitelist { + whitelist: String, + }, + Purge {}, + UpdateMintPrice { + price: u128, + }, + UpdateStartTime(Timestamp), + /// Runs custom checks against TradingStartTime on VendingMinter, then updates by calling sg721-base + UpdateStartTradingTime(Option), + UpdatePerAddressLimit { + per_address_limit: u32, + }, + MintTo { + recipient: String, + }, + MintFor { + token_id: u32, + recipient: String, + }, + Shuffle {}, + BurnRemaining {}, + UpdateDiscountPrice { + price: u128, + }, + RemoveDiscountPrice {}, +} + +#[cw_serde] +pub enum QueryMsg { + Config {}, + MintableNumTokens {}, + StartTime {}, + MintPrice {}, + MintCount { address: String }, + Status {}, +} + +#[cw_serde] +pub struct ConfigResponse { + pub admin: String, + pub base_token_uri: String, + pub num_tokens: u32, + pub per_address_limit: u32, + pub sg721_address: String, + pub sg721_code_id: u64, + pub start_time: Timestamp, + pub mint_price: Coin, + pub whitelist: Option, + pub factory: String, + pub discount_price: Option, +} + +#[cw_serde] +pub struct MintableNumTokensResponse { + pub count: u32, +} + +#[cw_serde] +pub struct StartTimeResponse { + pub start_time: String, +} + +#[cw_serde] +pub struct MintPriceResponse { + pub public_price: Coin, + pub airdrop_price: Coin, + pub whitelist_price: Option, + pub current_price: Coin, + pub discount_price: Option, +} + +#[cw_serde] +pub struct MintCountResponse { + pub address: String, + pub count: u32, +} diff --git a/contracts/minters/vending-minter-featured/src/state.rs b/contracts/minters/vending-minter-featured/src/state.rs new file mode 100644 index 000000000..04c98b3c1 --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/state.rs @@ -0,0 +1,27 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, Coin, Timestamp}; +use cw_storage_plus::{Item, Map}; +use sg4::{MinterConfig, Status}; + +#[cw_serde] +pub struct ConfigExtension { + pub admin: Addr, + pub payment_address: Option, + pub base_token_uri: String, + pub num_tokens: u32, + pub whitelist: Option, + pub start_time: Timestamp, + pub per_address_limit: u32, + pub discount_price: Option, +} +pub type Config = MinterConfig; + +pub const CONFIG: Item = Item::new("config"); +pub const SG721_ADDRESS: Item = Item::new("sg721_address"); +// map of index position and token id +pub const MINTABLE_TOKEN_POSITIONS: Map = Map::new("mt"); +pub const MINTABLE_NUM_TOKENS: Item = Item::new("mintable_num_tokens"); +pub const MINTER_ADDRS: Map<&Addr, u32> = Map::new("ma"); + +/// Holds the status of the minter. Can be changed with on-chain governance proposals. +pub const STATUS: Item = Item::new("status"); diff --git a/contracts/minters/vending-minter-featured/src/testing.rs b/contracts/minters/vending-minter-featured/src/testing.rs new file mode 100644 index 000000000..8af010928 --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/testing.rs @@ -0,0 +1,2 @@ +mod setup; +mod tests; diff --git a/contracts/minters/vending-minter-featured/src/validation.rs b/contracts/minters/vending-minter-featured/src/validation.rs new file mode 100644 index 000000000..a3eb1acef --- /dev/null +++ b/contracts/minters/vending-minter-featured/src/validation.rs @@ -0,0 +1,28 @@ +use crate::ContractError; +use crate::ContractError::CheckedMultiplyFractionError; +use cosmwasm_std::Uint128; + +pub fn get_three_percent_of_tokens(num_tokens: u32) -> Result { + let three_percent = (Uint128::new(3), Uint128::new(100)); + let three_percent_tokens = Uint128::from(num_tokens) + .checked_mul_ceil(three_percent) + .map_err(|_| CheckedMultiplyFractionError {})?; + Ok(three_percent_tokens) +} + +// Check per address limit to make sure it's <= 1% num tokens +pub fn check_dynamic_per_address_limit( + per_address_limit: u32, + num_tokens: u32, + max_per_address_limit: u32, +) -> Result { + if per_address_limit > max_per_address_limit { + return Ok(false); + } + if num_tokens < 100 { + return Ok(per_address_limit <= 3); + } + let three_percent_tokens = get_three_percent_of_tokens(num_tokens)?; + let result = Uint128::from(per_address_limit) <= three_percent_tokens; + Ok(result) +}