diff --git a/Cargo.lock b/Cargo.lock index dfb7a94d5..675cd062f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4290,6 +4290,53 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "token-merge-factory" +version = "3.15.0" +dependencies = [ + "base-factory", + "cosmwasm-schema", + "cosmwasm-std", + "cw-storage-plus 1.2.0", + "cw-utils 1.0.3", + "cw2 1.1.2", + "schemars", + "semver", + "serde", + "sg-std", + "sg1", + "sg721", + "thiserror", +] + +[[package]] +name = "token-merge-minter" +version = "3.15.0" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-storage-plus 1.2.0", + "cw-utils 1.0.3", + "cw2 1.1.2", + "cw721 0.18.0", + "cw721-base 0.18.0", + "rand_core 0.6.4", + "rand_xoshiro", + "schemars", + "semver", + "serde", + "sg-std", + "sg-whitelist", + "sg1", + "sg4", + "sg721", + "sha2 0.10.8", + "shuffle", + "thiserror", + "token-merge-factory", + "url", +] + [[package]] name = "tokio" version = "1.40.0" diff --git a/Cargo.toml b/Cargo.toml index cca0d98c4..4729f35eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,8 @@ vending-factory = { version = "3.14.0", path = "contracts/factories/vending vending-minter = { version = "3.14.0", path = "contracts/minters/vending-minter" } open-edition-factory = { version = "3.14.0", path = "contracts/factories/open-edition-factory" } open-edition-minter = { version = "3.14.0", path = "contracts/minters/open-edition-minter" } +token-merge-factory = { version = "3.14.0", path = "contracts/factories/token-merge-factory" } +token-merge-minter = { version = "3.14.0", path = "contracts/minters/token-merge-minter" } whitelist-immutable = { version = "3.14.0", path = "contracts/whitelists/whitelist-immutable" } sg-whitelist-flex = { version = "3.14.0", path = "contracts/whitelists/whitelist-flex" } ethereum-verify = { version = "3.14.0", path = "packages/ethereum-verify" } diff --git a/contracts/factories/token-merge-factory/.cargo/config b/contracts/factories/token-merge-factory/.cargo/config new file mode 100644 index 000000000..ab407a024 --- /dev/null +++ b/contracts/factories/token-merge-factory/.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/factories/token-merge-factory/.gitignore b/contracts/factories/token-merge-factory/.gitignore new file mode 100644 index 000000000..dfdaaa6bc --- /dev/null +++ b/contracts/factories/token-merge-factory/.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/factories/token-merge-factory/Cargo.toml b/contracts/factories/token-merge-factory/Cargo.toml new file mode 100644 index 000000000..9cc0dd852 --- /dev/null +++ b/contracts/factories/token-merge-factory/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "token-merge-factory" +authors = ["Shane Vitarana "] +description = "Stargaze token merge factory 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] +base-factory = { workspace = true, features = ["library"] } +cosmwasm-schema = { workspace = true } +cosmwasm-std = { workspace = true } +cw2 = { workspace = true } +cw-storage-plus = { workspace = true } +cw-utils = { workspace = true } +schemars = { workspace = true } +semver = { workspace = true } +serde = { workspace = true } +sg1 = { workspace = true } +sg721 = { workspace = true } +sg-std = { workspace = true } +thiserror = { workspace = true } diff --git a/contracts/factories/token-merge-factory/README.md b/contracts/factories/token-merge-factory/README.md new file mode 100644 index 000000000..8e4c37ef5 --- /dev/null +++ b/contracts/factories/token-merge-factory/README.md @@ -0,0 +1,7 @@ +# Token Merge Minter Factory + +A contract that maintains all token merge minter governance parameters. + +It's responsible for creating new minters with the latest governance parameters. + +It also maintains status lists for token merge minters. This is inherited from sg4. diff --git a/contracts/factories/token-merge-factory/examples/schema.rs b/contracts/factories/token-merge-factory/examples/schema.rs new file mode 100644 index 000000000..3e2aa7b9c --- /dev/null +++ b/contracts/factories/token-merge-factory/examples/schema.rs @@ -0,0 +1,16 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use token_merge_factory::msg::{InstantiateMsg, QueryMsg}; + +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!(QueryMsg), &out_dir); +} diff --git a/contracts/factories/token-merge-factory/schema/instantiate_msg.json b/contracts/factories/token-merge-factory/schema/instantiate_msg.json new file mode 100644 index 000000000..0c85e9fe6 --- /dev/null +++ b/contracts/factories/token-merge-factory/schema/instantiate_msg.json @@ -0,0 +1,123 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "InstantiateMsg", + "type": "object", + "required": [ + "params" + ], + "properties": { + "params": { + "$ref": "#/definitions/MinterParams_for_ParamsExtension" + } + }, + "additionalProperties": false, + "definitions": { + "Coin": { + "type": "object", + "required": [ + "amount", + "denom" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "denom": { + "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 + }, + "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/factories/token-merge-factory/schema/sg2_query_msg.json b/contracts/factories/token-merge-factory/schema/sg2_query_msg.json new file mode 100644 index 000000000..865ce4364 --- /dev/null +++ b/contracts/factories/token-merge-factory/schema/sg2_query_msg.json @@ -0,0 +1,47 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Sg2QueryMsg", + "oneOf": [ + { + "description": "Returns `ParamsResponse`", + "type": "object", + "required": [ + "params" + ], + "properties": { + "params": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "allowed_collection_code_ids" + ], + "properties": { + "allowed_collection_code_ids": { + "type": "object", + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "allowed_collection_code_id" + ], + "properties": { + "allowed_collection_code_id": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + } + }, + "additionalProperties": false + } + ] +} diff --git a/contracts/factories/token-merge-factory/src/contract.rs b/contracts/factories/token-merge-factory/src/contract.rs new file mode 100644 index 000000000..1cdc1131e --- /dev/null +++ b/contracts/factories/token-merge-factory/src/contract.rs @@ -0,0 +1,262 @@ +use base_factory::ContractError as BaseContractError; +#[cfg(not(feature = "library"))] +use cosmwasm_std::entry_point; +use cosmwasm_std::{ + ensure, ensure_eq, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, StdError, + StdResult, WasmMsg, +}; +use cw2::set_contract_version; +use cw_utils::must_pay; +use semver::Version; +use sg1::{checked_fair_burn, transfer_funds_to_launchpad_dao}; +use sg_std::{Response, NATIVE_DENOM}; + +use crate::error::ContractError; +use crate::msg::{ + AllowedCollectionCodeIdResponse, AllowedCollectionCodeIdsResponse, ExecuteMsg, InstantiateMsg, + ParamsResponse, QueryMsg, SudoMsg, TokenMergeMinterCreateMsg, TokenMergeUpdateParamsMsg, +}; +use crate::state::SUDO_PARAMS; + +// version info for migration info +const CONTRACT_NAME: &str = "crates.io:token-merge-factory"; +const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +///Can only be called by Factory DAO +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + _env: Env, + _info: MessageInfo, + msg: InstantiateMsg, +) -> Result { + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + + SUDO_PARAMS.save(deps.storage, &msg.params)?; + + Ok(Response::new()) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::CreateMinter(msg) => execute_create_minter(deps, env, info, msg), + } +} + +pub fn execute_create_minter( + deps: DepsMut, + _env: Env, + info: MessageInfo, + msg: TokenMergeMinterCreateMsg, +) -> Result { + let params = SUDO_PARAMS.load(deps.storage)?; + must_pay(&info, ¶ms.creation_fee.denom)?; + ensure!( + params + .allowed_sg721_code_ids + .contains(&msg.collection_params.code_id), + ContractError::InvalidCollectionCodeId {} + ); + + ensure!(!params.frozen, ContractError::Frozen {}); + + let mut res = Response::new(); + if params.creation_fee.denom == NATIVE_DENOM { + checked_fair_burn(&info, params.creation_fee.amount.u128(), None, &mut res)?; + } else { + transfer_funds_to_launchpad_dao( + &info, + params.creation_fee.amount.u128(), + ¶ms.creation_fee.denom, + &mut res, + )?; + } + + // Check the number of tokens is more than zero and less than the max limit + if msg.init_msg.num_tokens == 0 || msg.init_msg.num_tokens > params.max_token_limit { + return Err(ContractError::InvalidNumTokens { + min: 1, + max: params.max_token_limit, + }); + } + + // Check per address limit is valid + if msg.init_msg.per_address_limit == 0 + || msg.init_msg.per_address_limit > params.max_per_address_limit + { + return Err(ContractError::InvalidPerAddressLimit { + max: params.max_per_address_limit, + min: 1, + got: msg.init_msg.per_address_limit, + }); + } + + let wasm_msg = WasmMsg::Instantiate { + admin: Some(info.sender.to_string()), + code_id: params.code_id, + msg: to_json_binary(&msg)?, + funds: vec![], + label: format!("TokenMergeMinter-{}", msg.collection_params.name.trim()), + }; + + Ok(res + .add_attribute("action", "create_minter") + .add_message(wasm_msg)) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn sudo(deps: DepsMut, env: Env, msg: SudoMsg) -> Result { + match msg { + SudoMsg::UpdateParams(params_msg) => sudo_update_params(deps, env, *params_msg), + } +} + +/// Only governance can update contract params +pub fn sudo_update_params( + deps: DepsMut, + _env: Env, + param_msg: TokenMergeUpdateParamsMsg, +) -> Result { + let mut params = SUDO_PARAMS.load(deps.storage)?; + + params.max_token_limit = param_msg + .extension + .max_token_limit + .unwrap_or(params.max_token_limit); + params.max_per_address_limit = param_msg + .extension + .max_per_address_limit + .unwrap_or(params.max_per_address_limit); + + if let Some(airdrop_mint_price) = param_msg.extension.airdrop_mint_price { + ensure_eq!( + &airdrop_mint_price.denom, + &NATIVE_DENOM, + ContractError::BaseError(BaseContractError::InvalidDenom {}) + ); + params.airdrop_mint_price = airdrop_mint_price; + } + + params.airdrop_mint_fee_bps = param_msg + .extension + .airdrop_mint_fee_bps + .unwrap_or(params.airdrop_mint_fee_bps); + + if let Some(shuffle_fee) = param_msg.extension.shuffle_fee { + ensure_eq!( + &shuffle_fee.denom, + &NATIVE_DENOM, + ContractError::BaseError(BaseContractError::InvalidDenom {}) + ); + params.shuffle_fee = shuffle_fee; + } + + SUDO_PARAMS.save(deps.storage, ¶ms)?; + + Ok(Response::new().add_attribute("action", "sudo_update_params")) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { + match msg { + QueryMsg::Params {} => to_json_binary(&query_params(deps)?), + QueryMsg::AllowedCollectionCodeIds {} => { + to_json_binary(&query_allowed_collection_code_ids(deps)?) + } + QueryMsg::AllowedCollectionCodeId(code_id) => { + to_json_binary(&query_allowed_collection_code_id(deps, code_id)?) + } + } +} + +fn query_params(deps: Deps) -> StdResult { + let params = SUDO_PARAMS.load(deps.storage)?; + Ok(ParamsResponse { params }) +} + +fn query_allowed_collection_code_ids(deps: Deps) -> StdResult { + let params = SUDO_PARAMS.load(deps.storage)?; + let code_ids = params.allowed_sg721_code_ids; + Ok(AllowedCollectionCodeIdsResponse { code_ids }) +} + +fn query_allowed_collection_code_id( + deps: Deps, + code_id: u64, +) -> StdResult { + let params = SUDO_PARAMS.load(deps.storage)?; + let code_ids = params.allowed_sg721_code_ids; + let allowed = code_ids.contains(&code_id); + Ok(AllowedCollectionCodeIdResponse { allowed }) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn migrate( + deps: DepsMut, + _env: Env, + msg: Option, +) -> Result { + let prev_contract_info = cw2::get_contract_version(deps.storage)?; + let prev_contract_name: String = prev_contract_info.contract; + let prev_contract_version: Version = prev_contract_info + .version + .parse() + .map_err(|_| StdError::generic_err("Unable to retrieve previous contract version"))?; + + let new_version: Version = CONTRACT_VERSION + .parse() + .map_err(|_| StdError::generic_err("Invalid contract version"))?; + + if prev_contract_name != CONTRACT_NAME { + return Err(StdError::generic_err("Cannot migrate to a different contract").into()); + } + + if prev_contract_version > new_version { + return Err(StdError::generic_err("Cannot migrate to a previous contract version").into()); + } + + if let Some(msg) = msg { + let mut params = SUDO_PARAMS.load(deps.storage)?; + + params.max_token_limit = msg + .extension + .max_token_limit + .unwrap_or(params.max_token_limit); + params.max_per_address_limit = msg + .extension + .max_per_address_limit + .unwrap_or(params.max_per_address_limit); + + if let Some(airdrop_mint_price) = msg.extension.airdrop_mint_price { + ensure_eq!( + &airdrop_mint_price.denom, + &NATIVE_DENOM, + ContractError::BaseError(BaseContractError::InvalidDenom {}) + ); + params.airdrop_mint_price = airdrop_mint_price; + } + + params.airdrop_mint_fee_bps = msg + .extension + .airdrop_mint_fee_bps + .unwrap_or(params.airdrop_mint_fee_bps); + + if let Some(shuffle_fee) = msg.extension.shuffle_fee { + ensure_eq!( + &shuffle_fee.denom, + &NATIVE_DENOM, + ContractError::BaseError(BaseContractError::InvalidDenom {}) + ); + params.shuffle_fee = shuffle_fee; + } + + SUDO_PARAMS.save(deps.storage, ¶ms)?; + } + Ok(Response::new().add_attribute("action", "migrate")) +} diff --git a/contracts/factories/token-merge-factory/src/error.rs b/contracts/factories/token-merge-factory/src/error.rs new file mode 100644 index 000000000..a7f27174e --- /dev/null +++ b/contracts/factories/token-merge-factory/src/error.rs @@ -0,0 +1,35 @@ +use base_factory::ContractError as BaseContractError; +use cosmwasm_std::StdError; +use cw_utils::PaymentError; +use sg1::FeeError; +use thiserror::Error; + +#[derive(Error, Debug, PartialEq)] +pub enum ContractError { + #[error("{0}")] + Std(#[from] StdError), + + #[error("{0}")] + Fee(#[from] FeeError), + + #[error("{0}")] + Payment(#[from] PaymentError), + + #[error("Unauthorized")] + Unauthorized {}, + + #[error("Factory frozen. Cannot make new minters.")] + Frozen {}, + + #[error("InvalidCodeId")] + InvalidCollectionCodeId {}, + + #[error("InvalidNumTokens {max}, min: 1")] + InvalidNumTokens { max: u32, min: u32 }, + + #[error("Invalid minting limit per address. max: {max}, min: 1, got: {got}")] + InvalidPerAddressLimit { max: u32, min: u32, got: u32 }, + + #[error("{0}")] + BaseError(#[from] BaseContractError), +} diff --git a/contracts/factories/token-merge-factory/src/helpers.rs b/contracts/factories/token-merge-factory/src/helpers.rs new file mode 100644 index 000000000..476e02d99 --- /dev/null +++ b/contracts/factories/token-merge-factory/src/helpers.rs @@ -0,0 +1,57 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{ + to_json_binary, Addr, Coin, ContractInfoResponse, CustomQuery, Querier, QuerierWrapper, + StdResult, WasmMsg, WasmQuery, +}; +use sg_std::CosmosMsg; + +use crate::msg::ExecuteMsg; + +/// CwTemplateContract is a wrapper around Addr that provides a lot of helpers +/// for working with this. +#[cw_serde] +pub struct FactoryContract(pub Addr); + +impl FactoryContract { + pub fn addr(&self) -> Addr { + self.0.clone() + } + + pub fn call>(&self, msg: T) -> StdResult { + let msg = to_json_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_json_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) + } +} diff --git a/contracts/factories/token-merge-factory/src/lib.rs b/contracts/factories/token-merge-factory/src/lib.rs new file mode 100644 index 000000000..0f47974b1 --- /dev/null +++ b/contracts/factories/token-merge-factory/src/lib.rs @@ -0,0 +1,6 @@ +pub mod contract; +mod error; +pub mod helpers; +pub mod msg; +pub mod state; +pub use crate::error::ContractError; diff --git a/contracts/factories/token-merge-factory/src/msg.rs b/contracts/factories/token-merge-factory/src/msg.rs new file mode 100644 index 000000000..0ef5ff20b --- /dev/null +++ b/contracts/factories/token-merge-factory/src/msg.rs @@ -0,0 +1,92 @@ +use crate::state::TokenMergeFactoryParams; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Coin, Timestamp}; +use sg721::{CollectionInfo, RoyaltyInfoResponse}; + +#[cw_serde] +pub struct InstantiateMsg { + pub params: TokenMergeFactoryParams, +} + +#[cw_serde] +pub struct TokenMergeMinterInitMsgExtension { + pub base_token_uri: String, + pub start_time: Timestamp, + pub num_tokens: u32, + pub mint_tokens: Vec, + pub per_address_limit: u32, +} + +#[cw_serde] +pub struct CollectionParams { + /// The collection code id + pub code_id: u64, + pub name: String, + pub symbol: String, + pub info: CollectionInfo, +} +#[cw_serde] +pub struct CreateMinterMsg { + pub init_msg: T, + pub collection_params: CollectionParams, +} + +pub type TokenMergeMinterCreateMsg = CreateMinterMsg; + +#[cw_serde] +pub enum ExecuteMsg { + CreateMinter(TokenMergeMinterCreateMsg), +} + +#[cw_serde] +pub enum QueryMsg { + Params {}, + AllowedCollectionCodeIds {}, + AllowedCollectionCodeId(u64), +} + +#[cw_serde] +pub struct TokenMergeUpdateParamsExtension { + pub max_token_limit: Option, + pub max_per_address_limit: Option, + pub airdrop_mint_price: Option, + pub airdrop_mint_fee_bps: Option, + pub shuffle_fee: Option, +} +#[cw_serde] +pub struct UpdateMinterParamsMsg { + /// The minter code id + pub code_id: Option, + pub add_sg721_code_ids: Option>, + pub rm_sg721_code_ids: Option>, + pub frozen: Option, + pub creation_fee: Option, + pub max_trading_offset_secs: Option, + pub extension: T, +} +pub type TokenMergeUpdateParamsMsg = UpdateMinterParamsMsg; + +#[cw_serde] +pub enum SudoMsg { + UpdateParams(Box), +} + +#[cw_serde] +pub struct MintToken { + pub collection: String, + pub amount: u32, +} +#[cw_serde] +pub struct ParamsResponse { + pub params: TokenMergeFactoryParams, +} + +#[cw_serde] +pub struct AllowedCollectionCodeIdsResponse { + pub code_ids: Vec, +} + +#[cw_serde] +pub struct AllowedCollectionCodeIdResponse { + pub allowed: bool, +} diff --git a/contracts/factories/token-merge-factory/src/state.rs b/contracts/factories/token-merge-factory/src/state.rs new file mode 100644 index 000000000..2266b182e --- /dev/null +++ b/contracts/factories/token-merge-factory/src/state.rs @@ -0,0 +1,19 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::Coin; +use cw_storage_plus::Item; + +#[cw_serde] +pub struct TokenMergeFactoryParams { + pub code_id: u64, + pub allowed_sg721_code_ids: Vec, + pub frozen: bool, + pub creation_fee: Coin, + pub max_trading_offset_secs: u64, + pub max_token_limit: u32, + pub max_per_address_limit: u32, + pub airdrop_mint_price: Coin, + pub airdrop_mint_fee_bps: u64, + pub shuffle_fee: Coin, +} + +pub const SUDO_PARAMS: Item = Item::new("sudo-params"); diff --git a/contracts/minters/token-merge-minter/.cargo/config b/contracts/minters/token-merge-minter/.cargo/config new file mode 100644 index 000000000..ab407a024 --- /dev/null +++ b/contracts/minters/token-merge-minter/.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/token-merge-minter/.editorconfig b/contracts/minters/token-merge-minter/.editorconfig new file mode 100644 index 000000000..3d36f20b1 --- /dev/null +++ b/contracts/minters/token-merge-minter/.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/token-merge-minter/.gitignore b/contracts/minters/token-merge-minter/.gitignore new file mode 100644 index 000000000..dfdaaa6bc --- /dev/null +++ b/contracts/minters/token-merge-minter/.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/token-merge-minter/Cargo.toml b/contracts/minters/token-merge-minter/Cargo.toml new file mode 100644 index 000000000..f3ae95f00 --- /dev/null +++ b/contracts/minters/token-merge-minter/Cargo.toml @@ -0,0 +1,53 @@ +[package] +name = "token-merge-minter" +authors = [ + "Jake Hartnell ", + "Shane Vitarana ", +] +description = "Stargaze token merge 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 } +sg4 = { workspace = true } +sg721 = { workspace = true } +sg-std = { workspace = true } +sg-whitelist = { workspace = true, features = ["library"] } +thiserror = { workspace = true } +url = { workspace = true } +token-merge-factory = { workspace = true, features = ["library"] } +semver = {workspace = true } diff --git a/contracts/minters/token-merge-minter/LICENSE b/contracts/minters/token-merge-minter/LICENSE new file mode 100644 index 000000000..1520ce81b --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/README.md b/contracts/minters/token-merge-minter/README.md new file mode 100644 index 000000000..3b7d1380c --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/examples/schema.rs b/contracts/minters/token-merge-minter/examples/schema.rs new file mode 100644 index 000000000..673289aeb --- /dev/null +++ b/contracts/minters/token-merge-minter/examples/schema.rs @@ -0,0 +1,27 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use sg4::StatusResponse; +use token_merge_minter::msg::{ + ConfigResponse, ExecuteMsg, MintCountResponse, MintableNumTokensResponse, QueryMsg, + StartTimeResponse, +}; +use token_merge_minter::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!(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!(StatusResponse), &out_dir); +} diff --git a/contracts/minters/token-merge-minter/rustfmt.toml b/contracts/minters/token-merge-minter/rustfmt.toml new file mode 100644 index 000000000..79d13fd0a --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/config_response.json b/contracts/minters/token-merge-minter/schema/config_response.json new file mode 100644 index 000000000..7b69be083 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/execute_msg.json b/contracts/minters/token-merge-minter/schema/execute_msg.json new file mode 100644 index 000000000..a6044d1ab --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/instantiate_msg.json b/contracts/minters/token-merge-minter/schema/instantiate_msg.json new file mode 100644 index 000000000..e36b41465 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/mint_count_response.json b/contracts/minters/token-merge-minter/schema/mint_count_response.json new file mode 100644 index 000000000..8cb578300 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/mint_price_response.json b/contracts/minters/token-merge-minter/schema/mint_price_response.json new file mode 100644 index 000000000..e6857d00b --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/mintable_num_tokens_response.json b/contracts/minters/token-merge-minter/schema/mintable_num_tokens_response.json new file mode 100644 index 000000000..8b80aa85b --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/minter_config_for__config_extension.json b/contracts/minters/token-merge-minter/schema/minter_config_for__config_extension.json new file mode 100644 index 000000000..0556ef225 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/query_msg.json b/contracts/minters/token-merge-minter/schema/query_msg.json new file mode 100644 index 000000000..56821a1c8 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/start_time_response.json b/contracts/minters/token-merge-minter/schema/start_time_response.json new file mode 100644 index 000000000..40a03518d --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/schema/status_response.json b/contracts/minters/token-merge-minter/schema/status_response.json new file mode 100644 index 000000000..dfcf3dc33 --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/src/contract.rs b/contracts/minters/token-merge-minter/src/contract.rs new file mode 100644 index 000000000..3e3d85832 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/contract.rs @@ -0,0 +1,1026 @@ +use crate::error::ContractError; +use crate::msg::{ + ConfigResponse, ExecuteMsg, MintCountResponse, MintTokensResponse, MintableNumTokensResponse, + QueryMsg, ReceiveNftMsg, StartTimeResponse, +}; +use crate::state::{ + Config, ConfigExtension, CONFIG, MINTABLE_NUM_TOKENS, MINTABLE_TOKEN_POSITIONS, MINTER_ADDRS, + RECEIVED_TOKENS, 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, from_json, to_json_binary, Addr, 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::Cw721ReceiveMsg; +use cw721_base::Extension; +use cw_utils::{may_pay, nonpayable, parse_reply_instantiate_data}; +use rand_core::{RngCore, SeedableRng}; +use rand_xoshiro::Xoshiro128PlusPlus; +use semver::Version; +use sg1::{checked_fair_burn, distribute_mint_fees}; +use sg4::{Status, StatusResponse, SudoMsg}; +use sg721::{ExecuteMsg as Sg721ExecuteMsg, InstantiateMsg as Sg721InstantiateMsg}; +use sg_std::{StargazeMsgWrapper, GENESIS_MINT_START_TIME}; +use sha2::{Digest, Sha256}; +use shuffle::{fy::FisherYates, shuffler::Shuffler}; +use std::convert::TryInto; +use token_merge_factory::msg::QueryMsg as FactoryQueryMsg; +use token_merge_factory::msg::{MintToken, ParamsResponse, TokenMergeMinterCreateMsg}; +use url::Url; +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: TokenMergeMinterCreateMsg, +) -> 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(), &FactoryQueryMsg::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.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.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, + )); + } + + // 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)?, + base_token_uri, + num_tokens: msg.init_msg.num_tokens, + per_address_limit: msg.init_msg.per_address_limit, + start_time: msg.init_msg.start_time, + mint_tokens: msg.init_msg.mint_tokens, + }, + }; + + 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_json_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::ReceiveNft(Cw721ReceiveMsg { + sender, + token_id, + msg: raw_msg, + }) => { + let msg: ReceiveNftMsg = from_json(raw_msg)?; + match msg { + ReceiveNftMsg::DepositToken { recipient } => { + execute_receive_nft(deps, env, info, sender, token_id, recipient) + } + } + } + ExecuteMsg::Purge {} => execute_purge(deps, env, info), + 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::Shuffle {} => execute_shuffle(deps, env, info), + ExecuteMsg::BurnRemaining {} => execute_burn_remaining(deps, env, info), + } +} + +pub fn execute_receive_nft( + deps: DepsMut, + env: Env, + info: MessageInfo, + sender: String, + token_id: String, + recipient: Option, +) -> Result { + let config = CONFIG.load(deps.storage)?; + let mut action = "receive_and_burn_nft"; + ensure!( + env.block.time > config.extension.start_time, + ContractError::BeforeMintStartTime {} + ); + + let recipient_addr = deps + .api + .addr_validate(&recipient.unwrap_or(sender.clone()))?; + + let mint_count = mint_count(deps.as_ref(), recipient_addr.clone())?; + if mint_count >= config.extension.per_address_limit { + return Err(ContractError::MaxPerAddressLimitExceeded {}); + } + + // Check received token is from an expected collection + let valid_mint_token = config + .extension + .mint_tokens + .iter() + .find(|token| token.collection == info.sender); + ensure!( + valid_mint_token.is_some(), + ContractError::InvalidCollection {} + ); + + let already_received_amount = RECEIVED_TOKENS + .load(deps.storage, (&recipient_addr, info.sender.to_string())) + .unwrap_or(0); + ensure!( + already_received_amount < valid_mint_token.unwrap().amount, + ContractError::TooManyTokens {} + ); + RECEIVED_TOKENS.save( + deps.storage, + (&recipient_addr, info.sender.to_string()), + &(already_received_amount + 1), + )?; + + let mint_requirement_fulfilled = check_all_mint_tokens_received( + deps.as_ref(), + recipient_addr.clone(), + config.extension.mint_tokens, + )?; + + // Create the burn message for the received token + let burn_msg = Sg721ExecuteMsg::::Burn { + token_id: token_id.clone(), + }; + let burn_cosmos_msg = CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: info.sender.to_string(), + msg: to_json_binary(&burn_msg)?, + funds: vec![], + }); + + if !mint_requirement_fulfilled { + return Ok(Response::new() + .add_message(burn_cosmos_msg) + .add_attribute("action", action) + .add_attribute("sender", sender) + .add_attribute("collection", info.sender.to_string()) + .add_attribute("token_id", token_id)); + } + + action = "mint_sender"; + _execute_mint( + deps, + env, + info, + action, + false, + Some(recipient_addr), + None, + Some(burn_cosmos_msg), + ) +} + +// 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, &FactoryQueryMsg::Params {})?; + let factory_params = factory.params; + + // Check exact shuffle fee payment included in message + checked_fair_burn( + &info, + factory_params.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_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, 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), + None, + ) +} + +fn check_all_mint_tokens_received( + deps: Deps, + sender: Addr, + mint_tokens: Vec, +) -> Result { + for mint_token in mint_tokens { + let received_amount = RECEIVED_TOKENS + .load(deps.storage, (&sender, mint_token.collection.clone())) + .unwrap_or(0); + if received_amount < mint_token.amount { + return Ok(false); + } + } + Ok(true) +} + +// Generalize checks and mint message creation +// ReceiveNFT -> _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) +#[allow(clippy::too_many_arguments)] +fn _execute_mint( + deps: DepsMut, + env: Env, + info: MessageInfo, + action: &str, + is_admin: bool, + recipient: Option, + token_id: Option, + burn_message: Option>, +) -> Result { + let mut network_fee = Uint128::zero(); + 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 factory: ParamsResponse = deps + .querier + .query_wasm_smart(config.factory, &FactoryQueryMsg::Params {})?; + let factory_params = factory.params; + + if is_admin { + let airdrop_price: Coin = coin( + factory_params.airdrop_mint_price.amount.u128(), + factory_params.airdrop_mint_price.denom.clone(), + ); + + // Exact payment only accepted + let payment = may_pay(&info, &airdrop_price.denom)?; + if payment != airdrop_price.amount { + return Err(ContractError::IncorrectPaymentAmount( + coin( + payment.u128(), + factory_params.airdrop_mint_price.denom.clone(), + ), + factory_params.airdrop_mint_price, + )); + } + let airdrop_fee_bps = Decimal::bps(factory_params.airdrop_mint_fee_bps); + network_fee = airdrop_price.amount * airdrop_fee_bps; + } + + let mut res = Response::new(); + + if !network_fee.is_zero() { + distribute_mint_fees( + coin( + network_fee.u128(), + factory_params.airdrop_mint_price.clone().denom, + ), + &mut res, + false, + None, + )?; + } + + 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_json_binary(&mint_msg)?, + funds: vec![], + }); + res = res.add_message(msg); + + // Burn the final token received + if let Some(burn_message) = burn_message { + res = res.add_message(burn_message); + // Clear received tokens record for recipient + for mint_token in config.extension.mint_tokens.iter() { + RECEIVED_TOKENS.remove( + deps.storage, + (&recipient_addr, mint_token.collection.clone()), + ); + } + } + + // 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 recipient's address + let new_mint_count = mint_count(deps.as_ref(), recipient_addr.clone())? + 1; + MINTER_ADDRS.save(deps.storage, &recipient_addr, &new_mint_count)?; + + Ok(res + .add_attribute("action", action) + .add_attribute("recipient", recipient_addr) + .add_attribute("token_id", mintable_token_mapping.token_id.to_string()) + .add_attribute( + "network_fee", + coin(network_fee.u128(), factory_params.airdrop_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_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(), &FactoryQueryMsg::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_json_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(), &FactoryQueryMsg::Params {})?; + let factory_params = factory.params; + + if per_address_limit == 0 || per_address_limit > factory_params.max_per_address_limit { + return Err(ContractError::InvalidPerAddressLimit { + max: factory_params.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.max_per_address_limit, + )? { + return Err(ContractError::InvalidPerAddressLimit { + max: display_max_mintable_tokens( + per_address_limit, + config.extension.num_tokens, + factory_params.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)) +} + +fn mint_count(deps: Deps, address: Addr) -> Result { + let mint_count = (MINTER_ADDRS.key(&address).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_json_binary(&query_config(deps)?), + QueryMsg::Status {} => to_json_binary(&query_status(deps)?), + QueryMsg::StartTime {} => to_json_binary(&query_start_time(deps)?), + QueryMsg::MintableNumTokens {} => to_json_binary(&query_mintable_num_tokens(deps)?), + QueryMsg::MintCount { address } => to_json_binary(&query_mint_count(deps, address)?), + QueryMsg::MintTokens {} => to_json_binary(&query_mint_tokens(deps)?), + QueryMsg::DepositedTokens { address } => { + to_json_binary(&query_deposited_tokens(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, + per_address_limit: config.extension.per_address_limit, + factory: config.factory.to_string(), + mint_tokens: config.extension.mint_tokens, + }) +} + +pub fn query_status(deps: Deps) -> StdResult { + let status = STATUS.load(deps.storage)?; + + Ok(StatusResponse { status }) +} + +pub fn query_mint_tokens(deps: Deps) -> StdResult> { + let config = CONFIG.load(deps.storage)?; + Ok(config.extension.mint_tokens) +} + +pub fn query_deposited_tokens(deps: Deps, address: String) -> StdResult { + let addr = deps.api.addr_validate(&address)?; + let received_tokens = RECEIVED_TOKENS + .prefix(&addr) + .range(deps.storage, None, None, Order::Ascending) + .map(|item| { + let (k, v) = item?; + Ok((k, v)) + }) + .collect::>>()? + .iter() + .map(|(k, v)| MintToken { + collection: k.to_string(), + amount: *v, + }) + .collect::>(); + Ok(MintTokensResponse { + mint_tokens: received_tokens, + }) +} + +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 }) +} + +// 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/token-merge-minter/src/error.rs b/contracts/minters/token-merge-minter/src/error.rs new file mode 100644 index 000000000..28eea0af7 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/error.rs @@ -0,0 +1,118 @@ +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("Deposit requirement is already met")] + TooManyTokens {}, + + #[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("Token received from invalid collection")] + InvalidCollection {}, + + #[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("Discount price can only be updated every 12 hours")] + DiscountUpdateTooSoon {}, + + #[error("Discount price can only be removed 1 hour after the last update")] + DiscountRemovalTooSoon {}, + + #[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/token-merge-minter/src/helpers.rs b/contracts/minters/token-merge-minter/src/helpers.rs new file mode 100644 index 000000000..78c7ea196 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/helpers.rs @@ -0,0 +1,62 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{ + to_json_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_json_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_json_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/token-merge-minter/src/lib.rs b/contracts/minters/token-merge-minter/src/lib.rs new file mode 100644 index 000000000..e061fa43c --- /dev/null +++ b/contracts/minters/token-merge-minter/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/token-merge-minter/src/msg.rs b/contracts/minters/token-merge-minter/src/msg.rs new file mode 100644 index 000000000..720064725 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/msg.rs @@ -0,0 +1,75 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::Timestamp; +use cw721::Cw721ReceiveMsg; +use token_merge_factory::msg::MintToken; + +#[cw_serde] +pub enum ExecuteMsg { + ReceiveNft(Cw721ReceiveMsg), + Purge {}, + UpdateStartTime(Timestamp), + /// Runs custom checks against TradingStartTime on TokenMergeMinter, then updates by calling sg721-base + UpdateStartTradingTime(Option), + UpdatePerAddressLimit { + per_address_limit: u32, + }, + MintTo { + recipient: String, + }, + MintFor { + token_id: u32, + recipient: String, + }, + Shuffle {}, + BurnRemaining {}, +} + +#[cw_serde] +pub enum QueryMsg { + Config {}, + MintableNumTokens {}, + StartTime {}, + MintTokens {}, + MintCount { address: String }, + DepositedTokens { address: String }, + Status {}, +} + +#[cw_serde] +pub enum ReceiveNftMsg { + DepositToken { recipient: Option }, +} + +#[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_tokens: Vec, + pub factory: String, +} + +#[cw_serde] +pub struct MintableNumTokensResponse { + pub count: u32, +} + +#[cw_serde] +pub struct StartTimeResponse { + pub start_time: String, +} + +#[cw_serde] +pub struct MintTokensResponse { + pub mint_tokens: Vec, +} + +#[cw_serde] +pub struct MintCountResponse { + pub address: String, + pub count: u32, +} diff --git a/contracts/minters/token-merge-minter/src/state.rs b/contracts/minters/token-merge-minter/src/state.rs new file mode 100644 index 000000000..81ef48058 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/state.rs @@ -0,0 +1,34 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, Timestamp}; +use cw_storage_plus::{Item, Map}; +use sg4::Status; +use token_merge_factory::msg::MintToken; + +#[cw_serde] +pub struct ConfigExtension { + pub admin: Addr, + pub base_token_uri: String, + pub num_tokens: u32, + pub start_time: Timestamp, + pub per_address_limit: u32, + pub mint_tokens: Vec, +} + +#[cw_serde] +pub struct MinterConfig { + pub factory: Addr, + pub collection_code_id: u64, + pub extension: T, +} + +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"); +pub const RECEIVED_TOKENS: Map<(&Addr, String), u32> = Map::new("rt"); +/// 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/token-merge-minter/src/testing.rs b/contracts/minters/token-merge-minter/src/testing.rs new file mode 100644 index 000000000..8af010928 --- /dev/null +++ b/contracts/minters/token-merge-minter/src/testing.rs @@ -0,0 +1,2 @@ +mod setup; +mod tests; diff --git a/contracts/minters/token-merge-minter/src/validation.rs b/contracts/minters/token-merge-minter/src/validation.rs new file mode 100644 index 000000000..a3eb1acef --- /dev/null +++ b/contracts/minters/token-merge-minter/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) +}