diff --git a/.github/scripts/test_generate.sh b/.github/scripts/test_generate.sh index 9fc6983..26b7225 100755 --- a/.github/scripts/test_generate.sh +++ b/.github/scripts/test_generate.sh @@ -20,7 +20,7 @@ function test-template() { GIT_BRANCH=$(git -C "$REPO_ROOT" branch --show-current) echo "Generating project from local repository (branch $GIT_BRANCH) ..." - cargo generate --path "$REPO_ROOT" --name "$PROJECT_NAME" -d minimal=false "$TEMPLATE" + cargo generate --path "$REPO_ROOT" --name "$PROJECT_NAME" -d version=full "$TEMPLATE" ( cd "$PROJECT_NAME" diff --git a/base-workspace/.cargo/config b/base-workspace/.cargo/config index 7d1a066..4fa7f37 100644 --- a/base-workspace/.cargo/config +++ b/base-workspace/.cargo/config @@ -1,5 +1,5 @@ [alias] -wasm = "build --release --target wasm32-unknown-unknown" +wasm = "build --release --lib --target wasm32-unknown-unknown" wasm-debug = "build --target wasm32-unknown-unknown" unit-test = "test --lib" -schema = "run --example schema" +schema = "run --bin schema" diff --git a/base-workspace/.gitpod.Dockerfile b/base-workspace/.gitpod.Dockerfile deleted file mode 100644 index bff8bc5..0000000 --- a/base-workspace/.gitpod.Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -### wasmd ### -FROM cosmwasm/wasmd:v0.18.0 as wasmd - -### rust-optimizer ### -FROM cosmwasm/rust-optimizer:0.11.5 as rust-optimizer - -FROM gitpod/workspace-full:latest - -COPY --from=wasmd /usr/bin/wasmd /usr/local/bin/wasmd -COPY --from=wasmd /opt/* /opt/ - -RUN sudo apt-get update \ - && sudo apt-get install -y jq \ - && sudo rm -rf /var/lib/apt/lists/* - -RUN rustup update stable \ - && rustup target add wasm32-unknown-unknown diff --git a/base-workspace/.gitpod.yml b/base-workspace/.gitpod.yml deleted file mode 100644 index d03610c..0000000 --- a/base-workspace/.gitpod.yml +++ /dev/null @@ -1,10 +0,0 @@ -image: cosmwasm/cw-gitpod-base:v0.16 - -vscode: - extensions: - - rust-lang.rust - -tasks: - - name: Dependencies & Build - init: | - cargo build diff --git a/base-workspace/Developing.md b/base-workspace/Developing.md index 6aa7cb1..33263b1 100644 --- a/base-workspace/Developing.md +++ b/base-workspace/Developing.md @@ -71,10 +71,14 @@ produce an extremely small build output in a consistent manner. The suggest way to run it is this: ```sh -docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.11.4 +docker run --rm \ + -e CARGO_TERM_COLOR=always \ + -v "$(pwd)":/code + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer:0.14.0 ``` We must mount the contract code to `/code`. You can use a absolute path instead diff --git a/cw20/base/.cargo/config b/cw20/base/.cargo/config index 7d1a066..4fa7f37 100644 --- a/cw20/base/.cargo/config +++ b/cw20/base/.cargo/config @@ -1,5 +1,5 @@ [alias] -wasm = "build --release --target wasm32-unknown-unknown" +wasm = "build --release --lib --target wasm32-unknown-unknown" wasm-debug = "build --target wasm32-unknown-unknown" unit-test = "test --lib" -schema = "run --example schema" +schema = "run --bin schema" diff --git a/cw20/base/.gitpod.Dockerfile b/cw20/base/.gitpod.Dockerfile deleted file mode 100644 index bff8bc5..0000000 --- a/cw20/base/.gitpod.Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -### wasmd ### -FROM cosmwasm/wasmd:v0.18.0 as wasmd - -### rust-optimizer ### -FROM cosmwasm/rust-optimizer:0.11.5 as rust-optimizer - -FROM gitpod/workspace-full:latest - -COPY --from=wasmd /usr/bin/wasmd /usr/local/bin/wasmd -COPY --from=wasmd /opt/* /opt/ - -RUN sudo apt-get update \ - && sudo apt-get install -y jq \ - && sudo rm -rf /var/lib/apt/lists/* - -RUN rustup update stable \ - && rustup target add wasm32-unknown-unknown diff --git a/cw20/base/.gitpod.yml b/cw20/base/.gitpod.yml deleted file mode 100644 index d03610c..0000000 --- a/cw20/base/.gitpod.yml +++ /dev/null @@ -1,10 +0,0 @@ -image: cosmwasm/cw-gitpod-base:v0.16 - -vscode: - extensions: - - rust-lang.rust - -tasks: - - name: Dependencies & Build - init: | - cargo build diff --git a/cw20/base/Cargo.toml b/cw20/base/Cargo.toml index 3a15bdf..dfb4800 100644 --- a/cw20/base/Cargo.toml +++ b/cw20/base/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "{{project-name}}" -version = "0.1.0" +version = "0.0.1" authors = ["{{authors}}"] -edition = "2018" +edition = "2021" 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. @@ -32,23 +32,29 @@ backtraces = ["cosmwasm-std/backtraces"] library = [] [package.metadata.scripts] -optimize = """docker run --rm -v "$(pwd)":/code \ +optimize = """docker run --rm \ -e CARGO_TERM_COLOR=always \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.12.5 + -v "$(pwd)":/code \ + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer:0.14.0 """ [dependencies] -cosmwasm-std = "=1.0.0" -cosmwasm-storage = "=1.0.0" -cw-storage-plus = "0.12" -cw0 = "0.10" -cw2 = "0.12" -cw20 = "0.12" -schemars = "0.8" -serde = { version = "1.0", default-features = false, features = ["derive"] } -thiserror = "1.0" +cosmwasm-schema = "1.3.1" +cosmwasm-std = "1.3.1" +cosmwasm-storage = "1.3.1" +cw-storage-plus = "1.1.0" +cw-utils = "1.0.1" +cw0 = "0.10.3" +cw2 = "1.1.0" +cw20 = "1.1.0" +schemars = "0.8.12" +semver = "1" +serde = { version = "1.0.183", default-features = false, features = ["derive"] } +thiserror = "1.0.44" [dev-dependencies] -cosmwasm-schema = "=1.0.0" +cw-multi-test = "0.16.5" diff --git a/cw20/base/Developing.md b/cw20/base/Developing.md index 6aa7cb1..33263b1 100644 --- a/cw20/base/Developing.md +++ b/cw20/base/Developing.md @@ -71,10 +71,14 @@ produce an extremely small build output in a consistent manner. The suggest way to run it is this: ```sh -docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.11.4 +docker run --rm \ + -e CARGO_TERM_COLOR=always \ + -v "$(pwd)":/code + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer:0.14.0 ``` We must mount the contract code to `/code`. You can use a absolute path instead diff --git a/cw20/base/schema/all_accounts_response.json b/cw20/base/schema/all_accounts_response.json deleted file mode 100644 index cea50fb..0000000 --- a/cw20/base/schema/all_accounts_response.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "AllAccountsResponse", - "type": "object", - "required": [ - "accounts" - ], - "properties": { - "accounts": { - "type": "array", - "items": { - "type": "string" - } - } - } -} diff --git a/cw20/base/schema/all_allowances_response.json b/cw20/base/schema/all_allowances_response.json deleted file mode 100644 index a8a11a5..0000000 --- a/cw20/base/schema/all_allowances_response.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "AllAllowancesResponse", - "type": "object", - "required": [ - "allowances" - ], - "properties": { - "allowances": { - "type": "array", - "items": { - "$ref": "#/definitions/AllowanceInfo" - } - } - }, - "definitions": { - "AllowanceInfo": { - "type": "object", - "required": [ - "allowance", - "expires", - "spender" - ], - "properties": { - "allowance": { - "$ref": "#/definitions/Uint128" - }, - "expires": { - "$ref": "#/definitions/Expiration" - }, - "spender": { - "type": "string" - } - } - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "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/cw20/base/schema/allowance_response.json b/cw20/base/schema/allowance_response.json deleted file mode 100644 index 71b49ad..0000000 --- a/cw20/base/schema/allowance_response.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "AllowanceResponse", - "type": "object", - "required": [ - "allowance", - "expires" - ], - "properties": { - "allowance": { - "$ref": "#/definitions/Uint128" - }, - "expires": { - "$ref": "#/definitions/Expiration" - } - }, - "definitions": { - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "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/cw20/base/schema/balance_response.json b/cw20/base/schema/balance_response.json deleted file mode 100644 index 4e1a0be..0000000 --- a/cw20/base/schema/balance_response.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "BalanceResponse", - "type": "object", - "required": [ - "balance" - ], - "properties": { - "balance": { - "$ref": "#/definitions/Uint128" - } - }, - "definitions": { - "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/cw20/base/schema/cw20_execute_msg.json b/cw20/base/schema/cw20_execute_msg.json deleted file mode 100644 index 4dd7b8a..0000000 --- a/cw20/base/schema/cw20_execute_msg.json +++ /dev/null @@ -1,442 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "Cw20ExecuteMsg", - "anyOf": [ - { - "description": "Transfer is a base message to move tokens to another account without triggering actions", - "type": "object", - "required": [ - "transfer" - ], - "properties": { - "transfer": { - "type": "object", - "required": [ - "amount", - "recipient" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "recipient": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Burn is a base message to destroy tokens forever", - "type": "object", - "required": [ - "burn" - ], - "properties": { - "burn": { - "type": "object", - "required": [ - "amount" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Send is a base message to transfer tokens to a contract and trigger an action on the receiving contract.", - "type": "object", - "required": [ - "send" - ], - "properties": { - "send": { - "type": "object", - "required": [ - "amount", - "contract", - "msg" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "contract": { - "type": "string" - }, - "msg": { - "$ref": "#/definitions/Binary" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"approval\" extension. Allows spender to access an additional amount tokens from the owner's (env.sender) account. If expires is Some(), overwrites current allowance expiration with this one.", - "type": "object", - "required": [ - "increase_allowance" - ], - "properties": { - "increase_allowance": { - "type": "object", - "required": [ - "amount", - "spender" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "expires": { - "anyOf": [ - { - "$ref": "#/definitions/Expiration" - }, - { - "type": "null" - } - ] - }, - "spender": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"approval\" extension. Lowers the spender's access of tokens from the owner's (env.sender) account by amount. If expires is Some(), overwrites current allowance expiration with this one.", - "type": "object", - "required": [ - "decrease_allowance" - ], - "properties": { - "decrease_allowance": { - "type": "object", - "required": [ - "amount", - "spender" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "expires": { - "anyOf": [ - { - "$ref": "#/definitions/Expiration" - }, - { - "type": "null" - } - ] - }, - "spender": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"approval\" extension. Transfers amount tokens from owner -> recipient if `env.sender` has sufficient pre-approval.", - "type": "object", - "required": [ - "transfer_from" - ], - "properties": { - "transfer_from": { - "type": "object", - "required": [ - "amount", - "owner", - "recipient" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "owner": { - "type": "string" - }, - "recipient": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"approval\" extension. Sends amount tokens from owner -> contract if `env.sender` has sufficient pre-approval.", - "type": "object", - "required": [ - "send_from" - ], - "properties": { - "send_from": { - "type": "object", - "required": [ - "amount", - "contract", - "msg", - "owner" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "contract": { - "type": "string" - }, - "msg": { - "$ref": "#/definitions/Binary" - }, - "owner": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"approval\" extension. Destroys tokens forever", - "type": "object", - "required": [ - "burn_from" - ], - "properties": { - "burn_from": { - "type": "object", - "required": [ - "amount", - "owner" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "owner": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with the \"mintable\" extension. If authorized, creates amount new tokens and adds to the recipient balance.", - "type": "object", - "required": [ - "mint" - ], - "properties": { - "mint": { - "type": "object", - "required": [ - "amount", - "recipient" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "recipient": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with the \"marketing\" extension. If authorized, updates marketing metadata. Setting None/null for any of these will leave it unchanged. Setting Some(\"\") will clear this field on the contract storage", - "type": "object", - "required": [ - "update_marketing" - ], - "properties": { - "update_marketing": { - "type": "object", - "properties": { - "description": { - "description": "A longer description of the token and it's utility. Designed for tooltips or such", - "type": [ - "string", - "null" - ] - }, - "marketing": { - "description": "The address (if any) who can update this data structure", - "type": [ - "string", - "null" - ] - }, - "project": { - "description": "A URL pointing to the project behind this token.", - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "If set as the \"marketing\" role on the contract, upload a new URL, SVG, or PNG for the token", - "type": "object", - "required": [ - "upload_logo" - ], - "properties": { - "upload_logo": { - "$ref": "#/definitions/Logo" - } - }, - "additionalProperties": false - } - ], - "definitions": { - "Binary": { - "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec", - "type": "string" - }, - "EmbeddedLogo": { - "description": "This is used to store the logo on the blockchain in an accepted format. Enforce maximum size of 5KB on all variants.", - "anyOf": [ - { - "description": "Store the Logo as an SVG file. The content must conform to the spec at https://en.wikipedia.org/wiki/Scalable_Vector_Graphics (The contract should do some light-weight sanity-check validation)", - "type": "object", - "required": [ - "svg" - ], - "properties": { - "svg": { - "$ref": "#/definitions/Binary" - } - }, - "additionalProperties": false - }, - { - "description": "Store the Logo as a PNG file. This will likely only support up to 64x64 or so within the 5KB limit.", - "type": "object", - "required": [ - "png" - ], - "properties": { - "png": { - "$ref": "#/definitions/Binary" - } - }, - "additionalProperties": false - } - ] - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "additionalProperties": false - } - ] - }, - "Logo": { - "description": "This is used for uploading logo data, or setting it in InstantiateData", - "anyOf": [ - { - "description": "A reference to an externally hosted logo. Must be a valid HTTP or HTTPS URL.", - "type": "object", - "required": [ - "url" - ], - "properties": { - "url": { - "type": "string" - } - }, - "additionalProperties": false - }, - { - "description": "Logo content stored on the blockchain. Enforce maximum size of 5KB on all variants", - "type": "object", - "required": [ - "embedded" - ], - "properties": { - "embedded": { - "$ref": "#/definitions/EmbeddedLogo" - } - }, - "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/cw20/base/schema/instantiate_msg.json b/cw20/base/schema/instantiate_msg.json deleted file mode 100644 index c8a3fca..0000000 --- a/cw20/base/schema/instantiate_msg.json +++ /dev/null @@ -1,192 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "InstantiateMsg", - "type": "object", - "required": [ - "decimals", - "initial_balances", - "name", - "symbol" - ], - "properties": { - "decimals": { - "type": "integer", - "format": "uint8", - "minimum": 0.0 - }, - "initial_balances": { - "type": "array", - "items": { - "$ref": "#/definitions/Cw20Coin" - } - }, - "marketing": { - "anyOf": [ - { - "$ref": "#/definitions/InstantiateMarketingInfo" - }, - { - "type": "null" - } - ] - }, - "mint": { - "anyOf": [ - { - "$ref": "#/definitions/MinterResponse" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "symbol": { - "type": "string" - } - }, - "definitions": { - "Binary": { - "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec", - "type": "string" - }, - "Cw20Coin": { - "type": "object", - "required": [ - "address", - "amount" - ], - "properties": { - "address": { - "type": "string" - }, - "amount": { - "$ref": "#/definitions/Uint128" - } - } - }, - "EmbeddedLogo": { - "description": "This is used to store the logo on the blockchain in an accepted format. Enforce maximum size of 5KB on all variants.", - "anyOf": [ - { - "description": "Store the Logo as an SVG file. The content must conform to the spec at https://en.wikipedia.org/wiki/Scalable_Vector_Graphics (The contract should do some light-weight sanity-check validation)", - "type": "object", - "required": [ - "svg" - ], - "properties": { - "svg": { - "$ref": "#/definitions/Binary" - } - }, - "additionalProperties": false - }, - { - "description": "Store the Logo as a PNG file. This will likely only support up to 64x64 or so within the 5KB limit.", - "type": "object", - "required": [ - "png" - ], - "properties": { - "png": { - "$ref": "#/definitions/Binary" - } - }, - "additionalProperties": false - } - ] - }, - "InstantiateMarketingInfo": { - "type": "object", - "properties": { - "description": { - "type": [ - "string", - "null" - ] - }, - "logo": { - "anyOf": [ - { - "$ref": "#/definitions/Logo" - }, - { - "type": "null" - } - ] - }, - "marketing": { - "type": [ - "string", - "null" - ] - }, - "project": { - "type": [ - "string", - "null" - ] - } - } - }, - "Logo": { - "description": "This is used for uploading logo data, or setting it in InstantiateData", - "anyOf": [ - { - "description": "A reference to an externally hosted logo. Must be a valid HTTP or HTTPS URL.", - "type": "object", - "required": [ - "url" - ], - "properties": { - "url": { - "type": "string" - } - }, - "additionalProperties": false - }, - { - "description": "Logo content stored on the blockchain. Enforce maximum size of 5KB on all variants", - "type": "object", - "required": [ - "embedded" - ], - "properties": { - "embedded": { - "$ref": "#/definitions/EmbeddedLogo" - } - }, - "additionalProperties": false - } - ] - }, - "MinterResponse": { - "type": "object", - "required": [ - "minter" - ], - "properties": { - "cap": { - "description": "cap is a hard cap on total supply that can be achieved by minting. Note that this refers to total_supply. If None, there is unlimited cap.", - "anyOf": [ - { - "$ref": "#/definitions/Uint128" - }, - { - "type": "null" - } - ] - }, - "minter": { - "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/cw20/base/schema/query_msg.json b/cw20/base/schema/query_msg.json deleted file mode 100644 index 60aac9e..0000000 --- a/cw20/base/schema/query_msg.json +++ /dev/null @@ -1,168 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "QueryMsg", - "anyOf": [ - { - "description": "Returns the current balance of the given address, 0 if unset. Return type: BalanceResponse.", - "type": "object", - "required": [ - "balance" - ], - "properties": { - "balance": { - "type": "object", - "required": [ - "address" - ], - "properties": { - "address": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Returns metadata on the contract - name, decimals, supply, etc. Return type: TokenInfoResponse.", - "type": "object", - "required": [ - "token_info" - ], - "properties": { - "token_info": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"mintable\" extension. Returns who can mint and the hard cap on maximum tokens after minting. Return type: MinterResponse.", - "type": "object", - "required": [ - "minter" - ], - "properties": { - "minter": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"allowance\" extension. Returns how much spender can use from owner account, 0 if unset. Return type: AllowanceResponse.", - "type": "object", - "required": [ - "allowance" - ], - "properties": { - "allowance": { - "type": "object", - "required": [ - "owner", - "spender" - ], - "properties": { - "owner": { - "type": "string" - }, - "spender": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"enumerable\" extension (and \"allowances\") Returns all allowances this owner has approved. Supports pagination. Return type: AllAllowancesResponse.", - "type": "object", - "required": [ - "all_allowances" - ], - "properties": { - "all_allowances": { - "type": "object", - "required": [ - "owner" - ], - "properties": { - "limit": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0.0 - }, - "owner": { - "type": "string" - }, - "start_after": { - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"enumerable\" extension Returns all accounts that have balances. Supports pagination. Return type: AllAccountsResponse.", - "type": "object", - "required": [ - "all_accounts" - ], - "properties": { - "all_accounts": { - "type": "object", - "properties": { - "limit": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0.0 - }, - "start_after": { - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"marketing\" extension Returns more metadata on the contract to display in the client: - description, logo, project url, etc. Return type: MarketingInfoResponse", - "type": "object", - "required": [ - "marketing_info" - ], - "properties": { - "marketing_info": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "description": "Only with \"marketing\" extension Downloads the mbeded logo data (if stored on chain). Errors if no logo data ftored for this contract. Return type: DownloadLogoResponse.", - "type": "object", - "required": [ - "download_logo" - ], - "properties": { - "download_logo": { - "type": "object" - } - }, - "additionalProperties": false - } - ] -} diff --git a/cw20/base/schema/token_info_response.json b/cw20/base/schema/token_info_response.json deleted file mode 100644 index 9920c84..0000000 --- a/cw20/base/schema/token_info_response.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "TokenInfoResponse", - "type": "object", - "required": [ - "decimals", - "name", - "symbol", - "total_supply" - ], - "properties": { - "decimals": { - "type": "integer", - "format": "uint8", - "minimum": 0.0 - }, - "name": { - "type": "string" - }, - "symbol": { - "type": "string" - }, - "total_supply": { - "$ref": "#/definitions/Uint128" - } - }, - "definitions": { - "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/cw20/base/src/allowances.rs b/cw20/base/src/allowances.rs index 663d808..38b36da 100644 --- a/cw20/base/src/allowances.rs +++ b/cw20/base/src/allowances.rs @@ -5,11 +5,11 @@ use cosmwasm_std::{ use cw20::{AllowanceResponse, Cw20ReceiveMsg, Expiration}; use crate::error::ContractError; -use crate::state::{ALLOWANCES, BALANCES, TOKEN_INFO}; +use crate::state::{ALLOWANCES, ALLOWANCES_SPENDER, BALANCES, TOKEN_INFO}; pub fn execute_increase_allowance( deps: DepsMut, - _env: Env, + env: Env, info: MessageInfo, spender: String, amount: Uint128, @@ -20,18 +20,19 @@ pub fn execute_increase_allowance( return Err(ContractError::CannotSetOwnAccount {}); } - ALLOWANCES.update( - deps.storage, - (&info.sender, &spender_addr), - |allow| -> StdResult<_> { - let mut val = allow.unwrap_or_default(); - if let Some(exp) = expires { - val.expires = exp; + let update_fn = |allow: Option| -> Result<_, _> { + let mut val = allow.unwrap_or_default(); + if let Some(exp) = expires { + if exp.is_expired(&env.block) { + return Err(ContractError::InvalidExpiration {}); } - val.allowance += amount; - Ok(val) - }, - )?; + val.expires = exp; + } + val.allowance += amount; + Ok(val) + }; + ALLOWANCES.update(deps.storage, (&info.sender, &spender_addr), update_fn)?; + ALLOWANCES_SPENDER.update(deps.storage, (&spender_addr, &info.sender), update_fn)?; let res = Response::new().add_attributes(vec![ attr("action", "increase_allowance"), @@ -44,7 +45,7 @@ pub fn execute_increase_allowance( pub fn execute_decrease_allowance( deps: DepsMut, - _env: Env, + env: Env, info: MessageInfo, spender: String, amount: Uint128, @@ -56,6 +57,11 @@ pub fn execute_decrease_allowance( } let key = (&info.sender, &spender_addr); + + fn reverse<'a>(t: (&'a Addr, &'a Addr)) -> (&'a Addr, &'a Addr) { + (t.1, t.0) + } + // load value and delete if it hits 0, or update otherwise let mut allowance = ALLOWANCES.load(deps.storage, key)?; if amount < allowance.allowance { @@ -65,11 +71,16 @@ pub fn execute_decrease_allowance( .checked_sub(amount) .map_err(StdError::overflow)?; if let Some(exp) = expires { + if exp.is_expired(&env.block) { + return Err(ContractError::InvalidExpiration {}); + } allowance.expires = exp; } ALLOWANCES.save(deps.storage, key, &allowance)?; + ALLOWANCES_SPENDER.save(deps.storage, reverse(key), &allowance)?; } else { ALLOWANCES.remove(deps.storage, key); + ALLOWANCES_SPENDER.remove(deps.storage, reverse(key)); } let res = Response::new().add_attributes(vec![ @@ -89,7 +100,7 @@ pub fn deduct_allowance( block: &BlockInfo, amount: Uint128, ) -> Result { - ALLOWANCES.update(storage, (owner, spender), |current| { + let update_fn = |current: Option| -> _ { match current { Some(mut a) => { if a.expires.is_expired(block) { @@ -105,7 +116,9 @@ pub fn deduct_allowance( } None => Err(ContractError::NoAllowance {}), } - }) + }; + ALLOWANCES.update(storage, (owner, spender), update_fn)?; + ALLOWANCES_SPENDER.update(storage, (spender, owner), update_fn) } pub fn execute_transfer_from( @@ -293,7 +306,7 @@ mod tests { // set allowance with height expiration let allow1 = Uint128::new(7777); - let expires = Expiration::AtHeight(5432); + let expires = Expiration::AtHeight(123_456); let msg = ExecuteMsg::IncreaseAllowance { spender: spender.clone(), amount: allow1, @@ -386,7 +399,7 @@ mod tests { // set allowance with height expiration let allow1 = Uint128::new(7777); - let expires = Expiration::AtHeight(5432); + let expires = Expiration::AtHeight(123_456); let msg = ExecuteMsg::IncreaseAllowance { spender: spender.clone(), amount: allow1, @@ -541,15 +554,17 @@ mod tests { let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::Overflow { .. }))); - // let us increase limit, but set the expiration (default env height is 12_345) + // let us increase limit, but set the expiration to expire in the next block let info = mock_info(owner.as_ref(), &[]); - let env = mock_env(); + let mut env = mock_env(); let msg = ExecuteMsg::IncreaseAllowance { spender: spender.clone(), amount: Uint128::new(1000), - expires: Some(Expiration::AtHeight(env.block.height)), + expires: Some(Expiration::AtHeight(env.block.height + 1)), }; - execute(deps.as_mut(), env, info, msg).unwrap(); + execute(deps.as_mut(), env.clone(), info, msg).unwrap(); + + env.block.height += 1; // we should now get the expiration error let msg = ExecuteMsg::TransferFrom { @@ -558,7 +573,6 @@ mod tests { amount: Uint128::new(33443), }; let info = mock_info(spender.as_ref(), &[]); - let env = mock_env(); let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert_eq!(err, ContractError::Expired {}); } @@ -618,15 +632,18 @@ mod tests { let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::Overflow { .. }))); - // let us increase limit, but set the expiration (default env height is 12_345) + // let us increase limit, but set the expiration to expire in the next block let info = mock_info(owner.as_ref(), &[]); - let env = mock_env(); + let mut env = mock_env(); let msg = ExecuteMsg::IncreaseAllowance { spender: spender.clone(), amount: Uint128::new(1000), - expires: Some(Expiration::AtHeight(env.block.height)), + expires: Some(Expiration::AtHeight(env.block.height + 1)), }; - execute(deps.as_mut(), env, info, msg).unwrap(); + execute(deps.as_mut(), env.clone(), info, msg).unwrap(); + + // increase block height, so the limit is expired now + env.block.height += 1; // we should now get the expiration error let msg = ExecuteMsg::BurnFrom { @@ -634,7 +651,6 @@ mod tests { amount: Uint128::new(33443), }; let info = mock_info(spender.as_ref(), &[]); - let env = mock_env(); let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert_eq!(err, ContractError::Expired {}); } @@ -719,15 +735,18 @@ mod tests { let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::Overflow { .. }))); - // let us increase limit, but set the expiration to current block (expired) + // let us increase limit, but set the expiration to the next block let info = mock_info(owner.as_ref(), &[]); - let env = mock_env(); + let mut env = mock_env(); let msg = ExecuteMsg::IncreaseAllowance { spender: spender.clone(), amount: Uint128::new(1000), - expires: Some(Expiration::AtHeight(env.block.height)), + expires: Some(Expiration::AtHeight(env.block.height + 1)), }; - execute(deps.as_mut(), env, info, msg).unwrap(); + execute(deps.as_mut(), env.clone(), info, msg).unwrap(); + + // increase block height, so the limit is expired now + env.block.height += 1; // we should now get the expiration error let msg = ExecuteMsg::SendFrom { @@ -737,8 +756,124 @@ mod tests { msg: send_msg, }; let info = mock_info(spender.as_ref(), &[]); - let env = mock_env(); let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); assert_eq!(err, ContractError::Expired {}); } + + #[test] + fn no_past_expiration() { + let mut deps = mock_dependencies_with_balance(&coins(2, "token")); + + let owner = String::from("addr0001"); + let spender = String::from("addr0002"); + let info = mock_info(owner.as_ref(), &[]); + let env = mock_env(); + do_instantiate(deps.as_mut(), owner.clone(), Uint128::new(12340000)); + + // set allowance with height expiration at current block height + let expires = Expiration::AtHeight(env.block.height); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: Uint128::new(7777), + expires: Some(expires), + }; + + // ensure it is rejected + assert_eq!( + Err(ContractError::InvalidExpiration {}), + execute(deps.as_mut(), env.clone(), info.clone(), msg) + ); + + // set allowance with time expiration in the past + let expires = Expiration::AtTime(env.block.time.minus_seconds(1)); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: Uint128::new(7777), + expires: Some(expires), + }; + + // ensure it is rejected + assert_eq!( + Err(ContractError::InvalidExpiration {}), + execute(deps.as_mut(), env.clone(), info.clone(), msg) + ); + + // set allowance with height expiration at next block height + let expires = Expiration::AtHeight(env.block.height + 1); + let allow = Uint128::new(7777); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: allow, + expires: Some(expires), + }; + + execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap(); + + // ensure it looks good + let allowance = query_allowance(deps.as_ref(), owner.clone(), spender.clone()).unwrap(); + assert_eq!( + allowance, + AllowanceResponse { + allowance: allow, + expires + } + ); + + // set allowance with time expiration in the future + let expires = Expiration::AtTime(env.block.time.plus_seconds(10)); + let allow = Uint128::new(7777); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: allow, + expires: Some(expires), + }; + + execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap(); + + // ensure it looks good + let allowance = query_allowance(deps.as_ref(), owner.clone(), spender.clone()).unwrap(); + assert_eq!( + allowance, + AllowanceResponse { + allowance: allow + allow, // we increased twice + expires + } + ); + + // decrease with height expiration at current block height + let expires = Expiration::AtHeight(env.block.height); + let allow = Uint128::new(7777); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: allow, + expires: Some(expires), + }; + + // ensure it is rejected + assert_eq!( + Err(ContractError::InvalidExpiration {}), + execute(deps.as_mut(), env.clone(), info.clone(), msg) + ); + + // decrease with height expiration at next block height + let expires = Expiration::AtHeight(env.block.height + 1); + let allow = Uint128::new(7777); + let msg = ExecuteMsg::DecreaseAllowance { + spender: spender.clone(), + amount: allow, + expires: Some(expires), + }; + + execute(deps.as_mut(), env, info, msg).unwrap(); + + // ensure it looks good + let allowance = query_allowance(deps.as_ref(), owner, spender).unwrap(); + assert_eq!( + allowance, + AllowanceResponse { + allowance: allow, + expires + } + ); + } } diff --git a/cw20/base/src/bin/schema.rs b/cw20/base/src/bin/schema.rs new file mode 100644 index 0000000..b378cc2 --- /dev/null +++ b/cw20/base/src/bin/schema.rs @@ -0,0 +1,11 @@ +use cosmwasm_schema::write_api; + +use {{crate_name}}::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; + +fn main() { + write_api! { + instantiate: InstantiateMsg, + execute: ExecuteMsg, + query: QueryMsg, + } +} diff --git a/cw20/base/src/contract.rs b/cw20/base/src/contract.rs index 7e999fd..6d4e68d 100644 --- a/cw20/base/src/contract.rs +++ b/cw20/base/src/contract.rs @@ -1,5 +1,6 @@ #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; +use cosmwasm_std::Order::Ascending; use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128, }; @@ -9,18 +10,22 @@ use cw20::{ BalanceResponse, Cw20Coin, Cw20ReceiveMsg, DownloadLogoResponse, EmbeddedLogo, Logo, LogoInfo, MarketingInfoResponse, MinterResponse, TokenInfoResponse, }; +use cw_utils::ensure_from_older_version; use crate::allowances::{ execute_burn_from, execute_decrease_allowance, execute_increase_allowance, execute_send_from, execute_transfer_from, query_allowance, }; -use crate::enumerable::{query_all_accounts, query_all_allowances}; +use crate::enumerable::{query_all_accounts, query_owner_allowances, query_spender_allowances}; use crate::error::ContractError; -use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; -use crate::state::{MinterData, TokenInfo, BALANCES, LOGO, MARKETING_INFO, TOKEN_INFO}; +use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; +use crate::state::{ + MinterData, TokenInfo, ALLOWANCES, ALLOWANCES_SPENDER, BALANCES, LOGO, MARKETING_INFO, + TOKEN_INFO, +}; // version info for migration info -const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; +const CONTRACT_NAME: &str = "crates.io:cw20-base"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); const LOGO_SIZE_CAP: usize = 5 * 1024; @@ -151,16 +156,34 @@ pub fn instantiate( Ok(Response::default()) } -pub fn create_accounts(deps: &mut DepsMut, accounts: &[Cw20Coin]) -> StdResult { +pub fn create_accounts( + deps: &mut DepsMut, + accounts: &[Cw20Coin], +) -> Result { + validate_accounts(accounts)?; + let mut total_supply = Uint128::zero(); for row in accounts { let address = deps.api.addr_validate(&row.address)?; BALANCES.save(deps.storage, &address, &row.amount)?; total_supply += row.amount; } + Ok(total_supply) } +pub fn validate_accounts(accounts: &[Cw20Coin]) -> Result<(), ContractError> { + let mut addresses = accounts.iter().map(|c| &c.address).collect::>(); + addresses.sort(); + addresses.dedup(); + + if addresses.len() != accounts.len() { + Err(ContractError::DuplicateInitialBalanceAddresses {}) + } else { + Ok(()) + } +} + #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, @@ -207,6 +230,9 @@ pub fn execute( marketing, } => execute_update_marketing(deps, env, info, project, description, marketing), ExecuteMsg::UploadLogo(logo) => execute_upload_logo(deps, env, info, logo), + ExecuteMsg::UpdateMinter { new_minter } => { + execute_update_minter(deps, env, info, new_minter) + } } } @@ -217,10 +243,6 @@ pub fn execute_transfer( recipient: String, amount: Uint128, ) -> Result { - if amount == Uint128::zero() { - return Err(ContractError::InvalidZeroAmount {}); - } - let rcpt_addr = deps.api.addr_validate(&recipient)?; BALANCES.update( @@ -250,10 +272,6 @@ pub fn execute_burn( info: MessageInfo, amount: Uint128, ) -> Result { - if amount == Uint128::zero() { - return Err(ContractError::InvalidZeroAmount {}); - } - // lower balance BALANCES.update( deps.storage, @@ -282,12 +300,17 @@ pub fn execute_mint( recipient: String, amount: Uint128, ) -> Result { - if amount == Uint128::zero() { - return Err(ContractError::InvalidZeroAmount {}); - } + let mut config = TOKEN_INFO + .may_load(deps.storage)? + .ok_or(ContractError::Unauthorized {})?; - let mut config = TOKEN_INFO.load(deps.storage)?; - if config.mint.is_none() || config.mint.as_ref().unwrap().minter != info.sender { + if config + .mint + .as_ref() + .ok_or(ContractError::Unauthorized {})? + .minter + != info.sender + { return Err(ContractError::Unauthorized {}); } @@ -323,10 +346,6 @@ pub fn execute_send( amount: Uint128, msg: Binary, ) -> Result { - if amount == Uint128::zero() { - return Err(ContractError::InvalidZeroAmount {}); - } - let rcpt_addr = deps.api.addr_validate(&contract)?; // move the tokens to the contract @@ -359,6 +378,44 @@ pub fn execute_send( Ok(res) } +pub fn execute_update_minter( + deps: DepsMut, + _env: Env, + info: MessageInfo, + new_minter: Option, +) -> Result { + let mut config = TOKEN_INFO + .may_load(deps.storage)? + .ok_or(ContractError::Unauthorized {})?; + + let mint = config.mint.as_ref().ok_or(ContractError::Unauthorized {})?; + if mint.minter != info.sender { + return Err(ContractError::Unauthorized {}); + } + + let minter_data = new_minter + .map(|new_minter| deps.api.addr_validate(&new_minter)) + .transpose()? + .map(|minter| MinterData { + minter, + cap: mint.cap, + }); + + config.mint = minter_data; + + TOKEN_INFO.save(deps.storage, &config)?; + + Ok(Response::default() + .add_attribute("action", "update_minter") + .add_attribute( + "new_minter", + config + .mint + .map(|m| m.minter.into_string()) + .unwrap_or_else(|| "None".to_string()), + )) +} + pub fn execute_update_marketing( deps: DepsMut, _env: Env, @@ -375,7 +432,7 @@ pub fn execute_update_marketing( .marketing .as_ref() .ok_or(ContractError::Unauthorized {})? - != &info.sender + != info.sender { return Err(ContractError::Unauthorized {}); } @@ -428,7 +485,7 @@ pub fn execute_upload_logo( .marketing .as_ref() .ok_or(ContractError::Unauthorized {})? - != &info.sender + != info.sender { return Err(ContractError::Unauthorized {}); } @@ -460,7 +517,17 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { owner, start_after, limit, - } => to_binary(&query_all_allowances(deps, owner, start_after, limit)?), + } => to_binary(&query_owner_allowances(deps, owner, start_after, limit)?), + QueryMsg::AllSpenderAllowances { + spender, + start_after, + limit, + } => to_binary(&query_spender_allowances( + deps, + spender, + start_after, + limit, + )?), QueryMsg::AllAccounts { start_after, limit } => { to_binary(&query_all_accounts(deps, start_after, limit)?) } @@ -519,6 +586,23 @@ pub fn query_download_logo(deps: Deps) -> StdResult { } } +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result { + let original_version = + ensure_from_older_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + + if original_version < "0.14.0".parse::().unwrap() { + // Build reverse map of allowances per spender + let data = ALLOWANCES + .range(deps.storage, None, None, Ascending) + .collect::>>()?; + for ((owner, spender), allowance) in data { + ALLOWANCES_SPENDER.save(deps.storage, (&spender, &owner), &allowance)?; + } + } + Ok(Response::default()) +} + #[cfg(test)] mod tests { use cosmwasm_std::testing::{ @@ -810,15 +894,14 @@ mod tests { assert_eq!(get_balance(deps.as_ref(), genesis), amount); assert_eq!(get_balance(deps.as_ref(), winner.clone()), prize); - // but cannot mint nothing + // Allows minting 0 let msg = ExecuteMsg::Mint { recipient: winner.clone(), amount: Uint128::zero(), }; let info = mock_info(minter.as_ref(), &[]); let env = mock_env(); - let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); - assert_eq!(err, ContractError::InvalidZeroAmount {}); + execute(deps.as_mut(), env, info, msg).unwrap(); // but if it exceeds cap (even over multiple rounds), it fails // cap is enforced @@ -853,6 +936,96 @@ mod tests { assert_eq!(err, ContractError::Unauthorized {}); } + #[test] + fn minter_can_update_minter_but_not_cap() { + let mut deps = mock_dependencies(); + let minter = String::from("minter"); + let cap = Some(Uint128::from(3000000u128)); + do_instantiate_with_minter( + deps.as_mut(), + &String::from("genesis"), + Uint128::new(1234), + &minter, + cap, + ); + + let new_minter = "new_minter"; + let msg = ExecuteMsg::UpdateMinter { + new_minter: Some(new_minter.to_string()), + }; + + let info = mock_info(&minter, &[]); + let env = mock_env(); + let res = execute(deps.as_mut(), env.clone(), info, msg); + assert!(res.is_ok()); + let query_minter_msg = QueryMsg::Minter {}; + let res = query(deps.as_ref(), env, query_minter_msg); + let mint: MinterResponse = from_binary(&res.unwrap()).unwrap(); + + // Minter cannot update cap. + assert!(mint.cap == cap); + assert!(mint.minter == new_minter) + } + + #[test] + fn others_cannot_update_minter() { + let mut deps = mock_dependencies(); + let minter = String::from("minter"); + do_instantiate_with_minter( + deps.as_mut(), + &String::from("genesis"), + Uint128::new(1234), + &minter, + None, + ); + + let msg = ExecuteMsg::UpdateMinter { + new_minter: Some("new_minter".to_string()), + }; + + let info = mock_info("not the minter", &[]); + let env = mock_env(); + let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); + assert_eq!(err, ContractError::Unauthorized {}); + } + + #[test] + fn unset_minter() { + let mut deps = mock_dependencies(); + let minter = String::from("minter"); + let cap = None; + do_instantiate_with_minter( + deps.as_mut(), + &String::from("genesis"), + Uint128::new(1234), + &minter, + cap, + ); + + let msg = ExecuteMsg::UpdateMinter { new_minter: None }; + + let info = mock_info(&minter, &[]); + let env = mock_env(); + let res = execute(deps.as_mut(), env.clone(), info, msg); + assert!(res.is_ok()); + let query_minter_msg = QueryMsg::Minter {}; + let res = query(deps.as_ref(), env, query_minter_msg); + let mint: Option = from_binary(&res.unwrap()).unwrap(); + + // Check that mint information was removed. + assert_eq!(mint, None); + + // Check that old minter can no longer mint. + let msg = ExecuteMsg::Mint { + recipient: String::from("lucky"), + amount: Uint128::new(222), + }; + let info = mock_info("minter", &[]); + let env = mock_env(); + let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); + assert_eq!(err, ContractError::Unauthorized {}); + } + #[test] fn no_one_mints_if_minter_unset() { let mut deps = mock_dependencies(); @@ -875,6 +1048,32 @@ mod tests { let addr1 = String::from("addr0001"); let amount2 = Uint128::from(7890987u128); let addr2 = String::from("addr0002"); + let info = mock_info("creator", &[]); + let env = mock_env(); + + // Fails with duplicate addresses + let instantiate_msg = InstantiateMsg { + name: "Bash Shell".to_string(), + symbol: "BASH".to_string(), + decimals: 6, + initial_balances: vec![ + Cw20Coin { + address: addr1.clone(), + amount: amount1, + }, + Cw20Coin { + address: addr1.clone(), + amount: amount2, + }, + ], + mint: None, + marketing: None, + }; + let err = + instantiate(deps.as_mut(), env.clone(), info.clone(), instantiate_msg).unwrap_err(); + assert_eq!(err, ContractError::DuplicateInitialBalanceAddresses {}); + + // Works with unique addresses let instantiate_msg = InstantiateMsg { name: "Bash Shell".to_string(), symbol: "BASH".to_string(), @@ -892,11 +1091,8 @@ mod tests { mint: None, marketing: None, }; - let info = mock_info("creator", &[]); - let env = mock_env(); let res = instantiate(deps.as_mut(), env, info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); - assert_eq!( query_token_info(deps.as_ref()).unwrap(), TokenInfoResponse { @@ -958,15 +1154,14 @@ mod tests { do_instantiate(deps.as_mut(), &addr1, amount1); - // cannot transfer nothing + // Allows transferring 0 let info = mock_info(addr1.as_ref(), &[]); let env = mock_env(); let msg = ExecuteMsg::Transfer { recipient: addr2.clone(), amount: Uint128::zero(), }; - let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); - assert_eq!(err, ContractError::InvalidZeroAmount {}); + execute(deps.as_mut(), env, info, msg).unwrap(); // cannot send more than we have let info = mock_info(addr1.as_ref(), &[]); @@ -1017,14 +1212,13 @@ mod tests { do_instantiate(deps.as_mut(), &addr1, amount1); - // cannot burn nothing + // Allows burning 0 let info = mock_info(addr1.as_ref(), &[]); let env = mock_env(); let msg = ExecuteMsg::Burn { amount: Uint128::zero(), }; - let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); - assert_eq!(err, ContractError::InvalidZeroAmount {}); + execute(deps.as_mut(), env, info, msg).unwrap(); assert_eq!( query_token_info(deps.as_ref()).unwrap().total_supply, amount1 @@ -1068,7 +1262,7 @@ mod tests { do_instantiate(deps.as_mut(), &addr1, amount1); - // cannot send nothing + // Allows sending 0 let info = mock_info(addr1.as_ref(), &[]); let env = mock_env(); let msg = ExecuteMsg::Send { @@ -1076,8 +1270,7 @@ mod tests { amount: Uint128::zero(), msg: send_msg.clone(), }; - let err = execute(deps.as_mut(), env, info, msg).unwrap_err(); - assert_eq!(err, ContractError::InvalidZeroAmount {}); + execute(deps.as_mut(), env, info, msg).unwrap(); // cannot send more than we have let info = mock_info(addr1.as_ref(), &[]); @@ -1130,6 +1323,126 @@ mod tests { ); } + mod migration { + use super::*; + + use cosmwasm_std::Empty; + use cw20::{AllAllowancesResponse, AllSpenderAllowancesResponse, SpenderAllowanceInfo}; + use cw_multi_test::{App, Contract, ContractWrapper, Executor}; + use cw_utils::Expiration; + + fn cw20_contract() -> Box> { + let contract = ContractWrapper::new( + crate::contract::execute, + crate::contract::instantiate, + crate::contract::query, + ) + .with_migrate(crate::contract::migrate); + Box::new(contract) + } + + #[test] + fn test_migrate() { + let mut app = App::default(); + + let cw20_id = app.store_code(cw20_contract()); + let cw20_addr = app + .instantiate_contract( + cw20_id, + Addr::unchecked("sender"), + &InstantiateMsg { + name: "Token".to_string(), + symbol: "TOKEN".to_string(), + decimals: 6, + initial_balances: vec![Cw20Coin { + address: "sender".to_string(), + amount: Uint128::new(100), + }], + mint: None, + marketing: None, + }, + &[], + "TOKEN", + Some("sender".to_string()), + ) + .unwrap(); + + // no allowance to start + let allowance: AllAllowancesResponse = app + .wrap() + .query_wasm_smart( + cw20_addr.to_string(), + &QueryMsg::AllAllowances { + owner: "sender".to_string(), + start_after: None, + limit: None, + }, + ) + .unwrap(); + assert_eq!(allowance, AllAllowancesResponse::default()); + + // Set allowance + let allow1 = Uint128::new(7777); + let expires = Expiration::AtHeight(123_456); + let msg = CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: cw20_addr.to_string(), + msg: to_binary(&ExecuteMsg::IncreaseAllowance { + spender: "spender".into(), + amount: allow1, + expires: Some(expires), + }) + .unwrap(), + funds: vec![], + }); + app.execute(Addr::unchecked("sender"), msg).unwrap(); + + // Now migrate + app.execute( + Addr::unchecked("sender"), + CosmosMsg::Wasm(WasmMsg::Migrate { + contract_addr: cw20_addr.to_string(), + new_code_id: cw20_id, + msg: to_binary(&MigrateMsg {}).unwrap(), + }), + ) + .unwrap(); + + // Smoke check that the contract still works. + let balance: cw20::BalanceResponse = app + .wrap() + .query_wasm_smart( + cw20_addr.clone(), + &QueryMsg::Balance { + address: "sender".to_string(), + }, + ) + .unwrap(); + + assert_eq!(balance.balance, Uint128::new(100)); + + // Confirm that the allowance per spender is there + let allowance: AllSpenderAllowancesResponse = app + .wrap() + .query_wasm_smart( + cw20_addr, + &QueryMsg::AllSpenderAllowances { + spender: "spender".to_string(), + start_after: None, + limit: None, + }, + ) + .unwrap(); + assert_eq!( + allowance.allowances, + &[SpenderAllowanceInfo { + owner: "sender".to_string(), + allowance: allow1, + expires + }] + ); + } + } + mod marketing { use super::*; diff --git a/cw20/base/src/enumerable.rs b/cw20/base/src/enumerable.rs index 7f7991c..f465134 100644 --- a/cw20/base/src/enumerable.rs +++ b/cw20/base/src/enumerable.rs @@ -1,14 +1,17 @@ use cosmwasm_std::{Deps, Order, StdResult}; -use cw20::{AllAccountsResponse, AllAllowancesResponse, AllowanceInfo}; +use cw20::{ + AllAccountsResponse, AllAllowancesResponse, AllSpenderAllowancesResponse, AllowanceInfo, + SpenderAllowanceInfo, +}; -use crate::state::{ALLOWANCES, BALANCES}; +use crate::state::{ALLOWANCES, ALLOWANCES_SPENDER, BALANCES}; use cw_storage_plus::Bound; // settings for pagination const MAX_LIMIT: u32 = 30; const DEFAULT_LIMIT: u32 = 10; -pub fn query_all_allowances( +pub fn query_owner_allowances( deps: Deps, owner: String, start_after: Option, @@ -33,6 +36,31 @@ pub fn query_all_allowances( Ok(AllAllowancesResponse { allowances }) } +pub fn query_spender_allowances( + deps: Deps, + spender: String, + start_after: Option, + limit: Option, +) -> StdResult { + let spender_addr = deps.api.addr_validate(&spender)?; + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + let start = start_after.map(|s| Bound::ExclusiveRaw(s.into_bytes())); + + let allowances = ALLOWANCES_SPENDER + .prefix(&spender_addr) + .range(deps.storage, start, None, Order::Ascending) + .take(limit) + .map(|item| { + item.map(|(addr, allow)| SpenderAllowanceInfo { + owner: addr.into(), + allowance: allow.allowance, + expires: allow.expires, + }) + }) + .collect::>()?; + Ok(AllSpenderAllowancesResponse { allowances }) +} + pub fn query_all_accounts( deps: Deps, start_after: Option, @@ -55,11 +83,11 @@ mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies_with_balance, mock_env, mock_info}; - use cosmwasm_std::{coins, DepsMut, Uint128}; + use cosmwasm_std::{coins, from_binary, DepsMut, Uint128}; use cw20::{Cw20Coin, Expiration, TokenInfoResponse}; - use crate::contract::{execute, instantiate, query_token_info}; - use crate::msg::{ExecuteMsg, InstantiateMsg}; + use crate::contract::{execute, instantiate, query, query_token_info}; + use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; // this will set up the instantiation for other tests fn do_instantiate(mut deps: DepsMut, addr: &str, amount: Uint128) -> TokenInfoResponse { @@ -81,7 +109,7 @@ mod tests { } #[test] - fn query_all_allowances_works() { + fn query_all_owner_allowances_works() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); let owner = String::from("owner"); @@ -94,12 +122,12 @@ mod tests { do_instantiate(deps.as_mut(), &owner, Uint128::new(12340000)); // no allowance to start - let allowances = query_all_allowances(deps.as_ref(), owner.clone(), None, None).unwrap(); + let allowances = query_owner_allowances(deps.as_ref(), owner.clone(), None, None).unwrap(); assert_eq!(allowances.allowances, vec![]); // set allowance with height expiration let allow1 = Uint128::new(7777); - let expires = Expiration::AtHeight(5432); + let expires = Expiration::AtHeight(123_456); let msg = ExecuteMsg::IncreaseAllowance { spender: spender1.clone(), amount: allow1, @@ -117,11 +145,12 @@ mod tests { execute(deps.as_mut(), env, info, msg).unwrap(); // query list gets 2 - let allowances = query_all_allowances(deps.as_ref(), owner.clone(), None, None).unwrap(); + let allowances = query_owner_allowances(deps.as_ref(), owner.clone(), None, None).unwrap(); assert_eq!(allowances.allowances.len(), 2); // first one is spender1 (order of CanonicalAddr uncorrelated with String) - let allowances = query_all_allowances(deps.as_ref(), owner.clone(), None, Some(1)).unwrap(); + let allowances = + query_owner_allowances(deps.as_ref(), owner.clone(), None, Some(1)).unwrap(); assert_eq!(allowances.allowances.len(), 1); let allow = &allowances.allowances[0]; assert_eq!(&allow.spender, &spender1); @@ -129,7 +158,7 @@ mod tests { assert_eq!(&allow.allowance, &allow1); // next one is spender2 - let allowances = query_all_allowances( + let allowances = query_owner_allowances( deps.as_ref(), owner, Some(allow.spender.clone()), @@ -143,6 +172,86 @@ mod tests { assert_eq!(&allow.allowance, &allow2); } + #[test] + fn query_all_spender_allowances_works() { + let mut deps = mock_dependencies_with_balance(&coins(2, "token")); + + // these are in alphabetical order same than insert order + let owner1 = String::from("owner1"); + let owner2 = String::from("owner2"); + let spender = String::from("spender"); + + let info = mock_info(owner1.as_ref(), &[]); + let env = mock_env(); + do_instantiate(deps.as_mut(), &owner1, Uint128::new(12340000)); + + // no allowance to start + let allowances = + query_spender_allowances(deps.as_ref(), spender.clone(), None, None).unwrap(); + assert_eq!(allowances.allowances, vec![]); + + // set allowance with height expiration + let allow1 = Uint128::new(7777); + let expires = Expiration::AtHeight(123_456); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: allow1, + expires: Some(expires), + }; + execute(deps.as_mut(), env, info, msg).unwrap(); + + // set allowance with no expiration, from the other owner + let info = mock_info(owner2.as_ref(), &[]); + let env = mock_env(); + do_instantiate(deps.as_mut(), &owner2, Uint128::new(12340000)); + + let allow2 = Uint128::new(54321); + let msg = ExecuteMsg::IncreaseAllowance { + spender: spender.clone(), + amount: allow2, + expires: None, + }; + execute(deps.as_mut(), env.clone(), info, msg).unwrap(); + + // query list gets both + let msg = QueryMsg::AllSpenderAllowances { + spender: spender.clone(), + start_after: None, + limit: None, + }; + let allowances: AllSpenderAllowancesResponse = + from_binary(&query(deps.as_ref(), env.clone(), msg).unwrap()).unwrap(); + assert_eq!(allowances.allowances.len(), 2); + + // one is owner1 (order of CanonicalAddr uncorrelated with String) + let msg = QueryMsg::AllSpenderAllowances { + spender: spender.clone(), + start_after: None, + limit: Some(1), + }; + let allowances: AllSpenderAllowancesResponse = + from_binary(&query(deps.as_ref(), env.clone(), msg).unwrap()).unwrap(); + assert_eq!(allowances.allowances.len(), 1); + let allow = &allowances.allowances[0]; + assert_eq!(&allow.owner, &owner1); + assert_eq!(&allow.expires, &expires); + assert_eq!(&allow.allowance, &allow1); + + // other one is owner2 + let msg = QueryMsg::AllSpenderAllowances { + spender, + start_after: Some(owner1), + limit: Some(10000), + }; + let allowances: AllSpenderAllowancesResponse = + from_binary(&query(deps.as_ref(), env, msg).unwrap()).unwrap(); + assert_eq!(allowances.allowances.len(), 1); + let allow = &allowances.allowances[0]; + assert_eq!(&allow.owner, &owner2); + assert_eq!(&allow.expires, &Expiration::Never {}); + assert_eq!(&allow.allowance, &allow2); + } + #[test] fn query_all_accounts_works() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); diff --git a/cw20/base/src/error.rs b/cw20/base/src/error.rs index 264f375..a0b880c 100644 --- a/cw20/base/src/error.rs +++ b/cw20/base/src/error.rs @@ -12,6 +12,8 @@ pub enum ContractError { #[error("Cannot set to own account")] CannotSetOwnAccount {}, + // Unused error case. Zero is now treated like every other value. + #[deprecated(note = "Unused. All zero amount checks have been removed")] #[error("Invalid zero amount")] InvalidZeroAmount {}, @@ -32,4 +34,10 @@ pub enum ContractError { #[error("Invalid png header")] InvalidPngHeader {}, + + #[error("Invalid expiration value")] + InvalidExpiration {}, + + #[error("Duplicate initial balance addresses")] + DuplicateInitialBalanceAddresses {}, } diff --git a/cw20/base/src/msg.rs b/cw20/base/src/msg.rs index b234ffd..2088712 100644 --- a/cw20/base/src/msg.rs +++ b/cw20/base/src/msg.rs @@ -1,3 +1,4 @@ +use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::{StdError, StdResult, Uint128}; use cw20::{Cw20Coin, Logo, MinterResponse}; use schemars::JsonSchema; @@ -5,7 +6,7 @@ use serde::{Deserialize, Serialize}; pub use cw20::Cw20ExecuteMsg as ExecuteMsg; -#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] +#[cw_serde] pub struct InstantiateMarketingInfo { pub project: Option, pub description: Option, @@ -13,7 +14,8 @@ pub struct InstantiateMarketingInfo { pub logo: Option, } -#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] +#[cw_serde] +#[cfg_attr(test, derive(Default))] pub struct InstantiateMsg { pub name: String, pub symbol: String, @@ -30,12 +32,12 @@ impl InstantiateMsg { pub fn validate(&self) -> StdResult<()> { // Check name, symbol, decimals - if !is_valid_name(&self.name) { + if !self.has_valid_name() { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", )); } - if !is_valid_symbol(&self.symbol) { + if !self.has_valid_symbol() { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); @@ -45,57 +47,65 @@ impl InstantiateMsg { } Ok(()) } -} -fn is_valid_name(name: &str) -> bool { - let bytes = name.as_bytes(); - if bytes.len() < 3 || bytes.len() > 50 { - return false; + fn has_valid_name(&self) -> bool { + let bytes = self.name.as_bytes(); + if bytes.len() < 3 || bytes.len() > 50 { + return false; + } + true } - true -} -fn is_valid_symbol(symbol: &str) -> bool { - let bytes = symbol.as_bytes(); - if bytes.len() < 3 || bytes.len() > 12 { - return false; - } - for byte in bytes.iter() { - if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { + fn has_valid_symbol(&self) -> bool { + let bytes = self.symbol.as_bytes(); + if bytes.len() < 3 || bytes.len() > 12 { return false; } + for byte in bytes.iter() { + if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { + return false; + } + } + true } - true } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] +#[cw_serde] +#[derive(QueryResponses)] pub enum QueryMsg { /// Returns the current balance of the given address, 0 if unset. - /// Return type: BalanceResponse. + #[returns(cw20::BalanceResponse)] Balance { address: String }, /// Returns metadata on the contract - name, decimals, supply, etc. - /// Return type: TokenInfoResponse. + #[returns(cw20::TokenInfoResponse)] TokenInfo {}, /// Only with "mintable" extension. /// Returns who can mint and the hard cap on maximum tokens after minting. - /// Return type: MinterResponse. + #[returns(cw20::MinterResponse)] Minter {}, /// Only with "allowance" extension. /// Returns how much spender can use from owner account, 0 if unset. - /// Return type: AllowanceResponse. + #[returns(cw20::AllowanceResponse)] Allowance { owner: String, spender: String }, /// Only with "enumerable" extension (and "allowances") /// Returns all allowances this owner has approved. Supports pagination. - /// Return type: AllAllowancesResponse. + #[returns(cw20::AllAllowancesResponse)] AllAllowances { owner: String, start_after: Option, limit: Option, }, + /// Only with "enumerable" extension (and "allowances") + /// Returns all allowances this spender has been granted. Supports pagination. + #[returns(cw20::AllSpenderAllowancesResponse)] + AllSpenderAllowances { + spender: String, + start_after: Option, + limit: Option, + }, /// Only with "enumerable" extension /// Returns all accounts that have balances. Supports pagination. - /// Return type: AllAccountsResponse. + #[returns(cw20::AllAccountsResponse)] AllAccounts { start_after: Option, limit: Option, @@ -103,11 +113,63 @@ pub enum QueryMsg { /// Only with "marketing" extension /// Returns more metadata on the contract to display in the client: /// - description, logo, project url, etc. - /// Return type: MarketingInfoResponse + #[returns(cw20::MarketingInfoResponse)] MarketingInfo {}, /// Only with "marketing" extension - /// Downloads the mbeded logo data (if stored on chain). Errors if no logo data ftored for this + /// Downloads the embedded logo data (if stored on chain). Errors if no logo data is stored for this /// contract. - /// Return type: DownloadLogoResponse. + #[returns(cw20::DownloadLogoResponse)] DownloadLogo {}, } + +#[derive(Serialize, Deserialize, JsonSchema)] +pub struct MigrateMsg {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validate_instantiatemsg_name() { + // Too short + let mut msg = InstantiateMsg { + name: str::repeat("a", 2), + ..InstantiateMsg::default() + }; + assert!(!msg.has_valid_name()); + + // In the correct length range + msg.name = str::repeat("a", 3); + assert!(msg.has_valid_name()); + + // Too long + msg.name = str::repeat("a", 51); + assert!(!msg.has_valid_name()); + } + + #[test] + fn validate_instantiatemsg_symbol() { + // Too short + let mut msg = InstantiateMsg { + symbol: str::repeat("a", 2), + ..InstantiateMsg::default() + }; + assert!(!msg.has_valid_symbol()); + + // In the correct length range + msg.symbol = str::repeat("a", 3); + assert!(msg.has_valid_symbol()); + + // Too long + msg.symbol = str::repeat("a", 13); + assert!(!msg.has_valid_symbol()); + + // Has illegal char + let illegal_chars = [[64u8], [91u8], [123u8]]; + illegal_chars.iter().for_each(|c| { + let c = std::str::from_utf8(c).unwrap(); + msg.symbol = str::repeat(c, 3); + assert!(!msg.has_valid_symbol()); + }); + } +} diff --git a/cw20/base/src/state.rs b/cw20/base/src/state.rs index d52f561..dc02c6f 100644 --- a/cw20/base/src/state.rs +++ b/cw20/base/src/state.rs @@ -1,13 +1,10 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - +use cosmwasm_schema::cw_serde; use cosmwasm_std::{Addr, Uint128}; use cw_storage_plus::{Item, Map}; use cw20::{AllowanceResponse, Logo, MarketingInfoResponse}; -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] -#[serde(rename_all = "snake_case")] +#[cw_serde] pub struct TokenInfo { pub name: String, pub symbol: String, @@ -16,7 +13,7 @@ pub struct TokenInfo { pub mint: Option, } -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[cw_serde] pub struct MinterData { pub minter: Addr, /// cap is how many more tokens can be issued by the minter @@ -34,3 +31,6 @@ pub const MARKETING_INFO: Item = Item::new("marketing_inf pub const LOGO: Item = Item::new("logo"); pub const BALANCES: Map<&Addr, Uint128> = Map::new("balance"); pub const ALLOWANCES: Map<(&Addr, &Addr), AllowanceResponse> = Map::new("allowance"); +// TODO: After https://github.com/CosmWasm/cw-plus/issues/670 is implemented, replace this with a `MultiIndex` over `ALLOWANCES` +pub const ALLOWANCES_SPENDER: Map<(&Addr, &Addr), AllowanceResponse> = + Map::new("allowance_spender"); diff --git a/cw20/escrow/.cargo/config b/cw20/escrow/.cargo/config index 8d4bc73..83eab94 100644 --- a/cw20/escrow/.cargo/config +++ b/cw20/escrow/.cargo/config @@ -1,6 +1,6 @@ [alias] -wasm = "build --release --target wasm32-unknown-unknown" +wasm = "build --release --lib --target wasm32-unknown-unknown" wasm-debug = "build --target wasm32-unknown-unknown" unit-test = "test --lib" integration-test = "test --test integration" -schema = "run --example schema" +schema = "run --bin schema" diff --git a/cw20/escrow/Cargo.toml b/cw20/escrow/Cargo.toml index ee5fd79..11109ad 100644 --- a/cw20/escrow/Cargo.toml +++ b/cw20/escrow/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "{{project-name}}" -version = "0.12.1" +version = "0.0.1" authors = ["{{authors}}"] -edition = "2018" +edition = "2021" description = "Implementation of an escrow that accepts CosmWasm-20 tokens as well as native tokens" license = "Apache-2.0" repository = "https://github.com/CosmWasm/cw-tokens" @@ -18,17 +18,17 @@ backtraces = ["cosmwasm-std/backtraces"] library = [] [dependencies] -cosmwasm-std = "=1.0.0" -cosmwasm-storage = "=1.0.0" -cw-storage-plus = "0.14" -cw-utils = "0.14" -cw2 = "0.14" -cw20 = "0.14" -schemars = "0.8" -serde = { version = "1.0", default-features = false, features = ["derive"] } -thiserror = "1.0" +cosmwasm-schema = "1.3.1" +cosmwasm-std = "1.3.1" +cosmwasm-storage = "1.3.1" +cw-storage-plus = "1.1.0" +cw-utils = "1.0.1" +cw2 = "1.1.0" +cw20 = "1.1.0" +schemars = "0.8.12" +serde = { version = "1.0.183", default-features = false, features = ["derive"] } +thiserror = "1.0.44" [dev-dependencies] -cosmwasm-schema = "=1.0.0" -cw-multi-test = "0.14" -cw20-base = { version = "0.14", features = ["library"] } +cw-multi-test = "0.16.5" +cw20-base = { version = "1.1.0", features = ["library"] } diff --git a/cw20/escrow/examples/schema.rs b/cw20/escrow/examples/schema.rs deleted file mode 100644 index 24bf65e..0000000 --- a/cw20/escrow/examples/schema.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::fs::create_dir_all; -use std::path::PathBuf; - -use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; - -use cw20_escrow::msg::{ - DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse, QueryMsg, ReceiveMsg, -}; - -fn main() { - let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - out_dir.push("schema"); - create_dir_all(&out_dir).unwrap(); - remove_schemas(&out_dir).unwrap(); - - export_schema(&schema_for!(InstantiateMsg), &out_dir); - export_schema(&schema_for!(ExecuteMsg), &out_dir); - export_schema(&schema_for!(QueryMsg), &out_dir); - export_schema(&schema_for!(ReceiveMsg), &out_dir); - export_schema(&schema_for!(DetailsResponse), &out_dir); - export_schema(&schema_for!(ListResponse), &out_dir); -} diff --git a/cw20/escrow/src/bin/schema.rs b/cw20/escrow/src/bin/schema.rs new file mode 100644 index 0000000..b378cc2 --- /dev/null +++ b/cw20/escrow/src/bin/schema.rs @@ -0,0 +1,11 @@ +use cosmwasm_schema::write_api; + +use {{crate_name}}::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; + +fn main() { + write_api! { + instantiate: InstantiateMsg, + execute: ExecuteMsg, + query: QueryMsg, + } +} diff --git a/cw20/escrow/src/contract.rs b/cw20/escrow/src/contract.rs index 251f09b..446ecc9 100644 --- a/cw20/escrow/src/contract.rs +++ b/cw20/escrow/src/contract.rs @@ -89,7 +89,7 @@ pub fn execute_create( }, Balance::Cw20(token) => { // make sure the token sent is on the whitelist by default - if !cw20_whitelist.iter().any(|t| t == &token.address) { + if !cw20_whitelist.iter().any(|t| t == token.address) { cw20_whitelist.push(token.address.clone()) } GenericBalance { @@ -161,7 +161,7 @@ pub fn execute_top_up( if let Balance::Cw20(token) = &balance { // ensure the token is on the whitelist - if !escrow.cw20_whitelist.iter().any(|t| t == &token.address) { + if !escrow.cw20_whitelist.iter().any(|t| t == token.address) { return Err(ContractError::NotInWhitelist {}); } }; diff --git a/cw20/escrow/src/integration_test.rs b/cw20/escrow/src/integration_test.rs index 7120bfe..7239543 100644 --- a/cw20/escrow/src/integration_test.rs +++ b/cw20/escrow/src/integration_test.rs @@ -1,6 +1,6 @@ #![cfg(test)] -use cosmwasm_std::{coins, to_binary, Addr, Empty, Uint128}; +use cosmwasm_std::{coins, to_binary, Addr, Empty, QuerierWrapper, Uint128}; use cw20::{Cw20Coin, Cw20Contract, Cw20ExecuteMsg}; use cw_multi_test::{App, Contract, ContractWrapper, Executor}; @@ -75,10 +75,11 @@ fn escrow_happy_path_cw20_tokens() { let cash = Cw20Contract(cash_addr.clone()); // ensure our balances - let owner_balance = cash.balance::<_, _, Empty>(&router, owner.clone()).unwrap(); + let querier = QuerierWrapper::::new(&router); + let owner_balance = cash.balance::<_, Empty>(&querier, owner.clone()).unwrap(); assert_eq!(owner_balance, Uint128::new(5000)); let escrow_balance = cash - .balance::<_, _, Empty>(&router, escrow_addr.clone()) + .balance::<_, Empty>(&querier, escrow_addr.clone()) .unwrap(); assert_eq!(escrow_balance, Uint128::zero()); @@ -118,10 +119,11 @@ fn escrow_happy_path_cw20_tokens() { assert_eq!(2, escrow_attr.len()); // ensure balances updated - let owner_balance = cash.balance::<_, _, Empty>(&router, owner.clone()).unwrap(); + let querier = QuerierWrapper::::new(&router); + let owner_balance = cash.balance::<_, Empty>(&querier, owner.clone()).unwrap(); assert_eq!(owner_balance, Uint128::new(3800)); let escrow_balance = cash - .balance::<_, _, Empty>(&router, escrow_addr.clone()) + .balance::<_, Empty>(&querier, escrow_addr.clone()) .unwrap(); assert_eq!(escrow_balance, Uint128::new(1200)); @@ -148,10 +150,11 @@ fn escrow_happy_path_cw20_tokens() { .unwrap(); // ensure balances updated - release to ben - let owner_balance = cash.balance::<_, _, Empty>(&router, owner).unwrap(); + let querier = QuerierWrapper::::new(&router); + let owner_balance = cash.balance::<_, Empty>(&querier, owner).unwrap(); assert_eq!(owner_balance, Uint128::new(3800)); - let escrow_balance = cash.balance::<_, _, Empty>(&router, escrow_addr).unwrap(); + let escrow_balance = cash.balance::<_, Empty>(&querier, escrow_addr).unwrap(); assert_eq!(escrow_balance, Uint128::zero()); - let ben_balance = cash.balance::<_, _, Empty>(&router, ben).unwrap(); + let ben_balance = cash.balance::<_, Empty>(&querier, ben).unwrap(); assert_eq!(ben_balance, Uint128::new(1200)); } diff --git a/cw20/escrow/src/msg.rs b/cw20/escrow/src/msg.rs index 6c328fc..7c33ccd 100644 --- a/cw20/escrow/src/msg.rs +++ b/cw20/escrow/src/msg.rs @@ -1,15 +1,13 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; +use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::{Addr, Api, Coin, StdResult}; use cw20::{Cw20Coin, Cw20ReceiveMsg}; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[cw_serde] pub struct InstantiateMsg {} -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] +#[cw_serde] pub enum ExecuteMsg { Create(CreateMsg), /// Adds all sent native tokens to the contract @@ -37,8 +35,7 @@ pub enum ExecuteMsg { Receive(Cw20ReceiveMsg), } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] +#[cw_serde] pub enum ReceiveMsg { Create(CreateMsg), /// Adds all sent native tokens to the contract @@ -47,7 +44,7 @@ pub enum ReceiveMsg { }, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[cw_serde] pub struct CreateMsg { /// id is a human-readable name for the escrow to use later /// 3-20 bytes of utf-8 text @@ -90,23 +87,25 @@ pub fn is_valid_name(name: &str) -> bool { true } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] +#[cw_serde] +#[derive(QueryResponses)] pub enum QueryMsg { /// Show all open escrows. Return type is ListResponse. + #[returns(ListResponse)] List {}, /// Returns the details of the named escrow, error if not created /// Return type: DetailsResponse. + #[returns(DetailsResponse)] Details { id: String }, } -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[cw_serde] pub struct ListResponse { /// list all registered ids pub escrows: Vec, } -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[cw_serde] pub struct DetailsResponse { /// id of this escrow pub id: String, diff --git a/cw721/on-chain-metadata/.cargo/config b/cw721/on-chain-metadata/.cargo/config index 7d1a066..4fa7f37 100644 --- a/cw721/on-chain-metadata/.cargo/config +++ b/cw721/on-chain-metadata/.cargo/config @@ -1,5 +1,5 @@ [alias] -wasm = "build --release --target wasm32-unknown-unknown" +wasm = "build --release --lib --target wasm32-unknown-unknown" wasm-debug = "build --target wasm32-unknown-unknown" unit-test = "test --lib" -schema = "run --example schema" +schema = "run --bin schema" diff --git a/cw721/on-chain-metadata/.circleci/config.yml b/cw721/on-chain-metadata/.circleci/config.yml deleted file mode 100644 index 9b07669..0000000 --- a/cw721/on-chain-metadata/.circleci/config.yml +++ /dev/null @@ -1,61 +0,0 @@ -version: 2.1 - -executors: - builder: - docker: - - image: buildpack-deps:trusty - -jobs: - docker-image: - executor: builder - steps: - - checkout - - setup_remote_docker - docker_layer_caching: true - - run: - name: Build Docker artifact - command: docker build --pull -t "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" . - - run: - name: Push application Docker image to docker hub - command: | - if [ "${CIRCLE_BRANCH}" = "master" ]; then - docker tag "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" cosmwasm/cw-gitpod-base:latest - docker login --password-stdin -u "$DOCKER_USER" \<<<"$DOCKER_PASS" - docker push cosmwasm/cw-gitpod-base:latest - docker logout - fi - - docker-tagged: - executor: builder - steps: - - checkout - - setup_remote_docker - docker_layer_caching: true - - run: - name: Push application Docker image to docker hub - command: | - docker tag "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" "cosmwasm/cw-gitpod-base:${CIRCLE_TAG}" - docker login --password-stdin -u "$DOCKER_USER" \<<<"$DOCKER_PASS" - docker push - docker logout - -workflows: - version: 2 - test-suite: - jobs: - # this is now a slow process... let's only run on master - - docker-image: - filters: - branches: - only: - - master - - docker-tagged: - filters: - tags: - only: - - /^v.*/ - branches: - ignore: - - /.*/ - requires: - - docker-image diff --git a/cw721/on-chain-metadata/.genignore b/cw721/on-chain-metadata/.genignore deleted file mode 100644 index 4fe5fd0..0000000 --- a/cw721/on-chain-metadata/.genignore +++ /dev/null @@ -1 +0,0 @@ -meta/ diff --git a/cw721/on-chain-metadata/.gitpod.Dockerfile b/cw721/on-chain-metadata/.gitpod.Dockerfile deleted file mode 100644 index bff8bc5..0000000 --- a/cw721/on-chain-metadata/.gitpod.Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -### wasmd ### -FROM cosmwasm/wasmd:v0.18.0 as wasmd - -### rust-optimizer ### -FROM cosmwasm/rust-optimizer:0.11.5 as rust-optimizer - -FROM gitpod/workspace-full:latest - -COPY --from=wasmd /usr/bin/wasmd /usr/local/bin/wasmd -COPY --from=wasmd /opt/* /opt/ - -RUN sudo apt-get update \ - && sudo apt-get install -y jq \ - && sudo rm -rf /var/lib/apt/lists/* - -RUN rustup update stable \ - && rustup target add wasm32-unknown-unknown diff --git a/cw721/on-chain-metadata/.gitpod.yml b/cw721/on-chain-metadata/.gitpod.yml deleted file mode 100644 index d03610c..0000000 --- a/cw721/on-chain-metadata/.gitpod.yml +++ /dev/null @@ -1,10 +0,0 @@ -image: cosmwasm/cw-gitpod-base:v0.16 - -vscode: - extensions: - - rust-lang.rust - -tasks: - - name: Dependencies & Build - init: | - cargo build diff --git a/cw721/on-chain-metadata/Cargo.toml b/cw721/on-chain-metadata/Cargo.toml index a9f709c..d23f260 100644 --- a/cw721/on-chain-metadata/Cargo.toml +++ b/cw721/on-chain-metadata/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "{{project-name}}" -version = "0.1.0" +version = "0.0.1" authors = ["{{authors}}"] -edition = "2018" +edition = "2021" 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. @@ -15,15 +15,15 @@ exclude = [ crate-type = ["cdylib", "rlib"] [profile.release] -opt-level = 3 +codegen-units = 1 debug = false -rpath = false -lto = true debug-assertions = false -codegen-units = 1 -panic = 'abort' incremental = false +lto = true +opt-level = 3 overflow-checks = true +panic = 'abort' +rpath = false [features] # for more explicit tests, cargo test --features=backtraces @@ -32,21 +32,22 @@ backtraces = ["cosmwasm-std/backtraces"] library = [] [package.metadata.scripts] -optimize = """docker run --rm -v "$(pwd)":/code \ +optimize = """docker run --rm \ -e CARGO_TERM_COLOR=always \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.12.5 + -v "$(pwd)":/code \ + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer:0.14.0 """ [dependencies] -cosmwasm-std = "~1.0.0-beta" -cw2 = "0.11" -cw721 = "0.11" -cw721-base = { version = "0.11", features = ["library"] } -schemars = "0.8" -serde = { version = "1.0", default-features = false, features = ["derive"] } -thiserror = "1.0" - -[dev-dependencies] -cosmwasm-schema = "~1.0.0-beta" +cosmwasm-schema = "1.3.1" +cosmwasm-std = "1.3.1" +cw2 = "1.1.0" +cw721 = "0.18.0" +cw721-base = { version = "0.18.0", features = ["library"] } +schemars = "0.8.12" +serde = { version = "1.0.183", default-features = false, features = ["derive"] } +thiserror = "1.0.44" diff --git a/cw721/on-chain-metadata/Developing.md b/cw721/on-chain-metadata/Developing.md index 6aa7cb1..41f1fb1 100644 --- a/cw721/on-chain-metadata/Developing.md +++ b/cw721/on-chain-metadata/Developing.md @@ -8,7 +8,7 @@ version of Rust already (eg. 1.51.0+). ## Prerequisites Before starting, make sure you have [rustup](https://rustup.rs/) along with a -recent `rustc` and `cargo` version installed. Currently, we are testing on 1.51.0+. +recent `rustc` and `cargo` version installed. Currently, we are testing on 1.51.1+. And you need to have the `wasm32-unknown-unknown` target installed as well. @@ -40,7 +40,7 @@ cargo schema ### Understanding the tests -The main code is in `src/contract.rs` and the unit tests there run in pure rust, +The main code is in `src/lib.rs` and the unit tests there run in pure rust, which makes them very quick to execute and give nice output on failures, especially if you do `RUST_BACKTRACE=1 cargo unit-test`. @@ -71,10 +71,27 @@ produce an extremely small build output in a consistent manner. The suggest way to run it is this: ```sh -docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.11.4 +docker run --rm \ + -e CARGO_TERM_COLOR=always \ + -v "$(pwd)":/code + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer:0.14.0 +``` + +Or, If you're on an arm64 machine, you should use a docker image built with arm64. + +```sh +docker run --rm \ + -e CARGO_TERM_COLOR=always \ + -v "$(pwd)":/code + -v "$(basename "$(pwd)")_cache":/code/target \ + -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ + -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ + --name "$(basename "$(pwd)")" \ + cosmwasm/rust-optimizer-arm64:0.14.0 ``` We must mount the contract code to `/code`. You can use a absolute path instead diff --git a/cw721/on-chain-metadata/README.md b/cw721/on-chain-metadata/README.md index 8734338..2a26e16 100644 --- a/cw721/on-chain-metadata/README.md +++ b/cw721/on-chain-metadata/README.md @@ -76,15 +76,3 @@ that have been published. Please replace this README file with information about your specific project. You can keep the `Developing.md` and `Publishing.md` files as useful referenced, but please set some proper description in the README. - -## Gitpod integration - -[Gitpod](https://www.gitpod.io/) container-based development platform will be enabled on your project by default. - -Workspace contains: - -- **rust**: for builds -- [wasmd](https://github.com/CosmWasm/wasmd): for local node setup and client -- **jq**: shell JSON manipulation tool - -Follow [Gitpod Getting Started](https://www.gitpod.io/docs/getting-started) and launch your workspace. diff --git a/cw721/on-chain-metadata/examples/schema.rs b/cw721/on-chain-metadata/examples/schema.rs deleted file mode 100644 index 2f44cd1..0000000 --- a/cw721/on-chain-metadata/examples/schema.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::fs::create_dir_all; -use std::path::PathBuf; - -use cosmwasm_schema::{export_schema, export_schema_with_title, remove_schemas, schema_for}; - -use cw721::{ - AllNftInfoResponse, ApprovalResponse, ApprovalsResponse, ContractInfoResponse, NftInfoResponse, - NumTokensResponse, OperatorsResponse, OwnerOfResponse, TokensResponse, -}; -use {{crate_name}}::{ExecuteMsg, Extension, InstantiateMsg, MinterResponse, QueryMsg}; - -fn main() { - let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - out_dir.push("schema"); - create_dir_all(&out_dir).unwrap(); - remove_schemas(&out_dir).unwrap(); - - export_schema(&schema_for!(InstantiateMsg), &out_dir); - export_schema_with_title(&schema_for!(ExecuteMsg), &out_dir, "ExecuteMsg"); - export_schema(&schema_for!(QueryMsg), &out_dir); - export_schema_with_title( - &schema_for!(AllNftInfoResponse), - &out_dir, - "AllNftInfoResponse", - ); - export_schema(&schema_for!(ApprovalResponse), &out_dir); - export_schema(&schema_for!(ApprovalsResponse), &out_dir); - export_schema(&schema_for!(OperatorsResponse), &out_dir); - export_schema(&schema_for!(ContractInfoResponse), &out_dir); - export_schema(&schema_for!(MinterResponse), &out_dir); - export_schema_with_title( - &schema_for!(NftInfoResponse), - &out_dir, - "NftInfoResponse", - ); - export_schema(&schema_for!(NumTokensResponse), &out_dir); - export_schema(&schema_for!(OwnerOfResponse), &out_dir); - export_schema(&schema_for!(TokensResponse), &out_dir); -} diff --git a/cw721/on-chain-metadata/meta/README.md b/cw721/on-chain-metadata/meta/README.md deleted file mode 100644 index 279d1db..0000000 --- a/cw721/on-chain-metadata/meta/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# The meta folder - -This folder is ignored via the `.genignore` file. It contains meta files -that should not make it into the generated project. - -In particular, it is used for an AppVeyor CI script that runs on `cw-template` -itself (running the cargo-generate script, then testing the generated project). -The `.circleci` and `.github` directories contain scripts destined for any projects created from -this template. - -## Files - -- `appveyor.yml`: The AppVeyor CI configuration -- `test_generate.sh`: A script for generating a project from the template and - runnings builds and tests in it. This works almost like the CI script but - targets local UNIX-like dev environments. diff --git a/cw721/on-chain-metadata/meta/appveyor.yml b/cw721/on-chain-metadata/meta/appveyor.yml deleted file mode 100644 index 00f6d3f..0000000 --- a/cw721/on-chain-metadata/meta/appveyor.yml +++ /dev/null @@ -1,61 +0,0 @@ -# This CI configuration tests the cw-template repository itself, -# not the resulting project. We want to ensure that -# 1. the template to project generation works -# 2. the template files are up to date -# -# We chose Appveyor for this task as it allows us to use an arbitrary config -# location. Furthermore it allows us to ship Circle CI and GitHub Actions configs -# generated for the resulting project. - -image: Ubuntu - -environment: - TOOLCHAIN: 1.51.0 - -services: - - docker - -cache: - - $HOME/.rustup/ -> meta/appveyor.yml - # For details about cargo caching see https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci - - $HOME/.cargo/bin/ -> meta/appveyor.yml - - $HOME/.cargo/registry/index/ -> meta/appveyor.yml - - $HOME/.cargo/registry/cache/ -> meta/appveyor.yml - - $HOME/.cargo/git/db/ -> meta/appveyor.yml - -install: - - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain "$TOOLCHAIN" -y - - source $HOME/.cargo/env - - rustc --version - - cargo --version - - rustup target add wasm32-unknown-unknown - - cargo install --features vendored-openssl cargo-generate || true - -build_script: - # No matter what is currently checked out by the CI (main, other branch, PR merge commit), - # we create a temporary local branch from that point with a constant name, which we need for - # cargo generate. - - git branch current-ci-checkout - - cd .. - - cargo generate --git cw-template --name testgen-ci --branch current-ci-checkout - - cd testgen-ci - - ls -lA - - cargo fmt -- --check - - cargo unit-test - - cargo wasm - - cargo schema - - docker build --pull -t "cosmwasm/cw-gitpod-base:${APPVEYOR_REPO_COMMIT}" . - - \[ "${APPVEYOR_REPO_BRANCH}" = "main" \] && image_tag=latest || image_tag=${APPVEYOR_REPO_TAG_NAME} - - docker tag "cosmwasm/cw-gitpod-base:${APPVEYOR_REPO_COMMIT}" "cosmwasm/cw-gitpod-base:${image_tag}" - -on_success: - # publish docker image - - docker login --password-stdin -u "$DOCKER_USER" <<<"$DOCKER_PASS" - - docker push - - docker logout - -branches: -# whitelist long living branches and tags - only: - # - main - - /v\d+\.\d+\.\d+/ \ No newline at end of file diff --git a/cw721/on-chain-metadata/meta/test_generate.sh b/cw721/on-chain-metadata/meta/test_generate.sh deleted file mode 100755 index b9aaa23..0000000 --- a/cw721/on-chain-metadata/meta/test_generate.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -command -v shellcheck > /dev/null && shellcheck "$0" - -REPO_ROOT="$(realpath "$(dirname "$0")/..")" - -TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/cw-template.XXXXXXXXX") -PROJECT_NAME="testgen-local" - -( - echo "Navigating to $TMP_DIR" - cd "$TMP_DIR" - - GIT_BRANCH=$(git -C "$REPO_ROOT" branch --show-current) - - echo "Generating project from local repository (branch $GIT_BRANCH) ..." - cargo generate --git "$REPO_ROOT" --name "$PROJECT_NAME" --branch "$GIT_BRANCH" - - ( - cd "$PROJECT_NAME" - echo "This is what was generated" - ls -lA - - # Check formatting - echo "Checking formatting ..." - cargo fmt -- --check - - # Debug builds first to fail fast - echo "Running unit tests ..." - cargo unit-test - echo "Creating schema ..." - cargo schema - - echo "Building wasm ..." - cargo wasm - ) -) diff --git a/cw721/on-chain-metadata/schema/all_nft_info_response.json b/cw721/on-chain-metadata/schema/all_nft_info_response.json deleted file mode 100644 index 152c3cf..0000000 --- a/cw721/on-chain-metadata/schema/all_nft_info_response.json +++ /dev/null @@ -1,234 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "AllNftInfoResponse", - "type": "object", - "required": [ - "access", - "info" - ], - "properties": { - "access": { - "description": "Who can transfer the token", - "allOf": [ - { - "$ref": "#/definitions/OwnerOfResponse" - } - ] - }, - "info": { - "description": "Data on the token itself,", - "allOf": [ - { - "$ref": "#/definitions/NftInfoResponse_for_Nullable_Metadata" - } - ] - } - }, - "definitions": { - "Approval": { - "type": "object", - "required": [ - "expires", - "spender" - ], - "properties": { - "expires": { - "description": "When the Approval expires (maybe Expiration::never)", - "allOf": [ - { - "$ref": "#/definitions/Expiration" - } - ] - }, - "spender": { - "description": "Account that can transfer/send the token", - "type": "string" - } - } - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "oneOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "additionalProperties": false - } - ] - }, - "Metadata": { - "type": "object", - "properties": { - "animation_url": { - "type": [ - "string", - "null" - ] - }, - "attributes": { - "type": [ - "array", - "null" - ], - "items": { - "$ref": "#/definitions/Trait" - } - }, - "background_color": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "external_url": { - "type": [ - "string", - "null" - ] - }, - "image": { - "type": [ - "string", - "null" - ] - }, - "image_data": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": [ - "string", - "null" - ] - }, - "youtube_url": { - "type": [ - "string", - "null" - ] - } - } - }, - "NftInfoResponse_for_Nullable_Metadata": { - "type": "object", - "properties": { - "extension": { - "description": "You can add any custom metadata here when you extend cw721-base", - "anyOf": [ - { - "$ref": "#/definitions/Metadata" - }, - { - "type": "null" - } - ] - }, - "token_uri": { - "description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema", - "type": [ - "string", - "null" - ] - } - } - }, - "OwnerOfResponse": { - "type": "object", - "required": [ - "approvals", - "owner" - ], - "properties": { - "approvals": { - "description": "If set this address is approved to transfer/send the token as well", - "type": "array", - "items": { - "$ref": "#/definitions/Approval" - } - }, - "owner": { - "description": "Owner of the token", - "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" - } - ] - }, - "Trait": { - "type": "object", - "required": [ - "trait_type", - "value" - ], - "properties": { - "display_type": { - "type": [ - "string", - "null" - ] - }, - "trait_type": { - "type": "string" - }, - "value": { - "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/cw721/on-chain-metadata/schema/approved_for_all_response.json b/cw721/on-chain-metadata/schema/approved_for_all_response.json deleted file mode 100644 index 453f17b..0000000 --- a/cw721/on-chain-metadata/schema/approved_for_all_response.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ApprovedForAllResponse", - "type": "object", - "required": [ - "operators" - ], - "properties": { - "operators": { - "type": "array", - "items": { - "$ref": "#/definitions/Approval" - } - } - }, - "definitions": { - "Approval": { - "type": "object", - "required": [ - "expires", - "spender" - ], - "properties": { - "expires": { - "description": "When the Approval expires (maybe Expiration::never)", - "allOf": [ - { - "$ref": "#/definitions/Expiration" - } - ] - }, - "spender": { - "description": "Account that can transfer/send the token", - "type": "string" - } - } - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "oneOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "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" - } - ] - }, - "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/cw721/on-chain-metadata/schema/contract_info_response.json b/cw721/on-chain-metadata/schema/contract_info_response.json deleted file mode 100644 index a167125..0000000 --- a/cw721/on-chain-metadata/schema/contract_info_response.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ContractInfoResponse", - "type": "object", - "required": [ - "name", - "symbol" - ], - "properties": { - "name": { - "type": "string" - }, - "symbol": { - "type": "string" - } - } -} diff --git a/cw721/on-chain-metadata/schema/execute_msg.json b/cw721/on-chain-metadata/schema/execute_msg.json deleted file mode 100644 index 348e00d..0000000 --- a/cw721/on-chain-metadata/schema/execute_msg.json +++ /dev/null @@ -1,368 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ExecuteMsg", - "description": "This is like Cw721ExecuteMsg but we add a Mint command for an owner to make this stand-alone. You will likely want to remove mint and use other control logic in any contract that inherits this.", - "oneOf": [ - { - "description": "Transfer is a base message to move a token to another account without triggering actions", - "type": "object", - "required": [ - "transfer_nft" - ], - "properties": { - "transfer_nft": { - "type": "object", - "required": [ - "recipient", - "token_id" - ], - "properties": { - "recipient": { - "type": "string" - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Send is a base message to transfer a token to a contract and trigger an action on the receiving contract.", - "type": "object", - "required": [ - "send_nft" - ], - "properties": { - "send_nft": { - "type": "object", - "required": [ - "contract", - "msg", - "token_id" - ], - "properties": { - "contract": { - "type": "string" - }, - "msg": { - "$ref": "#/definitions/Binary" - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Allows operator to transfer / send the token from the owner's account. If expiration is set, then this allowance has a time/height limit", - "type": "object", - "required": [ - "approve" - ], - "properties": { - "approve": { - "type": "object", - "required": [ - "spender", - "token_id" - ], - "properties": { - "expires": { - "anyOf": [ - { - "$ref": "#/definitions/Expiration" - }, - { - "type": "null" - } - ] - }, - "spender": { - "type": "string" - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Remove previously granted Approval", - "type": "object", - "required": [ - "revoke" - ], - "properties": { - "revoke": { - "type": "object", - "required": [ - "spender", - "token_id" - ], - "properties": { - "spender": { - "type": "string" - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Allows operator to transfer / send any token from the owner's account. If expiration is set, then this allowance has a time/height limit", - "type": "object", - "required": [ - "approve_all" - ], - "properties": { - "approve_all": { - "type": "object", - "required": [ - "operator" - ], - "properties": { - "expires": { - "anyOf": [ - { - "$ref": "#/definitions/Expiration" - }, - { - "type": "null" - } - ] - }, - "operator": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Remove previously granted ApproveAll permission", - "type": "object", - "required": [ - "revoke_all" - ], - "properties": { - "revoke_all": { - "type": "object", - "required": [ - "operator" - ], - "properties": { - "operator": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Mint a new NFT, can only be called by the contract minter", - "type": "object", - "required": [ - "mint" - ], - "properties": { - "mint": { - "$ref": "#/definitions/MintMsg_for_Nullable_Metadata" - } - }, - "additionalProperties": false - } - ], - "definitions": { - "Binary": { - "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec", - "type": "string" - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "oneOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "additionalProperties": false - } - ] - }, - "Metadata": { - "type": "object", - "properties": { - "animation_url": { - "type": [ - "string", - "null" - ] - }, - "attributes": { - "type": [ - "array", - "null" - ], - "items": { - "$ref": "#/definitions/Trait" - } - }, - "background_color": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "external_url": { - "type": [ - "string", - "null" - ] - }, - "image": { - "type": [ - "string", - "null" - ] - }, - "image_data": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": [ - "string", - "null" - ] - }, - "youtube_url": { - "type": [ - "string", - "null" - ] - } - } - }, - "MintMsg_for_Nullable_Metadata": { - "type": "object", - "required": [ - "owner", - "token_id" - ], - "properties": { - "extension": { - "description": "Any custom extension used by this contract", - "anyOf": [ - { - "$ref": "#/definitions/Metadata" - }, - { - "type": "null" - } - ] - }, - "owner": { - "description": "The owner of the newly minter NFT", - "type": "string" - }, - "token_id": { - "description": "Unique ID of the NFT", - "type": "string" - }, - "token_uri": { - "description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema", - "type": [ - "string", - "null" - ] - } - } - }, - "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" - } - ] - }, - "Trait": { - "type": "object", - "required": [ - "trait_type", - "value" - ], - "properties": { - "display_type": { - "type": [ - "string", - "null" - ] - }, - "trait_type": { - "type": "string" - }, - "value": { - "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/cw721/on-chain-metadata/schema/instantiate_msg.json b/cw721/on-chain-metadata/schema/instantiate_msg.json deleted file mode 100644 index b024c82..0000000 --- a/cw721/on-chain-metadata/schema/instantiate_msg.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "InstantiateMsg", - "type": "object", - "required": [ - "minter", - "name", - "symbol" - ], - "properties": { - "minter": { - "description": "The minter is the only one who can create new NFTs. This is designed for a base NFT that is controlled by an external program or contract. You will likely replace this with custom logic in custom NFTs", - "type": "string" - }, - "name": { - "description": "Name of the NFT contract", - "type": "string" - }, - "symbol": { - "description": "Symbol of the NFT contract", - "type": "string" - } - } -} diff --git a/cw721/on-chain-metadata/schema/minter_response.json b/cw721/on-chain-metadata/schema/minter_response.json deleted file mode 100644 index a20e0d7..0000000 --- a/cw721/on-chain-metadata/schema/minter_response.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "MinterResponse", - "description": "Shows who can mint these tokens", - "type": "object", - "required": [ - "minter" - ], - "properties": { - "minter": { - "type": "string" - } - } -} diff --git a/cw721/on-chain-metadata/schema/nft_info_response.json b/cw721/on-chain-metadata/schema/nft_info_response.json deleted file mode 100644 index fbd9b9b..0000000 --- a/cw721/on-chain-metadata/schema/nft_info_response.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "NftInfoResponse", - "type": "object", - "properties": { - "extension": { - "description": "You can add any custom metadata here when you extend cw721-base", - "anyOf": [ - { - "$ref": "#/definitions/Metadata" - }, - { - "type": "null" - } - ] - }, - "token_uri": { - "description": "Universal resource identifier for this NFT Should point to a JSON file that conforms to the ERC721 Metadata JSON Schema", - "type": [ - "string", - "null" - ] - } - }, - "definitions": { - "Metadata": { - "type": "object", - "properties": { - "animation_url": { - "type": [ - "string", - "null" - ] - }, - "attributes": { - "type": [ - "array", - "null" - ], - "items": { - "$ref": "#/definitions/Trait" - } - }, - "background_color": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "external_url": { - "type": [ - "string", - "null" - ] - }, - "image": { - "type": [ - "string", - "null" - ] - }, - "image_data": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": [ - "string", - "null" - ] - }, - "youtube_url": { - "type": [ - "string", - "null" - ] - } - } - }, - "Trait": { - "type": "object", - "required": [ - "trait_type", - "value" - ], - "properties": { - "display_type": { - "type": [ - "string", - "null" - ] - }, - "trait_type": { - "type": "string" - }, - "value": { - "type": "string" - } - } - } - } -} diff --git a/cw721/on-chain-metadata/schema/num_tokens_response.json b/cw721/on-chain-metadata/schema/num_tokens_response.json deleted file mode 100644 index 4647c23..0000000 --- a/cw721/on-chain-metadata/schema/num_tokens_response.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "NumTokensResponse", - "type": "object", - "required": [ - "count" - ], - "properties": { - "count": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - } -} diff --git a/cw721/on-chain-metadata/schema/owner_of_response.json b/cw721/on-chain-metadata/schema/owner_of_response.json deleted file mode 100644 index 1258d67..0000000 --- a/cw721/on-chain-metadata/schema/owner_of_response.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "OwnerOfResponse", - "type": "object", - "required": [ - "approvals", - "owner" - ], - "properties": { - "approvals": { - "description": "If set this address is approved to transfer/send the token as well", - "type": "array", - "items": { - "$ref": "#/definitions/Approval" - } - }, - "owner": { - "description": "Owner of the token", - "type": "string" - } - }, - "definitions": { - "Approval": { - "type": "object", - "required": [ - "expires", - "spender" - ], - "properties": { - "expires": { - "description": "When the Approval expires (maybe Expiration::never)", - "allOf": [ - { - "$ref": "#/definitions/Expiration" - } - ] - }, - "spender": { - "description": "Account that can transfer/send the token", - "type": "string" - } - } - }, - "Expiration": { - "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "oneOf": [ - { - "description": "AtHeight will expire when `env.block.height` >= height", - "type": "object", - "required": [ - "at_height" - ], - "properties": { - "at_height": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - { - "description": "AtTime will expire when `env.block.time` >= time", - "type": "object", - "required": [ - "at_time" - ], - "properties": { - "at_time": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - }, - { - "description": "Never will never expire. Used to express the empty variant", - "type": "object", - "required": [ - "never" - ], - "properties": { - "never": { - "type": "object" - } - }, - "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" - } - ] - }, - "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/cw721/on-chain-metadata/schema/query_msg.json b/cw721/on-chain-metadata/schema/query_msg.json deleted file mode 100644 index bcf6a51..0000000 --- a/cw721/on-chain-metadata/schema/query_msg.json +++ /dev/null @@ -1,227 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "QueryMsg", - "oneOf": [ - { - "description": "Return the owner of the given token, error if token does not exist Return type: OwnerOfResponse", - "type": "object", - "required": [ - "owner_of" - ], - "properties": { - "owner_of": { - "type": "object", - "required": [ - "token_id" - ], - "properties": { - "include_expired": { - "description": "unset or false will filter out expired approvals, you must set to true to see them", - "type": [ - "boolean", - "null" - ] - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "List all operators that can access all of the owner's tokens Return type: `ApprovedForAllResponse`", - "type": "object", - "required": [ - "approved_for_all" - ], - "properties": { - "approved_for_all": { - "type": "object", - "required": [ - "owner" - ], - "properties": { - "include_expired": { - "description": "unset or false will filter out expired items, you must set to true to see them", - "type": [ - "boolean", - "null" - ] - }, - "limit": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0.0 - }, - "owner": { - "type": "string" - }, - "start_after": { - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Total number of tokens issued", - "type": "object", - "required": [ - "num_tokens" - ], - "properties": { - "num_tokens": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "description": "With MetaData Extension. Returns top-level metadata about the contract: `ContractInfoResponse`", - "type": "object", - "required": [ - "contract_info" - ], - "properties": { - "contract_info": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "description": "With MetaData Extension. Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema* but directly from the contract: `NftInfoResponse`", - "type": "object", - "required": [ - "nft_info" - ], - "properties": { - "nft_info": { - "type": "object", - "required": [ - "token_id" - ], - "properties": { - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "With MetaData Extension. Returns the result of both `NftInfo` and `OwnerOf` as one query as an optimization for clients: `AllNftInfo`", - "type": "object", - "required": [ - "all_nft_info" - ], - "properties": { - "all_nft_info": { - "type": "object", - "required": [ - "token_id" - ], - "properties": { - "include_expired": { - "description": "unset or false will filter out expired approvals, you must set to true to see them", - "type": [ - "boolean", - "null" - ] - }, - "token_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "With Enumerable extension. Returns all tokens owned by the given address, [] if unset. Return type: TokensResponse.", - "type": "object", - "required": [ - "tokens" - ], - "properties": { - "tokens": { - "type": "object", - "required": [ - "owner" - ], - "properties": { - "limit": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0.0 - }, - "owner": { - "type": "string" - }, - "start_after": { - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "With Enumerable extension. Requires pagination. Lists all token_ids controlled by the contract. Return type: TokensResponse.", - "type": "object", - "required": [ - "all_tokens" - ], - "properties": { - "all_tokens": { - "type": "object", - "properties": { - "limit": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0.0 - }, - "start_after": { - "type": [ - "string", - "null" - ] - } - } - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "minter" - ], - "properties": { - "minter": { - "type": "object" - } - }, - "additionalProperties": false - } - ] -} diff --git a/cw721/on-chain-metadata/schema/tokens_response.json b/cw721/on-chain-metadata/schema/tokens_response.json deleted file mode 100644 index b8e3d75..0000000 --- a/cw721/on-chain-metadata/schema/tokens_response.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "TokensResponse", - "type": "object", - "required": [ - "tokens" - ], - "properties": { - "tokens": { - "description": "Contains all token_ids in lexicographical ordering If there are more than `limit`, use `start_from` in future queries to achieve pagination.", - "type": "array", - "items": { - "type": "string" - } - } - } -} diff --git a/cw721/on-chain-metadata/src/bin/schema.rs b/cw721/on-chain-metadata/src/bin/schema.rs new file mode 100644 index 0000000..a01a7b9 --- /dev/null +++ b/cw721/on-chain-metadata/src/bin/schema.rs @@ -0,0 +1,12 @@ +use cosmwasm_schema::write_api; + +use cosmwasm_std::Empty; +use {{crate_name}}::{ExecuteMsg, InstantiateMsg, QueryMsg}; + +fn main() { + write_api! { + instantiate: InstantiateMsg, + execute: ExecuteMsg, + query: QueryMsg, + } +} diff --git a/cw721/on-chain-metadata/src/lib.rs b/cw721/on-chain-metadata/src/lib.rs index 40e2440..cdb1779 100644 --- a/cw721/on-chain-metadata/src/lib.rs +++ b/cw721/on-chain-metadata/src/lib.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use cosmwasm_std::Empty; use cw2::set_contract_version; use cw721::ContractInfoResponse; -pub use cw721_base::{ContractError, InstantiateMsg, MintMsg, MinterResponse, QueryMsg}; +pub use cw721_base::{ContractError, InstantiateMsg, MinterResponse, QueryMsg}; #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)] pub struct Trait { @@ -29,8 +29,8 @@ pub struct Metadata { pub type Extension = Option; -pub type Cw721MetadataContract<'a> = cw721_base::Cw721Contract<'a, Extension, Empty>; -pub type ExecuteMsg = cw721_base::ExecuteMsg; +pub type Cw721MetadataContract<'a> = cw721_base::Cw721Contract<'a, Extension, Empty, Empty, Empty>; +pub type ExecuteMsg = cw721_base::ExecuteMsg; const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -61,10 +61,6 @@ pub mod entry { Cw721MetadataContract::default() .contract_info .save(deps.storage, &info)?; - let minter = deps.api.addr_validate(&msg.minter)?; - Cw721MetadataContract::default() - .minter - .save(deps.storage, &minter)?; Ok(Response::default()) } @@ -79,7 +75,7 @@ pub mod entry { } #[entry_point] - pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { + pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { Cw721MetadataContract::default().query(deps, env, msg) } } @@ -109,7 +105,7 @@ mod tests { .unwrap(); let token_id = "Enterprise"; - let mint_msg = MintMsg { + let mint_msg = ExecuteMsg::Mint { token_id: token_id.to_string(), owner: "john".to_string(), token_uri: Some("https://starships.example.com/Starship/Enterprise.json".into()), @@ -119,13 +115,20 @@ mod tests { ..Metadata::default() }), }; - let exec_msg = ExecuteMsg::Mint(mint_msg.clone()); contract - .execute(deps.as_mut(), mock_env(), info, exec_msg) + .execute(deps.as_mut(), mock_env(), info, mint_msg.clone()) .unwrap(); let res = contract.nft_info(deps.as_ref(), token_id.into()).unwrap(); - assert_eq!(res.token_uri, mint_msg.token_uri); - assert_eq!(res.extension, mint_msg.extension); + if let ExecuteMsg::Mint { + token_id: _, + owner: _, + token_uri, + extension, + } = mint_msg + { + assert_eq!(res.token_uri, token_uri); + assert_eq!(res.extension, extension); + } } } diff --git a/default/.cargo/config b/default/.cargo/config deleted file mode 100644 index 7d1a066..0000000 --- a/default/.cargo/config +++ /dev/null @@ -1,5 +0,0 @@ -[alias] -wasm = "build --release --target wasm32-unknown-unknown" -wasm-debug = "build --target wasm32-unknown-unknown" -unit-test = "test --lib" -schema = "run --example schema" diff --git a/default/.circleci/config.yml b/default/.circleci/config.yml deleted file mode 100644 index 9b07669..0000000 --- a/default/.circleci/config.yml +++ /dev/null @@ -1,61 +0,0 @@ -version: 2.1 - -executors: - builder: - docker: - - image: buildpack-deps:trusty - -jobs: - docker-image: - executor: builder - steps: - - checkout - - setup_remote_docker - docker_layer_caching: true - - run: - name: Build Docker artifact - command: docker build --pull -t "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" . - - run: - name: Push application Docker image to docker hub - command: | - if [ "${CIRCLE_BRANCH}" = "master" ]; then - docker tag "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" cosmwasm/cw-gitpod-base:latest - docker login --password-stdin -u "$DOCKER_USER" \<<<"$DOCKER_PASS" - docker push cosmwasm/cw-gitpod-base:latest - docker logout - fi - - docker-tagged: - executor: builder - steps: - - checkout - - setup_remote_docker - docker_layer_caching: true - - run: - name: Push application Docker image to docker hub - command: | - docker tag "cosmwasm/cw-gitpod-base:${CIRCLE_SHA1}" "cosmwasm/cw-gitpod-base:${CIRCLE_TAG}" - docker login --password-stdin -u "$DOCKER_USER" \<<<"$DOCKER_PASS" - docker push - docker logout - -workflows: - version: 2 - test-suite: - jobs: - # this is now a slow process... let's only run on master - - docker-image: - filters: - branches: - only: - - master - - docker-tagged: - filters: - tags: - only: - - /^v.*/ - branches: - ignore: - - /.*/ - requires: - - docker-image diff --git a/default/.editorconfig b/default/.editorconfig deleted file mode 100644 index 3d36f20..0000000 --- a/default/.editorconfig +++ /dev/null @@ -1,11 +0,0 @@ -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/default/.genignore b/default/.genignore deleted file mode 100644 index 4fe5fd0..0000000 --- a/default/.genignore +++ /dev/null @@ -1 +0,0 @@ -meta/ diff --git a/default/.github/workflows/Basic.yml b/default/.github/workflows/Basic.yml deleted file mode 100644 index 6170933..0000000 --- a/default/.github/workflows/Basic.yml +++ /dev/null @@ -1,83 +0,0 @@ -# Based on https://github.com/actions-rs/example/blob/master/.github/workflows/quickstart.yml - -on: [push, pull_request] - -name: Basic - -jobs: - - test: - name: Test Suite - runs-on: ubuntu-latest - steps: - - name: Checkout sources - uses: actions/checkout@v2 - - - name: Install stable toolchain - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - target: wasm32-unknown-unknown - override: true - profile: minimal - - - name: Run unit tests - uses: actions-rs/cargo@v1 - with: - command: unit-test - args: --locked - env: - RUST_BACKTRACE: 1 - - - name: Compile WASM contract - uses: actions-rs/cargo@v1 - with: - command: wasm - args: --locked - env: - RUSTFLAGS: "-C link-arg=-s" - - lints: - name: Lints - runs-on: ubuntu-latest - steps: - - name: Checkout sources - uses: actions/checkout@v2 - - - name: Install stable toolchain - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - override: true - profile: minimal - components: rustfmt, clippy - - - name: Run cargo fmt - uses: actions-rs/cargo@v1 - with: - command: fmt - args: --all -- --check - - - name: Run cargo clippy - uses: actions-rs/cargo@v1 - with: - command: clippy - args: -- -D warnings - - - name: Generate schema - uses: actions-rs/cargo@v1 - with: - command: schema - args: --locked - - - name: Verify schema - uses: tj-actions/verify-changed-files@v8 - id: verify-schema - with: - files: schema/.*\.json - - - name: Display changed schemas - if: steps.verify-schema.outputs.files_changed == 'true' - run: | - echo "The schema files are not in sync with the repository. Please, run 'cargo schema' to generate them again and commit the changes." - exit 1 diff --git a/default/.gitignore b/default/.gitignore deleted file mode 100644 index f9b9a83..0000000 --- a/default/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -# Build results -/target -/artifacts - -# 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/default/.gitpod.Dockerfile b/default/.gitpod.Dockerfile deleted file mode 100644 index bff8bc5..0000000 --- a/default/.gitpod.Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -### wasmd ### -FROM cosmwasm/wasmd:v0.18.0 as wasmd - -### rust-optimizer ### -FROM cosmwasm/rust-optimizer:0.11.5 as rust-optimizer - -FROM gitpod/workspace-full:latest - -COPY --from=wasmd /usr/bin/wasmd /usr/local/bin/wasmd -COPY --from=wasmd /opt/* /opt/ - -RUN sudo apt-get update \ - && sudo apt-get install -y jq \ - && sudo rm -rf /var/lib/apt/lists/* - -RUN rustup update stable \ - && rustup target add wasm32-unknown-unknown diff --git a/default/.gitpod.yml b/default/.gitpod.yml deleted file mode 100644 index d03610c..0000000 --- a/default/.gitpod.yml +++ /dev/null @@ -1,10 +0,0 @@ -image: cosmwasm/cw-gitpod-base:v0.16 - -vscode: - extensions: - - rust-lang.rust - -tasks: - - name: Dependencies & Build - init: | - cargo build diff --git a/default/Cargo.toml b/default/Cargo.toml deleted file mode 100644 index 0e61005..0000000 --- a/default/Cargo.toml +++ /dev/null @@ -1,53 +0,0 @@ -[package] -name = "{{project-name}}" -version = "0.1.0" -authors = ["{{authors}}"] -edition = "2018" - -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"] - -[profile.release] -opt-level = 3 -debug = false -rpath = false -lto = true -debug-assertions = false -codegen-units = 1 -panic = 'abort' -incremental = false -overflow-checks = true - -[features] -# for more explicit tests, cargo test --features=backtraces -backtraces = ["cosmwasm-std/backtraces"] -# use library feature to disable all instantiate/execute/query exports -library = [] - -[package.metadata.scripts] -optimize = """docker run --rm -v "$(pwd)":/code \ - -e CARGO_TERM_COLOR=always \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.12.5 -""" - -[dependencies] -cosmwasm-std = "=1.0.0" -cosmwasm-storage = "=1.0.0" -cw-storage-plus = "0.14" -cw2 = "0.14" -schemars = "0.8" -serde = { version = "1.0", default-features = false, features = ["derive"] } -thiserror = "1.0" - -[dev-dependencies] -cosmwasm-schema = "=1.0.0" diff --git a/default/Developing.md b/default/Developing.md deleted file mode 100644 index 6aa7cb1..0000000 --- a/default/Developing.md +++ /dev/null @@ -1,96 +0,0 @@ -# Developing - -If you have recently created a contract with this template, you probably could use some -help on how to build and test the contract, as well as prepare it for production. This -file attempts to provide a brief overview, assuming you have installed a recent -version of Rust already (eg. 1.51.0+). - -## Prerequisites - -Before starting, make sure you have [rustup](https://rustup.rs/) along with a -recent `rustc` and `cargo` version installed. Currently, we are testing on 1.51.0+. - -And you need to have the `wasm32-unknown-unknown` target installed as well. - -You can check that via: - -```sh -rustc --version -cargo --version -rustup target list --installed -# if wasm32 is not listed above, run this -rustup target add wasm32-unknown-unknown -``` - -## Compiling and running tests - -Now that you created your custom contract, make sure you can compile and run it before -making any changes. Go into the repository and do: - -```sh -# this will produce a wasm build in ./target/wasm32-unknown-unknown/release/YOUR_NAME_HERE.wasm -cargo wasm - -# this runs unit tests with helpful backtraces -RUST_BACKTRACE=1 cargo unit-test - -# auto-generate json schema -cargo schema -``` - -### Understanding the tests - -The main code is in `src/contract.rs` and the unit tests there run in pure rust, -which makes them very quick to execute and give nice output on failures, especially -if you do `RUST_BACKTRACE=1 cargo unit-test`. - -We consider testing critical for anything on a blockchain, and recommend to always keep -the tests up to date. - -## Generating JSON Schema - -While the Wasm calls (`instantiate`, `execute`, `query`) accept JSON, this is not enough -information to use it. We need to expose the schema for the expected messages to the -clients. You can generate this schema by calling `cargo schema`, which will output -4 files in `./schema`, corresponding to the 3 message types the contract accepts, -as well as the internal `State`. - -These files are in standard json-schema format, which should be usable by various -client side tools, either to auto-generate codecs, or just to validate incoming -json wrt. the defined schema. - -## Preparing the Wasm bytecode for production - -Before we upload it to a chain, we need to ensure the smallest output size possible, -as this will be included in the body of a transaction. We also want to have a -reproducible build process, so third parties can verify that the uploaded Wasm -code did indeed come from the claimed rust code. - -To solve both these issues, we have produced `rust-optimizer`, a docker image to -produce an extremely small build output in a consistent manner. The suggest way -to run it is this: - -```sh -docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/rust-optimizer:0.11.4 -``` - -We must mount the contract code to `/code`. You can use a absolute path instead -of `$(pwd)` if you don't want to `cd` to the directory first. The other two -volumes are nice for speedup. Mounting `/code/target` in particular is useful -to avoid docker overwriting your local dev files with root permissions. -Note the `/code/target` cache is unique for each contract being compiled to limit -interference, while the registry cache is global. - -This is rather slow compared to local compilations, especially the first compile -of a given contract. The use of the two volume caches is very useful to speed up -following compiles of the same contract. - -This produces an `artifacts` directory with a `PROJECT_NAME.wasm`, as well as -`checksums.txt`, containing the Sha256 hash of the wasm file. -The wasm file is compiled deterministically (anyone else running the same -docker on the same git commit should get the identical file with the same Sha256 hash). -It is also stripped and minimized for upload to a blockchain (we will also -gzip it in the uploading process to make it even smaller). diff --git a/default/Importing.md b/default/Importing.md deleted file mode 100644 index 7dcec4f..0000000 --- a/default/Importing.md +++ /dev/null @@ -1,62 +0,0 @@ -# Importing - -In [Publishing](./Publishing.md), we discussed how you can publish your contract to the world. -This looks at the flip-side, how can you use someone else's contract (which is the same -question as how they will use your contract). Let's go through the various stages. - -## Verifying Artifacts - -Before using remote code, you most certainly want to verify it is honest. - -The simplest audit of the repo is to simply check that the artifacts in the repo -are correct. This involves recompiling the claimed source with the claimed builder -and validating that the locally compiled code (hash) matches the code hash that was -uploaded. This will verify that the source code is the correct preimage. Which allows -one to audit the original (Rust) source code, rather than looking at wasm bytecode. - -We have a script to do this automatic verification steps that can -easily be run by many individuals. Please check out -[`cosmwasm-verify`](https://github.com/CosmWasm/cosmwasm-verify/blob/master/README.md) -to see a simple shell script that does all these steps and easily allows you to verify -any uploaded contract. - -## Reviewing - -Once you have done the quick programatic checks, it is good to give at least a quick -look through the code. A glance at `examples/schema.rs` to make sure it is outputing -all relevant structs from `contract.rs`, and also ensure `src/lib.rs` is just the -default wrapper (nothing funny going on there). After this point, we can dive into -the contract code itself. Check the flows for the execute methods, any invariants and -permission checks that should be there, and a reasonable data storage format. - -You can dig into the contract as far as you want, but it is important to make sure there -are no obvious backdoors at least. - -## Decentralized Verification - -It's not very practical to do a deep code review on every dependency you want to use, -which is a big reason for the popularity of code audits in the blockchain world. We trust -some experts review in lieu of doing the work ourselves. But wouldn't it be nice to do this -in a decentralized manner and peer-review each other's contracts? Bringing in deeper domain -knowledge and saving fees. - -Luckily, there is an amazing project called [crev](https://github.com/crev-dev/cargo-crev/blob/master/cargo-crev/README.md) -that provides `A cryptographically verifiable code review system for the cargo (Rust) package manager`. - -I highly recommend that CosmWasm contract developers get set up with this. At minimum, we -can all add a review on a package that programmatically checked out that the json schemas -and wasm bytecode do match the code, and publish our claim, so we don't all rely on some -central server to say it validated this. As we go on, we can add deeper reviews on standard -packages. - -If you want to use `cargo-crev`, please follow their -[getting started guide](https://github.com/crev-dev/cargo-crev/blob/master/cargo-crev/src/doc/getting_started.md) -and once you have made your own *proof repository* with at least one *trust proof*, -please make a PR to the [`cawesome-wasm`]() repo with a link to your repo and -some public name or pseudonym that people know you by. This allows people who trust you -to also reuse your proofs. - -There is a [standard list of proof repos](https://github.com/crev-dev/cargo-crev/wiki/List-of-Proof-Repositories) -with some strong rust developers in there. This may cover dependencies like `serde` and `snafu` -but will not hit any CosmWasm-related modules, so we look to bootstrap a very focused -review community. diff --git a/default/LICENSE b/default/LICENSE deleted file mode 100644 index d645695..0000000 --- a/default/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/default/NOTICE b/default/NOTICE deleted file mode 100644 index 216c969..0000000 --- a/default/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright {{ "now" | date: "%Y" }} {{authors}} - -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/default/Publishing.md b/default/Publishing.md deleted file mode 100644 index df868b9..0000000 --- a/default/Publishing.md +++ /dev/null @@ -1,115 +0,0 @@ -# Publishing Contracts - -This is an overview of how to publish the contract's source code in this repo. -We use Cargo's default registry [crates.io](https://crates.io/) for publishing contracts written in Rust. - -## Preparation - -Ensure the `Cargo.toml` file in the repo is properly configured. In particular, you want to -choose a name starting with `cw-`, which will help a lot finding CosmWasm contracts when -searching on crates.io. For the first publication, you will probably want version `0.1.0`. -If you have tested this on a public net already and/or had an audit on the code, -you can start with `1.0.0`, but that should imply some level of stability and confidence. -You will want entries like the following in `Cargo.toml`: - -```toml -name = "cw-escrow" -version = "0.1.0" -description = "Simple CosmWasm contract for an escrow with arbiter and timeout" -repository = "https://github.com/confio/cosmwasm-examples" -``` - -You will also want to add a valid [SPDX license statement](https://spdx.org/licenses/), -so others know the rules for using this crate. You can use any license you wish, -even a commercial license, but we recommend choosing one of the following, unless you have -specific requirements. - -* Permissive: [`Apache-2.0`](https://spdx.org/licenses/Apache-2.0.html#licenseText) or [`MIT`](https://spdx.org/licenses/MIT.html#licenseText) -* Copyleft: [`GPL-3.0-or-later`](https://spdx.org/licenses/GPL-3.0-or-later.html#licenseText) or [`AGPL-3.0-or-later`](https://spdx.org/licenses/AGPL-3.0-or-later.html#licenseText) -* Commercial license: `Commercial` (not sure if this works, I cannot find examples) - -It is also helpful to download the LICENSE text (linked to above) and store this -in a LICENSE file in your repo. Now, you have properly configured your crate for use -in a larger ecosystem. - -### Updating schema - -To allow easy use of the contract, we can publish the schema (`schema/*.json`) together -with the source code. - -```sh -cargo schema -``` - -Ensure you check in all the schema files, and make a git commit with the final state. -This commit will be published and should be tagged. Generally, you will want to -tag with the version (eg. `v0.1.0`), but in the `cosmwasm-examples` repo, we have -multiple contracts and label it like `escrow-0.1.0`. Don't forget a -`git push && git push --tags` - -### Note on build results - -Build results like Wasm bytecode or expected hash don't need to be updated since -the don't belong to the source publication. However, they are excluded from packaging -in `Cargo.toml` which allows you to commit them to your git repository if you like. - -```toml -exclude = ["artifacts"] -``` - -A single source code can be built with multiple different optimizers, so -we should not make any strict assumptions on the tooling that will be used. - -## Publishing - -Now that your package is properly configured and all artifacts are committed, it -is time to share it with the world. -Please refer to the [complete instructions for any questions](https://rurust.github.io/cargo-docs-ru/crates-io.html), -but I will try to give a quick overview of the happy path here. - -### Registry - -You will need an account on [crates.io](https://crates.io) to publish a rust crate. -If you don't have one already, just click on "Log in with GitHub" in the top-right -to quickly set up a free account. Once inside, click on your username (top-right), -then "Account Settings". On the bottom, there is a section called "API Access". -If you don't have this set up already, create a new token and use `cargo login` -to set it up. This will now authenticate you with the `cargo` cli tool and allow -you to publish. - -### Uploading - -Once this is set up, make sure you commit the current state you want to publish. -Then try `cargo publish --dry-run`. If that works well, review the files that -will be published via `cargo package --list`. If you are satisfied, you can now -officially publish it via `cargo publish`. - -Congratulations, your package is public to the world. - -### Sharing - -Once you have published your package, people can now find it by -[searching for "cw-" on crates.io](https://crates.io/search?q=cw). -But that isn't exactly the simplest way. To make things easier and help -keep the ecosystem together, we suggest making a PR to add your package -to the [`cawesome-wasm`](https://github.com/cosmwasm/cawesome-wasm) list. - -### Organizations - -Many times you are writing a contract not as a solo developer, but rather as -part of an organization. You will want to allow colleagues to upload new -versions of the contract to crates.io when you are on holiday. -[These instructions show how]() you can set up your crate to allow multiple maintainers. - -You can add another owner to the crate by specifying their github user. Note, you will -now both have complete control of the crate, and they can remove you: - -`cargo owner --add ethanfrey` - -You can also add an existing github team inside your organization: - -`cargo owner --add github:confio:developers` - -The team will allow anyone who is currently in the team to publish new versions of the crate. -And this is automatically updated when you make changes on github. However, it will not allow -anyone in the team to add or remove other owners. diff --git a/default/README.md b/default/README.md deleted file mode 100644 index 8734338..0000000 --- a/default/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Archway Network Starter Pack - -This is a template to build smart contracts in Rust to run inside a -[Cosmos SDK](https://github.com/cosmos/cosmos-sdk) module on all chains that enable it. -To understand the framework better, please read the overview in the -[archway repo](https://github.com/archway-network/archway/blob/main/README.md), -and dig into the [archway docs](https://docs.archway.io). - -The below instructions assume you understand the theory and just want to get coding. - -## Creating a new project from a template - -Assuming you have a recent version of rust and cargo (v1.51.0+) installed -(via [rustup](https://rustup.rs/)), -then the following should get you a new repo to start a contract: - -Install [cargo-generate](https://github.com/ashleygwilliams/cargo-generate) and cargo-run-script. -If you didn't install them already, run the following commands: - -```sh -cargo install cargo-generate --features vendored-openssl -cargo install cargo-run-script -``` - -Now, use it to create your new contract. -Go to the folder in which you want to place it and run: - -```sh -cargo generate --git archway-network/archway-templates.git --name PROJECT_NAME default -``` - -You will now have a new folder called `PROJECT_NAME` (I hope you changed that to something else) -containing a simple working contract and build system that you can customize. - -## Create a Repo - -After generating, you have a initialized local git repo, but no commits, and no remote. -Go to a server (eg. github) and create a new upstream repo (called `YOUR-GIT-URL` below). -Then run the following: - -```sh -# this is needed to create a valid Cargo.lock file (see below) -cargo check -git branch -M main -git add . -git commit -m 'Initial Commit' -git remote add origin YOUR-GIT-URL -git push -u origin main -``` - -## CI Support - -We have template configurations for both [GitHub Actions](.github/workflows/Basic.yml) -and [Circle CI](.circleci/config.yml) in the generated project, so you can -get up and running with CI right away. - -One note is that the CI runs all `cargo` commands -with `--locked` to ensure it uses the exact same versions as you have locally. This also means -you must have an up-to-date `Cargo.lock` file, which is not auto-generated. -The first time you set up the project (or after adding any dep), you should ensure the -`Cargo.lock` file is updated, so the CI will test properly. This can be done simply by -running `cargo check` or `cargo unit-test`. - -## Using your project - -Once you have your custom repo, you should check out [Developing](./Developing.md) to explain -more on how to run tests and develop code. Or go through the -[online tutorial](https://docs.archway.io/docs/create/guides/my-first-dapp/start) to get a better feel -of how to develop. - -[Publishing](./Publishing.md) contains useful information on how to publish your contract -to the world, once you are ready to deploy it on a running blockchain. And -[Importing](./Importing.md) contains information about pulling in other contracts or crates -that have been published. - -Please replace this README file with information about your specific project. You can keep -the `Developing.md` and `Publishing.md` files as useful referenced, but please set some -proper description in the README. - -## Gitpod integration - -[Gitpod](https://www.gitpod.io/) container-based development platform will be enabled on your project by default. - -Workspace contains: - -- **rust**: for builds -- [wasmd](https://github.com/CosmWasm/wasmd): for local node setup and client -- **jq**: shell JSON manipulation tool - -Follow [Gitpod Getting Started](https://www.gitpod.io/docs/getting-started) and launch your workspace. diff --git a/default/cargo-generate.toml b/default/cargo-generate.toml deleted file mode 100644 index b5c5e3c..0000000 --- a/default/cargo-generate.toml +++ /dev/null @@ -1,5 +0,0 @@ -[template] -# Files listed here will not be processed by the template engine when a project is generated. -# This is needed when files contains curly brackets as in `v4-cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }}`. -# The files will be copied 1:1 to the target project. To avoid shipping them completely add them to `.genignore`. -exclude = [".circleci/config.yml"] diff --git a/default/examples/schema.rs b/default/examples/schema.rs deleted file mode 100644 index d778c95..0000000 --- a/default/examples/schema.rs +++ /dev/null @@ -1,20 +0,0 @@ -use std::fs::create_dir_all; -use std::path::PathBuf; - -use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; - -use {{crate_name}}::msg::{ExecuteMsg, HelloResponse, InstantiateMsg, QueryMsg}; -use {{crate_name}}::state::State; - -fn main() { - let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - out_dir.push("schema"); - create_dir_all(&out_dir).unwrap(); - remove_schemas(&out_dir).unwrap(); - - export_schema(&schema_for!(InstantiateMsg), &out_dir); - export_schema(&schema_for!(ExecuteMsg), &out_dir); - export_schema(&schema_for!(QueryMsg), &out_dir); - export_schema(&schema_for!(State), &out_dir); - export_schema(&schema_for!(HelloResponse), &out_dir); -} diff --git a/default/meta/README.md b/default/meta/README.md deleted file mode 100644 index 279d1db..0000000 --- a/default/meta/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# The meta folder - -This folder is ignored via the `.genignore` file. It contains meta files -that should not make it into the generated project. - -In particular, it is used for an AppVeyor CI script that runs on `cw-template` -itself (running the cargo-generate script, then testing the generated project). -The `.circleci` and `.github` directories contain scripts destined for any projects created from -this template. - -## Files - -- `appveyor.yml`: The AppVeyor CI configuration -- `test_generate.sh`: A script for generating a project from the template and - runnings builds and tests in it. This works almost like the CI script but - targets local UNIX-like dev environments. diff --git a/default/meta/appveyor.yml b/default/meta/appveyor.yml deleted file mode 100644 index 00f6d3f..0000000 --- a/default/meta/appveyor.yml +++ /dev/null @@ -1,61 +0,0 @@ -# This CI configuration tests the cw-template repository itself, -# not the resulting project. We want to ensure that -# 1. the template to project generation works -# 2. the template files are up to date -# -# We chose Appveyor for this task as it allows us to use an arbitrary config -# location. Furthermore it allows us to ship Circle CI and GitHub Actions configs -# generated for the resulting project. - -image: Ubuntu - -environment: - TOOLCHAIN: 1.51.0 - -services: - - docker - -cache: - - $HOME/.rustup/ -> meta/appveyor.yml - # For details about cargo caching see https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci - - $HOME/.cargo/bin/ -> meta/appveyor.yml - - $HOME/.cargo/registry/index/ -> meta/appveyor.yml - - $HOME/.cargo/registry/cache/ -> meta/appveyor.yml - - $HOME/.cargo/git/db/ -> meta/appveyor.yml - -install: - - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain "$TOOLCHAIN" -y - - source $HOME/.cargo/env - - rustc --version - - cargo --version - - rustup target add wasm32-unknown-unknown - - cargo install --features vendored-openssl cargo-generate || true - -build_script: - # No matter what is currently checked out by the CI (main, other branch, PR merge commit), - # we create a temporary local branch from that point with a constant name, which we need for - # cargo generate. - - git branch current-ci-checkout - - cd .. - - cargo generate --git cw-template --name testgen-ci --branch current-ci-checkout - - cd testgen-ci - - ls -lA - - cargo fmt -- --check - - cargo unit-test - - cargo wasm - - cargo schema - - docker build --pull -t "cosmwasm/cw-gitpod-base:${APPVEYOR_REPO_COMMIT}" . - - \[ "${APPVEYOR_REPO_BRANCH}" = "main" \] && image_tag=latest || image_tag=${APPVEYOR_REPO_TAG_NAME} - - docker tag "cosmwasm/cw-gitpod-base:${APPVEYOR_REPO_COMMIT}" "cosmwasm/cw-gitpod-base:${image_tag}" - -on_success: - # publish docker image - - docker login --password-stdin -u "$DOCKER_USER" <<<"$DOCKER_PASS" - - docker push - - docker logout - -branches: -# whitelist long living branches and tags - only: - # - main - - /v\d+\.\d+\.\d+/ \ No newline at end of file diff --git a/default/meta/test_generate.sh b/default/meta/test_generate.sh deleted file mode 100755 index b9aaa23..0000000 --- a/default/meta/test_generate.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -command -v shellcheck > /dev/null && shellcheck "$0" - -REPO_ROOT="$(realpath "$(dirname "$0")/..")" - -TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/cw-template.XXXXXXXXX") -PROJECT_NAME="testgen-local" - -( - echo "Navigating to $TMP_DIR" - cd "$TMP_DIR" - - GIT_BRANCH=$(git -C "$REPO_ROOT" branch --show-current) - - echo "Generating project from local repository (branch $GIT_BRANCH) ..." - cargo generate --git "$REPO_ROOT" --name "$PROJECT_NAME" --branch "$GIT_BRANCH" - - ( - cd "$PROJECT_NAME" - echo "This is what was generated" - ls -lA - - # Check formatting - echo "Checking formatting ..." - cargo fmt -- --check - - # Debug builds first to fail fast - echo "Running unit tests ..." - cargo unit-test - echo "Creating schema ..." - cargo schema - - echo "Building wasm ..." - cargo wasm - ) -) diff --git a/default/rustfmt.toml b/default/rustfmt.toml deleted file mode 100644 index 11a85e6..0000000 --- a/default/rustfmt.toml +++ /dev/null @@ -1,15 +0,0 @@ -# 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/default/schema/count_response.json b/default/schema/count_response.json deleted file mode 100644 index fa1e81f..0000000 --- a/default/schema/count_response.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "CountResponse", - "type": "object", - "required": [ - "count" - ], - "properties": { - "count": { - "type": "integer", - "format": "int32" - } - } -} diff --git a/default/schema/execute_msg.json b/default/schema/execute_msg.json deleted file mode 100644 index 6fa0a75..0000000 --- a/default/schema/execute_msg.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ExecuteMsg", - "anyOf": [ - { - "type": "object", - "required": [ - "increment" - ], - "properties": { - "increment": { - "type": "object" - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "reset" - ], - "properties": { - "reset": { - "type": "object", - "required": [ - "count" - ], - "properties": { - "count": { - "type": "integer", - "format": "int32" - } - } - } - }, - "additionalProperties": false - } - ] -} diff --git a/default/schema/instantiate_msg.json b/default/schema/instantiate_msg.json deleted file mode 100644 index e794ec1..0000000 --- a/default/schema/instantiate_msg.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "InstantiateMsg", - "type": "object", - "required": [ - "count" - ], - "properties": { - "count": { - "type": "integer", - "format": "int32" - } - } -} diff --git a/default/schema/query_msg.json b/default/schema/query_msg.json deleted file mode 100644 index be0245b..0000000 --- a/default/schema/query_msg.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "QueryMsg", - "anyOf": [ - { - "type": "object", - "required": [ - "get_count" - ], - "properties": { - "get_count": { - "type": "object" - } - }, - "additionalProperties": false - } - ] -} diff --git a/default/schema/state.json b/default/schema/state.json deleted file mode 100644 index e18725d..0000000 --- a/default/schema/state.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "State", - "type": "object", - "required": [ - "count", - "owner" - ], - "properties": { - "count": { - "type": "integer", - "format": "int32" - }, - "owner": { - "$ref": "#/definitions/Addr" - } - }, - "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" - } - } -} diff --git a/default/src/contract.rs b/default/src/contract.rs deleted file mode 100644 index 0c5d416..0000000 --- a/default/src/contract.rs +++ /dev/null @@ -1,123 +0,0 @@ -#[cfg(not(feature = "library"))] -use cosmwasm_std::entry_point; -use cosmwasm_std::{ - to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, -}; -use cw2::set_contract_version; - -use crate::error::ContractError; -use crate::msg::{ExecuteMsg, HelloResponse, InstantiateMsg, QueryMsg}; -use crate::state::{State, STATE}; - -// version info for migration info -const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn instantiate( - deps: DepsMut, - _env: Env, - info: MessageInfo, - _msg: InstantiateMsg, -) -> Result { - let state = State { - owner: info.sender.clone(), - }; - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - STATE.save(deps.storage, &state)?; - - Ok(Response::new() - .add_attribute("method", "instantiate") - .add_attribute("owner", info.sender)) -} - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn execute( - deps: DepsMut, - _env: Env, - _info: MessageInfo, - msg: ExecuteMsg, -) -> Result { - match msg { - ExecuteMsg::Dummy {} => try_execute(deps), - } -} - -pub fn try_execute(_deps: DepsMut) -> Result { - Err(ContractError::Std(StdError::generic_err("Not implemented"))) - // TODO: Ok(Response::new().add_attribute("method", "try_execute")) -} - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { - match msg { - QueryMsg::Hello {} => to_binary(&hello_world()?), - } -} - -fn hello_world() -> StdResult { - Ok(HelloResponse { - msg: String::from("Hello, Archway!"), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use cosmwasm_std::testing::{ - mock_dependencies, mock_dependencies_with_balance, mock_env, mock_info, - }; - use cosmwasm_std::{coins, from_binary}; - - #[test] - fn can_instantiate() { - let mut deps = mock_dependencies(); - - let res = instantiate_contract(deps.as_mut()); - assert_eq!(0, res.messages.len()); - - let owner = &res - .attributes - .iter() - .find(|a| a.key == "owner") - .unwrap() - .value; - assert_eq!("creator", owner); - } - - #[test] - fn can_execute() { - let mut deps = mock_dependencies_with_balance(&coins(2, "token")); - - instantiate_contract(deps.as_mut()); - - let info = mock_info("anyone", &coins(2, "token")); - let msg = ExecuteMsg::Dummy {}; - - // TODO: fix this test when execute() is implemented - let res = execute(deps.as_mut(), mock_env(), info, msg); - match res { - Err(ContractError::Std(StdError::GenericErr { msg })) => { - assert_eq!("Not implemented", msg) - } - _ => panic!("Must return not implemented error"), - } - } - - #[test] - fn can_query() { - let mut deps = mock_dependencies_with_balance(&coins(2, "token")); - - instantiate_contract(deps.as_mut()); - - let res = query(deps.as_ref(), mock_env(), QueryMsg::Hello {}).unwrap(); - let value: HelloResponse = from_binary(&res).unwrap(); - assert_eq!("Hello, Archway!", value.msg); - } - - fn instantiate_contract(deps: DepsMut) -> Response { - let msg = InstantiateMsg {}; - let info = mock_info("creator", &coins(1000, "token")); - instantiate(deps, mock_env(), info, msg).unwrap() - } -} diff --git a/default/src/error.rs b/default/src/error.rs deleted file mode 100644 index 4a69d8f..0000000 --- a/default/src/error.rs +++ /dev/null @@ -1,13 +0,0 @@ -use cosmwasm_std::StdError; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum ContractError { - #[error("{0}")] - Std(#[from] StdError), - - #[error("Unauthorized")] - Unauthorized {}, - // Add any other custom errors you like here. - // Look at https://docs.rs/thiserror/1.0.21/thiserror/ for details. -} diff --git a/default/src/lib.rs b/default/src/lib.rs deleted file mode 100644 index dfedc9d..0000000 --- a/default/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod contract; -mod error; -pub mod msg; -pub mod state; - -pub use crate::error::ContractError; diff --git a/default/src/msg.rs b/default/src/msg.rs deleted file mode 100644 index 6e4dd2e..0000000 --- a/default/src/msg.rs +++ /dev/null @@ -1,23 +0,0 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct InstantiateMsg {} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum ExecuteMsg { - Dummy {}, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum QueryMsg { - Hello {}, -} - -// We define a custom struct for each query response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct HelloResponse { - pub msg: String, -} diff --git a/default/src/state.rs b/default/src/state.rs deleted file mode 100644 index bc116fa..0000000 --- a/default/src/state.rs +++ /dev/null @@ -1,12 +0,0 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use cosmwasm_std::Addr; -use cw_storage_plus::Item; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct State { - pub owner: Addr, -} - -pub const STATE: Item = Item::new("state"); diff --git a/increment/.cargo/config b/increment/.cargo/config index af5698e..4fa7f37 100644 --- a/increment/.cargo/config +++ b/increment/.cargo/config @@ -1,4 +1,5 @@ [alias] wasm = "build --release --lib --target wasm32-unknown-unknown" +wasm-debug = "build --target wasm32-unknown-unknown" unit-test = "test --lib" schema = "run --bin schema" diff --git a/increment/Cargo.toml b/increment/Cargo.toml index 6574f9d..ff6988b 100644 --- a/increment/Cargo.toml +++ b/increment/Cargo.toml @@ -1,13 +1,12 @@ [package] name = "{{project-name}}" -version = "0.1.0" +version = "0.0.1" authors = ["{{authors}}"] edition = "2021" 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", + "artifacts/*", ] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -35,24 +34,24 @@ library = [] [package.metadata.scripts] optimize = """docker run --rm \ -e CARGO_TERM_COLOR=always \ - -v "$(pwd)":/code + -v "$(pwd)":/code \ -v "$(basename "$(pwd)")_cache":/code/target \ -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ --name "$(basename "$(pwd)")" \ - cosmwasm/rust-optimizer:0.12.12 + cosmwasm/rust-optimizer:0.14.0 """ [dependencies] archway-bindings = "0.1.0" -cosmwasm-schema = "1.2.2" -cosmwasm-std = "1.2.2" -cosmwasm-storage = "1.2.2" -cw-storage-plus = "1.0.1" -cw2 = "1.0.1" +cosmwasm-schema = "1.3.1" +cosmwasm-std = "1.3.1" +cosmwasm-storage = "1.3.1" +cw-storage-plus = "1.1.0" +cw2 = "1.1.0" schemars = "0.8.12" -serde = { version = "1.0.152", default-features = false, features = ["derive"] } -thiserror = { version = "1.0.38" } +serde = { version = "1.0.183", default-features = false, features = ["derive"] } +thiserror = "1.0.44" [dev-dependencies] -cw-multi-test = "0.16.2" +cw-multi-test = "0.16.5" diff --git a/increment/Developing.md b/increment/Developing.md index 55a37f6..0ce573a 100644 --- a/increment/Developing.md +++ b/increment/Developing.md @@ -78,7 +78,7 @@ docker run --rm \ -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ --name "$(basename "$(pwd)")" \ - cosmwasm/rust-optimizer:0.12.12 + cosmwasm/rust-optimizer:0.14.0 ``` Or, If you're on an arm64 machine, you should use a docker image built with arm64. @@ -91,7 +91,7 @@ docker run --rm \ -v "$(basename "$(pwd)")_registry_cache":/usr/local/cargo/registry \ -v "$(basename "$(pwd)")_cosmwasm_sccache":/root/.cache/sccache \ --name "$(basename "$(pwd)")" \ - cosmwasm/rust-optimizer-arm64:0.12.12 + cosmwasm/rust-optimizer-arm64:0.14.0 ``` We must mount the contract code to `/code`. You can use a absolute path instead diff --git a/increment/cargo-generate.toml b/increment/cargo-generate.toml index 72f4e4f..aef178b 100644 --- a/increment/cargo-generate.toml +++ b/increment/cargo-generate.toml @@ -4,15 +4,18 @@ # The files will be copied 1:1 to the target project. To avoid shipping them completely add them to `.genignore`. exclude = [".circleci/config.yml"] -[placeholders.minimal] -type = "bool" -prompt = """The full template includes some example logic in case you're new to CosmWasm smart contracts. -The minimal template assumes you already know how to write your own logic, and doesn't get in your way. +[placeholders.version] +type = "string" +choices = ["full", "minimal"] +prompt = """This template has 2 versions: -Would you like to generate the minimal template?""" -default = false +- The full template includes example logic in case you're new to CosmWasm smart contracts. +- The minimal template assumes you already know how to write your own logic, includes the bare minimum and doesn't get in your way. -[conditional.'minimal'] +Which version do you want to generate?""" +default = "full" + +[conditional.'version == "minimal"'] ignore = [ "Developing.md", "Importing.md", diff --git a/increment/src/contract.rs b/increment/src/contract.rs index 8df0eea..9671725 100644 --- a/increment/src/contract.rs +++ b/increment/src/contract.rs @@ -1,26 +1,26 @@ #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; -use cosmwasm_std::{% raw %}{{% endraw %}{% unless minimal %}to_binary, {% endunless %}Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult}; -{% if minimal %}// {% endif %}use cw2::set_contract_version; +use cosmwasm_std::{% raw %}{{% endraw %}{% unless version == "minimal" %}to_binary, {% endunless %}Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult}; +{% if version == "minimal" %}// {% endif %}use cw2::set_contract_version; use crate::error::ContractError; -use crate::msg::{ExecuteMsg, {% unless minimal %}GetCountResponse, {% endunless %}InstantiateMsg, QueryMsg}; -{% unless minimal %}use crate::state::{State, STATE}; +use crate::msg::{ExecuteMsg, {% unless version == "minimal" %}GetCountResponse, {% endunless %}InstantiateMsg, QueryMsg}; +{% unless version == "minimal" %}use crate::state::{State, STATE}; {% endunless %} -{% if minimal %}/* +{% if version == "minimal" %}/* {% endif %}// version info for migration info const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); -{% if minimal %}*/ +{% if version == "minimal" %}*/ {% endif %} #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( - {% if minimal %}_{% endif %}deps: DepsMut, + {% if version == "minimal" %}_{% endif %}deps: DepsMut, _env: Env, - {% if minimal %}_{% endif %}info: MessageInfo, - {% if minimal %}_{% endif %}msg: InstantiateMsg, + {% if version == "minimal" %}_{% endif %}info: MessageInfo, + {% if version == "minimal" %}_{% endif %}msg: InstantiateMsg, ) -> Result { - {% if minimal %}unimplemented!(){% else %}let state = State { + {% if version == "minimal" %}unimplemented!(){% else %}let state = State { count: msg.count, owner: info.sender.clone(), }; @@ -35,16 +35,16 @@ pub fn instantiate( #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( - {% if minimal %}_{% endif %}deps: DepsMut, + {% if version == "minimal" %}_{% endif %}deps: DepsMut, _env: Env, - {% if minimal %}_{% endif %}info: MessageInfo, - {% if minimal %}_{% endif %}msg: ExecuteMsg, + {% if version == "minimal" %}_{% endif %}info: MessageInfo, + {% if version == "minimal" %}_{% endif %}msg: ExecuteMsg, ) -> Result { - {% if minimal %}unimplemented!(){% else %}match msg { + {% if version == "minimal" %}unimplemented!(){% else %}match msg { ExecuteMsg::Increment {} => execute::increment(deps), ExecuteMsg::Reset { count } => execute::reset(deps, info, count), }{% endif %} -}{% unless minimal %} +}{% unless version == "minimal" %} pub mod execute { use super::*; @@ -71,11 +71,11 @@ pub mod execute { }{% endunless %} #[cfg_attr(not(feature = "library"), entry_point)] -pub fn query({% if minimal %}_{% endif %}deps: Deps, _env: Env, {% if minimal %}_{% endif %}msg: QueryMsg) -> StdResult { - {% if minimal %}unimplemented!(){% else %}match msg { +pub fn query({% if version == "minimal" %}_{% endif %}deps: Deps, _env: Env, {% if version == "minimal" %}_{% endif %}msg: QueryMsg) -> StdResult { + {% if version == "minimal" %}unimplemented!(){% else %}match msg { QueryMsg::GetCount {} => to_binary(&query::count(deps)?), }{% endif %} -}{% unless minimal %} +}{% unless version == "minimal" %} pub mod query { use super::*; @@ -87,7 +87,7 @@ pub mod query { }{% endunless %} #[cfg(test)] -mod tests {% raw %}{{% endraw %}{% unless minimal %} +mod tests {% raw %}{{% endraw %}{% unless version == "minimal" %} use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, from_binary}; diff --git a/increment/src/helpers.rs b/increment/src/helpers.rs index 62a6299..3956aa8 100644 --- a/increment/src/helpers.rs +++ b/increment/src/helpers.rs @@ -1,11 +1,11 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -{% if minimal %}use cosmwasm_std::{to_binary, Addr, CosmosMsg, StdResult, WasmMsg};{% else %}use cosmwasm_std::{ +{% if version == "minimal" %}use cosmwasm_std::{to_binary, Addr, CosmosMsg, StdResult, WasmMsg};{% else %}use cosmwasm_std::{ to_binary, Addr, CosmosMsg, CustomQuery, Querier, QuerierWrapper, StdResult, WasmMsg, WasmQuery, };{% endif %} -{% if minimal %}use crate::msg::ExecuteMsg;{% else %}use crate::msg::{ExecuteMsg, GetCountResponse, QueryMsg};{% endif %} +{% if version == "minimal" %}use crate::msg::ExecuteMsg;{% else %}use crate::msg::{ExecuteMsg, GetCountResponse, QueryMsg};{% endif %} /// CwTemplateContract is a wrapper around Addr that provides a lot of helpers /// for working with this. @@ -25,7 +25,7 @@ impl CwTemplateContract { funds: vec![], } .into()) - }{% unless minimal %} + }{% unless version == "minimal" %} /// Get Count pub fn count(&self, querier: &Q) -> StdResult diff --git a/increment/src/lib.rs b/increment/src/lib.rs index 4c7c0ef..c3814f1 100644 --- a/increment/src/lib.rs +++ b/increment/src/lib.rs @@ -1,7 +1,7 @@ pub mod contract; mod error; pub mod helpers; -{% unless minimal %}pub mod integration_tests; +{% unless version == "minimal" %}pub mod integration_tests; {% endunless %}pub mod msg; pub mod state; diff --git a/increment/src/msg.rs b/increment/src/msg.rs index adf6ef1..d9d87f8 100644 --- a/increment/src/msg.rs +++ b/increment/src/msg.rs @@ -1,24 +1,24 @@ use cosmwasm_schema::{cw_serde, QueryResponses}; #[cw_serde] -pub struct InstantiateMsg {% raw %}{{% endraw %}{% unless minimal %} +pub struct InstantiateMsg {% raw %}{{% endraw %}{% unless version == "minimal" %} pub count: i32, {% endunless %}} #[cw_serde] -pub enum ExecuteMsg {% raw %}{{% endraw %}{% unless minimal %} +pub enum ExecuteMsg {% raw %}{{% endraw %}{% unless version == "minimal" %} Increment {}, Reset { count: i32 }, {% endunless %}} #[cw_serde] #[derive(QueryResponses)] -pub enum QueryMsg {% raw %}{{% endraw %}{% unless minimal %} +pub enum QueryMsg {% raw %}{{% endraw %}{% unless version == "minimal" %} // GetCount returns the current count as a json-encoded number #[returns(GetCountResponse)] GetCount {}, {% endunless %}} -{% unless minimal %} +{% unless version == "minimal" %} // We define a custom struct for each query response #[cw_serde] pub struct GetCountResponse { diff --git a/increment/src/state.rs b/increment/src/state.rs index 50aa373..2c65c4c 100644 --- a/increment/src/state.rs +++ b/increment/src/state.rs @@ -1,4 +1,4 @@ -{% unless minimal %}use schemars::JsonSchema; +{% unless version == "minimal" %}use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::Addr;