diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 00000000..c3c61032 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,61 @@ +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: + - main + - docker-tagged: + filters: + tags: + only: + - /^v.*/ + branches: + ignore: + - /.*/ + requires: + - docker-image \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..3d36f20b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.rs] +indent_size = 4 diff --git a/.github/workflows/Basic.yml b/.github/workflows/Basic.yml new file mode 100644 index 00000000..e2a8f429 --- /dev/null +++ b/.github/workflows/Basic.yml @@ -0,0 +1,67 @@ +# 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: + profile: minimal + toolchain: stable + target: wasm32-unknown-unknown + override: true + + - name: Compile WASM contract + uses: actions-rs/cargo@v1 + with: + command: build + args: --release --target wasm32-unknown-unknown + 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: + profile: minimal + toolchain: stable + override: true + 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: run + args: --example schema + + - name: Schema Changes + # fails if any changes not committed + run: git diff --exit-code schema \ No newline at end of file diff --git a/.github/workflows/Release.yml b/.github/workflows/Release.yml new file mode 100644 index 00000000..af2f8d3f --- /dev/null +++ b/.github/workflows/Release.yml @@ -0,0 +1,35 @@ +name: release wasm + +on: + release: + types: [created] + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v2 + - name: Install cargo-run-script + uses: actions-rs/cargo@v1 + with: + command: install + args: cargo-run-script + - name: Run cargo optimize + uses: actions-rs/cargo@v1 + with: + command: run-script + args: optimize + - name: Get release ID + id: get_release + uses: bruceadams/get-release@v1.2.3 + env: + GITHUB_TOKEN: ${{ github.token }} + - name: Upload optimized wasm + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: ./artifacts/*.wasm + tag: ${{ github.ref }} + overwrite: true + file_glob: true \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..bc2652d9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,23 @@ +name: Contract CI + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: wasm32-unknown-unknown + override: true + - name: Run tests + run: cargo test --verbose + - name: Build WASM + run: cargo build --release --target wasm32-unknown-unknown \ No newline at end of file diff --git a/.gitignore b/.gitignore index 4d29575d..e69de29b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js - -# testing -/coverage - -# production -/build - -# misc -.DS_Store -.env.local -.env.development.local -.env.test.local -.env.production.local - -npm-debug.log* -yarn-debug.log* -yarn-error.log* diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile new file mode 100644 index 00000000..bff8bc53 --- /dev/null +++ b/.gitpod.Dockerfile @@ -0,0 +1,17 @@ +### 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/.gitpod.yml b/.gitpod.yml new file mode 100644 index 00000000..d03610c2 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,10 @@ +image: cosmwasm/cw-gitpod-base:v0.16 + +vscode: + extensions: + - rust-lang.rust + +tasks: + - name: Dependencies & Build + init: | + cargo build diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..32b1c666 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,838 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom", + "once_cell", + "version_check", +] + +[[package]] +name = "anyhow" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + +[[package]] +name = "bech32" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d86b93f97252c47b41663388e6d155714a9d0c398b99f1005cbc5f978b29f445" + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bnum" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56953345e39537a3e18bdaeba4cb0c58a78c1f61f361dc0fa7c5c7340ae87c5f" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cosmwasm-crypto" +version = "1.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58535cbcd599b3c193e3967c8292fe1dbbb5de7c2a2d87380661091dd4744044" +dependencies = [ + "digest 0.10.7", + "ed25519-zebra", + "k256", + "rand_core 0.6.4", + "thiserror", +] + +[[package]] +name = "cosmwasm-derive" +version = "1.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8e07de16c800ac82fd188d055ecdb923ead0cf33960d3350089260bb982c09f" +dependencies = [ + "syn 1.0.109", +] + +[[package]] +name = "cosmwasm-schema" +version = "1.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d388adfa9cb449557a92e9318121ac1a481fc4f599213b03a5b62699b403b4" +dependencies = [ + "cosmwasm-schema-derive", + "schemars", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "cosmwasm-schema-derive" +version = "1.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2411b389e56e6484f81ba955b758d02522d620c98fc960c4bd2251d48b7aa19f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "cosmwasm-std" +version = "1.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c21fde95ccd20044a23c0ac6fd8c941f3e8c158169dc94b5aa6491a2d9551a8d" +dependencies = [ + "base64", + "bech32", + "bnum", + "cosmwasm-crypto", + "cosmwasm-derive", + "derivative", + "forward_ref", + "hex", + "schemars", + "serde", + "serde-json-wasm", + "sha2 0.10.8", + "static_assertions", + "thiserror", +] + +[[package]] +name = "cosmwasm-storage" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66de2ab9db04757bcedef2b5984fbe536903ada4a8a9766717a4a71197ef34f6" +dependencies = [ + "cosmwasm-std", + "serde", +] + +[[package]] +name = "cpufeatures" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61" +dependencies = [ + "byteorder", + "digest 0.9.0", + "rand_core 0.5.1", + "subtle", + "zeroize", +] + +[[package]] +name = "cw-multi-test" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc392a5cb7e778e3f90adbf7faa43c4db7f35b6623224b08886d796718edb875" +dependencies = [ + "anyhow", + "bech32", + "cosmwasm-std", + "cw-storage-plus", + "cw-utils", + "derivative", + "itertools", + "prost", + "schemars", + "serde", + "sha2 0.10.8", + "thiserror", +] + +[[package]] +name = "cw-otc-dex" +version = "0.1.0" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cosmwasm-storage", + "cw-multi-test", + "cw-storage-plus", + "cw2", + "cw20", + "schemars", + "serde", + "thiserror", +] + +[[package]] +name = "cw-storage-plus" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5ff29294ee99373e2cd5fd21786a3c0ced99a52fec2ca347d565489c61b723c" +dependencies = [ + "cosmwasm-std", + "schemars", + "serde", +] + +[[package]] +name = "cw-utils" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4a657e5caacc3a0d00ee96ca8618745d050b8f757c709babafb81208d4239c" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw2", + "schemars", + "semver", + "serde", + "thiserror", +] + +[[package]] +name = "cw2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6c120b24fbbf5c3bedebb97f2cc85fbfa1c3287e09223428e7e597b5293c1fa" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-storage-plus", + "schemars", + "semver", + "serde", + "thiserror", +] + +[[package]] +name = "cw20" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e39bb20534e25a1cd0386727f0038f4da294e5e535729ba3ef54055246abd" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-utils", + "schemars", + "serde", +] + +[[package]] +name = "der" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "dyn-clone" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519-zebra" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c24f403d068ad0b359e577a77f92392118be3f3c927538f2bb544a5ecd828c6" +dependencies = [ + "curve25519-dalek", + "hashbrown", + "hex", + "rand_core 0.6.4", + "serde", + "sha2 0.9.9", + "zeroize", +] + +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "forward_ref" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8cbd1169bd7b4a0a20d92b9af7a7e0422888bd38a6f5ec29c1fd8c1558a272e" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "once_cell", + "sha2 0.10.8", + "signature", +] + +[[package]] +name = "libc" +version = "0.2.162" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "once_cell" +version = "1.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "proc-macro2" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.87", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "schemars" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.87", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" + +[[package]] +name = "serde" +version = "1.0.214" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde-json-wasm" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9213a07d53faa0b8dd81e767a54a8188a242fdb9be99ab75ec576a774bfdd7" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.214" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + +[[package]] +name = "serde_json" +version = "1.0.132" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures", + "digest 0.9.0", + "opaque-debug", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.7", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02dd99dc800bbb97186339685293e1cc5d9df1f8fae2d0aecd9ff1c77efea892" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c61ec9a6f64d2793d8a45faba21efbe3ced62a886d44c36a009b2b519b4c7e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-ident" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..01a29e70 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,54 @@ +[package] +name = "cw-otc-dex" +description = "CosmWasm OTC Trading Platform" +version = "0.1.0" +authors = ["anilcse "] +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[[example]] +name = "schema" +path = "examples/schema.rs" + + +[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 \ + --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.14.0 +""" + +[dependencies] +cosmwasm-schema = "1.5.0" +cosmwasm-std = "1.5.0" +cosmwasm-storage = "1.5.0" +cw-storage-plus = "1.1.0" +cw2 = "1.1.1" +cw20 = "1.1.1" +schemars = "0.8.15" +serde = { version = "1.0.188", default-features = false, features = ["derive"] } +thiserror = "1.0.49" + +[dev-dependencies] +cw-multi-test = "0.20.0" \ No newline at end of file diff --git a/Developing.md b/Developing.md new file mode 100644 index 00000000..1b3245e3 --- /dev/null +++ b/Developing.md @@ -0,0 +1,104 @@ +# 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.58.1+). + +## 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.58.1+. + +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=/target \ + --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ + cosmwasm/optimizer:0.15.0 +``` + +Or, If you're on an arm64 machine, you should use a docker image built with arm64. + +```sh +docker run --rm -v "$(pwd)":/code \ + --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ + --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ + cosmwasm/optimizer-arm64:0.15.0 +``` + +We must mount the contract code to `/code`. You can use an absolute path instead +of `$(pwd)` if you don't want to `cd` to the directory first. The other two +volumes are nice for speedup. +Note the `/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/Importing.md b/Importing.md new file mode 100644 index 00000000..2601dd8d --- /dev/null +++ b/Importing.md @@ -0,0 +1,62 @@ +# 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 programmatic 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 outputting +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/LICENSE b/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [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/NOTICE b/NOTICE new file mode 100644 index 00000000..57c6d088 --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright 2024 anilcse + +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/Publishing.md b/Publishing.md new file mode 100644 index 00000000..c94f8675 --- /dev/null +++ b/Publishing.md @@ -0,0 +1,115 @@ +# 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 +they 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/README.md b/README.md index 58beeacc..19366fb9 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,127 @@ -# Getting Started with Create React App +# cosmos-otc-platform ๐ŸŒŸ + +A decentralized Over-The-Counter (OTC) trading platform built with CosmWasm. This smart contract enables secure, transparent, and efficient OTC trading of tokens with customizable discount rates and bidding mechanisms. + +## Features ๐Ÿš€ + +- **Flexible Deal Creation**: Sellers can create OTC deals with: + - Custom token selection + - Configurable discount percentages + - Minimum price protection + - Minimum cap requirements + - Customizable bidding timeframes + +- **Advanced Bidding System**: + - Buyers can place bids with desired quantities + - Maximum price protection for buyers + - Real-time bid updates and withdrawals + - Automatic bid sorting by discount rates -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). +- **Secure Deal Settlement**: + - Automatic deal conclusion at specified time + - Fair distribution prioritizing lowest discount bids + - Automatic refunds for unsuccessful bids + - Platform fee management -## Available Scripts +## Prerequisites ๐Ÿ“‹ -In the project directory, you can run: +- Rust 1.63.0+ +- [wasmd](https://github.com/CosmWasm/wasmd) 0.30.0+ +- [cargo-generate](https://github.com/cargo-generate/cargo-generate) -### `npm start` +## Installation ๐Ÿ› ๏ธ -Runs the app in the development mode.\ -Open [http://localhost:3000](http://localhost:3000) to view it in your browser. +```bash +# Clone the repository +git clone https://github.com/yourusername/cosmos-otc-platform +cd cosmos-otc-platform -The page will reload when you make changes.\ -You may also see any lint errors in the console. +# Compile the contract +cargo build -### `npm test` +# Run tests +cargo test -Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. +# Generate Wasm binary +cargo wasm +``` -### `npm run build` +## Usage ๐Ÿ“ -Builds the app for production to the `build` folder.\ -It correctly bundles React in production mode and optimizes the build for the best performance. +### Creating an OTC Deal -The build is minified and the filenames include the hashes.\ -Your app is ready to be deployed! +```rust +let msg = ExecuteMsg::CreateDeal { + sell_token: "token_address", + total_amount: Uint128::new(1000000), + min_price: Uint128::new(100), + discount_percentage: 10, + min_cap: Uint128::new(500000), + bid_start_time: 1234567890, + bid_end_time: 1234657890, + conclude_time: 1234747890, +}; +``` -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. +### Placing a Bid -### `npm run eject` +```rust +let msg = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(100000), + discount_percentage: 5, + max_price: Some(Uint128::new(110)), +}; +``` -**Note: this is a one-way operation. Once you `eject`, you can't go back!** +## Contract Architecture ๐Ÿ—๏ธ -If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. +``` +src/ +โ”œโ”€โ”€ lib.rs # Entry point +โ”œโ”€โ”€ contract.rs # Core contract logic +โ”œโ”€โ”€ msg.rs # Message definitions +โ”œโ”€โ”€ state.rs # State management +โ”œโ”€โ”€ error.rs # Error handling +โ””โ”€โ”€ helpers.rs # Utility functions +``` -Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. +## Testing ๐Ÿงช -You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. +```bash +# Run all tests +cargo test -## Learn More +# Run specific test +cargo test test_create_deal +``` -You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). +## Security Considerations ๐Ÿ”’ -To learn React, check out the [React documentation](https://reactjs.org/). +- All monetary operations are atomic +- Time-based validations prevent premature or late actions +- Minimum price protection for sellers +- Maximum price protection for buyers +- Automatic refund mechanism +- Platform fee validation + +## Contributing ๐Ÿค -### Code Splitting +1. Fork the repository +2. Create your feature branch (`git checkout -b feature/AmazingFeature`) +3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) +4. Push to the branch (`git push origin feature/AmazingFeature`) +5. Open a Pull Request -This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) +## Contact ๐Ÿ“ง -### Analyzing the Bundle Size +Anil - [@anilcse](https://twitter.com/anilcse_) -This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) +Project Link: [https://github.com/vitwit/cw-otc-dex](https://github.com/vitwit/cw-otc-dex) -### Making a Progressive Web App +## Acknowledgments ๐Ÿ™ -This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) +- CosmWasm team for the amazing smart contract platform -### Advanced Configuration - -This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) - -### Deployment - -This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) - -### `npm run build` fails to minify - -This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) +--- +Made with โค๏ธ for the Cosmos ecosystem diff --git a/examples/schema.rs b/examples/schema.rs new file mode 100644 index 00000000..0be3c1ca --- /dev/null +++ b/examples/schema.rs @@ -0,0 +1,23 @@ +// examples/schema.rs + +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use cw_otc_dex::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; +use cw_otc_dex::state::{Bid, Config, Deal}; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(Config), &out_dir); + export_schema(&schema_for!(Deal), &out_dir); + export_schema(&schema_for!(Bid), &out_dir); +} diff --git a/src/bin/schema.rs b/src/bin/schema.rs new file mode 100644 index 00000000..c74eac7f --- /dev/null +++ b/src/bin/schema.rs @@ -0,0 +1,21 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use cw_otc_dex::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; +use cw_otc_dex::state::{Bid, Config, Deal}; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(Config), &out_dir); + export_schema(&schema_for!(Deal), &out_dir); + export_schema(&schema_for!(Bid), &out_dir); +} diff --git a/src/contract.rs b/src/contract.rs new file mode 100644 index 00000000..6b9fd0d9 --- /dev/null +++ b/src/contract.rs @@ -0,0 +1,773 @@ +use crate::error::ContractError; +use crate::helpers::{ + calculate_platform_fee, create_payment_msg, create_token_transfer_msg, get_sorted_bids, + validate_deal_times, +}; +use crate::msg::{ExecuteMsg, InstantiateMsg}; +use crate::state::{Bid, Config, Deal, BIDS, CONFIG, DEALS, DEAL_COUNTER}; +use cosmwasm_std::Addr; +use cosmwasm_std::StdError; +use cosmwasm_std::{ + entry_point, to_binary, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Order, Response, + StdResult, Storage, Uint128, +}; +use cw2::set_contract_version; + +use crate::msg::{BidResponse, DealResponse, DealStatsResponse, DealsResponse, QueryMsg}; +use cw_storage_plus::Bound; + +/// Contract name and version info for migration +const CONTRACT_NAME: &str = "crates.io:cosmos-otc-platform"; +const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// Initializes the contract with the specified configuration +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + _env: Env, + info: MessageInfo, + msg: InstantiateMsg, +) -> Result { + // Validate platform fee percentage (must be between 0 and 10000) + if msg.platform_fee_percentage > 10000 { + return Err(ContractError::InvalidTimeParameters { + reason: "Platform fee percentage must not exceed 100%".to_string(), + }); + } + + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + + let config = Config { + platform_fee_percentage: msg.platform_fee_percentage, + }; + + CONFIG.save(deps.storage, &config)?; + DEAL_COUNTER.save(deps.storage, &0u64)?; + + Ok(Response::new() + .add_attribute("method", "instantiate") + .add_attribute("owner", info.sender)) +} + +/// Handles all execute messages +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::CreateDeal { + sell_token, + total_amount, + min_price, + discount_percentage, + min_cap, + bid_start_time, + bid_end_time, + conclude_time, + } => execute_create_deal( + deps, + env, + info, + sell_token, + total_amount, + min_price, + discount_percentage, + min_cap, + bid_start_time, + bid_end_time, + conclude_time, + ), + ExecuteMsg::PlaceBid { + deal_id, + amount, + discount_percentage, + max_price, + } => execute_place_bid( + deps, + env, + info, + deal_id, + amount, + discount_percentage, + max_price, + ), + ExecuteMsg::UpdateBid { + deal_id, + new_amount, + new_discount_percentage, + new_max_price, + } => execute_update_bid( + deps, + env, + info, + deal_id, + new_amount, + new_discount_percentage, + new_max_price, + ), + ExecuteMsg::WithdrawBid { deal_id } => execute_withdraw_bid(deps, env, info, deal_id), + ExecuteMsg::ConcludeDeal { deal_id } => execute_conclude_deal(deps, env, info, deal_id), + } +} + +/// Creates a new OTC deal +pub fn execute_create_deal( + deps: DepsMut, + env: Env, + info: MessageInfo, + sell_token: String, + total_amount: Uint128, + min_price: Uint128, + discount_percentage: u64, + min_cap: Uint128, + bid_start_time: u64, + bid_end_time: u64, + conclude_time: u64, +) -> Result { + // Validate time parameters + validate_deal_times( + bid_start_time, + bid_end_time, + conclude_time, + env.block.time.seconds(), + )?; + + // Validate discount percentage + if discount_percentage > 10000 { + return Err(ContractError::InvalidTimeParameters { + reason: "Discount percentage must not exceed 100%".to_string(), + }); + } + + // Calculate and validate platform fee + let config = CONFIG.load(deps.storage)?; + let platform_fee = calculate_platform_fee(total_amount, config.platform_fee_percentage)?; + + // Ensure seller has sent enough platform fee + let provided_fee = info + .funds + .iter() + .find(|c| c.denom == "uusd") // Replace with your desired denomination + .map(|c| c.amount) + .unwrap_or_default(); + + if provided_fee < platform_fee { + return Err(ContractError::InsufficientPlatformFee { + required: platform_fee.u128(), + provided: provided_fee.u128(), + }); + } + + // Create and save new deal + let deal_id = DEAL_COUNTER.load(deps.storage)? + 1; + DEAL_COUNTER.save(deps.storage, &deal_id)?; + + let deal = Deal { + seller: info.sender.to_string(), + sell_token, + total_amount, + min_price, + discount_percentage, + min_cap, + bid_start_time, + bid_end_time, + conclude_time, + is_concluded: false, + total_bids_amount: Uint128::zero(), + }; + + DEALS.save(deps.storage, deal_id, &deal)?; + + Ok(Response::new() + .add_attribute("method", "create_deal") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("seller", info.sender)) +} + +/// Places a new bid on an existing deal +pub fn execute_place_bid( + deps: DepsMut, + env: Env, + info: MessageInfo, + deal_id: u64, + amount: Uint128, + discount_percentage: u64, + max_price: Option, +) -> Result { + let deal = DEALS.load(deps.storage, deal_id)?; + + // Validate bid timing + let current_time = env.block.time.seconds(); + if current_time < deal.bid_start_time { + return Err(ContractError::BiddingNotStarted {}); + } + if current_time >= deal.bid_end_time { + return Err(ContractError::BiddingEnded {}); + } + + // Validate bid amount + if amount.is_zero() { + return Err(ContractError::InvalidBidAmount { + reason: "Bid amount must be greater than zero".to_string(), + }); + } + + // Validate discount percentage + if discount_percentage > 10000 { + return Err(ContractError::InvalidBidAmount { + reason: "Discount percentage must not exceed 100%".to_string(), + }); + } + + let bid = Bid { + bidder: info.sender.to_string(), + amount, + discount_percentage, + max_price, + }; + + BIDS.save(deps.storage, (deal_id, &info.sender), &bid)?; + + // Update total bids amount + let new_total = deal.total_bids_amount + amount; + DEALS.update(deps.storage, deal_id, |deal_opt| -> StdResult<_> { + let mut deal = deal_opt.unwrap(); + deal.total_bids_amount = new_total; + Ok(deal) + })?; + + Ok(Response::new() + .add_attribute("method", "place_bid") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("bidder", info.sender) + .add_attribute("amount", amount)) +} + +/// Updates an existing bid +pub fn execute_update_bid( + deps: DepsMut, + env: Env, + info: MessageInfo, + deal_id: u64, + new_amount: Uint128, + new_discount_percentage: u64, + new_max_price: Option, +) -> Result { + let deal = DEALS.load(deps.storage, deal_id)?; + + // Validate timing + if env.block.time.seconds() >= deal.bid_end_time { + return Err(ContractError::BiddingEnded {}); + } + + // Load existing bid + let old_bid = BIDS.load(deps.storage, (deal_id, &info.sender))?; + + // Update total bids amount + let amount_diff = new_amount.checked_sub(old_bid.amount)?; + DEALS.update(deps.storage, deal_id, |deal_opt| -> StdResult<_> { + let mut deal = deal_opt.unwrap(); + deal.total_bids_amount = deal.total_bids_amount.checked_add(amount_diff)?; + Ok(deal) + })?; + + // Save updated bid + let new_bid = Bid { + bidder: info.sender.to_string(), + amount: new_amount, + discount_percentage: new_discount_percentage, + max_price: new_max_price, + }; + BIDS.save(deps.storage, (deal_id, &info.sender), &new_bid)?; + + Ok(Response::new() + .add_attribute("method", "update_bid") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("bidder", info.sender)) +} + +/// Withdraws an existing bid +pub fn execute_withdraw_bid( + deps: DepsMut, + env: Env, + info: MessageInfo, + deal_id: u64, +) -> Result { + let deal = DEALS.load(deps.storage, deal_id)?; + + // Validate timing + if env.block.time.seconds() >= deal.bid_end_time { + return Err(ContractError::BiddingEnded {}); + } + + // Load and remove bid + let bid = BIDS.load(deps.storage, (deal_id, &info.sender))?; + BIDS.remove(deps.storage, (deal_id, &info.sender)); + + // Update total bids amount + DEALS.update(deps.storage, deal_id, |deal_opt| -> StdResult<_> { + let mut deal = deal_opt.unwrap(); + deal.total_bids_amount = deal.total_bids_amount.checked_sub(bid.amount)?; + Ok(deal) + })?; + + Ok(Response::new() + .add_attribute("method", "withdraw_bid") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("bidder", info.sender)) +} + +/// Concludes an OTC deal by processing all bids and distributing tokens +/// +/// # Deal Conclusion Process +/// 1. Validates deal timing and status +/// 2. Checks if minimum cap is met +/// 3. If min cap not met: refunds all bidders +/// 4. If min cap met: +/// - Sorts bids by discount (lowest first) +/// - Processes bids until all tokens are allocated +/// - Transfers tokens to successful bidders +/// - Transfers payments to seller +/// - Refunds unsuccessful bidders +/// +/// # Arguments +/// * `deps` - Mutable dependencies for storage access +/// * `env` - Environment variables, primarily used for time validation +/// * `_info` - Message information (unused but kept for consistency) +/// * `deal_id` - Identifier of the deal to conclude +/// +/// # Returns +/// * `Response` - Success response with transfer messages and events +/// * `ContractError` - Various error conditions that might occur +pub fn execute_conclude_deal( + deps: DepsMut, + env: Env, + _info: MessageInfo, + deal_id: u64, +) -> Result { + // Load deal data + let mut deal = DEALS.load(deps.storage, deal_id)?; + + // Validation: Check timing and conclusion status + if env.block.time.seconds() < deal.conclude_time { + return Err(ContractError::ConclusionTimeNotReached {}); + } + if deal.is_concluded { + return Err(ContractError::DealAlreadyConcluded {}); + } + + // Case 1: Minimum cap not met - refund all bidders + if deal.total_bids_amount < deal.min_cap { + let refund_messages = process_failed_deal(deps.storage, deal_id)?; + + // Mark deal as concluded + deal.is_concluded = true; + DEALS.save(deps.storage, deal_id, &deal)?; + + return Ok(Response::new() + .add_messages(refund_messages) + .add_attribute("method", "conclude_deal_refund") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("reason", "min_cap_not_met") + .add_attribute("total_refunded", deal.total_bids_amount)); + } + + // Case 2: Process successful deal + let (messages, stats) = process_successful_deal(deps.storage, &deal, deal_id)?; + + // Mark deal as concluded + deal.is_concluded = true; + DEALS.save(deps.storage, deal_id, &deal)?; + + Ok(Response::new() + .add_messages(messages) + .add_attribute("method", "conclude_deal") + .add_attribute("deal_id", deal_id.to_string()) + .add_attribute("tokens_sold", stats.tokens_sold) + .add_attribute("total_payment", stats.total_payment) + .add_attribute("successful_bids", stats.successful_bids.to_string()) + .add_attribute("refunded_bids", stats.refunded_bids.to_string())) +} + +/// Helper struct to track deal conclusion statistics +struct DealStats { + tokens_sold: Uint128, + total_payment: Uint128, + successful_bids: u32, + refunded_bids: u32, +} + +/// Processes a failed deal by refunding all bidders +fn process_failed_deal( + storage: &dyn Storage, + deal_id: u64, +) -> Result, ContractError> { + let mut messages: Vec = vec![]; + let bids = get_sorted_bids(storage, deal_id)?; + + for (bidder, bid) in bids { + messages.push(create_payment_msg( + bidder, bid.amount, "uusd", // Replace with actual denom + )); + } + + Ok(messages) +} + +/// Processes a successful deal by allocating tokens and handling payments +fn process_successful_deal( + storage: &dyn Storage, + deal: &Deal, + deal_id: u64, +) -> Result<(Vec, DealStats), ContractError> { + let mut messages: Vec = vec![]; + let mut stats = DealStats { + tokens_sold: Uint128::zero(), + total_payment: Uint128::zero(), + successful_bids: 0, + refunded_bids: 0, + }; + + let mut remaining_tokens = deal.total_amount; + let bids = get_sorted_bids(storage, deal_id)?; + + // Process bids from lowest to highest discount + for (bidder, bid) in bids { + if remaining_tokens.is_zero() { + // Refund remaining bids + messages.push(create_payment_msg(bidder, bid.amount, "uusd")); + stats.refunded_bids += 1; + continue; + } + + // Calculate token allocation + let tokens_to_receive = std::cmp::min(bid.amount, remaining_tokens); + + // Calculate final price with discount + let base_price = tokens_to_receive.multiply_ratio(deal.min_price, Uint128::new(1u128)); + let discount = base_price.multiply_ratio(bid.discount_percentage, 100u128); + let final_price = base_price.checked_sub(discount)?; + + // Check if price meets buyer's max price constraint + if let Some(max_price) = bid.max_price { + if final_price > max_price { + messages.push(create_payment_msg(bidder, bid.amount, "uusd")); + stats.refunded_bids += 1; + continue; + } + } + + // Process successful bid + + // 1. Transfer tokens to buyer + messages.push(create_token_transfer_msg( + deal.sell_token.clone(), + bidder.clone(), + tokens_to_receive, + )?); + + // 2. Transfer payment to seller + messages.push(create_payment_msg(deal.seller.clone(), final_price, "uusd")); + + // Update running totals + remaining_tokens = remaining_tokens.checked_sub(tokens_to_receive)?; + stats.tokens_sold += tokens_to_receive; + stats.total_payment += final_price; + stats.successful_bids += 1; + } + + // Validate all tokens are accounted for + if stats.tokens_sold + remaining_tokens != deal.total_amount { + return Err(ContractError::InvalidBidAmount { + reason: "Token allocation mismatch".to_string(), + }); + } + + Ok((messages, stats)) +} + +const DEFAULT_LIMIT: u32 = 10; +const MAX_LIMIT: u32 = 30; + +pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { + let response = match msg { + QueryMsg::GetDeal { deal_id } => to_binary(&query_deal(deps, deal_id)?), + QueryMsg::ListDeals { start_after, limit } => { + to_binary(&list_deals(deps, start_after, limit)?) + } + QueryMsg::GetBid { deal_id, bidder } => to_binary(&query_bid(deps, deal_id, bidder)?), + QueryMsg::ListBidsForDeal { + deal_id, + start_after, + limit, + } => to_binary(&list_bids_for_deal(deps, deal_id, start_after, limit)?), + QueryMsg::ListDealsBySeller { + seller, + start_after, + limit, + } => to_binary(&list_deals_by_seller(deps, seller, start_after, limit)?), + QueryMsg::ListBidsByBidder { + bidder, + start_after, + limit, + } => to_binary(&list_bids_by_bidder(deps, bidder, start_after, limit)?), + QueryMsg::ListActiveDeals { start_after, limit } => { + to_binary(&list_active_deals(deps, env, start_after, limit)?) + } + QueryMsg::ListDealsByStatus { + is_concluded, + start_after, + limit, + } => to_binary(&list_deals_by_status( + deps, + is_concluded, + start_after, + limit, + )?), + QueryMsg::GetConfig {} => to_binary(&query_config(deps)?), + QueryMsg::GetDealStats { deal_id } => to_binary(&query_deal_stats(deps, env, deal_id)?), + }; + Ok(response?) +} + +// Update return types of query functions to use StdResult instead of Result<_, ContractError> +pub fn query_deal(deps: Deps, deal_id: u64) -> StdResult { + let deal = DEALS + .load(deps.storage, deal_id) + .map_err(|_| StdError::generic_err("Deal not found"))?; + Ok(DealResponse { deal }) +} + +pub fn query_bid(deps: Deps, deal_id: u64, bidder: String) -> StdResult { + let addr = deps.api.addr_validate(&bidder)?; + let bid = BIDS + .load(deps.storage, (deal_id, &addr)) + .map_err(|_| StdError::generic_err("Bid not found"))?; + Ok(BidResponse { bid }) +} + +pub fn list_bids_for_deal( + deps: Deps, + deal_id: u64, + start_after: Option, + limit: Option, +) -> StdResult> { + // Check if deal exists + DEALS + .load(deps.storage, deal_id) + .map_err(|_| StdError::generic_err("Deal not found"))?; + + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + + // Convert start_after to validated address + let start_addr = match start_after { + Some(addr_str) => Some(deps.api.addr_validate(&addr_str)?), + None => None, + }; + + let start_bound = start_addr.as_ref().map(|addr| { + let bound_key = (deal_id, addr); + Bound::exclusive(bound_key) + }); + + // Query bids + let bids = BIDS + .range( + deps.storage, + start_bound, + Some(Bound::inclusive((deal_id + 1, &Addr::unchecked("")))), + Order::Ascending, + ) + .filter(|r| matches!(r, Ok((key, _)) if key.0 == deal_id)) + .take(limit) + .map(|item| item.map(|(_, bid)| BidResponse { bid })) + .collect::>>()?; + + Ok(bids) +} + +pub fn list_deals( + deps: Deps, + start_after: Option, + limit: Option, +) -> StdResult { + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + let start = start_after.map(Bound::exclusive); + + let deals: StdResult> = DEALS + .range(deps.storage, start, None, Order::Ascending) + .take(limit) + .map(|item| item.map(|(_, deal)| deal)) + .collect(); + + Ok(DealsResponse { deals: deals? }) +} + +pub fn list_deals_by_seller( + deps: Deps, + seller: String, + start_after: Option, + limit: Option, +) -> StdResult { + let seller_addr = deps.api.addr_validate(&seller)?; + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + let start = start_after.map(Bound::exclusive); + + let deals: StdResult> = DEALS + .range(deps.storage, start, None, Order::Ascending) + .filter(|r| match r { + Ok((_, deal)) => deal.seller == seller_addr, + Err(_) => true, // Keep errors to handle them in collect + }) + .take(limit) + .map(|item| item.map(|(_, deal)| deal)) + .collect(); + + Ok(DealsResponse { deals: deals? }) +} + +pub fn list_bids_by_bidder( + deps: Deps, + bidder: String, + start_after: Option<(u64, String)>, + limit: Option, +) -> StdResult> { + let bidder_addr = deps.api.addr_validate(&bidder)?; + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + + // Convert start_after into a proper bound + let start = start_after + .map(|(deal_id, _)| deal_id) + .map(|id| (id, &bidder_addr)); + + let mut bids = vec![]; + + let bid_range = BIDS.range( + deps.storage, + start.map(Bound::exclusive), + None, + Order::Ascending, + ); + + for result in bid_range { + let ((deal_id, addr), bid) = result?; + if addr == bidder_addr { + bids.push((deal_id, BidResponse { bid })); + if bids.len() >= limit { + break; + } + } + } + + Ok(bids) +} + +pub fn list_active_deals( + deps: Deps, + env: Env, + start_after: Option, + limit: Option, +) -> StdResult { + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + let start = start_after.map(Bound::exclusive); + let current_time = env.block.time.seconds(); + + let deals: StdResult> = DEALS + .range(deps.storage, start, None, Order::Ascending) + .filter(|r| match r { + Ok((_, deal)) => { + !deal.is_concluded + && deal.bid_start_time <= current_time + && deal.bid_end_time > current_time + } + Err(_) => true, // Keep errors to handle them in collect + }) + .take(limit) + .map(|item| item.map(|(_, deal)| deal)) + .collect(); + + Ok(DealsResponse { deals: deals? }) +} + +pub fn list_deals_by_status( + deps: Deps, + is_concluded: bool, + start_after: Option, + limit: Option, +) -> StdResult { + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; + let start = start_after.map(Bound::exclusive); + + let deals: StdResult> = DEALS + .range(deps.storage, start, None, Order::Ascending) + .filter(|r| match r { + Ok((_, deal)) => deal.is_concluded == is_concluded, + Err(_) => true, // Keep errors to handle them in collect + }) + .take(limit) + .map(|item| item.map(|(_, deal)| deal)) + .collect(); + + Ok(DealsResponse { deals: deals? }) +} + +pub fn query_config(deps: Deps) -> StdResult { + CONFIG.load(deps.storage) +} + +pub fn query_deal_stats(deps: Deps, env: Env, deal_id: u64) -> StdResult { + let deal = DEALS + .load(deps.storage, deal_id) + .map_err(|_| StdError::generic_err("Deal not found"))?; + let current_time = env.block.time.seconds(); + + let mut total_bids_count = 0u32; + let mut total_discount = 0u64; + let mut highest_bid_amount = Uint128::zero(); + let mut lowest_bid_amount = None; + let mut total_bid_amount = Uint128::zero(); + let mut bidders = std::collections::HashSet::new(); + + // Process all bids for the deal + for result in BIDS + .prefix(deal_id) + .range(deps.storage, None, None, Order::Ascending) + { + let (_, bid) = result?; + total_bids_count += 1; + total_discount += bid.discount_percentage; + highest_bid_amount = std::cmp::max(highest_bid_amount, bid.amount); + lowest_bid_amount = Some( + lowest_bid_amount.map_or(bid.amount, |current| std::cmp::min(current, bid.amount)), + ); + total_bid_amount += bid.amount; + bidders.insert(bid.bidder); + } + + // Calculate time remaining if deal is active + let time_remaining = if !deal.is_concluded && current_time < deal.conclude_time { + Some(deal.conclude_time.saturating_sub(current_time)) + } else { + None + }; + + let average_discount = if total_bids_count > 0 { + total_discount / total_bids_count as u64 + } else { + 0 + }; + + Ok(DealStatsResponse { + total_bids_count, + unique_bidders_count: bidders.len() as u32, + average_discount, + highest_bid_amount, + lowest_bid_amount: lowest_bid_amount.unwrap_or_else(Uint128::zero), + total_bid_amount, + min_cap_reached: total_bid_amount >= deal.min_cap, + time_remaining, + }) +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 00000000..005181df --- /dev/null +++ b/src/error.rs @@ -0,0 +1,41 @@ +use cosmwasm_std::{OverflowError, StdError}; +use thiserror::Error; + +#[derive(Error, Debug, PartialEq)] +pub enum ContractError { + #[error("{0}")] + Std(#[from] StdError), + + #[error("{0}")] + Overflow(#[from] OverflowError), + + #[error("Unauthorized")] + Unauthorized {}, + + #[error("Deal not found")] + DealNotFound {}, + + #[error("Bid not found")] + BidNotFound {}, + + #[error("Deal already concluded")] + DealAlreadyConcluded {}, + + #[error("Invalid time parameters: {reason}")] + InvalidTimeParameters { reason: String }, + + #[error("Invalid bid amount: {reason}")] + InvalidBidAmount { reason: String }, + + #[error("Insufficient platform fee. Required: {required}, provided: {provided}")] + InsufficientPlatformFee { required: u128, provided: u128 }, + + #[error("Bidding has not started")] + BiddingNotStarted {}, + + #[error("Bidding has ended")] + BiddingEnded {}, + + #[error("Conclusion time not reached")] + ConclusionTimeNotReached {}, +} diff --git a/src/helpers.rs b/src/helpers.rs new file mode 100644 index 00000000..af646680 --- /dev/null +++ b/src/helpers.rs @@ -0,0 +1,76 @@ +use cosmwasm_std::{ + to_binary, BankMsg, Coin, CosmosMsg, Order, StdResult, Storage, Uint128, WasmMsg, +}; +use cw20::Cw20ExecuteMsg; + +use crate::error::ContractError; +use crate::state::{Bid, BIDS}; + +/// Creates a CosmosMsg for transferring CW20 tokens +pub fn create_token_transfer_msg( + token_addr: String, + recipient: String, + amount: Uint128, +) -> StdResult { + Ok(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: token_addr, + msg: to_binary(&Cw20ExecuteMsg::Transfer { recipient, amount })?, + funds: vec![], + })) +} + +/// Creates a CosmosMsg for sending native tokens +pub fn create_payment_msg(recipient: String, amount: Uint128, denom: &str) -> CosmosMsg { + CosmosMsg::Bank(BankMsg::Send { + to_address: recipient, + amount: vec![Coin { + denom: denom.to_string(), + amount, + }], + }) +} + +/// Retrieves all bids for a deal, sorted by discount percentage +pub fn get_sorted_bids(storage: &dyn Storage, deal_id: u64) -> StdResult> { + let mut bids: Vec<(String, Bid)> = BIDS + .prefix(deal_id) + .range(storage, None, None, Order::Ascending) + .map(|item| { + let (addr, bid) = item?; + Ok((addr.to_string(), bid)) + }) + .collect::>>()?; + + bids.sort_by(|a, b| a.1.discount_percentage.cmp(&b.1.discount_percentage)); + Ok(bids) +} + +/// Validates deal time parameters +pub fn validate_deal_times( + bid_start_time: u64, + bid_end_time: u64, + conclude_time: u64, + current_time: u64, +) -> Result<(), ContractError> { + if bid_start_time >= bid_end_time { + return Err(ContractError::InvalidTimeParameters { + reason: "Bid start time must be before bid end time".to_string(), + }); + } + if bid_end_time >= conclude_time { + return Err(ContractError::InvalidTimeParameters { + reason: "Bid end time must be before conclude time".to_string(), + }); + } + if bid_start_time < current_time { + return Err(ContractError::InvalidTimeParameters { + reason: "Bid start time must be in the future".to_string(), + }); + } + Ok(()) +} + +/// Calculates the platform fee for a given amount +pub fn calculate_platform_fee(amount: Uint128, fee_percentage: u64) -> StdResult { + Ok(amount.multiply_ratio(fee_percentage, 10000u128)) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..55f52bf1 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,20 @@ +//! CosmWasm OTC Platform Smart Contract +//! +//! This contract implements a decentralized over-the-counter (OTC) trading platform +//! where sellers can create deals with customizable parameters and buyers can place +//! bids with their desired discount rates. +//! +//! ## Features +//! +//! * Create OTC deals with custom parameters +//! * Place, update, and withdraw bids +//! * Automatic deal conclusion +//! * Minimum price protection for sellers +//! * Maximum price protection for buyers +//! * Platform fee mechanism + +pub mod contract; +pub mod error; +pub mod helpers; +pub mod msg; +pub mod state; diff --git a/src/msg.rs b/src/msg.rs new file mode 100644 index 00000000..b97c92e9 --- /dev/null +++ b/src/msg.rs @@ -0,0 +1,178 @@ +use crate::state::{Bid, Config, Deal}; +use cosmwasm_schema::{cw_serde, QueryResponses}; +use cosmwasm_std::Uint128; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Message for contract instantiation +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct InstantiateMsg { + /// Platform fee percentage in basis points + pub platform_fee_percentage: u64, +} + +/// Messages for executing contract functions +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExecuteMsg { + /// Creates a new OTC deal + CreateDeal { + /// Address of the token being sold + sell_token: String, + /// Total amount of tokens to sell + total_amount: Uint128, + /// Minimum price per token + min_price: Uint128, + /// Maximum discount percentage offered + discount_percentage: u64, + /// Minimum total value required for deal conclusion + min_cap: Uint128, + /// Unix timestamp for bid start + bid_start_time: u64, + /// Unix timestamp for bid end + bid_end_time: u64, + /// Unix timestamp for deal conclusion + conclude_time: u64, + }, + /// Places a new bid on an existing deal + PlaceBid { + /// ID of the deal to bid on + deal_id: u64, + /// Amount of tokens to buy + amount: Uint128, + /// Requested discount percentage + discount_percentage: u64, + /// Optional maximum price willing to pay + max_price: Option, + }, + /// Updates an existing bid + UpdateBid { + /// ID of the deal + deal_id: u64, + /// New amount of tokens to buy + new_amount: Uint128, + /// New requested discount percentage + new_discount_percentage: u64, + /// New maximum price willing to pay + new_max_price: Option, + }, + /// Withdraws an existing bid + WithdrawBid { + /// ID of the deal + deal_id: u64, + }, + /// Concludes a deal after its conclusion time + ConcludeDeal { + /// ID of the deal to conclude + deal_id: u64, + }, +} + +/// Messages for querying contract state +#[cw_serde] +#[derive(QueryResponses)] +pub enum QueryMsg { + /// Get a specific deal by ID + #[returns(DealResponse)] + GetDeal { deal_id: u64 }, + + /// List all deals with optional pagination + #[returns(DealsResponse)] + ListDeals { + start_after: Option, + limit: Option, + }, + + /// Get a specific bid for a deal + #[returns(BidResponse)] + GetBid { deal_id: u64, bidder: String }, + + /// List all bids for a specific deal + #[returns(BidsResponse)] + ListBidsForDeal { + deal_id: u64, + start_after: Option, + limit: Option, + }, + + /// Get all deals by seller + #[returns(DealsResponse)] + ListDealsBySeller { + seller: String, + start_after: Option, + limit: Option, + }, + + /// Get all bids by bidder across all deals + #[returns(BidsResponse)] + ListBidsByBidder { + bidder: String, + start_after: Option<(u64, String)>, // (deal_id, bidder) + limit: Option, + }, + + /// Get active deals (not concluded and in bidding period) + #[returns(DealsResponse)] + ListActiveDeals { + start_after: Option, + limit: Option, + }, + + /// Get deals by status + #[returns(DealsResponse)] + ListDealsByStatus { + is_concluded: bool, + start_after: Option, + limit: Option, + }, + + /// Get contract configuration + #[returns(ConfigResponse)] + GetConfig {}, + + /// Get deal statistics + #[returns(DealStatsResponse)] + GetDealStats { deal_id: u64 }, +} + +/// Response for GetDeal query +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct DealResponse { + pub deal: Deal, +} + +/// Response for GetBid query +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct BidResponse { + pub bid: Bid, +} + +/// Response for GetBids query +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct BidsResponse { + pub bids: Vec<(String, Bid)>, +} + +/// Response for GetConfig query +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct ConfigResponse { + pub config: Config, +} + +/// Response for ListDeals query +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct DealsResponse { + pub deals: Vec, +} + +#[cw_serde] +pub struct DealStatsResponse { + pub total_bids_count: u32, + pub unique_bidders_count: u32, + pub average_discount: u64, + pub highest_bid_amount: Uint128, + pub lowest_bid_amount: Uint128, + pub total_bid_amount: Uint128, + pub min_cap_reached: bool, + pub time_remaining: Option, // None if concluded or expired +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 00000000..1e293569 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,83 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, Uint128}; +use cw_storage_plus::{Item, Map}; + +#[cw_serde] +pub struct Config { + pub platform_fee_percentage: u64, // In basis points (100 = 1%) +} + +#[cw_serde] +pub struct Deal { + pub seller: String, + pub sell_token: String, + pub total_amount: Uint128, + pub min_price: Uint128, + pub discount_percentage: u64, // In basis points (100 = 1%) + pub min_cap: Uint128, + pub bid_start_time: u64, + pub bid_end_time: u64, + pub conclude_time: u64, + pub is_concluded: bool, + pub total_bids_amount: Uint128, +} + +#[cw_serde] +pub struct Bid { + pub bidder: String, + pub amount: Uint128, + pub discount_percentage: u64, + pub max_price: Option, +} + +// Contract state storage +pub const CONFIG: Item = Item::new("config"); +pub const DEAL_COUNTER: Item = Item::new("deal_counter"); + +// Maps for storing deals and bids +pub const DEALS: Map = Map::new("deals"); +pub const BIDS: Map<(u64, &Addr), Bid> = Map::new("bids"); + +// Optional indexes for more efficient queries +pub const SELLER_DEALS: Map<(&Addr, u64), u64> = Map::new("seller_deals"); +pub const BIDDER_DEALS: Map<(&Addr, u64), u64> = Map::new("bidder_deals"); +pub const ACTIVE_DEALS: Map = Map::new("active_deals"); + +// Helper functions for state management +impl Deal { + pub fn is_active(&self, current_time: u64) -> bool { + !self.is_concluded + && self.bid_start_time <= current_time + && self.bid_end_time > current_time + } + + pub fn validate_times(&self, current_time: u64) -> bool { + self.bid_start_time > current_time + && self.bid_end_time > self.bid_start_time + && self.conclude_time > self.bid_end_time + } + + pub fn can_conclude(&self, current_time: u64) -> bool { + !self.is_concluded && current_time >= self.conclude_time + } + + pub fn can_bid(&self, current_time: u64) -> bool { + !self.is_concluded + && current_time >= self.bid_start_time + && current_time < self.bid_end_time + } +} + +impl Bid { + pub fn validate_bid(&self, deal: &Deal) -> bool { + self.amount > Uint128::zero() && self.discount_percentage <= 10000 // Max 100% + } + + pub fn calculate_final_price(&self, deal: &Deal) -> Uint128 { + let base_price = self + .amount + .multiply_ratio(deal.min_price, Uint128::new(1u128)); + let discount = base_price.multiply_ratio(self.discount_percentage, 100u128); + base_price.saturating_sub(discount) + } +} diff --git a/tests/common.rs b/tests/common.rs new file mode 100644 index 00000000..5ebda623 --- /dev/null +++ b/tests/common.rs @@ -0,0 +1,398 @@ +#[cfg(test)] +mod tests { + use super::*; + use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; + use cosmwasm_std::{coins, Addr, BankMsg, CosmosMsg, DepsMut, Env, SubMsg, Timestamp, Uint128}; + + use cw_otc_dex::contract::{execute, execute_conclude_deal, instantiate}; + use cw_otc_dex::error::ContractError; + use cw_otc_dex::msg::{ExecuteMsg, InstantiateMsg}; + use cw_otc_dex::state::{Bid, Config, Deal, BIDS, CONFIG, DEALS, DEAL_COUNTER}; + + const PLATFORM_FEE_PERCENTAGE: u64 = 100; // 1% + const MOCK_SELL_TOKEN: &str = "token"; + const MOCK_PAYMENT_DENOM: &str = "uusd"; + + // Helper function to create mock environment with specified time + fn mock_env_at_time(timestamp: u64) -> Env { + let mut env = mock_env(); + env.block.time = Timestamp::from_seconds(timestamp); + env + } + + // Helper function to create a standard test deal message with future timestamps + fn create_test_deal_msg(start_time: u64) -> ExecuteMsg { + ExecuteMsg::CreateDeal { + sell_token: MOCK_SELL_TOKEN.to_string(), + total_amount: Uint128::new(1000000u128), + min_price: Uint128::new(1u128), + discount_percentage: 1000, // 10% + min_cap: Uint128::new(500000u128), + bid_start_time: start_time + 1000, // Ensure future start + bid_end_time: start_time + 2000, // End time after start + conclude_time: start_time + 3000, // Conclude time after end + } + } + + fn setup_contract(deps: DepsMut) { + let msg = InstantiateMsg { + platform_fee_percentage: PLATFORM_FEE_PERCENTAGE, + }; + let info = mock_info("creator", &[]); + let res = instantiate(deps, mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + } + + #[test] + fn proper_initialization() { + let mut deps = mock_dependencies(); + let msg = InstantiateMsg { + platform_fee_percentage: PLATFORM_FEE_PERCENTAGE, + }; + let info = mock_info("creator", &[]); + let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + } + + #[test] + fn test_create_deal() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + let current_time = 1000u64; + let env = mock_env_at_time(current_time); + let total_amount = Uint128::new(1000000u128); + let platform_fee = total_amount.multiply_ratio(PLATFORM_FEE_PERCENTAGE as u128, 10000u128); + let msg = create_test_deal_msg(current_time); + + // Test with insufficient platform fee + let info = mock_info( + "seller", + &coins(platform_fee.u128() - 1, MOCK_PAYMENT_DENOM), + ); + let err = execute(deps.as_mut(), env.clone(), info, msg.clone()).unwrap_err(); + assert!(matches!(err, ContractError::InsufficientPlatformFee { .. })); + + // Test successful deal creation + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + let res = execute(deps.as_mut(), env.clone(), info, msg).unwrap(); + assert_eq!(res.attributes.len(), 3); + + let deal = DEALS.load(deps.as_ref().storage, 1).unwrap(); + assert_eq!(deal.seller, "seller"); + assert_eq!(deal.total_amount, total_amount); + assert_eq!(deal.is_concluded, false); + } + + #[test] + fn test_place_bid() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + let start_time = 1000u64; + let env = mock_env_at_time(start_time); + + // Create deal + let total_amount = Uint128::new(1000000u128); + let platform_fee = total_amount.multiply_ratio(PLATFORM_FEE_PERCENTAGE as u128, 10000u128); + let create_msg = create_test_deal_msg(start_time); + + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + execute(deps.as_mut(), env.clone(), info, create_msg).unwrap(); + + // Move to bidding period + let mut bid_env = mock_env_at_time(start_time + 1500); // During bidding period + + let bid_msg = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(100000u128), + discount_percentage: 500, + max_price: Some(Uint128::new(95000u128)), + }; + + let info = mock_info("bidder1", &[]); + let res = execute(deps.as_mut(), bid_env.clone(), info, bid_msg).unwrap(); + assert_eq!(res.attributes.len(), 4); + + let bid = BIDS + .load(deps.as_ref().storage, (1, &Addr::unchecked("bidder1"))) + .unwrap(); + assert_eq!(bid.amount, Uint128::new(100000u128)); + assert_eq!(bid.discount_percentage, 500); + } + + #[test] + fn test_update_bid() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + let start_time = 1000u64; + let env = mock_env_at_time(start_time); + + // Create deal + let total_amount = Uint128::new(1000000u128); + let platform_fee = total_amount.multiply_ratio(PLATFORM_FEE_PERCENTAGE as u128, 10000u128); + let create_msg = create_test_deal_msg(start_time); + + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + execute(deps.as_mut(), env.clone(), info, create_msg).unwrap(); + + // Move to bidding period + let mut bid_env = mock_env_at_time(start_time + 1500); + + // Place initial bid + let bid_msg = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(100000u128), + discount_percentage: 500, + max_price: Some(Uint128::new(95000u128)), + }; + let info = mock_info("bidder1", &[]); + execute(deps.as_mut(), bid_env.clone(), info.clone(), bid_msg).unwrap(); + + // Test bid update + let update_msg = ExecuteMsg::UpdateBid { + deal_id: 1, + new_amount: Uint128::new(150000u128), + new_discount_percentage: 600, + new_max_price: Some(Uint128::new(140000u128)), + }; + + let res = execute(deps.as_mut(), bid_env.clone(), info, update_msg).unwrap(); + assert_eq!(res.attributes.len(), 3); + + let bid = BIDS + .load(deps.as_ref().storage, (1, &Addr::unchecked("bidder1"))) + .unwrap(); + assert_eq!(bid.amount, Uint128::new(150000u128)); + assert_eq!(bid.discount_percentage, 600); + } + + fn test_conclude_deal() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + let start_time = 1000u64; + let env = mock_env_at_time(start_time); + + // Create test deal + let total_amount = Uint128::new(1000000u128); + let platform_fee = total_amount.multiply_ratio(PLATFORM_FEE_PERCENTAGE as u128, 10000u128); + let create_msg = create_test_deal_msg(start_time); + + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + execute(deps.as_mut(), env.clone(), info, create_msg).unwrap(); + + // Move to bidding period + let bid_env = mock_env_at_time(start_time + 1500); + + // Add some bids (but below min_cap) + let bid_msg = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(400000u128), + discount_percentage: 500, + max_price: None, + }; + let info = mock_info("bidder1", &[]); + execute(deps.as_mut(), bid_env.clone(), info, bid_msg).unwrap(); + + // Move to conclusion time + let conclude_env = mock_env_at_time(start_time + 3500); + + // Test failed deal (below min cap) + let conclude_msg = ExecuteMsg::ConcludeDeal { deal_id: 1 }; + let info = mock_info("anyone", &[]); + let res = execute( + deps.as_mut(), + conclude_env.clone(), + info.clone(), + conclude_msg.clone(), + ) + .unwrap(); + + assert!(res.messages.len() > 0); + assert!(res + .attributes + .iter() + .any(|attr| attr.value == "min_cap_not_met")); + + // Reset for successful conclusion test + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + // Create new deal + let env = mock_env_at_time(start_time); + // Create a new message instead of reusing the moved one + let new_create_msg = create_test_deal_msg(start_time); + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + execute(deps.as_mut(), env.clone(), info, new_create_msg).unwrap(); + + // Move to bidding period and place bid meeting min_cap + let bid_env = mock_env_at_time(start_time + 1500); + let bid_msg = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(600000u128), + discount_percentage: 500, + max_price: None, + }; + let info = mock_info("bidder1", &[]); + execute(deps.as_mut(), bid_env.clone(), info, bid_msg).unwrap(); + + // Test successful conclusion + let info = mock_info("anyone", &[]); + let res = execute(deps.as_mut(), conclude_env.clone(), info, conclude_msg).unwrap(); + + assert!(res.messages.len() > 0); + assert!(res.attributes.iter().any(|attr| attr.key == "tokens_sold")); + assert!(res + .attributes + .iter() + .any(|attr| attr.key == "total_payment")); + } + + #[test] + fn test_conclude_deal_min_cap_not_met() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + // Setup: Create a deal + let start_time = 1000u64; + let env = mock_env_at_time(start_time); + + let total_amount = Uint128::new(1000000u128); + let min_cap = Uint128::new(500000u128); + let platform_fee = total_amount.multiply_ratio(PLATFORM_FEE_PERCENTAGE as u128, 10000u128); + let create_msg = create_test_deal_msg(start_time); + + let info = mock_info("seller", &coins(platform_fee.u128(), MOCK_PAYMENT_DENOM)); + execute(deps.as_mut(), env.clone(), info, create_msg).unwrap(); + + // Add multiple bids that sum up to less than min_cap + let bid_env = mock_env_at_time(start_time + 1500); // During bidding period + + // First bid + let bid_msg1 = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(200000u128), + discount_percentage: 500, + max_price: None, + }; + let info = mock_info("bidder1", &[]); + execute(deps.as_mut(), bid_env.clone(), info, bid_msg1).unwrap(); + + // Second bid + let bid_msg2 = ExecuteMsg::PlaceBid { + deal_id: 1, + amount: Uint128::new(150000u128), + discount_percentage: 600, + max_price: None, + }; + let info = mock_info("bidder2", &[]); + execute(deps.as_mut(), bid_env.clone(), info, bid_msg2).unwrap(); + + // Verify total bids amount is less than min_cap + let deal = DEALS.load(deps.as_ref().storage, 1).unwrap(); + assert!(deal.total_bids_amount < min_cap); + assert_eq!(deal.total_bids_amount, Uint128::new(350000u128)); + + // Move to conclusion time and conclude the deal + let conclude_time = start_time + 3500; + let conclude_msg = ExecuteMsg::ConcludeDeal { deal_id: 1 }; + let info = mock_info("anyone", &[]); + let res = execute( + deps.as_mut(), + mock_env_at_time(conclude_time), + info, + conclude_msg, + ) + .unwrap(); + + // Verify response + assert!(res.messages.len() == 2); // Should have refund messages for both bidders + + // Check refund messages + let expected_refunds = vec![ + SubMsg::new(CosmosMsg::Bank(BankMsg::Send { + to_address: "bidder1".to_string(), + amount: coins(200000u128, MOCK_PAYMENT_DENOM), + })), + SubMsg::new(CosmosMsg::Bank(BankMsg::Send { + to_address: "bidder2".to_string(), + amount: coins(150000u128, MOCK_PAYMENT_DENOM), + })), + ]; + + for expected_msg in expected_refunds { + assert!(res.messages.contains(&expected_msg)); + } + + // Verify attributes + assert!(res + .attributes + .iter() + .any(|attr| attr.key == "method" && attr.value == "conclude_deal_refund")); + assert!(res + .attributes + .iter() + .any(|attr| attr.key == "reason" && attr.value == "min_cap_not_met")); + assert!(res + .attributes + .iter() + .any(|attr| attr.key == "total_refunded" && attr.value == "350000")); + + // Verify deal is marked as concluded + let deal = DEALS.load(deps.as_ref().storage, 1).unwrap(); + assert!(deal.is_concluded); + + // Try to conclude again - should fail + let conclude_msg = ExecuteMsg::ConcludeDeal { deal_id: 1 }; + let info = mock_info("anyone", &[]); + let err = execute( + deps.as_mut(), + mock_env_at_time(conclude_time), + info, + conclude_msg, + ) + .unwrap_err(); + assert!(matches!(err, ContractError::DealAlreadyConcluded {})); + + // Verify bids were not removed (optional, depending on your contract's behavior) + assert!(BIDS + .may_load(deps.as_ref().storage, (1, &Addr::unchecked("bidder1"))) + .unwrap() + .is_some()); + assert!(BIDS + .may_load(deps.as_ref().storage, (1, &Addr::unchecked("bidder2"))) + .unwrap() + .is_some()); + } + + #[test] + fn test_validation_errors() { + let mut deps = mock_dependencies(); + setup_contract(deps.as_mut()); + + let current_time = 1000u64; + let env = mock_env_at_time(current_time); + + let msg = ExecuteMsg::CreateDeal { + sell_token: MOCK_SELL_TOKEN.to_string(), + total_amount: Uint128::new(1000000u128), + min_price: Uint128::new(1u128), + discount_percentage: 11000, // Invalid: > 100% + min_cap: Uint128::new(500000u128), + bid_start_time: current_time + 1000, + bid_end_time: current_time + 2000, + conclude_time: current_time + 3000, + }; + + let info = mock_info("seller", &coins(10000, MOCK_PAYMENT_DENOM)); + let err = execute(deps.as_mut(), env.clone(), info, msg).unwrap_err(); + match err { + ContractError::InvalidTimeParameters { reason } => { + assert!(reason.contains("Discount percentage")); + } + _ => panic!("Expected InvalidTimeParameters error for invalid discount percentage"), + } + } +} diff --git a/tests/deals.rs b/tests/deals.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/deals.rs @@ -0,0 +1 @@ + diff --git a/tests/mod.rs b/tests/mod.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/mod.rs @@ -0,0 +1 @@ + diff --git a/tests/queries.rs b/tests/queries.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/queries.rs @@ -0,0 +1 @@ +