diff --git a/.cargo/config b/.cargo/config deleted file mode 100644 index 5bbab80..0000000 --- a/.cargo/config +++ /dev/null @@ -1,5 +0,0 @@ -[alias] -wasm = "build --release --target wasm32-unknown-unknown --lib" -wasm-debug = "build --target wasm32-unknown-unknown" -unit-test = "test --lib" -integration-test = "test --package e2e -- --ignored --test-threads 1" diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 013d362..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,612 +0,0 @@ -version: 2 -workflows: - version: 2 - test: - jobs: - - contract_sg721_base - - contract_sg721_nt - - contract_base_factory - - contract_base_minter - - contract_vending_factory - - contract_vending_minter - - contract_open_edition_factory - - contract_open_edition_minter - - contract_whitelist - - sg-eth-airdrop - - test-suite - - package_sg_std - - package_sg_utils - - lint - - wasm-build - - deploy: - jobs: - - build_and_upload_contracts: - filters: - tags: - only: /^v[0-9]+\.[0-9]+\.[0-9]+.*/ - branches: - ignore: /.*/ - -jobs: - contract_sg721_base: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/collections/sg721-base - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-sg721-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-sg721-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_sg721_nt: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/collections/sg721-nt - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-sg721-nt-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-sg721-nt-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_base_factory: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/factories/base-factory - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-base-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - # - run: - # name: Ensure checked-in schemas are up-to-date - # command: | - # CHANGES_IN_REPO=$(git status --porcelain) - # if [[ -n "$CHANGES_IN_REPO" ]]; then - # echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - # git status && git --no-pager diff - # exit 1 - # fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-base-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_base_minter: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/minters/base-minter - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-base-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - # - run: - # name: Ensure checked-in schemas are up-to-date - # command: | - # CHANGES_IN_REPO=$(git status --porcelain) - # if [[ -n "$CHANGES_IN_REPO" ]]; then - # echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - # git status && git --no-pager diff - # exit 1 - # fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-base-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_vending_factory: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/factories/vending-factory - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-vending-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-vending-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_vending_minter: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/minters/vending-minter - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-vending-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-vending-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_open_edition_factory: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/factories/open-edition-factory - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-open-edition-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-open-edition-factory-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_open_edition_minter: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/minters/open-edition-minter - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-open-edition-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-open-edition-minter-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - contract_whitelist: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/whitelists/whitelist - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-whitelist-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - - run: - name: Ensure checked-in schemas are up-to-date - command: | - CHANGES_IN_REPO=$(git status --porcelain) - if [[ -n "$CHANGES_IN_REPO" ]]; then - echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - git status && git --no-pager diff - exit 1 - fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-whitelist-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - test-suite: - docker: - - image: rust:1.69.0 - working_directory: ~/project/test-suite - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-test-suite-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-test-suite-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - package_sg_std: - docker: - - image: rust:1.69.0 - working_directory: ~/project/package/sg-std - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-sg-std-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-sg-std-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - package_sg_utils: - docker: - - image: rust:1.69.0 - working_directory: ~/project/package/sg-utils - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-sg-utils-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-sg-utils-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - sg-eth-airdrop: - docker: - - image: rust:1.69.0 - working_directory: ~/project/contracts/sg-eth-airdrop - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-sg-eth-airdrop-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Unit Tests - environment: - RUST_BACKTRACE: 1 - command: cargo unit-test --locked - - run: - name: Build and run schema generator - command: cargo schema --locked - # - run: - # name: Ensure checked-in schemas are up-to-date - # command: | - # CHANGES_IN_REPO=$(git status --porcelain) - # if [[ -n "$CHANGES_IN_REPO" ]]; then - # echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" - # git status && git --no-pager diff - # exit 1 - # fi - - save_cache: - paths: - - /usr/local/cargo/registry - - target - key: cargocache-sg-eth-airdrop-rust:1.69.0-{{ checksum "~/project/Cargo.lock" }} - - lint: - docker: - - image: rust:1.69.0 - steps: - - checkout - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version; rustup target list --installed - - restore_cache: - keys: - - cargocache-v2-lint-rust:1.69.0-{{ checksum "Cargo.lock" }} - - run: - name: Add rustfmt component - command: rustup component add rustfmt - - run: - name: Add clippy component - command: rustup component add clippy - - run: - name: Check formatting of workspace - command: cargo fmt -- --check - - run: - name: Clippy linting on workspace - command: cargo clippy --all-targets -- -D warnings - - save_cache: - paths: - - /usr/local/cargo/registry - - target/debug/.fingerprint - - target/debug/build - - target/debug/deps - key: cargocache-v2-lint-rust:1.69.0-{{ checksum "Cargo.lock" }} - - # This runs one time on the top level to ensure all contracts compile properly into wasm. - # We don't run the wasm build per contract build, and then reuse a lot of the same dependencies, so this speeds up CI time - # for all the other tests. - # We also sanity-check the resultant wasm files. - wasm-build: - docker: - - image: rust:1.69.0 - steps: - - checkout: - path: ~/project - - run: - name: Version information - command: rustc --version; cargo --version; rustup --version - - restore_cache: - keys: - - cargocache-wasm-rust-no-wasm:1.67.1-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Add wasm32 target - command: rustup target add wasm32-unknown-unknown - - run: - name: Build Wasm Release - command: | - for C in ./contracts/collections/*/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - for C in ./contracts/factories/*/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - for C in ./contracts/minters/*/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - for C in ./contracts/sg-eth-airdrop/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - for C in ./contracts/splits/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - for C in ./contracts/whitelists/*/ - do - echo "Compiling `basename $C`..." - (cd $C && cargo build --release --lib --target wasm32-unknown-unknown --locked) - done - - run: - name: Install check_contract - # Uses --debug for compilation speed - command: cargo install --debug --version 1.0.0 --features iterator --example check_contract -- cosmwasm-vm - - save_cache: - paths: - - /usr/local/cargo/registry - - /target/debug - - /target/release - - /target/tarpaulin - key: cargocache-wasm-rust-no-wasm:1.67.1-{{ checksum "~/project/Cargo.lock" }} - - run: - name: Check wasm contracts - command: | - for W in ./target/wasm32-unknown-unknown/release/*.wasm - do - echo -n "Checking `basename $W`... " - check_contract --supported-features iterator,staking,stargate,stargaze $W - done - - # This job roughly follows the instructions from https://circleci.com/blog/publishing-to-github-releases-via-circleci/ - build_and_upload_contracts: - docker: - # Image from https://github.com/cibuilds/github, based on alpine - - image: cibuilds/github:0.13 - steps: - - run: - name: Install Docker client - command: apk add docker-cli - - setup_remote_docker - - checkout - - run: - # We cannot mount local folders, see https://circleci.com/docs/2.0/building-docker-images/#mounting-folders - name: Prepare volume with source code - command: | - # create a dummy container which will hold a volume with config - docker create -v /code --name with_code alpine /bin/true - # copy a config file into this volume - docker cp Cargo.toml with_code:/code - docker cp Cargo.lock with_code:/code - # copy code into this volume - docker cp ./contracts with_code:/code - docker cp ./packages with_code:/code - docker cp ./test-suite with_code:/code - docker cp ./e2e with_code:/code - - run: - name: Build development contracts - command: | - docker run --volumes-from with_code cosmwasm/workspace-optimizer:0.12.13 - docker cp with_code:/code/artifacts ./artifacts - - run: - name: Show data - command: | - ls -l artifacts - cat artifacts/checksums.txt - - run: - name: Publish artifacts on GitHub - command: | - TAG="$CIRCLE_TAG" - TITLE="$TAG" - BODY="Attached there are some build artifacts generated at this tag. Those are for development purposes only! Please use crates.io to find the packages of this release." - ghr -t "$GITHUB_TOKEN" \ - -u "$CIRCLE_PROJECT_USERNAME" -r "$CIRCLE_PROJECT_REPONAME" \ - -c "$CIRCLE_SHA1" \ - -n "$TITLE" -b "$BODY" \ - -delete \ - "$TAG" ./artifacts/ diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..79a7f43 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,20 @@ + + +# Description + + + + +## Notable changes + + + +- Lowered gas price on contract handle +- Added new contract query + +## Next steps + + + +- Documentation should be updated for query +- More tests to calculate gas price diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..5f1ff4e --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,102 @@ +name: Rust + +on: [push] + +env: + CARGO_TERM_COLOR: always + +jobs: + find-contracts: # Job that list subdirectories + runs-on: ubuntu-latest + outputs: + dir: ${{ steps.set-dirs.outputs.dir }} + steps: + - uses: actions/checkout@v2 + - id: set-dirs + run: echo "::set-output name=dir::$(find ./contracts -name Cargo.toml | jq -R -s -c 'split("\n")[:-1]')" + + build-contracts: + runs-on: ubuntu-latest + needs: [find-contracts] # Depends on previous job + strategy: + matrix: + dir: ${{fromJson(needs.find-contracts.outputs.dir)}} # List matrix strategy from directories dynamically + steps: + - uses: actions/checkout@v2 + with: + submodules: recursive + + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + target: wasm32-unknown-unknown + + - uses: Swatinem/rust-cache@v2 + + - name: Install toolchain + run: rustup target add wasm32-unknown-unknown + + - uses: actions-rs/cargo@v1.0.3 + with: + command: build + args: --release --target wasm32-unknown-unknown --manifest-path=${{matrix.dir}} + + find-packages: # Job that list subdirectories + runs-on: ubuntu-latest + outputs: + dir: ${{ steps.set-dirs.outputs.dir }} + steps: + - uses: actions/checkout@v2 + - id: set-dirs + run: echo "::set-output name=dir::$(find ./packages/ -name Cargo.toml | jq -R -s -c 'split("\n")[:-1]')" + + check-packages: + runs-on: ubuntu-latest + needs: [find-packages] # Depends on previous job + strategy: + matrix: + dir: ${{fromJson(needs.find-packages.outputs.dir)}} # List matrix strategy from directories dynamically + steps: + - uses: actions/checkout@v2 + with: + submodules: recursive + + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + target: wasm32-unknown-unknown + + - uses: Swatinem/rust-cache@v2 + + - uses: actions-rs/cargo@v1.0.3 + with: + command: check + + coverage: + name: Collect test coverage + runs-on: ubuntu-latest + # nightly rust might break from time to time + continue-on-error: true + env: + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + target: wasm32-unknown-unknown + components: llvm-tools-preview + + - uses: Swatinem/rust-cache@v2 + + - name: Install latest nextest release + uses: taiki-e/install-action@nextest + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@cargo-llvm-cov + + - name: Collect coverage data + run: cargo llvm-cov nextest --lcov --output-path lcov.info --ignore-filename-regex network_integration\|network_tester\|secretcli\|contract_harness + - name: Upload coverage data to codecov + uses: codecov/codecov-action@v3 + with: + files: lcov.info diff --git a/.gitignore b/.gitignore index 1aedfa0..7d84bf6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,29 +7,23 @@ # Build results target/ +# Testing configs +packages/tools/headstash/package-lock.json + +# Code coverage stuff +*.profraw + # IDEs .vscode/ .idea/ *.iml -.env - -# User-gen -metadata.csv - -# ENV -.env +node_modules/ # Auto-gen .cargo-ok -# Build artifacts -*.wasm -hash.txt -contracts.txt -artifacts/ - -# code coverage -tarpaulin-report.* - -# integration tests -gas_reports/ \ No newline at end of file +*.pyc +__pycache__/ +compiled +logs +Cargo.lock diff --git a/.mergify.yml b/.mergify.yml deleted file mode 100644 index 28110cd..0000000 --- a/.mergify.yml +++ /dev/null @@ -1,26 +0,0 @@ -queue_rules: - - name: default - conditions: - - "#approved-reviews-by>2" - -pull_request_rules: - - name: automerge to main if approved and labeled - conditions: - - "#approved-reviews-by>2" - - base=main - - label=automerge - actions: - queue: - name: default - method: squash - commit_message_template: | - {{ title }} (#{{ number }}) - {{ body }} - - name: backport to v2 - conditions: - - base=main - - label=backport/2.x - actions: - backport: - branches: - - release/v2.x diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3684d40 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +info@securesecrets.org. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/Cargo.lock b/Cargo.lock index ccfb175..f4ad452 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,17 +13,46 @@ dependencies = [ "version_check", ] +[[package]] +name = "airdrop" +version = "0.1.0" +dependencies = [ + "ethereum-verify", + "hex", + "rs_merkle", + "sha2 0.10.8", + "shade-protocol", +] + +[[package]] +name = "anyhow" +version = "1.0.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca87830a3e3fb156dc96cfbd31cb620265dd053be734723f22b760d6cc3c3051" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + [[package]] name = "base16ct" -version = "0.2.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" [[package]] name = "base64" -version = "0.21.5" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" +checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64ct" @@ -33,9 +62,19 @@ checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" [[package]] name = "bech32" -version = "0.9.1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf9ff0bbfd639f15c74af777d81383cf53efb7c93613f6cab67c6c11e05bbf8b" + +[[package]] +name = "bincode2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d86b93f97252c47b41663388e6d155714a9d0c398b99f1005cbc5f978b29f445" +checksum = "f49f6183038e081170ebbbadee6678966c7d54728938a3e7de7f4e780770318f" +dependencies = [ + "byteorder", + "serde", +] [[package]] name = "block-buffer" @@ -56,16 +95,25 @@ dependencies = [ ] [[package]] -name = "bnum" -version = "0.8.1" +name = "byteorder" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab9008b6bb9fc80b5277f2fe481c09e828743d9151203e804583eb4c9e15b31d" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] -name = "byteorder" +name = "bytes" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" + +[[package]] +name = "cc" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" +dependencies = [ + "libc", +] [[package]] name = "cfg-if" @@ -73,24 +121,51 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" +dependencies = [ + "libc", + "num-integer", + "num-traits", + "time", + "winapi", +] + [[package]] name = "const-oid" -version = "0.9.5" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] -name = "cosmwasm-crypto" -version = "1.5.0" +name = "const_format" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bb3c77c3b7ce472056968c745eb501c440fbc07be5004eba02782c35bfbbe3" +checksum = "e3a214c7af3d04997541b18d432afaff4c455e79e2029079647e72fc2bd27673" dependencies = [ - "digest 0.10.7", - "ecdsa", - "ed25519-zebra", - "k256", - "rand_core 0.6.4", - "thiserror", + "const_format_proc_macros", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f6ff08fd20f4f299298a28e2dfa8a8ba1036e6cd2460ac1de7b425d76f2500" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "contract-derive" +version = "0.1.0" +dependencies = [ + "shade-protocol", + "syn 1.0.109", ] [[package]] @@ -126,28 +201,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "cosmwasm-std" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04d6864742e3a7662d024b51a94ea81c9af21db6faea2f9a6d2232bb97c6e53e" -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 = "cpufeatures" version = "0.2.11" @@ -157,11 +210,17 @@ dependencies = [ "libc", ] +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + [[package]] name = "crypto-bigint" -version = "0.5.5" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" dependencies = [ "generic-array", "rand_core 0.6.4", @@ -192,52 +251,11 @@ dependencies = [ "zeroize", ] -[[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 = "der" -version = "0.7.8" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" +checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" dependencies = [ "const-oid", "zeroize", @@ -270,7 +288,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid", "crypto-common", "subtle", ] @@ -283,16 +300,14 @@ checksum = "545b22097d44f8a9581187cdf93de7a71e4722bf51200cfaba810865b49a495d" [[package]] name = "ecdsa" -version = "0.16.9" +version = "0.14.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" dependencies = [ "der", - "digest 0.10.7", "elliptic-curve", "rfc6979", "signature", - "spki", ] [[package]] @@ -310,14 +325,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "either" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" + [[package]] name = "elliptic-curve" -version = "0.13.8" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" dependencies = [ "base16ct", "crypto-bigint", + "der", "digest 0.10.7", "ff", "generic-array", @@ -331,22 +353,20 @@ dependencies = [ [[package]] name = "ethereum-verify" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81ade645ce0bdfea36d04ba4642f8300c1387c650119732223fd2083c4aa359d" +version = "0.1.0" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", "hex", + "secret-cosmwasm-std", "sha2 0.10.8", "sha3", ] [[package]] name = "ff" -version = "0.13.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" dependencies = [ "rand_core 0.6.4", "subtle", @@ -366,7 +386,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", - "zeroize", ] [[package]] @@ -377,14 +396,14 @@ checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] name = "group" -version = "0.13.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" dependencies = [ "ff", "rand_core 0.6.4", @@ -401,22 +420,10 @@ dependencies = [ ] [[package]] -name = "headstash-contract" -version = "0.3.0" -dependencies = [ - "cosmwasm-schema", - "cosmwasm-std", - "cw-storage-plus", - "cw-utils", - "cw2", - "ethereum-verify", - "hex", - "schemars", - "serde", - "serde_json", - "sha2 0.9.9", - "thiserror", -] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hex" @@ -433,24 +440,31 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "k256" -version = "0.13.2" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f01b677d82ef7a676aa37e099defd83a28e15687112cafdd112d60236b6115b" +checksum = "72c1e0b51e7ec0a97369623508396067a486bd0cbed95a2659a4b863d28cfc8b" dependencies = [ "cfg-if", "ecdsa", "elliptic-curve", - "once_cell", "sha2 0.10.8", - "signature", ] [[package]] @@ -464,15 +478,47 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.150" +version = "0.2.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" + +[[package]] +name = "multi-derive" +version = "0.1.0" + +[[package]] +name = "nanoid" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +dependencies = [ + "autocfg", +] [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "opaque-debug" @@ -482,32 +528,109 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "pkcs8" -version = "0.10.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" dependencies = [ "der", "spki", ] +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "2dd5e8a1f1029c43224ad5898e50140c2aebb1705f19e67c918ebf5b9e797fe1" dependencies = [ "unicode-ident", ] +[[package]] +name = "prost" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "444879275cb4fd84958b1a1d5420d15e6fcf7c235fe47f053c9c2a80aceb6001" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9cc1a3263e07e0bf68e96268f37665207b49560d98739662cdfaae215c720fe" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "query-authentication" +version = "0.1.0" +source = "git+https://github.com/securesecrets/query-authentication?branch=cosmwasm_v1_upgrade#473dae556a10a811a4a55563813df9107b18781a" +dependencies = [ + "bech32", + "cosmwasm-schema", + "remain", + "ripemd160", + "schemars", + "secp256k1", + "secret-cosmwasm-std", + "serde", + "sha2 0.9.9", + "thiserror", +] + [[package]] name = "quote" -version = "1.0.33" +version = "1.0.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "22a37c9326af5ed140c86a46655b5278de879853be5573c01df185b6f49a580a" dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_core" version = "0.5.1" @@ -523,21 +646,58 @@ dependencies = [ "getrandom", ] +[[package]] +name = "remain" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bce3a7139d2ee67d07538ee5dba997364fbc243e7e7143e96eb830c74bfaa082" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.44", +] + [[package]] name = "rfc6979" -version = "0.4.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" dependencies = [ + "crypto-bigint", "hmac", - "subtle", + "zeroize", +] + +[[package]] +name = "ripemd160" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eca4ecc81b7f313189bf73ce724400a07da2a6dac19588b03c8bd76a2dcc251" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "opaque-debug", +] + +[[package]] +name = "rs_merkle" +version = "1.1.0" +source = "git+https://github.com/FloppyDisck/rs-merkle?branch=node_export#b35c0aa203fdd7ba6c963ba84efb46906792c660" +dependencies = [ + "sha2 0.9.9", ] +[[package]] +name = "rustversion" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" + [[package]] name = "ryu" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" [[package]] name = "schemars" @@ -565,9 +725,9 @@ dependencies = [ [[package]] name = "sec1" -version = "0.7.3" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" dependencies = [ "base16ct", "der", @@ -578,10 +738,115 @@ dependencies = [ ] [[package]] -name = "semver" -version = "1.0.20" +name = "secp256k1" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d03ceae636d0fed5bae6a7f4f664354c5f4fcedf6eef053fef17e49f837d0a" +dependencies = [ + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957da2573cde917463ece3570eab4a0b3f19de6f1646cde62e6fd3868f566036" +dependencies = [ + "cc", +] + +[[package]] +name = "secret-cosmwasm-crypto" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8535d61c88d0a6c222df2cebb69859d8e9ba419a299a1bc84c904b0d9c00c7b2" +dependencies = [ + "digest 0.10.7", + "ed25519-zebra", + "k256", + "rand_core 0.6.4", + "thiserror", +] + +[[package]] +name = "secret-cosmwasm-std" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" +checksum = "50e4393b01aa6587007161a6bb193859deaa8165ab06c8a35f253d329ff99e4d" +dependencies = [ + "base64 0.13.1", + "cosmwasm-derive", + "derivative", + "forward_ref", + "hex", + "schemars", + "secret-cosmwasm-crypto", + "serde", + "serde-json-wasm", + "thiserror", + "uint", +] + +[[package]] +name = "secret-cosmwasm-storage" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb43da2cb72a53b16ea1555bca794fb828b48ab24ebeb45f8e26f1881c45a783" +dependencies = [ + "secret-cosmwasm-std", + "serde", +] + +[[package]] +name = "secret-multi-test" +version = "0.13.4" +source = "git+https://github.com/securesecrets/secret-plus-utils#96438a5bf7f1fb0acc540fe3a43e934f01e6711f" +dependencies = [ + "anyhow", + "derivative", + "itertools", + "nanoid", + "prost", + "schemars", + "secret-cosmwasm-std", + "secret-storage-plus 0.13.4 (git+https://github.com/securesecrets/secret-plus-utils)", + "secret-utils", + "serde", + "thiserror", +] + +[[package]] +name = "secret-storage-plus" +version = "0.13.4" +source = "git+https://github.com/securesecrets/secret-plus-utils?tag=v0.1.1#96438a5bf7f1fb0acc540fe3a43e934f01e6711f" +dependencies = [ + "bincode2", + "schemars", + "secret-cosmwasm-std", + "serde", +] + +[[package]] +name = "secret-storage-plus" +version = "0.13.4" +source = "git+https://github.com/securesecrets/secret-plus-utils#96438a5bf7f1fb0acc540fe3a43e934f01e6711f" +dependencies = [ + "bincode2", + "schemars", + "secret-cosmwasm-std", + "serde", +] + +[[package]] +name = "secret-utils" +version = "0.13.4" +source = "git+https://github.com/securesecrets/secret-plus-utils#96438a5bf7f1fb0acc540fe3a43e934f01e6711f" +dependencies = [ + "schemars", + "secret-cosmwasm-std", + "serde", + "thiserror", +] [[package]] name = "serde" @@ -594,9 +859,9 @@ dependencies = [ [[package]] name = "serde-json-wasm" -version = "0.5.1" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a62a1fad1e1828b24acac8f2b468971dade7b8c3c2e672bcadefefb1f8c137" +checksum = "479b4dbc401ca13ee8ce902851b834893251404c4f3c65370a49e047a6be09a5" dependencies = [ "serde", ] @@ -609,7 +874,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.44", ] [[package]] @@ -625,9 +890,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.108" +version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" +checksum = "cb0652c533506ad7a2e353cce269330d6afd8bdfb6d75e0ace5b35aacbd7b9e9" dependencies = [ "itoa", "ryu", @@ -668,11 +933,47 @@ dependencies = [ "keccak", ] +[[package]] +name = "shade-multi-test" +version = "0.1.0" +dependencies = [ + "airdrop", + "multi-derive", + "shade-protocol", +] + +[[package]] +name = "shade-protocol" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.12.3", + "chrono", + "const_format", + "contract-derive", + "cosmwasm-schema", + "query-authentication", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "remain", + "schemars", + "secret-cosmwasm-std", + "secret-cosmwasm-storage", + "secret-multi-test", + "secret-storage-plus 0.13.4 (git+https://github.com/securesecrets/secret-plus-utils?tag=v0.1.1)", + "serde", + "sha2 0.9.9", + "strum", + "strum_macros", + "subtle", + "thiserror", +] + [[package]] name = "signature" -version = "2.2.0" +version = "1.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" dependencies = [ "digest 0.10.7", "rand_core 0.6.4", @@ -680,9 +981,9 @@ dependencies = [ [[package]] name = "spki" -version = "0.7.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" dependencies = [ "base64ct", "der", @@ -694,6 +995,25 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strum" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" + +[[package]] +name = "strum_macros" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 1.0.109", +] + [[package]] name = "subtle" version = "2.5.0" @@ -713,9 +1033,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "92d27c2c202598d05175a6dd3af46824b7f747f8d8e9b14c623f19fa5069735d" dependencies = [ "proc-macro2", "quote", @@ -724,22 +1044,33 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.50" +version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" +checksum = "b2cd5904763bad08ad5513ddbb12cf2ae273ca53fa9f68e843e236ec6dfccc09" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.50" +version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" +checksum = "3dcf4a824cce0aeacd6f38ae6f24234c8e80d68632338ebaa1443b5df9e29e19" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.44", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", ] [[package]] @@ -748,24 +1079,70 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "uint" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +[[package]] +name = "unicode-xid" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" + [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "zeroize" version = "1.7.0" diff --git a/Cargo.toml b/Cargo.toml index f10eeb5..54c6ad1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,51 +1,30 @@ [workspace] -members = [ - "contracts/headstash-contract", -] resolver = "2" +members = [ + # Packages + "packages/shade_protocol", + "packages/multi_test", + "packages/multi_derive", + "packages/contract_derive", + "packages/ethereum_verify", -[workspace.package] -version = "0.3.0" -edition = "2021" -homepage = "https://terp.network" -repository = "https://github.com/terpnetwork/headstash-patch" -license = "Apache-2.0" - -[workspace.dependencies] -cosmwasm-schema = "1.3.1" -cosmwasm-std = { version = "1.5.0", default-features = false, features = ["cosmwasm_1_3"] } -cw-controllers = "1.1.1" -cw2 = "1.1.1" -cw4 = "1.1.1" -cw4-group = "1.1.1" -cw721 = "0.18.0" -cw721-base = "0.18.0" -cw-multi-test = "0.16.2" -cw-storage-plus = "1.1.0" -cw-utils = "1.0.1" -schemars = "0.8.11" -serde = { version = "1.0.145", default-features = false, features = ["derive"] } -thiserror = "1.0.31" -url = "2.2.2" -sha2 = { version = "0.10.2", default-features = false } -ethereum-verify = "3.3.0" -headstash-contract = { version = "0.3.0", path = "contracts/headstash-contract" } -semver = "1" -cw-ownable = "0.5.1" + # Secret Headstash Contract + "contracts/airdrop", -[profile.release.package.headstash-contract] -codegen-units = 1 -incremental = false - -[profile.release.package.cw-goop] -codegen-units = 1 -incremental = false + # Tools + # "tools/doc2book", + # "launch" +] +exclude = ["packages/network_integration"] [profile.release] -rpath = false -lto = true -overflow-checks = true -opt-level = 3 -debug = false +opt-level = 3 +debug = false +rpath = false +lto = true debug-assertions = false +codegen-units = 1 +panic = 'abort' +incremental = false +overflow-checks = true diff --git a/LICENSE b/LICENSE index edc7db4..153d416 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,165 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2022 Public Awesome LLC - - 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. + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/Makefile.toml b/Makefile.toml new file mode 100644 index 0000000..c47498c --- /dev/null +++ b/Makefile.toml @@ -0,0 +1,140 @@ +[env] +CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true +BUILD_TARGET = "./target/wasm32-unknown-unknown/release/" +COMPILED_DIR = "compiled" +CHECKSUM_DIR = "${COMPILED_DIR}/checksum" +CURRENT_CRATE = "NONE" +# TODO: figure out how to only exclude when on a specific task +CARGO_MAKE_WORKSPACE_SKIP_MEMBERS = "packages/*" +DOCKER_IMAGE_VERSION = "v0.2" + +[tasks.set_flags] +workspace = false +private = true +script = ''' +RUSTFLAGS='-C link-arg=-s' +''' + +# Build for testnet + +[tasks.release] +workspace = false +run_task = [{ name = ["build_with_args", "compress_with_args"] }] +dependencies = ["set_flags"] + +[tasks.build_with_args] +private = true +workspace = false +command = "cargo" +args = ["build", "--release", "--package", "${@}", "--target", "wasm32-unknown-unknown"] + +[tasks.compress_with_args] +private = true +workspace = false +script = ''' +wasm-opt -Oz ${BUILD_TARGET}${@}.wasm -o ./${@}.wasm +echo $(md5sum ${@}.wasm | cut -f 1 -d " ") >> ${CHECKSUM_DIR}/${@}.txt +cat ./${@}.wasm | gzip -n -9 > ${COMPILED_DIR}/${@}.wasm.gz +rm ./${@}.wasm +''' + +[tasks.build-all] +# TODO: cargo skip workspace not working here +env = { "CURRENT_CRATE" = "${CARGO_MAKE_CRATE_NAME}", "CARGO_MAKE_WORKSPACE_SKIP_MEMBERS" = "packages/*" } +run_task = [{ name = ["build", "compress"] }] +dependencies = ["set_flags"] + +[tasks.build] +private = true +workspace = false +command = "cargo" +args = ["build", "--release", "--package", "${CURRENT_CRATE}", "--target", "wasm32-unknown-unknown"] + +[tasks.compress] +private = true +workspace = false +script = ''' +wasm-opt -Oz ${BUILD_TARGET}${CURRENT_CRATE}.wasm -o ./${CURRENT_CRATE}.wasm +echo $(md5sum ${CURRENT_CRATE}.wasm | cut -f 1 -d " ") >> ${CHECKSUM_DIR}/${CURRENT_CRATE}.txt +cat ./${CURRENT_CRATE}.wasm | gzip -n -9 > ${COMPILED_DIR}/${CURRENT_CRATE}.wasm.gz +rm ./${CURRENT_CRATE}.wasm +''' + +[tasks.schemas] +workspace = false +script = ''' +cargo run --bin schemas --features=" airdrop" +''' + +# Testing + +[tasks.test] +workspace = false +command = "cargo" +args = ["test", "--package", "${@}"] + +[tasks.test-all] +workspace = false +command = "cargo" +args = ["test"] + +# Cleanup + +[tasks.clean] +workspace = false +dependencies = ["remove_compile_dir", "create_compile_dir", "create_checksum_dir"] + +[tasks.remove_compile_dir] +private = true +workspace = false +command = "rm" +args = ["-r", "${COMPILED_DIR}", "-f"] + +[tasks.create_compile_dir] +private = true +workspace = false +command = "mkdir" +args = ["${COMPILED_DIR}"] + +[tasks.create_checksum_dir] +private = true +workspace = false +command = "mkdir" +args = ["${CHECKSUM_DIR}"] + +# Docker support - can be run with `cargo make server start|connect|download +[tasks.server] +private = false +workspace = false +extend = "subcommand" +env = { "SUBCOMMAND_PREFIX" = "server" } + +[tasks.subcommand] +private = true +workspace = false +script = ''' +#!@duckscript + +cm_run_task ${SUBCOMMAND_PREFIX}-${1} +''' + + +[tasks.server-download] +workspace = false +script = ''' +docker pull securesecrets/sn-testnet:${DOCKER_IMAGE_VERSION} +''' + +[tasks.server-start] +workspace = false +script = ''' +docker run -it --rm \ + -p 26657:26657 -p 26656:26656 -p 1337:1337 \ + -v $$(pwd):/root/code --name shade-testnet securesecrets/sn-testnet:${DOCKER_IMAGE_VERSION} +''' + +[tasks.server-connect] +workspace = false +script = ''' +docker exec -it shade-testnet /bin/bash +''' diff --git a/README.md b/README.md index a68faae..8dbf49d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ -# Headstash Patch Contracts +# Private Headstash Airdrop +### pulsar-3 +**code-id: `4461`** \ +**contract-address: ` `** -## [headstash-contract](./contracts/headstash-contract) -A fork of the [cw20-merkle-airdrop](https://github.com/CosmWasm/cw-plus/tree/0.9.x/contracts/cw20-merkle-airdrop), but also verifies a given signed hash is derived from a given eth_pubkey. \ No newline at end of file +## Unaudited fork of [Shade Protocol](https://shadeprotocol.io/) contracts. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..257e7ae --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,39 @@ +# Security Policy + +## Supported Versions + +The main tagged versions of the app should be the only ones deployed on the mainnet network. + +| Version | Supported | +| ------- | ------------------ | +| 1.x.x | :white_check_mark: | +| 0.x.x | :x: | + +## About Reporting a Vulnerability + +According to the [Github coordinated disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/about-coordinated-disclosure-of-security-vulnerabilities#about-disclosing-vulnerabilities-in-the-industry) + +> Vulnerability disclosure is an area where collaboration between vulnerability reporters, such as security researchers, and project maintainers is very important. Both parties need to work together from the moment a potentially harmful security vulnerability is found, right until a vulnerability is disclosed to the world, ideally with a patch available. Typically, when someone lets a maintainer know privately about a security vulnerability, the maintainer develops a fix, validates it, and notifies the users of the project or package. + +> The initial report of a vulnerability is made privately, and the full details are only published once the maintainer has acknowledged the issue, and ideally made remediations or a patch available, sometimes with a delay to allow more time for the patches to be installed. For more information, see the ["OWASP Cheat Sheet Series about vulnerability disclosure"](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html#commercial-and-open-source-software) on the OWASP Cheat Sheet Series website. + +## Best Practices According to Github + +According to the [Github coordinated disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/about-coordinated-disclosure-of-security-vulnerabilities#best-practices-for-maintainers) + +> It's good practice to report vulnerabilities privately to maintainers. When possible, as a vulnerability reporter, we recommend you avoid: + +- Disclosing the vulnerability publicly without giving maintainers a chance to remediate. +- Bypassing the maintainers. +- Disclosing the vulnerability before a fixed version of the code is available. +- Expecting to be compensated for reporting an issue, where no public bounty program exists. + +It's acceptable for vulnerability reporters to disclose a vulnerability publicly after a period of time, if they have tried to contact the maintainers and not received a response, or contacted them and been asked to wait too long to disclose it. + +## Process for Shade Protocol + +Although Github security reports are available for the main Shade Repository, we will follow custom reporting procedure so that the reports get submitted diretly to the relevant teams in the Shade organization. This will allow us to have a more streamlined process for handling reports across all the different repositories. + +Most of the reports will be handled by the [Secure Secrets Security Team](security@securesecrets.org) and the reports have to be submitted here: [Official Vulnerability Disclosure Portal](https://securesecrets.atlassian.net/servicedesk/customer/portal/3/group/11/create/37). When a security incident is reported, the user reporting accepts the terms and conditions of the Bounty Program, and is automtically enrolled into the Bounty Program detailed in the [Shade Protocol Responsible Disclosure](./Shade_Protocol_Resposible_Disclosure.md). The user can request to be not part of the Bounty Program by sending an email follow up to the initial report, but still needs to follow the process of the Github Coordinated Disclosure and Best Practices detailed by Github above. + + diff --git a/contractlib/contractlib.py b/contractlib/contractlib.py new file mode 100644 index 0000000..c050cb5 --- /dev/null +++ b/contractlib/contractlib.py @@ -0,0 +1,99 @@ +from .secretlib import secretlib + + + +import json + + +class PreInstantiatedContract: + def __init__(self, address, code_hash, code_id): + self.address = address + self.code_hash = code_hash + self.code_id = code_id + + def execute(self, msg, sender, amount=None, compute=True): + """ + Execute said msg + :param msg: Execute msg + :param sender: Who will be sending the message, defaults to contract admin + :param amount: Optional string amount to send along with transaction + :return: Result + """ + return secretlib.execute_contract(self.address, msg, sender, 'test', amount, compute) + + def query(self, msg): + """ + Query said msg + :param msg: Query msg + :return: Query + """ + return secretlib.query_contract(self.address, msg) + + def as_dict(self): + return {'address': self.address, 'code_hash': self.code_hash } + + +class Contract: + def __init__(self, contract, initMsg, label, admin='a', uploader='a', backend='test', + instantiated_contract=None, code_id=None): + self.label = label + self.admin = admin + self.uploader = uploader + self.backend = backend + + if code_id: + self.code_id = code_id + else: + self.code_id = secretlib.store_contract(contract, uploader, backend) + + if instantiated_contract: + self.code_id = instantiated_contract.code_id + self.address = instantiated_contract.address + self.code_hash = instantiated_contract.code_hash + else: + Response = secretlib.instantiate_contract(str(self.code_id), initMsg, label, admin, backend) + + try: + for log in Response['logs']: + for event in log['events']: + for attribute in event["attributes"]: + if attribute["key"] == "contract_address": + self.address = attribute["value"] + break + self.code_hash = secretlib.contract_hash(self.address) + except Exception as e: + print(Response) + raise e + + def execute(self, msg, sender=None, amount=None, compute=True): + """ + Execute said msg + :param msg: Execute msg + :param sender: Who will be sending the message, defaults to contract admin + :param amount: Optional string amount to send along with transaction + :return: Result + """ + signer = sender if sender is not None else self.admin + return secretlib.execute_contract(self.address, msg, signer, self.backend, amount, compute) + + def query(self, msg): + """ + Query said msg + :param msg: Query msg + :return: Query + """ + return secretlib.query_contract(self.address, msg) + + def print(self): + """ + Prints the contract info + :return: + """ + print(f"Label: {self.label}\n" + f"Address: {self.address}\n" + f"Id: {self.code_id}\n" + f"Hash: {self.code_hash}") + + def as_dict(self): + return {'address': self.address, 'code_hash': self.code_hash } + diff --git a/contractlib/initializerlib.py b/contractlib/initializerlib.py new file mode 100644 index 0000000..78b4bc2 --- /dev/null +++ b/contractlib/initializerlib.py @@ -0,0 +1,35 @@ +from .contractlib import Contract +import json + + +class Initializer(Contract): + def __init__(self, label, snip20_id, snip20_code_hash, silk_label, silk_seed, silk_initial_balances, + shade_label, shade_seed, shade_initial_balances, contract='initializer.wasm.gz', + admin='a', uploader='a', + backend='test', instantiated_contract=None, code_id=None): + init_msg = { + "snip20_id": int(snip20_id), + "snip20_code_hash": snip20_code_hash, + "shade": { + "label": shade_label, + "prng_seed": shade_seed, + "initial_balances": shade_initial_balances + }, + "silk": { + "label": silk_label, + "prng_seed": silk_seed, + "initial_balances": silk_initial_balances + }, + } + + init_msg = json.dumps(init_msg) + + super().__init__(contract, init_msg, label, admin, uploader, backend, + instantiated_contract=instantiated_contract, code_id=code_id) + + def get_contracts(self): + msg = json.dumps({ + "contracts": {} + }) + + return self.query(msg) \ No newline at end of file diff --git a/contractlib/mintlib.py b/contractlib/mintlib.py new file mode 100644 index 0000000..16ddbe8 --- /dev/null +++ b/contractlib/mintlib.py @@ -0,0 +1,108 @@ +import copy + +from .contractlib import Contract +from .secretlib import secretlib +import json + + +class Mint(Contract): + def __init__(self, label, native_asset, oracle, treasury=None, + asset_peg=None, + contract='mint.wasm.gz', + admin='a', uploader='a', + backend='test', instantiated_contract=None, code_id=None): + init_msg = { + "native_asset": { + "address": native_asset.address, + "code_hash": native_asset.code_hash, + }, + "oracle": { + "address": oracle.address, + "code_hash": oracle.code_hash + }, + } + if treasury: + init_msg['treasury'] = treasury.address + + if asset_peg: + init_msg['peg'] = asset_peg + + # print(json.dumps(init_msg, indent=2)) + init_msg = json.dumps(init_msg) + + super().__init__(contract, init_msg, label, admin, uploader, backend, + instantiated_contract=instantiated_contract, code_id=code_id) + + def update_config(self, owner=None, native_asset=None, oracle=None): + """ + Updates the minting contract's config + :param owner: New admin + :param native_asset: Snip20 to Mint + :param oracle: Oracle contract + :return: Result + """ + raw_msg = {"update_config": {}} + if owner is not None: + raw_msg["update_config"]["owner"] = owner + + if native_asset is not None: + contract = { + "address": native_asset.address, + "code_hash": native_asset.code_hash + } + raw_msg["update_config"]["native_asset"] = contract + + if oracle is not None: + contract = { + "address": oracle.address, + "code_hash": oracle.code_hash + } + raw_msg["update_config"]["oracle"] = contract + + msg = json.dumps(raw_msg) + return self.execute(msg) + + def register_asset(self, snip20, capture=None): + """ + Registers a SNIP20 asset + :param snip20: SNIP20 object to add + :param capture: Comission for the SNIP20 + :return: Result + """ + msg = {"register_asset": {"contract": {"address": snip20.address, "code_hash": snip20.code_hash}}} + + if capture: + msg['register_asset']['capture'] = str(capture) + + return self.execute(json.dumps(msg)) + + def get_supported_assets(self): + """ + Get all supported asset addressed + :return: Supported assets info + """ + msg = json.dumps( + {"get_supported_assets": {}}) + + return self.query(msg) + + def get_config(self): + """ + Get the contracts config information + :return: Contract config info + """ + msg = json.dumps( + {"get_config": {}}) + + return self.query(msg) + + def get_asset(self, snip20): + """ + Returns that assets info + :param snip20: SNIP20 object to query + :return: Asset info + """ + msg = json.dumps( + {"get_asset": {"contract": snip20.address}}) + + return self.query(msg) diff --git a/contractlib/secretlib/secretlib.py b/contractlib/secretlib/secretlib.py new file mode 100644 index 0000000..0c6479b --- /dev/null +++ b/contractlib/secretlib/secretlib.py @@ -0,0 +1,182 @@ +from subprocess import Popen, PIPE +import json +import time + +# Presetup some commands +query_list_code = ['secretcli', 'query', 'compute', 'list-code'] +MAX_TRIES = 10 + +GAS_METRICS = [] +STORE_GAS = '4000000' +GAS = '4000000' + + +def run_command(command): + """ + Will run any cli command and return its output after waiting a set amount + :param command: Array of command to run + :param wait: Time to wait for command + :return: Output string + """ + #print(' '.join(command)) + p = Popen(command, stdout=PIPE, stderr=PIPE, text=True) + output, err = p.communicate() + status = p.wait() + if err and not output: + return err + return output + + +def store_contract(contract, user='a', backend='test'): + """ + Store contract and return its ID + :param contract: Contract name + :param user: User to upload with + :param gas: Gas to use + :param backend: Keyring backend + :return: Contract ID + """ + + command = ['secretcli', 'tx', 'compute', 'store', f'./compiled/{contract}', + '--from', user, '--gas', STORE_GAS, '-y'] + + if backend is not None: + command += ['--keyring-backend', backend] + + output = run_command_query_hash(command) + try: + for attribute in output['logs'][0]['events'][0]['attributes']: + if attribute["key"] == "code_id": + return attribute['value'] + except: + # print(output) + return output + + +def instantiate_contract(contract, msg, label, user='a', backend='test'): + """ + Instantiates a contract + :param contract: Contract name + :param msg: Init msg + :param label: Name to give to the contract + :param user: User to instantiate with + :param backend: Keyring backend + :return: + """ + + command = ['secretcli', 'tx', 'compute', 'instantiate', contract, msg, '--from', + user, '--label', label, '-y', '--gas', '500000'] + + if backend is not None: + command += ['--keyring-backend', backend] + + return run_command_query_hash(command) + + +def list_code(): + command = ['secretcli', 'query', 'compute', 'list-code'] + + return json.loads(run_command(command)) + + +def list_contract_by_code(code): + command = ['secretcli', 'query', 'compute', 'list-contract-by-code', code] + + return json.loads(run_command(command)) + +def contract_hash(address): + command = ['secretcli', 'query', 'compute', 'contract-hash', address] + + return run_command(command) + + +def execute_contract(contract, msg, user='a', backend='test', amount=None, compute=True): + command = ['secretcli', 'tx', 'compute', 'execute', contract, json.dumps(msg), '--from', user, '--gas', GAS, '-y'] + + if backend is not None: + command += ['--keyring-backend', backend] + + if amount is not None: + command.append("--amount") + command.append(amount) + + if compute: + return run_command_compute_hash(command) + return run_command_query_hash(command) + + +def query_hash(hash): + return run_command(['secretcli', 'q', 'tx', hash]) + + +def compute_hash(hash): + print(hash) + return run_command(['secretcli', 'q', 'compute', 'tx', hash]) + + +def query_contract(contract, msg): + command = ['secretcli', 'query', 'compute', 'query', contract, json.dumps(msg)] + out = run_command(command) + try: + return json.loads(out) + except json.JSONDecodeError as e: + print(out) + raise e + + +def run_command_compute_hash(command): + out = run_command(command) + + try: + txhash = json.loads(out)["txhash"] + #print(txhash) + + except Exception as e: + # print(out) + raise e + + for _ in range(MAX_TRIES): + try: + out = compute_hash(txhash) + out = json.loads(out) + # print(out) + # querying hash once the hash is computed so we can check gas usage + tx_data = json.loads(query_hash(txhash)) + # print(json.dumps(tx_data)) + # print('gas:', tx_data['gas_used'], '\t/', tx_data['gas_wanted']) + GAS_METRICS.append({ + 'want': tx_data['gas_wanted'], + 'used': tx_data['gas_used'], + 'cmd': ' '.join(command) + }) + return out + except json.JSONDecodeError as e: + time.sleep(1) + print(out) + print(' '.join(command), f'exceeded max tries ({MAX_TRIES})') + + +def run_command_query_hash(command): + out = run_command(command) + try: + txhash = json.loads(out)["txhash"] + except json.JSONDecodeError as e: + print(out) + raise e + + for _ in range(MAX_TRIES): + try: + # TODO: Read the gas used and store somewhere for metrics + out = query_hash(txhash) + out = json.loads(out) + # print('gas:', out['gas_used'], '\t/', out['gas_wanted']) + GAS_METRICS.append({ + 'want': out['gas_wanted'], + 'used': out['gas_used'], + 'cmd': ' '.join(command) + }) + return out + except json.JSONDecodeError as e: + time.sleep(1) + print(out) + print(' '.join(command), f'exceeded max tries ({MAX_TRIES})') diff --git a/contractlib/snip20lib.py b/contractlib/snip20lib.py new file mode 100644 index 0000000..6199aec --- /dev/null +++ b/contractlib/snip20lib.py @@ -0,0 +1,124 @@ +from .contractlib import Contract +from .secretlib import secretlib +from base64 import b64encode +import json + + +class SNIP20(Contract): + def __init__(self, label, name="token", symbol="TKN", decimals=3, seed="cGFzc3dvcmQ=", public_total_supply=False, + enable_deposit=False, enable_redeem=False, enable_mint=False, enable_burn=False, initial_balances=[], + contract='snip20.wasm.gz', admin='a', uploader='a', backend='test', + instantiated_contract=None, code_id=None): + self.view_key = "" + self.name = name + self.symbol = symbol + self.decimals = decimals + + initMsg = json.dumps( + { + "name": name, + "symbol": symbol, + "decimals": decimals, + "prng_seed": seed, + "initial_balances": initial_balances, + "config": { + "public_total_supply": public_total_supply, + "enable_deposit": enable_deposit, + "enable_redeem": enable_redeem, + "enable_mint": enable_mint, + "enable_burn": enable_burn, + } + }) + super().__init__(contract, initMsg, label, admin, uploader, backend, + instantiated_contract=instantiated_contract, code_id=code_id) + + def set_minters(self, accounts): + """ + Sets minters + :param accounts: Accounts list + :return: Response + """ + msg = json.dumps( + {"set_minters": {"minters": accounts}}) + + return self.execute(msg) + + def deposit(self, account, amount): + """ + Deposit a specified amount to contract + :param account: User which will deposit + :param amount: uSCRT + :return: Response + """ + msg = json.dumps( + {"deposit": {}}) + + return self.execute(msg, account, amount) + + def mint(self, recipient, amount): + """ + Mint an amount into the recipients wallet + :param recipient: Address to be minted in + :param amount: Amount to mint + :return: Response + """ + msg = json.dumps( + {"mint": {"recipient": recipient, "amount": str(amount)}}) + + return self.execute(msg) + + def send(self, account, recipient, amount, message=None): + """ + Send amount from an account to a recipient + :param account: User to generate the key for + :param recipient: Address to be minted in + :param amount: Amount to mint + :param message: Base64 encoded message + :return: Response + """ + + raw_msg = {"send": {"recipient": recipient, "amount": str(amount)}} + + if message is not None: + raw_msg["send"]["msg"] = b64encode(json.dumps(message).encode('utf-8')).decode('utf-8') + + msg = json.dumps(raw_msg) + + return self.execute(msg, account) + + def set_view_key(self, account, entropy): + """ + Generate view key to query balance + :param account: User to generate the key for + :param entropy: Password generation entropy + :return: Password + """ + msg = json.dumps( + {"set_viewing_key": {"key": entropy}}) + + resp = self.execute(msg, account) + #print('RESP', json.dumps(resp, indent=2)) + return resp + #return json.loads(resp["output_data_as_string"])["create_viewing_key"]["key"] + + def get_balance(self, address, password): + """ + Gets amount of coins in wallet + :param address: Account to access + :param password: View key + :return: Response + """ + msg = json.dumps( + {"balance": {"key": password, "address": address}}) + + msg = {"balance": {"key": password, "address": address}} + res = self.query(msg) + + return res["balance"]["amount"] + + def get_token_info(self): + + msg = json.dumps( + {"token_info": {}}) + return self.query(msg) + diff --git a/contractlib/utils.py b/contractlib/utils.py new file mode 100644 index 0000000..83f8723 --- /dev/null +++ b/contractlib/utils.py @@ -0,0 +1,15 @@ +import string +import random +import base64 +import json + + +def gen_label(length): + # With combination of lower and upper case + return ''.join(random.choice(string.ascii_letters) for i in range(length)) + + +def to_base64(dict): + dict_str = json.dumps(dict).encode('ascii') + encoded_str = base64.b64encode(dict_str) + return encoded_str.decode() diff --git a/contracts/airdrop/.cargo/config b/contracts/airdrop/.cargo/config new file mode 100644 index 0000000..c1e7c50 --- /dev/null +++ b/contracts/airdrop/.cargo/config @@ -0,0 +1,5 @@ +[alias] +wasm = "build --release --target wasm32-unknown-unknown" +unit-test = "test --lib --features backtraces" +integration-test = "test --test integration" +schema = "run --example schema" \ No newline at end of file diff --git a/contracts/airdrop/.circleci/config.yml b/contracts/airdrop/.circleci/config.yml new file mode 100644 index 0000000..127e1ae --- /dev/null +++ b/contracts/airdrop/.circleci/config.yml @@ -0,0 +1,52 @@ +version: 2.1 + +jobs: + build: + docker: + - image: rust:1.43.1 + steps: + - checkout + - run: + name: Version information + command: rustc --version; cargo --version; rustup --version + - restore_cache: + keys: + - v4-cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }} + - run: + name: Add wasm32 target + command: rustup target add wasm32-unknown-unknown + - run: + name: Build + command: cargo wasm --locked + - run: + name: Unit tests + env: RUST_BACKTRACE=1 + command: cargo unit-test --locked + - run: + name: Integration tests + command: cargo integration-test --locked + - run: + name: Format source code + command: cargo fmt + - run: + name: Build and run schema generator + command: cargo schema --locked + - run: + name: Ensure checked-in source code and schemas are up-to-date + command: | + CHANGES_IN_REPO=$(git status --porcelain) + if [[ -n "$CHANGES_IN_REPO" ]]; then + echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" + git status && git --no-pager diff + exit 1 + fi + - save_cache: + paths: + - /usr/local/cargo/registry + - target/debug/.fingerprint + - target/debug/build + - target/debug/deps + - target/wasm32-unknown-unknown/release/.fingerprint + - target/wasm32-unknown-unknown/release/build + - target/wasm32-unknown-unknown/release/deps + key: v4-cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }} diff --git a/contracts/airdrop/Cargo.toml b/contracts/airdrop/Cargo.toml new file mode 100644 index 0000000..d9ff0bc --- /dev/null +++ b/contracts/airdrop/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "airdrop" +version = "0.1.0" +authors = ["Guy Garcia "] +edition = "2018" + +exclude = [ + # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. + "contract.wasm", + "hash.txt", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = [] +# for quicker tests, cargo test --lib +# for more explicit tests, cargo test --features=backtraces +backtraces = ["shade-protocol/backtraces"] +debug-print = ["shade-protocol/debug-print"] + +[dependencies] +shade-protocol = { version = "0.1.0", path = "../../packages/shade_protocol", features = ["airdrop"] } +ethereum-verify = { version = "0.1.0", path = "../../packages/ethereum_verify"} +hex = "0.4" +sha2 = { version = "0.10.2", default-features = false } +rs_merkle = { git = "https://github.com/FloppyDisck/rs-merkle", branch = "node_export" } \ No newline at end of file diff --git a/contracts/airdrop/Makefile b/contracts/airdrop/Makefile new file mode 100644 index 0000000..2493c22 --- /dev/null +++ b/contracts/airdrop/Makefile @@ -0,0 +1,68 @@ +.PHONY: check +check: + cargo check + +.PHONY: clippy +clippy: + cargo clippy + +PHONY: test +test: unit-test + +.PHONY: unit-test +unit-test: + cargo test + +# This is a local build with debug-prints activated. Debug prints only show up +# in the local development chain (see the `start-server` command below) +# and mainnet won't accept contracts built with the feature enabled. +.PHONY: build _build +build: _build compress-wasm +_build: + RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown --features="debug-print" + +# This is a build suitable for uploading to mainnet. +# Calls to `debug_print` get removed by the compiler. +.PHONY: build-mainnet _build-mainnet +build-mainnet: _build-mainnet compress-wasm +_build-mainnet: + RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown + +# like build-mainnet, but slower and more deterministic +.PHONY: build-mainnet-reproducible +build-mainnet-reproducible: + docker run --rm -v "$$(pwd)":/contract \ + --mount type=volume,source="$$(basename "$$(pwd)")_cache",target=/contract/target \ + --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ + enigmampc/secret-contract-optimizer:1.0.3 + +.PHONY: compress-wasm +compress-wasm: + cp ./target/wasm32-unknown-unknown/release/*.wasm ./contract.wasm + @## The following line is not necessary, may work only on linux (extra size optimization) + @# wasm-opt -Os ./contract.wasm -o ./contract.wasm + cat ./contract.wasm | gzip -9 > ./contract.wasm.gz + +.PHONY: schema +schema: + cargo run --example schema + +# Run local development chain with four funded accounts (named a, b, c, and d) +.PHONY: start-server +start-server: # CTRL+C to stop + docker run -it --rm \ + -p 26657:26657 -p 26656:26656 -p 1317:1317 \ + -v $$(pwd):/root/code \ + --name secretdev enigmampc/secret-network-sw-dev:v1.0.4-3 + +# This relies on running `start-server` in another console +# You can run other commands on the secretcli inside the dev image +# by using `docker exec secretdev secretcli`. +.PHONY: store-contract-local +store-contract-local: + docker exec secretdev secretcli tx compute store -y --from a --gas 1000000 /root/code/contract.wasm.gz + +.PHONY: clean +clean: + cargo clean + -rm -f ./contract.wasm ./contract.wasm.gz diff --git a/contracts/airdrop/README.md b/contracts/airdrop/README.md new file mode 100644 index 0000000..ed33134 --- /dev/null +++ b/contracts/airdrop/README.md @@ -0,0 +1,348 @@ + +# Airdrop Contract +* [Introduction](#Introduction) +* [Sections](#Sections) + * [Init](#Init) + * [Admin](#Admin) + * Messages + * [UpdateConfig](#UpdateConfig) + * [AddTasks](#AddTasks) + * [ClaimDecay](#ClaimDecay) + * [Task_Admin](#Task_Admin) + * Messages + * [CompleteTask](#CompleteTask) + * [User](#User) + * Messages + * [Account](#Account) + * [DisablePermitKey](#DisablePermitKey) + * [SetViewingKey](#SetViewingKey) + * [Claim](#Claim) + * Queries + * [Config](#Config) + * [Dates](#Dates) + * [TotalClaimed](#TotalClaimed) + * [Account](#Account) + * [AccountWithKey](#AccountWithKey) + +# Introduction +Contract responsible to handle snip20 airdrop + +# Sections + +## Init +##### Request +| Name | Type | Description | optional | +|----------------|---------------|----------------------------------------------------------------------------|----------| +| admin | String | New contract owner; SHOULD be a valid bech32 address | yes | +| dump_address | String | Where the decay amount will be sent | yes | +| airdrop_token | Contract | The token that will be airdropped | no | +| airdrop_amount | String | Total airdrop amount to be claimed | no | +| start_date | u64 | When the airdrop starts in UNIX time | yes | +| end_date | u64 | When the airdrop ends in UNIX time | yes | +| decay_start | u64 | When the airdrop decay starts in UNIX time | yes | +| merkle_root | String | Base 64 encoded merkle root of the airdrop data tree | no | +| total_accounts | u32 | Total accounts in airdrop (needed for merkle proof) | no | +| max_amount | String | Used to limit the user permit amounts (lowers exploit possibility) | no | +| default_claim | String | The default amount to be gifted regardless of tasks | no | +| task_claim | RequiredTasks | The amounts per tasks to gift | no | +| query_rounding | string | To prevent leaking information, total claimed is rounded off to this value | no | + +##Admin + +### Messages + +#### UpdateConfig +Updates the given values +##### Request +| Name | Type | Description | optional | +|----------------|--------|------------------------------------------------------|----------| +| admin | string | New contract admin; SHOULD be a valid bech32 address | yes | +| dump_address | string | Sets the dump address if there isnt any | yes | +| query_rounding | String | To prevent leaking information | yes | +| start_date | u64 | When the airdrop starts in UNIX time | yes | +| end_date | u64 | When the airdrop ends in UNIX time | yes | +| decay_start | u64 | When the airdrop decay starts in UNIX time | yes | +| padding | string | Allows for enforcing constant length messages | yes | + +#### AddTasks +Adds another task that can unlock the users claim percentage, total task percentage cannot exceed 100% +##### Task +| Name | Type | Description | optional | +|---------|--------|--------------------------------------------------|----------| +| address | String | The address that will grant the task to accounts | no | +| percent | string | The percent to be unlocked when completed | no | + +##### Request +| Name | Type | Description | optional | +|---------|--------|-----------------------------------------------|----------| +| tasks | Tasks | The new tasks to be added | no | +| padding | string | Allows for enforcing constant length messages | yes | + +##### Response +```json +{ + "add_tasks": { + "status": "success" + } +} +``` + +#### ClaimDecay +Drains the decayed amount of airdrop into the specified dump_address + +##### Response +```json +{ + "claim_decay": { + "status": "success" + } +} +``` + +##Task Admin + +### Messages + +#### CompleteTask +Complete that address' tasks for a given user +##### Request +| Name | Type | Description | optional | +|---------|--------|-----------------------------------------------|----------| +| address | String | The address that completed the task | no | +| padding | string | Allows for enforcing constant length messages | yes | + +##### Response +```json +{ + "complete_task": { + "status": "success" + } +} +``` + +##User + +### Messages + +### Account +(Creates / Updates) an account from which the user will claim all of his given addresses' rewards +##### Request +| Name | Type | Description | optional | +|--------------|----------------------------------------------------|-----------------------------------------------------------|----------| +| addresses | Array of [AddressProofPermit](#AddressProofPermit) | Proof that the user owns those addresses | no | +| partial_tree | Array of string | An array of nodes that serve as a proof for the addresses | no | +| padding | string | Allows for enforcing constant length messages | yes | + +##### Response +```json +{ + "account": { + "status": "success", + "total": "Total airdrop amount", + "claimed": "Claimed amount", + "finished_tasks": "All of the finished tasks", + "addresses": ["claimed addresses"] + } +} +``` + +### DisablePermitKey +Disables that permit's key. Any permit that has that key for that address will be declined. +##### Request +| Name | Type | Description | optional | +|---------|--------|-----------------------------------------------|----------| +| key | string | Permit key | no | +| padding | string | Allows for enforcing constant length messages | yes | + +##### Response +```json +{ + "disable_permit_key": { + "status": "success" + } +} +``` + +### SetViewingKey +Sets a viewing key for the account, useful for when the network is congested because of permits. +##### Request +| Name | Type | Description | optional | +|---------|--------|-----------------------------------------------|----------| +| key | string | Viewing key | no | +| padding | string | Allows for enforcing constant length messages | yes | + +##### Response +```json +{ + "set_viewing_key": { + "status": "success" + } +} +``` + +#### Claim +Claim the user's available claimable amount + +##### Response +```json +{ + "claim": { + "status": "success", + "total": "Total airdrop amount", + "claimed": "Claimed amount", + "finished_tasks": "All of the finished tasks", + "addresses": ["claimed addresses"] + } +} +``` + +### Queries + +#### GetConfig +Gets the contract's config +#### Response +```json +{ + "config": { + "config": "Contract's config" + } +} +``` + +## Dates +Get the contracts airdrop timeframe, can calculate the decay factor if a time is given +##### Request +| Name | Type | Description | optional | +|--------------|------|---------------------------------|----------| +| current_date | u64 | The current time in UNIX format | yes | +```json +{ + "dates": { + "start": "Airdrop start", + "end": "Airdrop end", + "decay_start": "Airdrop start of decay", + "decay_factor": "Decay percentage" + } +} +``` + +## TotalClaimed +Shows the total amount of the token that has been claimed. If airdrop hasn't ended then it'll just show an estimation. +##### Request +```json +{ + "total_claimed": { + "claimed": "Claimed amount" + } +} +``` + +## Account +Get the account's information +##### Request +| Name | Type | Description | optional | +|--------------|----------------------------------------|-----------------------------|----------| +| permit | [AccountProofPermit](#AccountProofMsg) | Address's permit | no | +| current_date | u64 | Current time in UNIT format | yes | +```json +{ + "account": { + "total": "Total airdrop amount", + "claimed": "Claimed amount", + "unclaimed": "Amount available to claim", + "finished_tasks": "All of the finished tasks", + "addresses": ["claimed addresses"] + } +} +``` + +## AccountWithKey +Get the account's information using a viewing key +##### Request +| Name | Type | Description | optional | +|--------------|--------|-----------------------------|----------| +| account | String | Accounts address | yes | +| key | String | Address's viewing key | no | +| current_date | u64 | Current time in UNIT format | yes | +```json +{ + "account_with_key": { + "total": "Total airdrop amount", + "claimed": "Claimed amount", + "unclaimed": "Amount available to claim", + "finished_tasks": "All of the finished tasks", + "addresses": ["claimed addresses"] + } +} +``` + +## AddressProofPermit +This is a structure used to prove that the user has permission to query that address's information (when querying account info). +This is also used to prove that the user owns that address (when creating/updating accounts) and the given amount is in the airdrop. +This permit is written differently from the rest since its made taking into consideration many of Terra's limitations compared to Keplr's flexibility. + +NOTE: The parameters must be in order + +[How to sign](https://github.com/securesecrets/shade/blob/77abdc70bc645d97aee7de5eb9a2347d22da425f/packages/shade_protocol/src/signature/mod.rs#L100) +#### Structure +| Name | Type | Description | optional | +|------------|-----------------|--------------------------------------------------------|----------| +| params | FillerMsg | Filler params accounting for Terra Ledgers limitations | no | +| memo | String | Base64Encoded AddressProofMsg | no | +| chain_id | String | Chain ID of the network this proof will be used in | no | +| signature | PermitSignature | Signature of the permit | no | + +## FillerMsg + +```json +{ + "coins": [], + "contract": "", + "execute_msg": "", + "sender": "" +} +``` + +## AddressProofMsg +The information inside permits that validate the airdrop eligibility and validate the account holder's key. + +NOTE: The parameters must be in order +### Structure +| Name | Type | Description | optional | +|----------|---------|---------------------------------------------------------|----------| +| address | String | Address of the signer (might be redundant) | no | +| amount | String | Airdrop amount | no | +| contract | String | Airdrop contract | no | +| index | Integer | Index of airdrop data in reference to the original tree | no | +| key | String | Some permit key | no | + +## AccountProofMsg +The information inside permits that validate account ownership + +NOTE: The parameters must be in order +### Structure +| Name | Type | Description | optional | +|----------|---------|---------------------------------------------------------|----------| +| contract | String | Airdrop contract | no | +| key | String | Some permit key | no | + + +## PermitSignature +The signature that proves the validity of the data + +NOTE: The parameters must be in order +### Structure +| Name | Type | Description | optional | +|-----------|--------|---------------------------|----------| +| pub_key | pubkey | Signer's public key | no | +| signature | String | Base 64 encoded signature | no | + +## Pubkey +Public key + +NOTE: The parameters must be in order +### Structure +| Name | Type | Description | optional | +|-------|--------|------------------------------------|----------| +| type | String | Must be tendermint/PubKeySecp256k1 | no | +| value | String | The base 64 key | no | \ No newline at end of file diff --git a/contracts/airdrop/src/contract.rs b/contracts/airdrop/src/contract.rs new file mode 100644 index 0000000..1966ae2 --- /dev/null +++ b/contracts/airdrop/src/contract.rs @@ -0,0 +1,193 @@ +use crate::{ + handle::{ + try_account, try_add_tasks, try_claim, try_claim_decay, try_complete_task, + try_disable_permit_key, try_set_viewing_key, try_update_config, + }, + query, + state::{config_w, decay_claimed_w, total_claimed_w}, +}; +use shade_protocol::{ + airdrop::{ + claim_info::RequiredTask, + errors::{invalid_dates, invalid_task_percentage}, + Config, ExecuteMsg, InstantiateMsg, QueryMsg, + }, + c_std::{ + shd_entry_point, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, + StdResult, Uint128, + }, + utils::{pad_handle_result, pad_query_result}, +}; + +// Used to pad up responses for better privacy. +pub const RESPONSE_BLOCK_SIZE: usize = 256; + +#[shd_entry_point] +pub fn instantiate( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: InstantiateMsg, +) -> StdResult { + // Setup task claim + let mut task_claim = vec![RequiredTask { + address: env.contract.address.clone(), + percent: msg.default_claim, + }]; + let mut claim = msg.task_claim; + task_claim.append(&mut claim); + + // Validate claim percentage + let mut count = Uint128::zero(); + for claim in task_claim.iter() { + count += claim.percent; + } + + if count > Uint128::new(100u128) { + return Err(invalid_task_percentage(count.to_string().as_str())); + } + + let start_date = match msg.start_date { + None => env.block.time.seconds(), + Some(date) => date, + }; + + if let Some(end_date) = msg.end_date { + if end_date < start_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + } + + // Avoid decay collisions + if let Some(start_decay) = msg.decay_start { + if start_decay < start_date { + return Err(invalid_dates( + "Decay", + start_decay.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + if let Some(end_date) = msg.end_date { + if start_decay > end_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "Decay", + start_decay.to_string().as_str(), + )); + } + } else { + return Err(StdError::generic_err("Decay must have an end date")); + } + } + + let config = Config { + admin: msg.admin.unwrap_or(info.sender), + contract: env.contract.address, + dump_address: msg.dump_address, + airdrop_snip20: msg.airdrop_token.clone(), + airdrop_snip20_optional: msg.airdrop_2.clone(), + airdrop_amount: msg.airdrop_amount, + task_claim, + start_date, + end_date: msg.end_date, + decay_start: msg.decay_start, + merkle_root: msg.merkle_root, + total_accounts: msg.total_accounts, + claim_msg_plaintext: msg.claim_msg_plaintext, + max_amount: msg.max_amount, + query_rounding: msg.query_rounding, + }; + + config_w(deps.storage).save(&config)?; + + // Initialize claim amount + total_claimed_w(deps.storage).save(&Uint128::zero())?; + + decay_claimed_w(deps.storage).save(&false)?; + + Ok(Response::new()) +} + +#[shd_entry_point] +pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult { + pad_handle_result( + match msg { + ExecuteMsg::UpdateConfig { + admin, + dump_address, + query_rounding: redeem_step_size, + start_date, + end_date, + decay_start: start_decay, + .. + } => try_update_config( + deps, + env, + &info, + admin, + dump_address, + redeem_step_size, + start_date, + end_date, + start_decay, + ), + ExecuteMsg::AddTasks { tasks, .. } => try_add_tasks(deps, &env, &info, tasks), + ExecuteMsg::CompleteTask { address, .. } => { + try_complete_task(deps, &env, &info, address) + } + ExecuteMsg::Account { + addresses, + eth_pubkey, + eth_sig, + partial_tree, + .. + } => try_account( + deps, + &env, + &info, + addresses, + eth_pubkey, + eth_sig, + partial_tree, + ), + ExecuteMsg::DisablePermitKey { key, .. } => { + try_disable_permit_key(deps, &env, &info, key) + } + ExecuteMsg::SetViewingKey { key, .. } => try_set_viewing_key(deps, &env, &info, key), + ExecuteMsg::Claim { .. } => try_claim(deps, &env, &info), + ExecuteMsg::ClaimDecay { .. } => try_claim_decay(deps, &env, &info), + }, + RESPONSE_BLOCK_SIZE, + ) +} + +#[shd_entry_point] +pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { + pad_query_result( + match msg { + QueryMsg::Config {} => to_binary(&query::config(deps)?), + QueryMsg::Dates { current_date } => to_binary(&query::dates(deps, current_date)?), + QueryMsg::TotalClaimed {} => to_binary(&query::total_claimed(deps)?), + QueryMsg::Account { + permit, + current_date, + } => to_binary(&query::account(deps, permit, current_date)?), + QueryMsg::AccountWithKey { + account, + key, + current_date, + } => to_binary(&query::account_with_key(deps, account, key, current_date)?), + }, + RESPONSE_BLOCK_SIZE, + ) +} diff --git a/contracts/airdrop/src/handle.rs b/contracts/airdrop/src/handle.rs new file mode 100644 index 0000000..cfb011e --- /dev/null +++ b/contracts/airdrop/src/handle.rs @@ -0,0 +1,818 @@ +use crate::state::{ + account_r, account_total_claimed_r, account_total_claimed_w, account_viewkey_w, account_w, + address_in_account_w, claim_status_r, claim_status_w, config_r, config_w, decay_claimed_w, + eth_pubkey_in_account_w, eth_sig_in_account_w, revoke_permit, total_claimed_r, total_claimed_w, + validate_address_permit, +}; +use rs_merkle::{algorithms::Sha256, Hasher, MerkleProof}; +use shade_protocol::{ + airdrop::{ + account::{Account, AccountKey, AddressProofMsg, AddressProofPermit}, + claim_info::RequiredTask, + errors::{ + account_does_not_exist, address_already_in_account, airdrop_ended, airdrop_not_started, + claim_too_high, decay_claimed, decay_not_set, expected_memo, invalid_dates, + invalid_partial_tree, invalid_task_percentage, not_admin, nothing_to_claim, + unexpected_error, + }, + Config, ExecuteAnswer, + }, + c_std::{ + from_binary, to_binary, Addr, Api, Binary, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, + Response, StdResult, Storage, Uint128, + }, + query_authentication::viewing_keys::ViewingKey, + snip20::helpers::send_msg, + utils::generic_response::ResponseStatus::{self, Success}, +}; + +#[allow(clippy::too_many_arguments)] +pub fn try_update_config( + deps: DepsMut, + _env: Env, + info: &MessageInfo, + admin: Option, + dump_address: Option, + query_rounding: Option, + start_date: Option, + end_date: Option, + decay_start: Option, +) -> StdResult { + let config = config_r(deps.storage).load()?; + // Check if admin + if info.sender != config.admin { + return Err(not_admin(config.admin.as_str())); + } + + // Save new info + let mut config = config_w(deps.storage); + config.update(|mut state| { + if let Some(admin) = admin { + state.admin = admin; + } + if let Some(dump_address) = dump_address { + state.dump_address = Some(dump_address); + } + if let Some(query_rounding) = query_rounding { + state.query_rounding = query_rounding; + } + if let Some(start_date) = start_date { + // Avoid date collisions + if let Some(end_date) = end_date { + if start_date > end_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + } else if let Some(end_date) = state.end_date { + if start_date > end_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + } + if let Some(start_decay) = decay_start { + if start_date > start_decay { + return Err(invalid_dates( + "Decay", + start_decay.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + } else if let Some(start_decay) = state.decay_start { + if start_date > start_decay { + return Err(invalid_dates( + "Decay", + start_decay.to_string().as_str(), + "before", + "StartDate", + start_date.to_string().as_str(), + )); + } + } + + state.start_date = start_date; + } + if let Some(end_date) = end_date { + // Avoid date collisions + if let Some(decay_start) = decay_start { + if decay_start > end_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "Decay", + decay_start.to_string().as_str(), + )); + } + } else if let Some(decay_start) = state.decay_start { + if decay_start > end_date { + return Err(invalid_dates( + "EndDate", + end_date.to_string().as_str(), + "before", + "Decay", + decay_start.to_string().as_str(), + )); + } + } + + state.end_date = Some(end_date); + } + if decay_start.is_some() { + state.decay_start = decay_start + } + + Ok(state) + })?; + Ok(Response::new().set_data(to_binary(&ExecuteAnswer::UpdateConfig { status: Success })?)) +} + +pub fn try_add_tasks( + deps: DepsMut, + _env: &Env, + info: &MessageInfo, + tasks: Vec, +) -> StdResult { + let config = config_r(deps.storage).load()?; + // Check if admin + if info.sender != config.admin { + return Err(not_admin(config.admin.as_str())); + } + + config_w(deps.storage).update(|mut config| { + let mut task_list = tasks; + config.task_claim.append(&mut task_list); + + //Validate that they do not exceed 100 + let mut count = Uint128::zero(); + for task in config.task_claim.iter() { + count += task.percent; + } + + if count > Uint128::new(100u128) { + return Err(invalid_task_percentage(count.to_string().as_str())); + } + + Ok(config) + })?; + + Ok(Response::new().set_data(to_binary(&ExecuteAnswer::AddTask { status: Success })?)) +} + +pub fn try_account( + deps: DepsMut, + env: &Env, + info: &MessageInfo, + addresses: Vec, + eth_pubkey: String, + eth_sig: String, + partial_tree: Vec, +) -> StdResult { + // Check if airdrop active + let config = config_r(deps.storage).load()?; + + // Check that airdrop hasn't ended + available(&config, env)?; + + // Setup account + let sender = info.sender.to_string(); + + // These variables are setup to facilitate updating + let updating_account: bool; + let old_claim_amount: Uint128; + + let mut account = match account_r(deps.storage).may_load(sender.as_bytes())? { + None => { + updating_account = false; + old_claim_amount = Uint128::zero(); + let mut account = Account::default(); + + // Validate permits + try_add_account_addresses( + deps.storage, + deps.api, + &config, + &info.sender, + &mut account, + &addresses, + ð_pubkey, + ð_sig, + &partial_tree, + )?; + + // Add default claim at index 0 + account_total_claimed_w(deps.storage).save(sender.as_bytes(), &Uint128::zero())?; + claim_status_w(deps.storage, 0).save(sender.as_bytes(), &false)?; + + account + } + Some(acc) => { + updating_account = true; + old_claim_amount = acc.total_claimable; + acc + } + }; + + // Claim airdrop + let mut messages = vec![]; + + let (completed_percentage, unclaimed_percentage) = + update_tasks(deps.storage, &config, sender.clone())?; + + let mut redeem_amount = Uint128::zero(); + + if unclaimed_percentage > Uint128::zero() { + redeem_amount = claim_tokens( + deps.storage, + env, + info, + &config, + &account, + completed_percentage, + unclaimed_percentage, + )?; + } + + // Update account after claim to calculate difference + if updating_account { + // Validate permits + try_add_account_addresses( + deps.storage, + deps.api, + &config, + &info.sender, + &mut account, + &addresses, + ð_pubkey, + ð_sig, + &partial_tree, + )?; + } + + if updating_account && completed_percentage > Uint128::zero() { + // Calculate the total new address amount + let added_address_total = account.total_claimable.checked_sub(old_claim_amount)?; + account_total_claimed_w(deps.storage).update(sender.as_bytes(), |claimed| { + if let Some(claimed) = claimed { + let new_redeem: Uint128; + if completed_percentage == Uint128::new(100u128) { + new_redeem = + added_address_total * decay_factor(env.block.time.seconds(), &config); + } else { + new_redeem = completed_percentage + .multiply_ratio(added_address_total, Uint128::new(100u128)) + * decay_factor(env.block.time.seconds(), &config); + } + + redeem_amount += new_redeem; + Ok(claimed + new_redeem) + } else { + Err(unexpected_error()) + } + })?; + } + + if redeem_amount > Uint128::zero() { + total_claimed_w(deps.storage) + .update(|claimed| -> StdResult { Ok(claimed + redeem_amount) })?; + + messages.push(send_msg( + info.sender.clone(), + redeem_amount.into(), + None, + None, + None, + &config.airdrop_snip20, + )?); + } + + // Save account + account_w(deps.storage).save(sender.as_bytes(), &account)?; + + Ok(Response::new().set_data(to_binary(&ExecuteAnswer::Account { + status: ResponseStatus::Success, + total: account.total_claimable, + claimed: account_total_claimed_r(deps.storage).load(sender.to_string().as_bytes())?, + // Will always be 0 since rewards are automatically claimed here + finished_tasks: finished_tasks(deps.storage, sender.clone())?, + addresses: account.addresses, + eth_pubkey, + eth_sig, + })?)) +} + +pub fn try_disable_permit_key( + deps: DepsMut, + _env: &Env, + info: &MessageInfo, + key: String, +) -> StdResult { + revoke_permit(deps.storage, info.sender.to_string(), key); + + Ok( + Response::new().set_data(to_binary(&ExecuteAnswer::DisablePermitKey { + status: Success, + })?), + ) +} + +pub fn try_set_viewing_key( + deps: DepsMut, + _env: &Env, + info: &MessageInfo, + key: String, +) -> StdResult { + account_viewkey_w(deps.storage) + .save(&info.sender.to_string().as_bytes(), &AccountKey(key).hash())?; + + Ok( + Response::new().set_data(to_binary(&ExecuteAnswer::SetViewingKey { + status: Success, + })?), + ) +} + +pub fn try_complete_task( + deps: DepsMut, + _env: &Env, + info: &MessageInfo, + account: Addr, +) -> StdResult { + let config = config_r(deps.storage).load()?; + + for (i, task) in config.task_claim.iter().enumerate() { + if task.address == info.sender { + claim_status_w(deps.storage, i).update( + account.to_string().as_bytes(), + |status| -> StdResult { + // If there was a state then ignore + if let Some(status) = status { + Ok(status) + } else { + Ok(false) + } + }, + )?; + } + } + + Ok(Response::new().set_data(to_binary(&ExecuteAnswer::CompleteTask { status: Success })?)) +} + +pub fn try_claim(deps: DepsMut, env: &Env, info: &MessageInfo) -> StdResult { + let config = config_r(deps.storage).load()?; + + // Check that airdrop hasn't ended + available(&config, env)?; + + // Get account + let sender = info.sender.clone(); + let account = account_r(deps.storage).load(sender.to_string().as_bytes())?; + + // validate eth_signature + validation::validate_claim( + &deps, + info.clone(), + account.eth_pubkey.clone(), // uses the saved account eth_pubkey + account.eth_sig.clone(), + config.clone(), + )?; + + // Calculate airdrop + let (completed_percentage, unclaimed_percentage) = + update_tasks(deps.storage, &config, sender.to_string())?; + + if unclaimed_percentage == Uint128::zero() { + return Err(nothing_to_claim()); + } + + let redeem_amount = claim_tokens( + deps.storage, + env, + info, + &config, + &account, + completed_percentage, + unclaimed_percentage, + )?; + + let mut msgs: Vec = vec![]; + let hs1 = send_msg( + sender.clone(), + redeem_amount.into(), + None, + None, + None, + &config.airdrop_snip20, + )?; + msgs.push(hs1); + + if !config.airdrop_snip20_optional.is_none() { + let hs2 = send_msg( + sender.clone(), + redeem_amount.into(), + None, + None, + None, + &config.airdrop_snip20_optional.unwrap(), + )?; + msgs.push(hs2); + }; + + total_claimed_w(deps.storage) + .update(|claimed| -> StdResult { Ok(claimed + redeem_amount) })?; + + Ok(Response::new() + .set_data(to_binary(&ExecuteAnswer::Claim { + status: ResponseStatus::Success, + total: account.total_claimable, + claimed: account_total_claimed_r(deps.storage).load(sender.to_string().as_bytes())?, + finished_tasks: finished_tasks(deps.storage, sender.to_string())?, + addresses: account.addresses, + eth_pubkey: account.eth_pubkey, + eth_sig: account.eth_sig, + })?) + .add_messages(msgs)) +} + +pub fn try_claim_decay(deps: DepsMut, env: &Env, _info: &MessageInfo) -> StdResult { + let config = config_r(deps.storage).load()?; + + // Check if airdrop ended + if let Some(end_date) = config.end_date { + if let Some(dump_address) = config.dump_address { + if env.block.time.seconds() > end_date { + decay_claimed_w(deps.storage).update(|claimed| { + if claimed { + Err(decay_claimed()) + } else { + Ok(true) + } + })?; + + let total_claimed = total_claimed_r(deps.storage).load()?; + let send_total = config.airdrop_amount.checked_sub(total_claimed)?; + let mut msgs: Vec = vec![]; + + let hs1 = send_msg( + dump_address.clone(), + send_total.into(), + None, + None, + None, + &config.airdrop_snip20, + )?; + msgs.push(hs1); + + if !config.airdrop_snip20_optional.is_none() { + let hs2 = send_msg( + dump_address.clone(), + send_total.into(), + None, + None, + None, + &config.airdrop_snip20_optional.unwrap(), + )?; + msgs.push(hs2); + }; + + return Ok(Response::new() + .set_data(to_binary(&ExecuteAnswer::ClaimDecay { status: Success })?) + .add_messages(msgs)); + } + } + } + + Err(decay_not_set()) +} + +pub fn finished_tasks(storage: &dyn Storage, account: String) -> StdResult> { + let mut finished_tasks = vec![]; + let config = config_r(storage).load()?; + + for (index, _task) in config.task_claim.iter().enumerate() { + match claim_status_r(storage, index).may_load(account.as_bytes())? { + None => {} + Some(_) => { + finished_tasks.push(config.task_claim[index].clone()); + } + } + } + + Ok(finished_tasks) +} + +/// Gets task information and sets them +pub fn update_tasks( + storage: &mut dyn Storage, + config: &Config, + sender: String, +) -> StdResult<(Uint128, Uint128)> { + // Calculate eligible tasks + let mut completed_percentage = Uint128::zero(); + let mut unclaimed_percentage = Uint128::zero(); + for (index, task) in config.task_claim.iter().enumerate() { + // Check if task has been completed + let state = claim_status_r(storage, index).may_load(sender.as_bytes())?; + + match state { + // Ignore if none + None => {} + Some(claimed) => { + completed_percentage += task.percent; + if !claimed { + // Set claim status to true since we're going to claim it now + claim_status_w(storage, index).save(sender.as_bytes(), &true)?; + + unclaimed_percentage += task.percent; + } + } + } + } + + Ok((completed_percentage, unclaimed_percentage)) +} + +pub fn claim_tokens( + storage: &mut dyn Storage, + env: &Env, + info: &MessageInfo, + config: &Config, + account: &Account, + completed_percentage: Uint128, + unclaimed_percentage: Uint128, +) -> StdResult { + // send_amount + let sender = info.sender.to_string(); + + // Amount to be redeemed + let mut redeem_amount = Uint128::zero(); + + // Update total claimed and calculate claimable + account_total_claimed_w(storage).update(sender.as_bytes(), |claimed| { + if let Some(claimed) = claimed { + // This solves possible uToken inaccuracies + if completed_percentage == Uint128::new(100u128) { + redeem_amount = account.total_claimable.checked_sub(claimed)?; + } else { + redeem_amount = unclaimed_percentage + .multiply_ratio(account.total_claimable, Uint128::new(100u128)); + } + + // Update redeem amount with the decay multiplier + redeem_amount = redeem_amount * decay_factor(env.block.time.seconds(), config); + + Ok(claimed + redeem_amount) + } else { + Err(account_does_not_exist()) + } + })?; + + Ok(redeem_amount) +} + +/// Validates all of the information and updates relevant states +pub fn try_add_account_addresses( + storage: &mut dyn Storage, + api: &dyn Api, + config: &Config, + sender: &Addr, + account: &mut Account, + addresses: &Vec, + eth_pubkey: &String, + eth_sig: &String, + partial_tree: &Vec, +) -> StdResult<()> { + // Setup the items to validate + let mut leaves_to_validate: Vec<(usize, [u8; 32])> = vec![]; + + // Iterate addresses + for permit in addresses.iter() { + if let Some(memo) = permit.memo.clone() { + let params: AddressProofMsg = from_binary(&Binary::from_base64(&memo)?)?; + + // Avoid verifying sender + if ¶ms.address != sender { + // Check permit legitimacy + validate_address_permit(storage, api, permit, ¶ms, config.contract.clone())?; + } + + // Check that airdrop amount does not exceed maximum + if params.amount > config.max_amount { + return Err(claim_too_high( + params.amount.to_string().as_str(), + config.max_amount.to_string().as_str(), + )); + } + + // Update address if its not in an account + address_in_account_w(storage).update( + params.address.to_string().as_bytes(), + |state| -> StdResult { + if state.is_some() { + return Err(address_already_in_account(params.address.as_str())); + } + + Ok(true) + }, + )?; + + // Update eth_pubkey if its not in an account + eth_pubkey_in_account_w(storage).update( + eth_pubkey.to_string().as_bytes(), + |state| -> StdResult { + if state.is_some() { + return Err(address_already_in_account(ð_pubkey.as_str())); + } + + Ok(true) + }, + )?; + + // Update eth_sig if its not in an account + eth_sig_in_account_w(storage).update( + eth_sig.to_string().as_bytes(), + |state| -> StdResult { + if state.is_some() { + return Err(address_already_in_account(ð_pubkey.as_str())); + } + + Ok(true) + }, + )?; + + // Add account as a leaf + let leaf_hash = + Sha256::hash((eth_pubkey.to_string() + ¶ms.amount.to_string()).as_bytes()); + leaves_to_validate.push((params.index as usize, leaf_hash)); + + // If valid then add to account array and sum total amount + account.addresses.push(params.address); + account.eth_pubkey = eth_pubkey.to_string(); + account.eth_sig = eth_sig.to_string(); + account.total_claimable += params.amount; + } else { + return Err(expected_memo()); + } + } + + // Need to sort by index in order for the proof to work + leaves_to_validate.sort_by_key(|item| item.0); + + let mut indices: Vec = vec![]; + let mut leaves: Vec<[u8; 32]> = vec![]; + + for leaf in leaves_to_validate.iter() { + indices.push(leaf.0); + leaves.push(leaf.1); + } + + // Convert partial tree from base64 to binary + let mut partial_tree_binary: Vec<[u8; 32]> = vec![]; + for node in partial_tree.iter() { + let mut arr: [u8; 32] = Default::default(); + arr.clone_from_slice(node.as_slice()); + partial_tree_binary.push(arr); + } + + // Prove that user is in airdrop + let proof = MerkleProof::::new(partial_tree_binary); + // Convert to a fixed length array without messing up the contract + let mut root: [u8; 32] = Default::default(); + root.clone_from_slice(config.merkle_root.as_slice()); + if !proof.verify(root, &indices, &leaves, config.total_accounts as usize) { + return Err(invalid_partial_tree()); + } + + Ok(()) +} + +pub fn available(config: &Config, env: &Env) -> StdResult<()> { + let current_time = env.block.time.seconds(); + + // Check if airdrop started + if current_time < config.start_date { + return Err(airdrop_not_started( + config.start_date.to_string().as_str(), + current_time.to_string().as_str(), + )); + } + if let Some(end_date) = config.end_date { + if current_time > end_date { + return Err(airdrop_ended( + end_date.to_string().as_str(), + current_time.to_string().as_str(), + )); + } + } + + Ok(()) +} + +/// Get the multiplier for decay, will return 1 when decay isnt in effect. +pub fn decay_factor(current_time: u64, config: &Config) -> Decimal { + // Calculate redeem amount after applying decay + if let Some(decay_start) = config.decay_start { + if current_time >= decay_start { + return inverse_normalizer(decay_start, current_time, config.end_date.unwrap()); + } + } + Decimal::one() +} + +/// Get the inverse normalized value [0,1] of x between [min, max] +pub fn inverse_normalizer(min: u64, x: u64, max: u64) -> Decimal { + Decimal::from_ratio(max - x, max - min) +} + +// src: https://github.com/public-awesome/launchpad/blob/main/contracts/sg-eth-airdrop/src/claim_airdrop.rs#L85 +pub mod validation { + use super::*; + use ethereum_verify::verify_ethereum_text; + use shade_protocol::{airdrop::InstantiateMsg, c_std::StdError}; + + pub fn validate_instantiation_params( + info: MessageInfo, + msg: InstantiateMsg, + ) -> Result<(), StdError> { + // validate_airdrop_amount(msg.airdrop_amount)?; + validate_plaintext_msg(msg.claim_msg_plaintext)?; + // validate_instantiate_funds(info)?; + Ok(()) + } + + pub fn compute_plaintext_msg(config: &Config, info: MessageInfo) -> String { + str::replace( + &config.claim_msg_plaintext, + "{wallet}", + info.sender.as_ref(), + ) + } + + pub fn validate_claim( + deps: &DepsMut, + info: MessageInfo, + eth_pubkey: String, + eth_sig: String, + config: Config, + ) -> Result<(), StdError> { + validate_eth_sig(deps, info, eth_pubkey.clone(), eth_sig, config)?; + Ok(()) + } + + fn validate_eth_sig( + deps: &DepsMut, + info: MessageInfo, + eth_pubkey: String, + eth_sig: String, + config: Config, + ) -> Result<(), StdError> { + let valid_eth_sig = + validate_ethereum_text(deps, info, &config, eth_sig, eth_pubkey.clone())?; + match valid_eth_sig { + true => Ok(()), + false => Err(StdError::generic_err("cannot validate eth_sig")), + } + } + + pub fn validate_ethereum_text( + deps: &DepsMut, + info: MessageInfo, + config: &Config, + eth_sig: String, + eth_pubkey: String, + ) -> StdResult { + let plaintext_msg = compute_plaintext_msg(config, info); + match hex::decode(eth_sig.clone()) { + Ok(eth_sig_hex) => { + verify_ethereum_text(deps.as_ref(), &plaintext_msg, ð_sig_hex, ð_pubkey) + } + Err(_) => Err(StdError::InvalidHex { + msg: format!("Could not decode {eth_sig}"), + }), + } + } + + pub fn validate_plaintext_msg(plaintext_msg: String) -> Result<(), StdError> { + if !plaintext_msg.contains("{wallet}") { + return Err(StdError::generic_err( + "Plaintext message must contain `{{wallet}}` string", + )); + } + if plaintext_msg.len() > 1000 { + return Err(StdError::generic_err("Plaintext message is too long")); + } + Ok(()) + } +} diff --git a/contracts/airdrop/src/lib.rs b/contracts/airdrop/src/lib.rs new file mode 100644 index 0000000..4fab968 --- /dev/null +++ b/contracts/airdrop/src/lib.rs @@ -0,0 +1,7 @@ +pub mod contract; +pub mod handle; +pub mod query; +pub mod state; + +#[cfg(test)] +mod test; \ No newline at end of file diff --git a/contracts/airdrop/src/query.rs b/contracts/airdrop/src/query.rs new file mode 100644 index 0000000..6780f15 --- /dev/null +++ b/contracts/airdrop/src/query.rs @@ -0,0 +1,134 @@ +use crate::{ + handle::decay_factor, + state::{ + account_r, + account_total_claimed_r, + account_viewkey_r, + claim_status_r, + config_r, + decay_claimed_r, + total_claimed_r, + validate_account_permit, + }, +}; +use shade_protocol::{ + airdrop::{ + account::{AccountKey, AccountPermit}, + claim_info::RequiredTask, + errors::invalid_viewing_key, + QueryAnswer, + }, + c_std::{Addr, Deps, StdResult, Uint128}, + query_authentication::viewing_keys::ViewingKey, +}; + +pub fn config(deps: Deps) -> StdResult { + Ok(QueryAnswer::Config { + config: config_r(deps.storage).load()?, + }) +} + +pub fn dates(deps: Deps, current_date: Option) -> StdResult { + let config = config_r(deps.storage).load()?; + Ok(QueryAnswer::Dates { + start: config.start_date, + end: config.end_date, + decay_start: config.decay_start, + decay_factor: current_date.map(|date| Uint128::new(100u128) * decay_factor(date, &config)), + }) +} + +pub fn total_claimed(deps: Deps) -> StdResult { + let claimed: Uint128; + let total_claimed = total_claimed_r(deps.storage).load()?; + if decay_claimed_r(deps.storage).load()? { + claimed = total_claimed; + } else { + let config = config_r(deps.storage).load()?; + claimed = total_claimed.checked_div(config.query_rounding)? * config.query_rounding; + } + Ok(QueryAnswer::TotalClaimed { claimed }) +} + +fn account_information( + deps: Deps, + account_address: Addr, + current_date: Option, +) -> StdResult { + let account = account_r(deps.storage).load(account_address.to_string().as_bytes())?; + + // Calculate eligible tasks + let config = config_r(deps.storage).load()?; + let mut finished_tasks: Vec = vec![]; + let mut completed_percentage = Uint128::zero(); + let mut unclaimed_percentage = Uint128::zero(); + for (index, task) in config.task_claim.iter().enumerate() { + // Check if task has been completed + let state = + claim_status_r(deps.storage, index).may_load(account_address.to_string().as_bytes())?; + + match state { + // Ignore if none + None => {} + Some(claimed) => { + finished_tasks.push(task.clone()); + if !claimed { + unclaimed_percentage += task.percent; + } else { + completed_percentage += task.percent; + } + } + } + } + + let mut unclaimed: Uint128; + + if unclaimed_percentage == Uint128::new(100u128) { + unclaimed = account.total_claimable; + } else { + unclaimed = + unclaimed_percentage.multiply_ratio(account.total_claimable, Uint128::new(100u128)); + } + + if let Some(time) = current_date { + unclaimed = unclaimed * decay_factor(time, &config); + } + + Ok(QueryAnswer::Account { + total: account.total_claimable, + claimed: account_total_claimed_r(deps.storage) + .load(account_address.to_string().as_bytes())?, + unclaimed, + finished_tasks, + addresses: account.addresses, + }) +} + +pub fn account( + deps: Deps, + permit: AccountPermit, + current_date: Option, +) -> StdResult { + let config = config_r(deps.storage).load()?; + account_information( + deps, + validate_account_permit(deps, &permit, config.contract)?, + current_date, + ) +} + +pub fn account_with_key( + deps: Deps, + account: Addr, + key: String, + current_date: Option, +) -> StdResult { + // Validate address + let stored_hash = account_viewkey_r(deps.storage).load(account.to_string().as_bytes())?; + + if !AccountKey(key).compare(&stored_hash) { + return Err(invalid_viewing_key()); + } + + account_information(deps, account, current_date) +} diff --git a/contracts/airdrop/src/state.rs b/contracts/airdrop/src/state.rs new file mode 100644 index 0000000..6d54af7 --- /dev/null +++ b/contracts/airdrop/src/state.rs @@ -0,0 +1,212 @@ +use shade_protocol::c_std::{Addr, Api, StdResult, Storage}; +use shade_protocol::c_std::{Deps, Uint128}; +use shade_protocol::contract_interfaces::airdrop::{ + account::{ + authenticate_ownership, Account, AccountPermit, AddressProofMsg, AddressProofPermit, + }, + errors::{permit_contract_mismatch, permit_key_revoked}, + Config, +}; +use shade_protocol::storage::{ + bucket, bucket_read, singleton, singleton_read, Bucket, ReadonlyBucket, ReadonlySingleton, + Singleton, +}; + +pub static CONFIG_KEY: &[u8] = b"config"; +pub static DECAY_CLAIMED_KEY: &[u8] = b"decay_claimed"; +pub static CLAIM_STATUS_KEY: &[u8] = b"claim_status_"; +pub static REWARD_IN_ACCOUNT_KEY: &[u8] = b"reward_in_account"; +pub static ACCOUNTS_KEY: &[u8] = b"accounts"; +pub static TOTAL_CLAIMED_KEY: &[u8] = b"total_claimed"; +pub static USER_TOTAL_CLAIMED_KEY: &[u8] = b"user_total_claimed"; +pub static ACCOUNT_PERMIT_KEY: &str = "account_permit_key"; +pub static ACCOUNT_VIEWING_KEY: &[u8] = b"account_viewing_key"; +pub static ETH_PUBKEY_IN_ACCOUNT_KEY: &str = "eth_pubkey_in_account"; +pub static ETH_SIG_IN_ACCOUNT_KEY: &str = "eth_sig_in_account"; +pub static ETH_PUBKEY: &str = "eth_pubkey"; + +pub fn config_w(storage: &mut dyn Storage) -> Singleton { + singleton(storage, CONFIG_KEY) +} + +pub fn config_r(storage: &dyn Storage) -> ReadonlySingleton { + singleton_read(storage, CONFIG_KEY) +} + +pub fn decay_claimed_w(storage: &mut dyn Storage) -> Singleton { + singleton(storage, DECAY_CLAIMED_KEY) +} + +pub fn decay_claimed_r(storage: &dyn Storage) -> ReadonlySingleton { + singleton_read(storage, DECAY_CLAIMED_KEY) +} + +// Is address added to an account +pub fn address_in_account_r(storage: &dyn Storage) -> ReadonlyBucket { + bucket_read(storage, REWARD_IN_ACCOUNT_KEY) +} + +pub fn address_in_account_w(storage: &mut dyn Storage) -> Bucket { + bucket(storage, REWARD_IN_ACCOUNT_KEY) +} + +// airdrop account +pub fn account_r(storage: &dyn Storage) -> ReadonlyBucket { + bucket_read(storage, ACCOUNTS_KEY) +} + +pub fn account_w(storage: &mut dyn Storage) -> Bucket { + bucket(storage, ACCOUNTS_KEY) +} + +// If not found then its unrewarded; if true then claimed +pub fn claim_status_r(storage: &dyn Storage, index: usize) -> ReadonlyBucket { + let mut key = CLAIM_STATUS_KEY.to_vec(); + key.push(index as u8); + bucket_read(storage, &key) +} + +pub fn claim_status_w(storage: &mut dyn Storage, index: usize) -> Bucket { + let mut key = CLAIM_STATUS_KEY.to_vec(); + key.push(index as u8); + bucket(storage, &key) +} + +// Total claimed +pub fn total_claimed_r(storage: &dyn Storage) -> ReadonlySingleton { + singleton_read(storage, TOTAL_CLAIMED_KEY) +} + +pub fn total_claimed_w(storage: &mut dyn Storage) -> Singleton { + singleton(storage, TOTAL_CLAIMED_KEY) +} + +// Total account claimed +pub fn account_total_claimed_r(storage: &dyn Storage) -> ReadonlyBucket { + bucket_read(storage, USER_TOTAL_CLAIMED_KEY) +} + +pub fn account_total_claimed_w(storage: &mut dyn Storage) -> Bucket { + bucket(storage, USER_TOTAL_CLAIMED_KEY) +} + +// Account viewing key +pub fn account_viewkey_r(storage: &dyn Storage) -> ReadonlyBucket<[u8; 32]> { + bucket_read(storage, ACCOUNT_VIEWING_KEY) +} + +pub fn account_viewkey_w(storage: &mut dyn Storage) -> Bucket<[u8; 32]> { + bucket(storage, ACCOUNT_VIEWING_KEY) +} + +// Account permit key +pub fn account_permit_key_r(storage: &dyn Storage, account: String) -> ReadonlyBucket { + let key = ACCOUNT_PERMIT_KEY.to_string() + &account; + bucket_read(storage, key.as_bytes()) +} + +pub fn account_permit_key_w(storage: &mut dyn Storage, account: String) -> Bucket { + let key = ACCOUNT_PERMIT_KEY.to_string() + &account; + bucket(storage, key.as_bytes()) +} + +pub fn revoke_permit(storage: &mut dyn Storage, account: String, permit_key: String) { + account_permit_key_w(storage, account) + .save(permit_key.as_bytes(), &false) + .unwrap(); +} + +// Is address added to an account +pub fn eth_pubkey_in_account_r(storage: &dyn Storage) -> ReadonlyBucket { + let key = ETH_PUBKEY_IN_ACCOUNT_KEY.to_string(); + bucket_read(storage, key.as_bytes()) +} + +pub fn eth_pubkey_in_account_w(storage: &mut dyn Storage) -> Bucket { + let key = ETH_PUBKEY_IN_ACCOUNT_KEY.to_string(); + bucket(storage, key.as_bytes()) +} +// Is address added to an account +pub fn eth_sig_in_account_r(storage: &dyn Storage) -> ReadonlyBucket { + let key = ETH_SIG_IN_ACCOUNT_KEY.to_string(); + bucket_read(storage, key.as_bytes()) +} + +pub fn eth_sig_in_account_w(storage: &mut dyn Storage) -> Bucket { + let key = ETH_SIG_IN_ACCOUNT_KEY.to_string(); + bucket(storage, key.as_bytes()) +} + +// Eth pubkey claimed +pub fn eth_pubkey_claim_r(storage: &dyn Storage) -> ReadonlyBucket { + let key = ETH_PUBKEY.to_string(); + bucket_read(storage, key.as_bytes()) +} + +pub fn eth_pubkey_claim_w(storage: &mut dyn Storage) -> Bucket { + let key = ETH_PUBKEY.to_string(); + bucket(storage, key.as_bytes()) +} + +pub fn is_permit_revoked( + storage: &dyn Storage, + account: String, + permit_key: String, +) -> StdResult { + if account_permit_key_r(storage, account) + .may_load(permit_key.as_bytes())? + .is_some() + { + Ok(true) + } else { + Ok(false) + } +} + +pub fn validate_address_permit( + storage: &dyn Storage, + api: &dyn Api, + permit: &AddressProofPermit, + params: &AddressProofMsg, + contract: Addr, +) -> StdResult<()> { + // Check that contract matches + if params.contract != contract { + return Err(permit_contract_mismatch( + params.contract.as_str(), + contract.as_str(), + )); + } + + // Check that permit is not revoked + if is_permit_revoked(storage, params.address.to_string(), params.key.clone())? { + return Err(permit_key_revoked(params.key.as_str())); + } + + // Authenticate permit + authenticate_ownership(api, permit, params.address.as_str()) +} + +pub fn validate_account_permit( + deps: Deps, + permit: &AccountPermit, + contract: Addr, +) -> StdResult { + // Check that contract matches + if permit.params.contract != contract { + return Err(permit_contract_mismatch( + permit.params.contract.as_str(), + contract.as_str(), + )); + } + + // Authenticate permit + let address = permit.validate(deps.api, None)?.as_addr(None)?; + + // Check that permit is not revoked + if is_permit_revoked(deps.storage, address.to_string(), permit.params.key.clone())? { + return Err(permit_key_revoked(permit.params.key.as_str())); + } + + return Ok(address); +} diff --git a/contracts/airdrop/src/test.rs b/contracts/airdrop/src/test.rs new file mode 100644 index 0000000..af4835c --- /dev/null +++ b/contracts/airdrop/src/test.rs @@ -0,0 +1,346 @@ +#[cfg(test)] +pub mod tests { + use crate::handle::inverse_normalizer; + use shade_protocol::{ + airdrop::account::{AddressProofMsg, AddressProofPermit, FillerMsg}, + c_std::{from_binary, testing::mock_dependencies, Addr, Binary, Uint128}, + query_authentication::{ + permit::bech32_to_canonical, + transaction::{PermitSignature, PubKey}, + }, + }; + + #[test] + fn decay_factor() { + assert_eq!( + Uint128::new(50u128), + Uint128::new(100u128) * inverse_normalizer(100, 200, 300) + ); + + assert_eq!( + Uint128::new(25u128), + Uint128::new(100u128) * inverse_normalizer(0, 75, 100) + ); + } + + const MSGTYPE: &str = "wasm/MsgExecuteContract"; + + #[test] + fn terra_station_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("columbus-5".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "Ar7aIv8k6Rm7ugLBAHShtRWmZ/CDgvwXYOc8Ffycwggc").unwrap()), + signature: Binary::from_base64( + "MM1UOheGCYX0Cb3r8zVhyZyWk/qIY61yqiDP53//31cjkd7G5FfEki+JC91kBRYCnt9NlI7gjnY8ZcJauDH3FA==").unwrap(), + }, + account_number: Some(Uint128::new(3441602u128).into()), + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("terra17dhvxnwzazszgtuc498qsudh7zq945qh29gj4e") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("terra19m2zgdyuq0crpww00jc2a9k70ut944dum53p7x") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // NOTE: New SN broke unit testing + // assert!( + // permit + // .validate(&deps.api, Some("wasm/MsgExecuteContract".to_string())) + // .is_err() + // ) + } + + #[test] + fn terra_station_non_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("columbus-5".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "A8r22cTiywZYSoWR5DnmAeP1jPDF3CLVKJe1QGorv9cM").unwrap()), + signature: Binary::from_base64( + "xhU2JkJDWO/eZEeJVp8vo1rNAK7H7G2uDucZAjAhfVRjLHHX7C+16dwQzr0Jmd2DdZHAJZNkGhGb5nucicN1TA==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("terra1j8wupj3kpclp98dgg4j5am44kjykx6uztjttyr") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("terra1ns69jhkjg5wmcgf8w8ecewnpca7sezyhvg0a29") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_terra_non_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("columbus-5".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "AyGKvc3OCs/pg7unFCJgKjtqiLYRACeR4ZU0f8UVDFbM").unwrap()), + signature: Binary::from_base64( + "fbgFeYUsAjI2CB2dwaqttolFE1wx/3MXbNWYKicJj20mV3marS4zz+k5aCKsYlv4HSd9NYxl4deuhasMKndB2w==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("terra18xg6g5yfzflnt8v45r2yndnydhg2vndvzsv3rn") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("terra1ns69jhkjg5wmcgf8w8ecewnpca7sezyhvg0a29") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_terra_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("columbus-5".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "AqjDFVbY+znM1F5XCDuaca0JT0uAdd3QyuHt04j9k0DB").unwrap()), + signature: Binary::from_base64( + "1kwDnlsltqgj8fqbohs0MMgEWiRMUmznM98ofOranBAe5f8Ja1tZCKmh5miPkgC6KoUdOam7BvBjuFhM1q0rBA==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("terra1ns69jhkjg5wmcgf8w8ecewnpca7sezyhvg0a29") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("terra18xg6g5yfzflnt8v45r2yndnydhg2vndvzsv3rn") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_sn_non_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("secret-4".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "A2uZZ02iy/QhPZ0s6WO8HTEfNZEnt5o5PsQ34WHmQFPK").unwrap()), + signature: Binary::from_base64( + "s80mH5OuZCudS20d0k73evWx5xGrC2l3uubQjIkukT4L5mcgsepDIq9d1YpAJwiUEitaHFOGy42MfHZJVY1LdA==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("secret19q7h2zy8mgesy3r39el5fcm986nxqjd7cgylrz") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("secret1ns69jhkjg5wmcgf8w8ecewnpca7sezyhgfp54e") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_sn_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("secret-4".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "AqjDFVbY+znM1F5XCDuaca0JT0uAdd3QyuHt04j9k0DB").unwrap()), + signature: Binary::from_base64( + "snd8k5nWAAVoUytxKZt1FCUNQNXLAQpBlF7h4YGbTmx3S5+rqaZnM2bKq1ifCvErz/pdeE7B/s+WsGLdQRpzoA==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("secret1ns69jhkjg5wmcgf8w8ecewnpca7sezyhgfp54e") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("secret19q7h2zy8mgesy3r39el5fcm986nxqjd7cgylrz") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_cosmos_non_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("cosmoshub-4".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "AqcyBLqPn7QnOctkK9i9KhnhD0aHA03+LppvNTCdZ1wK").unwrap()), + signature: Binary::from_base64( + "KLwotev7wnbj2VGBxbyTfIrRn/1vQY3x3I7BAUhu4FIC6OHVXqxIl/lclgdBWksnr32ULVfz8u78OqEbaePRZQ==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("cosmos1lj5vh5y8yp4a97jmfwpd98lsg0tf5lsqgnnhq3") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("cosmos1ns69jhkjg5wmcgf8w8ecewnpca7sezyh2v4ag9") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn keplr_cosmos_ledger() { + let mut permit = AddressProofPermit { + params: FillerMsg::default(), + chain_id: Some("cosmoshub-4".to_string()), + sequence: None, + signature: PermitSignature { + pub_key: PubKey::new(Binary::from_base64( + "AqjDFVbY+znM1F5XCDuaca0JT0uAdd3QyuHt04j9k0DB").unwrap()), + signature: Binary::from_base64( + "h/RpG1eKzN03oId0GvN7TSxoHOUibjmqPEQ1E+ZWh+BvghPL99lBj4L3BKpjjsaRtXX3lexO7ztafLKBVtq4xA==").unwrap(), + }, + account_number: None, + memo: Some("eyJhbW91bnQiOiIxMDAwMDAwMCIsImluZGV4IjoxMCwia2V5IjoiYWNjb3VudC1jcmVhdGlvbi1wZXJtaXQifQ==".to_string()) + }; + + let deps = mock_dependencies(); + let addr = permit + .validate(&deps.api, Some(MSGTYPE.to_string())) + .expect("Signature validation failed"); + assert_eq!( + addr.as_canonical(), + bech32_to_canonical("cosmos1ns69jhkjg5wmcgf8w8ecewnpca7sezyh2v4ag9") + ); + assert_ne!( + addr.as_canonical(), + bech32_to_canonical("cosmos1lj5vh5y8yp4a97jmfwpd98lsg0tf5lsqgnnhq3") + ); + + permit.memo = Some("OtherMemo".to_string()); + + // assert!(permit.validate(&deps.api, Some(MSGTYPE.to_string())).is_err()) + } + + #[test] + fn memo_deserialization() { + let expected_memo = AddressProofMsg { + address: Addr::unchecked("secret19q7h2zy8mgesy3r39el5fcm986nxqjd7cgylrz".to_string()), + amount: Uint128::new(1000000u128), + contract: Addr::unchecked("secret1sr62lehajgwhdzpmnl65u35rugjrgznh2572mv".to_string()), + index: 10, + key: "account-creation-permit".to_string(), + }; + + let deserialized_memo: AddressProofMsg = from_binary( + &Binary::from_base64( + &"eyJhZGRyZXNzIjoic2VjcmV0MTlxN2gyenk4bWdlc3kzcjM5ZWw1ZmNtOTg2bnhxamQ3Y2d5bHJ6IiwiYW1vdW50IjoiMTAwMDAwMCIsImNvbnRyYWN0Ijoic2VjcmV0MXNyNjJsZWhhamd3aGR6cG1ubDY1dTM1cnVnanJnem5oMjU3Mm12IiwiaW5kZXgiOjEwLCJrZXkiOiJhY2NvdW50LWNyZWF0aW9uLXBlcm1pdCJ9" + .to_string()).unwrap()).unwrap(); + + assert_eq!(deserialized_memo, expected_memo) + } + + #[test] + fn claim_query() { + assert_eq!( + Uint128::new(300u128), + (Uint128::new(345u128) / Uint128::new(100u128)) * Uint128::new(100u128) + ) + } + + #[test] + fn claim_query_odd_multiple() { + assert_eq!( + Uint128::new(13475u128), + (Uint128::new(13480u128) / Uint128::new(7u128)) * Uint128::new(7u128) + ) + } + + #[test] + fn claim_query_under_step() { + assert_eq!( + Uint128::zero(), + (Uint128::new(200u128) / Uint128::new(1000u128)) * Uint128::new(1000u128) + ) + } +} diff --git a/contracts/headstash-contract/.cargo/config b/contracts/headstash-contract/.cargo/config deleted file mode 100644 index de2d36a..0000000 --- a/contracts/headstash-contract/.cargo/config +++ /dev/null @@ -1,5 +0,0 @@ -[alias] -wasm = "build --release --lib --target wasm32-unknown-unknown" -wasm-debug = "build --lib --target wasm32-unknown-unknown" -unit-test = "test --lib" -schema = "run --bin schema" diff --git a/contracts/headstash-contract/.gitignore b/contracts/headstash-contract/.gitignore deleted file mode 100644 index dfdaaa6..0000000 --- a/contracts/headstash-contract/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# Build results -/target - -# Cargo+Git helper file (https://github.com/rust-lang/cargo/blob/0.44.1/src/cargo/sources/git/utils.rs#L320-L327) -.cargo-ok - -# Text file backups -**/*.rs.bk - -# macOS -.DS_Store - -# IDEs -*.iml -.idea diff --git a/contracts/headstash-contract/Cargo.toml b/contracts/headstash-contract/Cargo.toml deleted file mode 100644 index 4729731..0000000 --- a/contracts/headstash-contract/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "headstash-contract" -version = { workspace = true } -authors = ["A Hardnett "] -edition = { workspace = true } -description = "An Airdrop contract for allowing users to claim rewards with Merkle Tree based proof" -license = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -backtraces = ["cosmwasm-std/backtraces"] -library = [] - -[dependencies] -ethereum-verify = "3.3.0" -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -cw2 = { workspace = true } -cosmwasm-std = { workspace = true } -hex = "0.4" -schemars = { workspace = true } -serde = { workspace = true } -sha2 = { version = "0.9.5", default-features = false } -thiserror = { workspace = true } - -[dev-dependencies] -cosmwasm-schema = { workspace = true } -serde_json = "1" diff --git a/contracts/headstash-contract/examples/schema.rs b/contracts/headstash-contract/examples/schema.rs deleted file mode 100644 index 87cea6e..0000000 --- a/contracts/headstash-contract/examples/schema.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::env::current_dir; -use std::fs::create_dir_all; - -use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; -use headstash_contract::msg::{ - ConfigResponse, ExecuteMsg, InstantiateMsg, IsClaimedResponse, - MerkleRootResponse, QueryMsg, -}; - -fn main() { - let mut out_dir = current_dir().unwrap(); - out_dir.push("schema"); - create_dir_all(&out_dir).unwrap(); - remove_schemas(&out_dir).unwrap(); - - export_schema(&schema_for!(InstantiateMsg), &out_dir); - export_schema(&schema_for!(ExecuteMsg), &out_dir); - export_schema(&schema_for!(QueryMsg), &out_dir); - export_schema(&schema_for!(MerkleRootResponse), &out_dir); - export_schema(&schema_for!(IsClaimedResponse), &out_dir); - export_schema(&schema_for!(ConfigResponse), &out_dir); -} diff --git a/contracts/headstash-contract/src/contract.rs b/contracts/headstash-contract/src/contract.rs deleted file mode 100644 index 8f9409f..0000000 --- a/contracts/headstash-contract/src/contract.rs +++ /dev/null @@ -1,353 +0,0 @@ -#[cfg(not(feature = "library"))] -use cosmwasm_std::entry_point; -use cosmwasm_std::{ - attr, coin,to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, - Uint128, BankMsg, CosmosMsg, DistributionMsg, -}; -use cw2::{get_contract_version, set_contract_version}; -use crate::contract::validation::validate_claim; -use sha2::Digest; -use std::convert::TryInto; - -use crate::error::ContractError; -use crate::msg::{ - ConfigResponse, ExecuteMsg, InstantiateMsg, IsClaimedResponse, - MerkleRootResponse, MigrateMsg, QueryMsg, TotalClaimedResponse, -}; -use crate::state::{ - Config, NATIVE_FEE_DENOM, NATIVE_BOND_DENOM, CLAIM, CONFIG, MERKLE_ROOT, AMOUNT_CLAIMED, - PAUSED, AMOUNT -}; - -// Version info, for migration info -const CONTRACT_NAME: &str = "crates.io:headstash-contract"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn instantiate( - deps: DepsMut, - _env: Env, - info: MessageInfo, - msg: InstantiateMsg, -) -> Result { - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - - // set paused state to false - PAUSED.save(deps.storage, &false)?; - - // define config - let config = Config { - owner: info.sender, - claim_msg_plaintext: msg.claim_msg_plaintext, - }; - CONFIG.save(deps.storage, &config)?; - - // check merkle root length - let mut root_buf: [u8; 32] = [0; 32]; - hex::decode_to_slice(&msg.merkle_root, &mut root_buf)?; - - MERKLE_ROOT.save(deps.storage, &msg.merkle_root)?; - - // save total airdropped amount - let amount = msg.total_amount.unwrap_or_else(Uint128::zero); - AMOUNT.save(deps.storage, &amount)?; - AMOUNT_CLAIMED.save(deps.storage, &Uint128::zero())?; - - Ok(Response::new().add_attributes(vec![ - attr("action", "instantiate"), - attr("merkle_root", msg.merkle_root), - attr("total_amount", amount), - ])) -} - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn execute( - deps: DepsMut, - env: Env, - info: MessageInfo, - msg: ExecuteMsg, -) -> Result { - match msg { - ExecuteMsg::Claim { amount, eth_pubkey, eth_sig , proof } => execute_claim(deps, env, info, amount, eth_pubkey, eth_sig, proof ), - ExecuteMsg::ClawBack { recipient } => {execute_clawback(deps, env, info, Some(recipient))}, - ExecuteMsg::Pause {} => execute_pause(deps, env, info), - ExecuteMsg::Resume {} => execute_resume(deps,env,info) - } -} - -pub fn execute_claim( - deps: DepsMut, - _env: Env, - info: MessageInfo, - amount: Uint128, - eth_pubkey: String, - eth_sig: String, - proof: Vec, -) -> Result { - - let is_paused = PAUSED.load(deps.storage)?; - if is_paused { - return Err(ContractError::Paused {}); - } - - // verify not claimed - let claimed = CLAIM.may_load(deps.storage, eth_pubkey.clone())?; - if claimed.is_some() { - return Err(ContractError::Claimed {}); - } - - // verify merkle root - let config = CONFIG.load(deps.storage)?; - let merkle_root = MERKLE_ROOT.load(deps.storage)?; - - // validate the eth_sig was generated with the eth_pubkey provided - validate_claim( &deps, - info.clone(), - eth_pubkey.clone(), - eth_sig, - config.clone(), - )?; - - // generate merkleTree leaf with eth_pubkey & amount - let user_input = format!("{}{}", eth_pubkey, amount); - let hash = sha2::Sha256::digest(user_input.as_bytes()) - .as_slice() - .try_into() - .map_err(|_| ContractError::WrongLength {})?; - - let hash = proof.into_iter().try_fold(hash, |hash, p| { - let mut proof_buf = [0; 32]; - hex::decode_to_slice(p, &mut proof_buf)?; - let mut hashes = [hash, proof_buf]; - hashes.sort_unstable(); - sha2::Sha256::digest(&hashes.concat()) - .as_slice() - .try_into() - .map_err(|_| ContractError::WrongLength {}) - })?; - - let mut root_buf: [u8; 32] = [0; 32]; - hex::decode_to_slice(merkle_root, &mut root_buf)?; - if root_buf != hash { - return Err(ContractError::VerificationFailed {}); - } - - // update claim index - CLAIM.save(deps.storage, eth_pubkey, &true)?; - - // Update total claimed to reflect - let mut claimed_amount = AMOUNT_CLAIMED.load(deps.storage)?; - claimed_amount += amount; - AMOUNT_CLAIMED.save(deps.storage, &claimed_amount)?; - - let bank_msg = CosmosMsg::Bank(BankMsg::Send { - to_address: info.sender.to_string(), - amount: vec![coin(amount.u128(), NATIVE_BOND_DENOM), - coin(amount.u128(), NATIVE_FEE_DENOM),], - }); - - let res = Response::new() - .add_message(bank_msg) - .add_attributes(vec![ - attr("action", "claim"), - attr("address", info.sender), - attr("amount", amount), - ]); - Ok(res) -} - -pub fn execute_clawback( - deps: DepsMut, - _env: Env, - info: MessageInfo, - _recipient: Option, -) -> Result { - let cfg = CONFIG.load(deps.storage)?; - - // authorize owner - if info.sender != cfg.owner { - return Err(ContractError::Unauthorized {}) - } - - // error if contract is paused - let is_paused = PAUSED.load(deps.storage)?; - if is_paused { - return Err(ContractError::Paused {}); - } - - let claimed = AMOUNT_CLAIMED.load(deps.storage)?; - let total_amount = AMOUNT.load(deps.storage)?; - // get balance - let balance_to_burn = total_amount.checked_sub(claimed)?; - - // clawback to community pool - let clawback_msg = CosmosMsg::Distribution(DistributionMsg::FundCommunityPool { - amount: vec![coin(balance_to_burn.u128(), NATIVE_BOND_DENOM), - coin(balance_to_burn.u128(), NATIVE_FEE_DENOM),], - }); - - // Burn the tokens and response - let mut res = Response::new().add_attribute("action", "clawback"); - - res = res - .add_message(clawback_msg) - .add_attributes(vec![ - attr("amount", balance_to_burn), - ]); - - Ok(res) -} - -pub fn execute_pause( - deps: DepsMut, - _env: Env, - info: MessageInfo, -) -> Result { - let cfg = CONFIG.load(deps.storage)?; - if info.sender != cfg.owner { - return Err(ContractError::Unauthorized {}); - } - - PAUSED.save(deps.storage, &true)?; - Ok(Response::new().add_attributes(vec![attr("action", "pause"), attr("paused", "true")])) -} - -pub fn execute_resume( - deps: DepsMut, - _env: Env, - info: MessageInfo, -) -> Result { - // authorize owner - let cfg = CONFIG.load(deps.storage)?; - if info.sender != cfg.owner { - return Err(ContractError::Unauthorized {}); - } - - let is_paused = PAUSED.load(deps.storage)?; - if !is_paused { - return Err(ContractError::NotPaused {}); - } - - PAUSED.save(deps.storage, &false)?; - Ok(Response::new().add_attributes(vec![attr("action", "resume"), attr("paused", "false")])) -} - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { - match msg { - QueryMsg::Config {} => to_json_binary(&query_config(deps)?), - QueryMsg::MerkleRoot {} => to_json_binary(&query_merkle_root(deps)?), - QueryMsg::IsClaimed { address } => { - to_json_binary(&query_is_claimed(deps, address)?) - } - QueryMsg::TotalClaimed {} => to_json_binary(&query_total_claimed(deps)?), - } -} - -pub fn query_config(deps: Deps) -> StdResult { - let cfg = CONFIG.load(deps.storage)?; - Ok(ConfigResponse { - owner: Some(cfg.owner.to_string()), - claim_msg_plaintext: cfg.claim_msg_plaintext.to_string(), - }) -} - -pub fn query_merkle_root(deps: Deps) -> StdResult { - let merkle_root = MERKLE_ROOT.load(deps.storage)?; - let total_amount = AMOUNT.load(deps.storage)?; - - let resp = MerkleRootResponse { - merkle_root, - total_amount, - }; - - Ok(resp) -} - -pub fn query_is_claimed(deps: Deps, address: String) -> StdResult { - let is_claimed = CLAIM.may_load(deps.storage, address)?.unwrap_or(false); - let resp = IsClaimedResponse { is_claimed }; - - Ok(resp) -} - -pub fn query_total_claimed(deps: Deps) -> StdResult { - let total_claimed = AMOUNT_CLAIMED.load(deps.storage)?; - let resp = TotalClaimedResponse { total_claimed }; - - Ok(resp) -} - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result { - let version = get_contract_version(deps.storage)?; - if version.contract != CONTRACT_NAME { - return Err(ContractError::CannotMigrate { - previous_contract: version.contract, - }); - } - Ok(Response::default()) -} - -// src: https://github.com/public-awesome/launchpad/blob/main/contracts/sg-eth-airdrop/src/claim_airdrop.rs#L85 -mod validation { - use super::*; - use cosmwasm_std::StdError; - use ethereum_verify::verify_ethereum_text; - - use crate::state::Config; - - pub fn compute_plaintext_msg(config: &Config, info: MessageInfo) -> String { - str::replace( - &config.claim_msg_plaintext, - "{wallet}", - info.sender.as_ref(), - ) - } - - pub fn validate_claim( - deps: &DepsMut, - info: MessageInfo, - eth_pubkey: String, - eth_sig: String, - config: Config, - ) -> Result<(), ContractError> { - validate_eth_sig(deps, info, eth_pubkey.clone(), eth_sig, config)?; - Ok(()) - } - - fn validate_eth_sig( - deps: &DepsMut, - info: MessageInfo, - eth_pubkey: String, - eth_sig: String, - config: Config, - ) -> Result<(), ContractError> { - let valid_eth_sig = - validate_ethereum_text(deps, info, &config, eth_sig, eth_pubkey.clone())?; - match valid_eth_sig { - true => Ok(()), - false => Err(ContractError::AddressNotEligible { - eth_pubkey: eth_pubkey, - }), - } - } - - pub fn validate_ethereum_text( - deps: &DepsMut, - info: MessageInfo, - config: &Config, - eth_sig: String, - eth_pubkey: String, - ) -> StdResult { - let plaintext_msg = compute_plaintext_msg(config, info); - match hex::decode(eth_sig.clone()) { - Ok(eth_sig_hex) => { - verify_ethereum_text(deps.as_ref(), &plaintext_msg, ð_sig_hex, ð_pubkey) - } - Err(_) => Err(StdError::InvalidHex { - msg: format!("Could not decode {eth_sig}"), - }), - } - } -} diff --git a/contracts/headstash-contract/src/error.rs b/contracts/headstash-contract/src/error.rs deleted file mode 100644 index 9cf4209..0000000 --- a/contracts/headstash-contract/src/error.rs +++ /dev/null @@ -1,62 +0,0 @@ -use cosmwasm_std::{OverflowError, StdError}; -use hex::FromHexError; -use thiserror::Error; - -#[derive(Error, Debug, PartialEq)] -pub enum ContractError { - #[error("{0}")] - Std(#[from] StdError), - - #[error("{0}")] - Hex(#[from] FromHexError), - - #[error("Unauthorized")] - Unauthorized {}, - - #[error("Already claimed")] - Claimed {}, - - #[error("Wrong length")] - WrongLength {}, - - #[error("Verification failed")] - VerificationFailed {}, - - #[error("Cannot migrate from different contract type: {previous_contract}")] - CannotMigrate { previous_contract: String }, - - #[error("Invalid input")] - InvalidInput {}, - - #[error("Airdrop expired at {expiration}")] - Expired { expiration: u64 }, - - - #[error("Address {eth_pubkey} is not eligible")] - AddressNotEligible { eth_pubkey: String }, - - #[error("withdraw_all is unavailable, it will become available at {available_at}")] - WithdrawAllUnavailable { available_at: u64 }, - - #[error("Airdrop begins at {start}")] - NotBegun { start: u64 }, - - #[error("Airdrop is paused")] - Paused {}, - - #[error("Airdrop is not paused")] - NotPaused {}, - - #[error("Semver parsing error: {0}")] - SemVer(String), - - #[error("Airdrop has not yet expired, it will become available at {available_at}")] - ClawBackUnavailable {available_at: u64}, -} - - -impl From for ContractError { - fn from(err: OverflowError) -> Self { - ContractError::Std(err.into()) - } -} diff --git a/contracts/headstash-contract/src/lib.rs b/contracts/headstash-contract/src/lib.rs deleted file mode 100644 index e6e9265..0000000 --- a/contracts/headstash-contract/src/lib.rs +++ /dev/null @@ -1,28 +0,0 @@ -//#![warn(missing_docs)] -#![doc(html_logo_url = "../../../uml/logo.png")] -//! # WYND Vesting Airdrop -//! -//! ## Description -//! -//! We need a project that allow us to launch the WYND TOKEN and distribute to our community in a vested way. -//! -//! ## Objectives -//! -//! The main goal of the **WYND airdrop** is to: -//! - Distribute WYND TOKEN allowing community members to claim it. -//! - Vest the airdrop tokens to avoid sell presure and make the price of the token more stable at release -//! - -/// Main vesting-airdrop Module -pub mod contract; - -/// custom error handler -mod error; - -/// custom input output messages -pub mod msg; - -/// state on the blockchain -pub mod state; - -pub use crate::error::ContractError; diff --git a/contracts/headstash-contract/src/msg.rs b/contracts/headstash-contract/src/msg.rs deleted file mode 100644 index 8fc34d4..0000000 --- a/contracts/headstash-contract/src/msg.rs +++ /dev/null @@ -1,74 +0,0 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use cosmwasm_std::Uint128; - -#[derive(Serialize, Deserialize, JsonSchema)] -pub struct InstantiateMsg { - /// Owner if none set to info.sender. - pub owner: Option, - /// {address} - pub claim_msg_plaintext: String, - /// merkle root - pub merkle_root: String, - /// total amount - pub total_amount: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum ExecuteMsg { - /// Claim does not check if contract has enough funds, owner must ensure it. - Claim { - amount: Uint128, - /// pubkey (0x...) - eth_pubkey: String, - /// signed by pubkey - eth_sig: String, - /// Proof is hex-encoded merkle proof. - proof: Vec, - }, - /// Recycle the remaining tokens to specified address after expire time (only owner). - /// Don't use Option to avoid typo turning ClawBack into Burn - ClawBack { recipient: String }, - Pause {}, - Resume {}, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum QueryMsg { - Config {}, - MerkleRoot {}, - IsClaimed { address: String }, - TotalClaimed {}, -} - -#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)] -#[serde(rename_all = "snake_case")] -pub struct ConfigResponse { - pub owner: Option, - pub claim_msg_plaintext: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct MerkleRootResponse { - /// MerkleRoot is hex-encoded merkle root. - pub merkle_root: String, - pub total_amount: Uint128, -} - - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct IsClaimedResponse { - pub is_claimed: bool, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct TotalClaimedResponse { - pub total_claimed: Uint128, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct MigrateMsg {} - - diff --git a/contracts/headstash-contract/src/state.rs b/contracts/headstash-contract/src/state.rs deleted file mode 100644 index fe78621..0000000 --- a/contracts/headstash-contract/src/state.rs +++ /dev/null @@ -1,36 +0,0 @@ -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use cosmwasm_std::{Addr, Uint128}; -use cw_storage_plus::{Item, Map}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct Config { - /// Owner If None set, contract is frozen. - pub owner: Addr, - pub claim_msg_plaintext: String, -} -pub const CONFIG: Item = Item::new("config"); - -pub const NATIVE_FEE_DENOM: &str = "uterp"; -pub const NATIVE_BOND_DENOM: &str = "uthiol"; - -// saves external network airdrop accounts -pub const ACCOUNT_MAP_KEY: &str = "account_map"; -// external_address -> host_address -pub const ACCOUNT_MAP: Map = Map::new(ACCOUNT_MAP_KEY); - -pub const MERKLE_ROOT_PREFIX: &str = "merkle_root"; -pub const MERKLE_ROOT: Item = Item::new(MERKLE_ROOT_PREFIX); - -pub const AMOUNT_KEY: &str = "amount"; -pub const AMOUNT: Item = Item::new(AMOUNT_KEY); - -pub const CLAIM_PREFIX: &str = "claim"; -pub const CLAIM: Map = Map::new(CLAIM_PREFIX); - -pub const AMOUNT_CLAIMED_KEY: &str = "claimed_amount"; -pub const AMOUNT_CLAIMED: Item = Item::new(AMOUNT_CLAIMED_KEY); - -pub const PAUSED_KEY: &str = "paused"; -pub const PAUSED: Item = Item::new(PAUSED_KEY); \ No newline at end of file diff --git a/contracts/headstash-contract/testdata/airdrop_stage_1_list.json b/contracts/headstash-contract/testdata/airdrop_stage_1_list.json deleted file mode 100644 index 08368d7..0000000 --- a/contracts/headstash-contract/testdata/airdrop_stage_1_list.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { "address": "wasm1k9hwzxs889jpvd7env8z49gad3a3633vg350tq", "amount": "100"}, - { "address": "wasm1uy9ucvgerneekxpnfwyfnpxvlsx5dzdpf0mzjd", "amount": "1010"}, - { "address": "wasm1a4x6au55s0fusctyj2ulrxvfpmjcxa92k7ze2v", "amount": "10220"}, - { "address": "wasm1ylna88nach9sn5n7qe7u5l6lh7dmt6lp2y63xx", "amount": "10333"}, - { "address": "wasm1qzy8rg0f406uvvl54dlww6ptlh30303xq2u3xu", "amount": "10220"}, - { "address": "wasm1xn46zz5m3fhymcrcwe82m0ac8ytt588dkpaeas", "amount": "10220"} -] - diff --git a/contracts/headstash-contract/testdata/airdrop_stage_1_test_data.json b/contracts/headstash-contract/testdata/airdrop_stage_1_test_data.json deleted file mode 100644 index 2c8fa8c..0000000 --- a/contracts/headstash-contract/testdata/airdrop_stage_1_test_data.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "account": "wasm1k9hwzxs889jpvd7env8z49gad3a3633vg350tq", - "amount": "100", - "root": "b45c1ea28b26adb13e412933c9e055b01fdf7585304b00cd8f1cb220aa6c5e88", - "proofs": [ - "a714186eaedddde26b08b9afda38cf62fdf88d68e3aa0d5a4b55033487fe14a1", - "fb57090a813128eeb953a4210dd64ee73d2632b8158231effe2f0a18b2d3b5dd", - "c30992d264c74c58b636a31098c6c27a5fc08b3f61b7eafe2a33dcb445822343" - ] -} diff --git a/contracts/headstash-contract/testdata/airdrop_stage_1_test_multi_data.json b/contracts/headstash-contract/testdata/airdrop_stage_1_test_multi_data.json deleted file mode 100644 index 128d0a7..0000000 --- a/contracts/headstash-contract/testdata/airdrop_stage_1_test_multi_data.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "total_amount": "42103", - "total_claimed_amount": "21663", - "root": "b45c1ea28b26adb13e412933c9e055b01fdf7585304b00cd8f1cb220aa6c5e88", - "accounts": [ - { - "account": "wasm1k9hwzxs889jpvd7env8z49gad3a3633vg350tq", - "amount": "100", - "proofs": [ - "a714186eaedddde26b08b9afda38cf62fdf88d68e3aa0d5a4b55033487fe14a1", - "fb57090a813128eeb953a4210dd64ee73d2632b8158231effe2f0a18b2d3b5dd", - "c30992d264c74c58b636a31098c6c27a5fc08b3f61b7eafe2a33dcb445822343" - ] - }, - { - "account": "wasm1uy9ucvgerneekxpnfwyfnpxvlsx5dzdpf0mzjd", - "amount": "1010", - "proofs": [ - "d496b14f0a6207db1c9a1be70d5f3684d3c76f27c0bc75ee979f3e2a71a97ed0", - "e3746c7f0e1d1f60708f9e5facaaee77424a8c5f6527f1813f60e8c3755d3b5d", - "c30992d264c74c58b636a31098c6c27a5fc08b3f61b7eafe2a33dcb445822343" - ] - }, - { - "account": "wasm1a4x6au55s0fusctyj2ulrxvfpmjcxa92k7ze2v", - "amount": "10220", - "proofs": [ - "b69c5239d434753af2f6c3eab47f4e78c436f862f14e6989be5c9027c2b6dfe2", - "e3746c7f0e1d1f60708f9e5facaaee77424a8c5f6527f1813f60e8c3755d3b5d", - "c30992d264c74c58b636a31098c6c27a5fc08b3f61b7eafe2a33dcb445822343" - ] - }, - { - "account": "wasm1ylna88nach9sn5n7qe7u5l6lh7dmt6lp2y63xx", - "amount": "10333", - "proofs": [ - "f89c4ec6a98e26fb5690e50e16e189f9942f0576a5ba711ed75fe01140ddb2af", - "374f1a32b0a5d5dab16f8fbed8c248e183448732f897002375e0d4ca6e13ad73" - ] - } - ] -} \ No newline at end of file diff --git a/contracts/headstash-contract/testdata/airdrop_stage_2_list.json b/contracts/headstash-contract/testdata/airdrop_stage_2_list.json deleted file mode 100644 index 74437e3..0000000 --- a/contracts/headstash-contract/testdata/airdrop_stage_2_list.json +++ /dev/null @@ -1,13 +0,0 @@ -[ - { "address": "wasm1k9hwzxs889jpvd7env8z49gad3a3633vg350tq", "amount": "666666666"}, - { "address": "wasm1uy9ucvgerneekxpnfwyfnpxvlsx5dzdpf0mzjd", "amount": "1010"}, - { "address": "wasm1a4x6au55s0fusctyj2ulrxvfpmjcxa92k7ze2v", "amount": "999"}, - { "address": "wasm1ylna88nach9sn5n7qe7u5l6lh7dmt6lp2y63xx", "amount": "1000000000"}, - { "address": "wasm1qzy8rg0f406uvvl54dlww6ptlh30303xq2u3xu", "amount": "10220"}, - { "address": "wasm1c99d6aw39e027fmy5f2gj38g8p8c3cf0vn3qqn", "amount": "1322"}, - { "address": "wasm1uwcjkghqlz030r989clzqs8zlaujwyphx0yumy", "amount": "14"}, - { "address": "wasm1yggt0x0r3x5ujk96kfeps6v4yakgun8mdth90j", "amount": "9000000"}, - { "address": "wasm1f6s77fjplerjrh4yjj08msqdq36mam4xv9tjvs", "amount": "12333"}, - { "address": "wasm1xn46zz5m3fhymcrcwe82m0ac8ytt588dkpaeas", "amount": "1322"} -] - diff --git a/contracts/headstash-contract/testdata/airdrop_stage_2_test_data.json b/contracts/headstash-contract/testdata/airdrop_stage_2_test_data.json deleted file mode 100644 index 78646d8..0000000 --- a/contracts/headstash-contract/testdata/airdrop_stage_2_test_data.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "account": "wasm1uwcjkghqlz030r989clzqs8zlaujwyphx0yumy", - "amount": "14", - "root": "a5587bd4d158618b83badf57b1a4206f86e33407e18797ef690c931d73b36232", - "proofs": [ - "a714186eaedddde26b08b9afda38cf62fdf88d68e3aa0d5a4b55033487fe14a1", - "1eb08e61c40d5ba334f3c32f3f136e714f0841e5d53af6b78ec94e3b29a01e74", - "fe570ffb0015447c01bffdcd266fe4ee21a23eb6b499461b9ced5a03c6a9b2f0", - "fa0224da936bcebd0f018a46ba15a5a9fc2d637f72f7c14b31aeffd8964983b5" - ] -} \ No newline at end of file diff --git a/docker_setup b/docker_setup new file mode 100755 index 0000000..91f1f4f --- /dev/null +++ b/docker_setup @@ -0,0 +1,4 @@ +#!/usr/bin/bash +apt update -y +apt install python3-pip -y +pip3 install click diff --git a/makefile b/makefile new file mode 100755 index 0000000..77ca6f0 --- /dev/null +++ b/makefile @@ -0,0 +1,82 @@ +compiled_dir=compiled +checksum_dir=${compiled_dir}/checksum + +build-release=RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown +# build-debug=RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown --features="debug-print" + +# args (no extensions): wasm_name, contract_dir_name +define opt_and_compress = +wasm-opt -Oz ./target/wasm32-unknown-unknown/release/$(2).wasm -o ./$(1).wasm +echo $(md5sum $(1).wasm | cut -f 1 -d " ") >> ${checksum_dir}/$(1).txt +cat ./$(1).wasm | gzip -n -9 > ${compiled_dir}/$(1).wasm.gz +rm ./$(1).wasm +endef + +CONTRACTS = \ + airdrop + +PACKAGES = shade_protocol contract_harness cosmwasm_math_compat ethereum_verify + +release: setup + ${build-release} + @$(MAKE) compress_all + +compress_all: setup + @$(MAKE) $(addprefix compress-,$(CONTRACTS)) + +compress-%: setup + $(call opt_and_compress,$*,$*) + +$(CONTRACTS): setup + (${build-release} -p $@) + @$(MAKE) compress-$(@) + +$(PACKAGES): + (cd packages/$@; cargo build) + +test: + @$(MAKE) $(addprefix test-,$(CONTRACTS)) + +test-%: % + (cargo test -p $*) + + +cov: + (cargo llvm-cov --html; xdg-open target/llvm-cov/html/index.html) + +setup: $(compiled_dir) $(checksum_dir) + +$(compiled_dir) $(checksum_dir): + mkdir $@ + +check: + cargo check + +clippy: + cargo clippy + +clean: + find . -name "Cargo.lock" -delete + rm -rf target + rm -r $(compiled_dir) + +format: + cargo fmt + +# Downloads the docker server +server-download: + docker pull securesecrets/sn-testnet:v0.2 + +# Starts the docker server / private testnet +server-start: + docker run -it --rm \ + -p 26657:26657 -p 26656:26656 -p 1337:1337 \ + -v $$(pwd):/root/code --name shade-testnet securesecrets/sn-testnet:v0.2 + +# Connects to the docker server +server-connect: + docker exec -it shade-testnet /bin/bash + +# Runs integration tests +integration-tests: + cargo test -- --nocapture --test-threads=1 diff --git a/packages/contract_derive/Cargo.toml b/packages/contract_derive/Cargo.toml new file mode 100644 index 0000000..bb13329 --- /dev/null +++ b/packages/contract_derive/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "contract-derive" +version = "0.1.0" +authors = [ + "Guy Garcia ", +] +edition = "2021" + +[dependencies] +syn = { version = "1.0", features = ["full"] } + +[lib] +proc-macro = true + +[dev-dependencies] +shade-protocol = { version = "0.1.0", path = "../shade_protocol" } \ No newline at end of file diff --git a/packages/contract_derive/src/lib.rs b/packages/contract_derive/src/lib.rs new file mode 100644 index 0000000..1d1311f --- /dev/null +++ b/packages/contract_derive/src/lib.rs @@ -0,0 +1,86 @@ +#[macro_use] +extern crate syn; + +use proc_macro::TokenStream; +use std::str::FromStr; + +/// NOTE: This is copied from the original cosmwasm package, +/// this just has a minor change that adds support to the Shade Protocol +/// This attribute macro generates the boilerplate required to call into the +/// contract-specific logic from the entry-points to the Wasm module. +/// +/// It should be added to the contract's init, handle, migrate and query implementations +/// like this: +/// ``` +/// # use shade_protocol::c_std::{ +/// # Storage, Api, Querier, DepsMut, Deps, Env, StdError, MessageInfo, +/// # Response, QueryResponse, shd_entry_point +/// # }; +/// # +/// # type InstantiateMsg = (); +/// # type ExecuteMsg = (); +/// # type QueryMsg = (); +/// +/// #[shd_entry_point] +/// pub fn instantiate( +/// deps: DepsMut, +/// env: Env, +/// info: MessageInfo, +/// msg: InstantiateMsg, +/// ) -> Result { +/// # Ok(Default::default()) +/// } +/// +/// #[shd_entry_point] +/// pub fn handle( +/// deps: DepsMut, +/// env: Env, +/// info: MessageInfo, +/// msg: ExecuteMsg, +/// ) -> Result { +/// # Ok(Default::default()) +/// } +/// +/// #[shd_entry_point] +/// pub fn query( +/// deps: Deps, +/// env: Env, +/// msg: QueryMsg, +/// ) -> Result { +/// # Ok(Default::default()) +/// } +/// ``` +/// +/// where `InstantiateMsg`, `ExecuteMsg`, and `QueryMsg` are contract defined +/// types that implement `DeserializeOwned + JsonSchema`. +#[proc_macro_attribute] +pub fn shd_entry_point(_attr: TokenStream, mut item: TokenStream) -> TokenStream { + let cloned = item.clone(); + let function = parse_macro_input!(cloned as syn::ItemFn); + let name = function.sig.ident.to_string(); + // The first argument is `deps`, the rest is region pointers + let args = function.sig.inputs.len() - 1; + + // E.g. "ptr0: u32, ptr1: u32, ptr2: u32, " + let typed_ptrs = (0..args).fold(String::new(), |acc, i| format!("{}ptr{}: u32, ", acc, i)); + // E.g. "ptr0, ptr1, ptr2, " + let ptrs = (0..args).fold(String::new(), |acc, i| format!("{}ptr{}, ", acc, i)); + + let new_code = format!( + r##" + #[cfg(target_arch = "wasm32")] + mod __wasm_export_{name} {{ // new module to avoid conflict of function name + #[no_mangle] + extern "C" fn {name}({typed_ptrs}) -> u32 {{ + shade_protocol::c_std::do_{name}(&super::{name}, {ptrs}) + }} + }} + "##, + name = name, + typed_ptrs = typed_ptrs, + ptrs = ptrs + ); + let entry = TokenStream::from_str(&new_code).unwrap(); + item.extend(entry); + item +} diff --git a/packages/ethereum_verify/Cargo.toml b/packages/ethereum_verify/Cargo.toml new file mode 100644 index 0000000..4961042 --- /dev/null +++ b/packages/ethereum_verify/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "ethereum-verify" +authors = ["Michael Scotto ", +"A Hardnett "] +description = "Ethereum Cryptographic verification utility functions" +version = "0.1.0" +edition = "2021" +homepage = "https://shadeprotocol.io/" + +exclude = [ + # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. + "contract.wasm", + "hash.txt", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +sha2 = "0.10.8" +sha3 = "0.10" +hex = "0.4" +cosmwasm-schema = "1.1.5" +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } diff --git a/packages/ethereum_verify/README.md b/packages/ethereum_verify/README.md new file mode 100644 index 0000000..812e5b1 --- /dev/null +++ b/packages/ethereum_verify/README.md @@ -0,0 +1 @@ +# Ethereum Verify \ No newline at end of file diff --git a/packages/ethereum_verify/src/decode.rs b/packages/ethereum_verify/src/decode.rs new file mode 100644 index 0000000..0628aac --- /dev/null +++ b/packages/ethereum_verify/src/decode.rs @@ -0,0 +1,47 @@ +use cosmwasm_std::{StdError, StdResult}; +use sha3::{Digest, Keccak256}; + +/// Get the recovery param from the value `v` when no chain ID for replay protection is used. +/// +/// This is needed for chain-agnostig aignatures like signed text. +/// +/// See [EIP-155] for how `v` is composed. +/// +/// [EIP-155]: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md +pub fn get_recovery_param(v: u8) -> StdResult { + match v { + 27 => Ok(0), + 28 => Ok(1), + _ => Err(StdError::generic_err("Values of v other than 27 and 28 not supported. Replay protection (EIP-155) cannot be used here.")) + } +} + +/// Returns a raw 20 byte Ethereum address +pub fn ethereum_address_raw(pubkey: &[u8]) -> StdResult<[u8; 20]> { + let (tag, data) = match pubkey.split_first() { + Some(pair) => pair, + None => return Err(StdError::generic_err("Public key must not be empty")), + }; + if *tag != 0x04 { + return Err(StdError::generic_err("Public key must start with 0x04")); + } + if data.len() != 64 { + return Err(StdError::generic_err("Public key must be 65 bytes long")); + } + + let hash = Keccak256::digest(data); + Ok(hash[hash.len() - 20..].try_into().unwrap()) +} + +pub fn decode_address(input: &str) -> StdResult<[u8; 20]> { + if input.len() != 42 { + return Err(StdError::generic_err( + "Ethereum address must be 42 characters long", + )); + } + if !input.starts_with("0x") { + return Err(StdError::generic_err("Ethereum address must start with 0x")); + } + let data = hex::decode(&input[2..]).map_err(|_| StdError::generic_err("hex decoding error"))?; + Ok(data.try_into().unwrap()) +} diff --git a/packages/ethereum_verify/src/lib.rs b/packages/ethereum_verify/src/lib.rs new file mode 100644 index 0000000..e272e22 --- /dev/null +++ b/packages/ethereum_verify/src/lib.rs @@ -0,0 +1,5 @@ +mod decode; +pub use decode::{decode_address, ethereum_address_raw, get_recovery_param}; + +mod signature_verify; +pub use signature_verify::verify_ethereum_text; diff --git a/packages/ethereum_verify/src/signature_verify.rs b/packages/ethereum_verify/src/signature_verify.rs new file mode 100644 index 0000000..c970a67 --- /dev/null +++ b/packages/ethereum_verify/src/signature_verify.rs @@ -0,0 +1,43 @@ +use cosmwasm_std::{Deps, StdError, StdResult}; +use sha2::Digest; +use sha3::Keccak256; + +use crate::{decode_address, ethereum_address_raw, get_recovery_param}; + +#[allow(dead_code)] +pub const VERSION: &str = "crypto-verify-v2"; + +// TODO CHANGE TO VERIFY +pub fn verify_ethereum_text( + deps: Deps, + message: &str, + signature: &[u8], + signer_address: &str, +) -> StdResult { + let signer_address = decode_address(signer_address)?; + + // Hashing + let mut hasher = Keccak256::new(); + hasher.update(format!("\x19Ethereum Signed Message:\n{}", message.len())); + hasher.update(message); + let hash = hasher.finalize(); + + // Decompose signature + let (v, rs) = match signature.split_last() { + Some(pair) => pair, + None => return Err(StdError::generic_err("Signature must not be empty")), + }; + let recovery = get_recovery_param(*v)?; + + // Verification + let calculated_pubkey = deps.api.secp256k1_recover_pubkey(&hash, rs, recovery)?; + let calculated_address = ethereum_address_raw(&calculated_pubkey)?; + if signer_address != calculated_address { + return Ok(false); + } + let result = deps.api.secp256k1_verify(&hash, rs, &calculated_pubkey); + match result { + Ok(verifies) => Ok(verifies), + Err(err) => Err(err.into()), + } +} diff --git a/packages/multi_derive/Cargo.toml b/packages/multi_derive/Cargo.toml new file mode 100644 index 0000000..00d26e7 --- /dev/null +++ b/packages/multi_derive/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "multi-derive" +version = "0.1.0" +authors = [ + "hoomp " +] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = [] \ No newline at end of file diff --git a/packages/multi_derive/src/lib.rs b/packages/multi_derive/src/lib.rs new file mode 100644 index 0000000..edec4a8 --- /dev/null +++ b/packages/multi_derive/src/lib.rs @@ -0,0 +1,73 @@ +/// Used for creates a struct that implements the MultiTestable interface. +/// +/// Needs the implementing package to have shade_protocol as a dependency with features. +/// +/// First arg is the struct name that will implement the MultiTestable interface. +/// +/// Second is the name of the package containing the contract module itself. +#[macro_export] +macro_rules! implement_multi { + ($x:ident, $s:ident) => { + use shade_protocol::c_std::{ContractInfo, Empty, Env, Addr}; + use shade_protocol::multi_test::{Contract, ContractWrapper}; + use shade_protocol::utils::callback::MultiTestable; + + pub struct $x { info: ContractInfo } + + impl MultiTestable for $x { + fn contract(&self) -> Box> { + let contract = ContractWrapper::new_with_empty( + $s::contract::execute, + $s::contract::instantiate, + $s::contract::query + ); + Box::new(contract) + } + + fn default() -> Self { + let info = ContractInfo { + address: Addr::unchecked(""), + code_hash: String::default(), + }; + $x { info } + } + } + }; +} + +/// Used for creates a struct that implements the MultiTestable interface **(for contracts that implement the reply method)** +/// +/// Needs the implementing package to have shade_protocol as a dependency with features. +/// +/// First arg is the struct name that will implement the MultiTestable interface. +/// +/// Second is the name of the package containing the contract module itself. +#[macro_export] +macro_rules! implement_multi_with_reply { + ($x:ident, $s:ident) => { + use shade_protocol::c_std::{ContractInfo, Empty, Env, Addr}; + use shade_protocol::multi_test::{Contract, ContractWrapper}; + use shade_protocol::utils::callback::MultiTestable; + + pub struct $x { info: ContractInfo } + + impl MultiTestable for $x { + fn contract(&self) -> Box> { + let contract = ContractWrapper::new_with_empty( + $s::contract::execute, + $s::contract::instantiate, + $s::contract::query + ).with_reply($s::contract::reply); + Box::new(contract) + } + + fn default() -> Self { + let info = ContractInfo { + address: Addr::unchecked(""), + code_hash: String::default(), + }; + $x { info } + } + } + }; +} diff --git a/packages/multi_test/Cargo.toml b/packages/multi_test/Cargo.toml new file mode 100644 index 0000000..c16b591 --- /dev/null +++ b/packages/multi_test/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "shade-multi-test" +version = "0.1.0" +authors = [ + "hoomp " +] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = [] +airdrop = ["dep:airdrop"] + +[dependencies] +airdrop = { path = "../../contracts/airdrop", optional = true } +shade-protocol = { path = "../shade_protocol", features = ["multi-test"] } + +[target.'cfg(not(target_arch="wasm32"))'.dependencies] +shade-protocol = { path = "../shade_protocol", features = ["multi-test"] } +multi-derive = { path = "../multi_derive" } diff --git a/packages/multi_test/src/interfaces/mod.rs b/packages/multi_test/src/interfaces/mod.rs new file mode 100644 index 0000000..098e0e4 --- /dev/null +++ b/packages/multi_test/src/interfaces/mod.rs @@ -0,0 +1,4 @@ +#[cfg(feature = "snip20")] +pub mod snip20; + +pub mod utils; diff --git a/packages/multi_test/src/interfaces/snip20.rs b/packages/multi_test/src/interfaces/snip20.rs new file mode 100644 index 0000000..63bf6bd --- /dev/null +++ b/packages/multi_test/src/interfaces/snip20.rs @@ -0,0 +1,186 @@ +use crate::{ + interfaces::utils::{DeployedContracts, SupportedContracts}, + multi::snip20::Snip20, +}; +use shade_protocol::{ + c_std::{Addr, Binary, Coin, StdError, StdResult, Uint128}, + contract_interfaces::snip20, + multi_test::App, + utils::{asset::Contract, ExecuteCallback, InstantiateCallback, MultiTestable, Query}, +}; + +pub fn init( + chain: &mut App, + sender: &str, + contracts: &mut DeployedContracts, + name: &str, + snip20_symbol: &str, + decimals: u8, + config: Option, +) -> StdResult<()> { + let snip20 = Contract::from( + match (snip20::InstantiateMsg { + name: name.to_string(), + admin: Some(sender.into()), + symbol: snip20_symbol.to_string(), + decimals, + initial_balances: Some(vec![snip20::InitialBalance { + address: sender.into(), + amount: Uint128::from(1_000_000_000 * 10 ^ decimals as u128), + }]), + prng_seed: Binary::default(), + query_auth: None, + config, + } + .test_init( + Snip20::default(), + chain, + Addr::unchecked(sender), + "snip20", + &[], + )) { + Ok(contract_info) => contract_info, + Err(e) => return Err(StdError::generic_err(e.to_string())), + }, + ); + contracts.insert( + SupportedContracts::Snip20(snip20_symbol.to_string()), + snip20, + ); + Ok(()) +} + +pub fn deposit_exec( + chain: &mut App, + sender: &str, + contracts: &DeployedContracts, + snip20_symbol: &str, + coins: &Vec, +) -> StdResult<()> { + match (snip20::ExecuteMsg::Deposit { padding: None }.test_exec( + &contracts + .get(&SupportedContracts::Snip20(snip20_symbol.to_string())) + .unwrap() + .clone() + .into(), + chain, + Addr::unchecked(sender), + coins, + )) { + Ok(_) => Ok(()), + Err(e) => Err(StdError::generic_err(e.to_string())), + } +} + +pub fn set_viewing_key_exec( + chain: &mut App, + sender: &str, + contracts: &DeployedContracts, + snip20_symbol: &str, + key: String, +) -> StdResult<()> { + match (snip20::ExecuteMsg::SetViewingKey { key, padding: None }.test_exec( + &contracts + .get(&SupportedContracts::Snip20(snip20_symbol.to_string())) + .unwrap() + .clone() + .into(), + chain, + Addr::unchecked(sender), + &[], + )) { + Ok(_) => Ok(()), + Err(e) => Err(StdError::generic_err(e.to_string())), + } +} + +pub fn send_exec( + chain: &mut App, + sender: &str, + contracts: &DeployedContracts, + snip20_symbol: &str, + recipient: String, + amount: Uint128, + msg: Option, +) -> StdResult<()> { + match (snip20::ExecuteMsg::Send { + recipient, + amount, + msg, + memo: None, + padding: None, + recipient_code_hash: None, + } + .test_exec( + &contracts + .get(&SupportedContracts::Snip20(snip20_symbol.to_string())) + .unwrap() + .clone() + .into(), + chain, + Addr::unchecked(sender), + &[], + )) { + Ok(_) => Ok(()), + Err(_) => Err(StdError::generic_err("snip20 send failed")), + } +} + +pub fn send_from_exec( + chain: &mut App, + sender: &str, + contracts: &DeployedContracts, + snip20_symbol: &str, + owner: String, + recipient: String, + amount: Uint128, + msg: Option, +) -> StdResult<()> { + match (snip20::ExecuteMsg::SendFrom { + owner, + recipient, + amount, + msg, + memo: None, + padding: None, + recipient_code_hash: None, + } + .test_exec( + &contracts + .get(&SupportedContracts::Snip20(snip20_symbol.to_string())) + .unwrap() + .clone() + .into(), + chain, + Addr::unchecked(sender), + &[], + )) { + Ok(_) => Ok(()), + Err(_) => Err(StdError::generic_err("snip20 send failed")), + } +} + +pub fn balance_query( + chain: &App, + sender: &str, + contracts: &DeployedContracts, + snip20_symbol: &str, + key: String, +) -> StdResult { + let res = snip20::QueryMsg::Balance { + address: sender.to_string(), + key, + } + .test_query( + &contracts + .get(&SupportedContracts::Snip20(snip20_symbol.to_string())) + .unwrap() + .clone() + .into(), + chain, + )?; + match res { + snip20::QueryAnswer::Balance { amount } => Ok(amount), + _ => Err(StdError::generic_err("SetViewingKey failed")), + } +} diff --git a/packages/multi_test/src/interfaces/utils.rs b/packages/multi_test/src/interfaces/utils.rs new file mode 100644 index 0000000..e1b9946 --- /dev/null +++ b/packages/multi_test/src/interfaces/utils.rs @@ -0,0 +1,9 @@ +use shade_protocol::utils::asset::Contract; +use std::collections::HashMap; + +#[derive(Clone, Eq, PartialEq, Hash)] +pub enum SupportedContracts { + Snip20(String), +} + +pub type DeployedContracts = HashMap; diff --git a/packages/multi_test/src/lib.rs b/packages/multi_test/src/lib.rs new file mode 100644 index 0000000..51a504c --- /dev/null +++ b/packages/multi_test/src/lib.rs @@ -0,0 +1,4 @@ +#[cfg(not(target_arch = "wasm32"))] +pub mod multi; + +pub mod interfaces; diff --git a/packages/multi_test/src/multi.rs b/packages/multi_test/src/multi.rs new file mode 100644 index 0000000..9296174 --- /dev/null +++ b/packages/multi_test/src/multi.rs @@ -0,0 +1,140 @@ +#[cfg(feature = "admin")] +pub mod admin { + pub use admin; + use shade_protocol::{admin::InstantiateMsg, multi_test::App, utils::InstantiateCallback}; + multi_derive::implement_multi!(Admin, admin); + + // Multitest helper + pub fn init_admin_auth(app: &mut App, superadmin: &Addr) -> ContractInfo { + InstantiateMsg { + super_admin: Some(superadmin.clone().to_string()), + } + .test_init(Admin::default(), app, superadmin.clone(), "admin_auth", &[]) + .unwrap() + } +} + +#[cfg(feature = "snip20")] +pub mod snip20 { + use snip20; + multi_derive::implement_multi!(Snip20, snip20); +} + +#[cfg(feature = "liability_mint")] +pub mod liability_mint { + use liability_mint; + multi_derive::implement_multi!(LiabilityMint, liability_mint); +} + +#[cfg(feature = "stkd_scrt")] +pub mod stkd_scrt { + use stkd_scrt; + multi_derive::implement_multi!(StkdScrt, stkd_scrt); +} + +// #[cfg(feature = "mint")] +// pub mod mint { +// use mint; +// multi_derive::implement_multi!(Mint, mint); +// } + +// #[cfg(feature = "oracle")] +// pub mod oracle { +// use oracle; +// multi_derive::implement_multi!(Oracle, oracle); +// } + +// #[cfg(feature = "mock_band")] +// pub mod mock_band { +// use crate::multi_derive; +// use mock_band; + +// pub struct MockBand; +// multi_derive::implement_multi!(MockBand, mock_band); +// } + +#[cfg(feature = "governance")] +pub mod governance { + use governance; + + multi_derive::implement_multi_with_reply!(Governance, governance); +} + +// #[cfg(feature = "snip20_staking")] +// pub mod snip20_staking { +// use spip_stkd_0; +// +// multi_derive::implement_multi!(Snip20Staking, spip_stkd_0); +// } + +// #[cfg(feature = "bonds")] +// pub mod bonds { +// use crate::multi_derive; +// use bonds; + +// pub struct Bonds; +// multi_derive::implement_multi!(Bonds, bonds); +// } + +#[cfg(feature = "query_auth")] +pub mod query_auth { + use query_auth; + + multi_derive::implement_multi!(QueryAuth, query_auth); +} + +#[cfg(feature = "treasury_manager")] +pub mod treasury_manager { + use treasury_manager; + multi_derive::implement_multi!(TreasuryManager, treasury_manager); +} + +#[cfg(feature = "treasury")] +pub mod treasury { + use treasury; + multi_derive::implement_multi!(Treasury, treasury); +} + +#[cfg(feature = "mock_adapter")] +pub mod mock_adapter { + use mock_adapter; + multi_derive::implement_multi!(MockAdapter, mock_adapter); +} + +#[cfg(feature = "scrt_staking")] +pub mod scrt_staking { + use scrt_staking; + multi_derive::implement_multi!(ScrtStaking, scrt_staking); +} + +#[cfg(feature = "basic_staking")] +pub mod basic_staking { + use basic_staking; + multi_derive::implement_multi!(BasicStaking, basic_staking); +} + +#[cfg(feature = "peg_stability")] +pub mod peg_stability { + use peg_stability; + + multi_derive::implement_multi!(PegStability, peg_stability); +} + +#[cfg(feature = "mock_stkd")] +pub mod mock_stkd { + pub use mock_stkd; + multi_derive::implement_multi!(MockStkd, mock_stkd); +} + +#[cfg(feature = "mock_sienna")] +pub mod mock_sienna { + pub use mock_sienna; + multi_derive::implement_multi!(MockSienna, mock_sienna); +} + +#[cfg(feature = "snip20_migration")] +pub mod snip20_migration { + use snip20_migration; + + multi_derive::implement_multi!(Snip20Migration, snip20_migration); +} diff --git a/packages/secretcli/Cargo.toml b/packages/secretcli/Cargo.toml new file mode 100644 index 0000000..bc80738 --- /dev/null +++ b/packages/secretcli/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "secretcli" +version = "0.1.0" +authors = ["Guy Garcia "] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = [] + +[dependencies] +serde = { version = "1.0.103", default-features = false, features = ["derive"] } +serde_json = { version = "1.0.67"} diff --git a/packages/secretcli/src/cli_types.rs b/packages/secretcli/src/cli_types.rs new file mode 100644 index 0000000..31b0a9b --- /dev/null +++ b/packages/secretcli/src/cli_types.rs @@ -0,0 +1,94 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct TxResponse { + pub height: String, + pub txhash: String, + pub codespace: String, + pub code: Option, + pub data: String, + pub raw_log: String, +} + +#[derive(Serialize, Deserialize)] +pub struct TxCompute { + //#[serde(rename="key")] + //pub msg_key: String, + pub input: String, +} + +#[derive(Serialize, Deserialize)] +pub struct TxQuery { + pub height: String, + pub txhash: String, + pub data: String, + pub raw_log: String, + pub logs: Vec, + pub gas_wanted: String, + pub gas_used: String, + //pub tx: String, + pub timestamp: String, +} + +#[derive(Serialize, Deserialize)] +pub struct TxQueryLogs { + pub msg_index: i128, + pub log: String, + pub events: Vec, +} + +#[derive(Serialize, Deserialize)] +pub struct TxQueryEvents { + #[serde(rename = "type")] + pub msg_type: String, + pub attributes: Vec, +} + +#[derive(Serialize, Deserialize)] +pub struct TxQueryKeyValue { + #[serde(rename = "key")] + pub msg_key: String, + pub value: String, +} + +#[derive(Serialize, Deserialize)] +pub struct ListCodeResponse { + pub id: u128, + pub creator: String, + pub data_hash: String, +} + +#[derive(Serialize, Deserialize)] +pub struct ListContractCode { + pub code_id: u128, + pub creator: String, + pub label: String, + pub address: String, +} + +#[derive(Serialize, Deserialize)] +pub struct NetContract { + pub label: String, + pub id: String, + pub address: String, + pub code_hash: String, +} + +#[derive(Serialize, Deserialize)] +pub struct StoredContract { + pub id: String, + pub code_hash: String, +} + +#[derive(Serialize, Deserialize)] +pub struct SignedTx { + pub pub_key: PubKey, + pub signature: String, +} + +#[derive(Serialize, Deserialize)] +pub struct PubKey { + #[serde(rename = "type")] + pub msg_type: String, + pub value: String, +} diff --git a/packages/secretcli/src/lib.rs b/packages/secretcli/src/lib.rs new file mode 100644 index 0000000..98dd50a --- /dev/null +++ b/packages/secretcli/src/lib.rs @@ -0,0 +1,2 @@ +pub mod cli_types; +pub mod secretcli; diff --git a/packages/secretcli/src/secretcli.rs b/packages/secretcli/src/secretcli.rs new file mode 100644 index 0000000..e1f17d2 --- /dev/null +++ b/packages/secretcli/src/secretcli.rs @@ -0,0 +1,526 @@ +use crate::cli_types::{ + ListCodeResponse, + ListContractCode, + NetContract, + SignedTx, + StoredContract, + TxCompute, + TxQuery, + TxResponse, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Result, Value}; +use std::{ + fs::File, + io::{self, Write}, + process::Command, + thread, + time, +}; + +//secretcli tx sign-doc tx_to_sign --from sign-test + +fn vec_str_to_vec_string(str_in: Vec<&str>) -> Vec { + let mut str_out: Vec = vec![]; + + for val in str_in { + str_out.push(val.to_string()); + } + + str_out +} + +/// +/// Contains that specific transaction's information +/// +#[derive(Serialize, Deserialize)] +pub struct Report { + pub msg_type: String, + pub message: String, + pub gas_used: String, +} + +/// +/// Will run any scretcli command and return its output +/// +/// # Arguments +/// +/// * 'command' - a string array that contains the command to forward\ +/// +fn secretcli_run(command: Vec, max_retry: Option) -> Result { + let retry = max_retry.unwrap_or(30); + let mut commands = command; + commands.append(&mut vec_str_to_vec_string(vec!["--output", "json"])); + let mut cli = Command::new("secretd".to_string()); + if !commands.is_empty() { + cli.args(commands); + } + + let mut result = cli.output().expect("Unexpected error"); + // We wait cause sometimes the query/action takes a while + for _ in 0..retry { + if !result.stderr.is_empty() { + thread::sleep(time::Duration::from_secs(1)); + } else { + break; + } + result = cli.output().expect("Unexpected error"); + } + let out = result.stdout; + if String::from_utf8_lossy(&out).contains("output_error") { + println!("{:?}", &String::from_utf8_lossy(&out)); + } + serde_json::from_str(&String::from_utf8_lossy(&out)) +} + +/// +/// Stores the given `contract +/// +/// # Arguments +/// +/// * 'contract' - Contract to be stored +/// * 'user' - User that will handle the tx, defaults to a +/// * 'gas' - Gas to pay, defaults to 10000000 +/// * 'backend' - The backend keyring, defaults to test +/// +fn store_contract( + contract: &str, + user: Option<&str>, + gas: Option<&str>, + backend: Option<&str>, +) -> Result { + let mut command_arr = vec![ + "tx", + "compute", + "store", + contract, + "--from", + user.unwrap_or("a"), + "--gas", + gas.unwrap_or("10000000"), + "-y", + ]; + + if let Some(backend) = backend { + command_arr.push("--keyring-backend"); + command_arr.push(backend); + } + + let command = vec_str_to_vec_string(command_arr); + let json = secretcli_run(command, None)?; + let out: Result = serde_json::from_value(json); + out +} + +/// +/// Queries the hash information +/// +fn query_hash(hash: String) -> Result { + let command = vec!["q", "tx", &hash]; + let a = secretcli_run(vec_str_to_vec_string(command), None)?; + serde_json::from_value(a) +} + +/// +/// Computes the hash information +/// +fn compute_hash(hash: String) -> Result { + let command = vec!["q", "compute", "tx", &hash]; + + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), None)?) +} + +/// +/// Lists all uploaded contracts +/// +fn list_code() -> Result> { + let command = vec!["query", "compute", "list-code"]; + + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), None)?) +} + +pub fn list_contracts_by_code(code: String) -> Result> { + let command = vec!["query", "compute", "list-contract-by-code", &code]; + + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), None)?) +} + +fn trim_newline(s: &mut String) { + if s.ends_with('\n') { + s.pop(); + if s.ends_with('\r') { + s.pop(); + } + } +} + +/// +/// Displays an account from the keyring +/// +/// # Arguments +/// +/// * 'acc' - The requested account +/// +pub fn account_address(acc: &str) -> Result { + let command = vec_str_to_vec_string(vec!["keys", "show", "-a", acc]); + + let retry = 40; + let mut cli = Command::new("secretd".to_string()); + if !command.is_empty() { + cli.args(command); + } + + let mut result = cli.output().expect("Unexpected error"); + + // We wait cause sometimes the query/action takes a while + for _ in 0..retry { + if !result.stderr.is_empty() { + thread::sleep(time::Duration::from_secs(1)); + } else { + break; + } + result = cli.output().expect("Unexpected error"); + } + + let out = result.stdout; + + let mut s: String = String::from_utf8_lossy(&out).parse().unwrap(); + + // Sometimes the resulting string has a newline, so we trim that + trim_newline(&mut s); + + Ok(s) +} + +pub fn create_key_account(name: &str) -> Result<()> { + let command = vec_str_to_vec_string(vec!["keys", "add", name]); + + let retry = 40; + let mut cli = Command::new("secretd".to_string()); + if !command.is_empty() { + cli.args(command); + } + + let mut result = cli.output().expect("Unexpected error"); + + // We wait cause sometimes the query/action takes a while + for _ in 0..retry { + if !result.stderr.is_empty() { + thread::sleep(time::Duration::from_secs(1)); + } else { + break; + } + result = cli.output().expect("Unexpected error"); + } + + Ok(()) +} + +/// +/// Instantiate a contract +/// +/// # Arguments +/// +/// * 'code_id' - The contract to interact with +/// * 'msg' - The init msg to serialize +/// * 'label' - The contract label +/// * 'sender' - Msg sender +/// * 'gas' - Gas price to use, defaults to 8000000 +/// * 'backend' - Keyring backend defaults to none +/// +fn instantiate_contract( + contract: &NetContract, + msg: Init, + label: &str, + sender: &str, + gas: Option<&str>, + backend: Option<&str>, +) -> Result { + let message = serde_json::to_string(&msg)?; + + let mut command = vec![ + "tx", + "compute", + "instantiate", + &contract.id, + &message, + "--from", + sender, + "--label", + label, + "--gas", + ]; + + command.push(match gas { + None => "10000000", + Some(gas) => gas, + }); + + if let Some(backend) = backend { + command.push("--keyring-backend"); + command.push(backend); + } + + command.push("-y"); + + let response: TxResponse = + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), None)?)?; + + Ok(response) +} + +/// +/// Store the given contract and return the stored contract information +/// +/// * 'contract_file' - Contract file to store +/// * 'sender' - Msg sender +/// * 'store_gas' - Gas price to use when storing the contract, defaults to 10000000 +/// * 'backend' - Keyring backend defaults to none +/// +pub fn store_and_return_contract( + contract_file: &str, + sender: &str, + store_gas: Option<&str>, + backend: Option<&str>, +) -> Result { + let store_response = store_contract(contract_file, Option::from(&*sender), store_gas, backend)?; + let store_query = query_hash(store_response.txhash)?; + let mut contract = StoredContract { + id: "".to_string(), + code_hash: "".to_string(), + }; + + for attribute in &store_query.logs[0].events[0].attributes { + if attribute.msg_key == "code_id" { + contract.id = attribute.value.clone(); + break; + } + } + + let listed_contracts = list_code()?; + + for item in listed_contracts { + if item.id.to_string() == contract.id { + contract.code_hash = item.data_hash; + break; + } + } + + Ok(contract) +} + +/// +/// Allows contract init to be used in test scripts +/// +/// # Arguments +/// +/// * `msg` - Contract's init message +/// * 'contract_file' - The contract to interact with +/// * 'label' - The contract label +/// * 'sender' - Msg sender - must be registered in keyring +/// * 'store_gas' - Gas price to use when storing the contract, defaults to 10000000 +/// * 'init_gas' - Gas price to use when initializing the contract, defaults to 8000000 +/// * 'backend' - Keyring backend defaults to none +/// * `report` - Records the contract`s message and instantiation price +/// +pub fn init( + msg: &Message, + contract_file: &str, + label: &str, + sender: &str, + store_gas: Option<&str>, + init_gas: Option<&str>, + backend: Option<&str>, + report: &mut Vec, +) -> Result { + io::stdout().flush().unwrap(); + let store_response = store_contract(contract_file, Option::from(&*sender), store_gas, backend)?; + let store_query = query_hash(store_response.txhash)?; + let mut contract = NetContract { + label: label.to_string(), + id: "".to_string(), + address: "".to_string(), + code_hash: "".to_string(), + }; + + // Look for the code ID + for attribute in &store_query.logs[0].events[0].attributes { + if attribute.msg_key == "code_id" { + contract.id = attribute.value.clone(); + break; + } + } + + // Instantiate and get the info + let tx = instantiate_contract(&contract, msg, label, sender, init_gas, backend)?; + let init_query = query_hash(tx.txhash)?; + + // Include the instantiation info in the report + report.push(Report { + msg_type: "Instantiate".to_string(), + message: serde_json::to_string(&msg)?, + gas_used: init_query.gas_used, + }); + + // Look for the contract's address + for attribute in &init_query.logs[0].events[0].attributes { + if attribute.msg_key == "contract_address" { + contract.address = attribute.value.clone(); + break; + } + } + // Look for the contract's code hash + let listed_contracts = list_code()?; + + // Find the code_hash + for item in listed_contracts { + if item.id.to_string() == contract.id { + contract.code_hash = item.data_hash; + break; + } + } + Ok(contract) +} + +/// +/// Executes a contract's handle +/// +/// # Arguments +/// +/// * 'contract' - The contract to interact with +/// * 'msg' - The handle msg to serialize +/// * 'sender' - Msg sender +/// * 'gas' - Gas price to use, defaults to 8000000 +/// * 'backend' - Keyring backend defaults to none +/// * 'amount' - Included L1 tokens to send, defaults to none +/// +fn execute_contract( + contract: &NetContract, + msg: Handle, + sender: &str, + gas: Option<&str>, + backend: Option<&str>, + amount: Option<&str>, + max_tries: Option, +) -> Result { + let message = serde_json::to_string(&msg)?; + + let mut command = vec![ + "tx", + "compute", + "execute", + &contract.address, + &message, + "--from", + sender, + "--gas", + ]; + + command.push(match gas { + None => "800000", + Some(gas) => gas, + }); + + if let Some(backend) = backend { + command.push("--keyring-backend"); + command.push(backend); + } + + if let Some(amount) = amount { + command.push("--amount"); + command.push(amount); + } + + command.push("-y"); + + let response: TxResponse = + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), max_tries)?)?; + + Ok(response) +} + +/// +/// Allows contract handle enums to be used in test scripts +/// +/// # Arguments +/// +/// * `msg` - ExecuteMsg +/// * 'contract' - The contract to interact with +/// * 'sender' - Msg sender +/// * 'gas' - Gas price to use, defaults to 8000000 +/// * 'backend' - Keyring backend defaults to none +/// * 'amount' - Included L1 tokens to send, defaults to none +/// * `report` - Records the contract`s message and handle price +/// +pub fn handle( + msg: &Message, + contract: &NetContract, + sender: &str, + gas: Option<&str>, + backend: Option<&str>, + amount: Option<&str>, + report: &mut Vec, + max_tries: Option, +) -> Result<(TxCompute, TxQuery)> { + let tx = execute_contract(contract, msg, sender, gas, backend, amount, max_tries)?; + + let computed_response = compute_hash(tx.txhash.clone())?; + let queried_response = query_hash(tx.txhash)?; + + // Include the instantiation info in the report + report.push(Report { + msg_type: "Handle".to_string(), + message: serde_json::to_string(&msg)?, + gas_used: queried_response.gas_used.clone(), + }); + + Ok((computed_response, queried_response)) +} + +/// +/// Queries a given contract +/// +/// # Arguments +/// +/// * 'contract' - The contract to query +/// * 'msg' - The query to serialize, must have serde::Serialized +/// +pub fn query( + contract: &NetContract, + msg: Query, + max_tries: Option, +) -> Result { + let command = vec_str_to_vec_string(vec![ + "query", + "compute", + "query", + &contract.address, + &serde_json::to_string(&msg)?, + ]); + + let response: Result = serde_json::from_value(secretcli_run(command, max_tries)?); + response +} + +/// +/// Create a signed permit +/// +/// # Arguments +/// +/// * 'tx' - The message to sign +/// * 'signer' - The key of the signer +/// +pub fn create_permit(tx: Tx, signer: &str) -> Result { + let msg = serde_json::to_string(&tx)?; + + // send to a file + let mut file = File::create("./tx_to_sign").unwrap(); + file.write_all(msg.as_bytes()).unwrap(); + + let command = vec!["tx", "sign-doc", "tx_to_sign", "--from", signer]; + + let response: SignedTx = + serde_json::from_value(secretcli_run(vec_str_to_vec_string(command), None)?)?; + + Ok(response) +} diff --git a/packages/shade_protocol/.cargo/config b/packages/shade_protocol/.cargo/config new file mode 100644 index 0000000..882fe08 --- /dev/null +++ b/packages/shade_protocol/.cargo/config @@ -0,0 +1,5 @@ +[alias] +wasm = "build --release --target wasm32-unknown-unknown" +unit-test = "test --lib --features backtraces" +integration-test = "test --test integration" +schema = "run --example schema" diff --git a/packages/shade_protocol/Cargo.toml b/packages/shade_protocol/Cargo.toml new file mode 100644 index 0000000..f026a7c --- /dev/null +++ b/packages/shade_protocol/Cargo.toml @@ -0,0 +1,138 @@ +[package] +name = "shade-protocol" +version = "0.1.0" +authors = [ + "Guy Garcia ", + "Jackson Swenson ", + "Kyle Wahlberg ", + "Jack Sisson ", +] +edition = "2018" + +[[bin]] +name = "schemas" +path = "src/schemas.rs" +# Must have all of the contract_interfaces +required-features = ["airdrop"] + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["utils"] + +# Utils +utils = ["chrono"] +dao-utils = ["snip20"] +errors = [] +flexible_msg = [] +math = [] +storage = ["dao-utils"] +storage_plus = ["storage", "dep:secret-storage-plus", "chrono"] +query_auth_lib = ["dep:query-authentication"] +multi-test = ["dep:secret-multi-test", "dep:anyhow", "interface"] + +# Implementing new contracts: +# Contracts packages are divided by two different features, the interface and the implementation +# When creating a new contract; try to keep all interface (Init, Handle and Query) related content in the `mod.rs` file +# and move all implementation related content into separate files inside the package. +# When defining a new interface, first create a feature that imports this: +interface = ["utils", "errors"] +# Like so +# contract_name = ["interface"] +# Then add the following inside `/src/contract_interfaces/mod.rs` +# #[cfg(feature = "contract_name")] +# pub mod contract_name; + +# For the implementation you need to import this in your feature and prepend the feature name with `_impl` +implementation = ["storage_plus", "storage", "admin"] +# Like so +# contract_name_impl = ["contract_name", "implementation"] + +# TODO: Normalize usage, some features are using - while others use _ + +# Templates +dex = ["math", "snip20", "mint", "band", "oracles"] +band = ["interface"] +secretswap = ["interface"] +sienna = ["interface", "math"] + +# Protocol contracts NOTE: interfaces that have other interfaces as features already automatically have `interface` as a feature +airdrop = ["query_auth", "snip20"] +basic_staking = ["snip20"] +bonds = ["airdrop", "snip20"] +governance = ["query_auth", "flexible_msg"] +mint = ["snip20"] +#liability_mint = ["snip20", "adapter", "dao"] +mint_router = ["snip20"] +oracles = ["snip20", "dex"] +scrt_staking = ["adapter", "treasury"] +stkd_scrt = ["adapter"] +treasury = ["adapter", "dao-utils"] +treasury_manager = ["adapter"] +# rewards_emission = ["adapter"] +# lp_shdswap = ["interface"] +adapter = ["interface"] +manager = ["interface"] +snip20 = ["query_auth_impl", "dep:base64"] +query_auth = ["interface", "query_auth_lib", "dep:remain"] +snip20_staking = ["interface", "implementation"] +sky = ["snip20", "dex", "dao"] +dao = ["interface", "cosmwasm-std/staking"] +admin = ["interface"] +peg_stability = ["sky-utils", "adapter"] +snip20_migration = [] + +chrono = ["dep:chrono"] + +stargate = ["cosmwasm-std/stargate"] +staking = ["cosmwasm-std/staking"] + +stkd = [] +mock = [] + +# Protocol Implementation Contracts +# Used in internal smart contracts +governance-impl = ["implementation", "governance"] +snip20-impl = ["snip20", "query_auth_impl"] +query_auth_impl = ["implementation", "query_auth", "dep:base64"] +sky-utils = ["implementation", "sky"] +admin_impl = ["implementation", "admin"] + +# for quicker tests, cargo test --lib +# for more explicit tests, cargo test --features=backtraces +backtraces = ["cosmwasm-std/backtraces"] +debug-print = [] # TODO: remove this from all cargo configs + +[dependencies] +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.0.0" } +cosmwasm-schema = "1.1.5" +contract-derive = { version = "0.1.0", path = "../contract_derive" } + +schemars = "0.8.9" +serde = { version = "1.0.103", default-features = false, features = ["derive", "alloc"] } +thiserror = "1.0" + +secret-storage-plus = { git = "https://github.com/securesecrets/secret-plus-utils", tag = "v0.1.1", optional = true, features = [] } + +# Testing +anyhow = { version = "1", optional = true } + +chrono = { version = "=0.4.19", optional = true } +base64 = { version = "0.12.3", optional = true } +#query-authentication = {git = "https://github.com/securesecrets/query-authentication", tag = "v1.3.0", optional = true } +query-authentication = { git = "https://github.com/securesecrets/query-authentication", branch = "cosmwasm_v1_upgrade", optional = true } +remain = { version = "0.2.2", optional = true } +subtle = { version = "2.2.3", default-features = false } +sha2 = { version = "0.9.1", default-features = false } +rand_chacha = { version = "0.2.2", default-features = false } +rand_core = { version = "0.5.1", default-features = false } + +# for EnumIter +strum = "0.24" +strum_macros = "0.24" +const_format = "0.2.26" +#strum = { version = "0.24", features = ["derive"] } +[target.'cfg(not(target_arch="wasm32"))'.dependencies] +secret-multi-test = { git = "https://github.com/securesecrets/secret-plus-utils", version = "0.13.4", optional = true } diff --git a/packages/shade_protocol/src/contract_interfaces/admin/errors.rs b/packages/shade_protocol/src/contract_interfaces/admin/errors.rs new file mode 100644 index 0000000..1ab53bb --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/admin/errors.rs @@ -0,0 +1,74 @@ +use crate::{ + impl_into_u8, + utils::errors::{build_string, CodeType, DetailedError}, +}; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::StdError; + +#[cw_serde] +#[repr(u8)] +pub enum Error { + UnregisteredAdmin, + UnauthorizedAdmin, + UnauthorizedSuper, + NoPermissions, + IsShutdown, + IsUnderMaintenance, + InvalidPermissionFormat, +} + +impl_into_u8!(Error); + +impl CodeType for Error { + fn to_verbose(&self, context: &Vec<&str>) -> String { + build_string( + match self { + Error::UnregisteredAdmin => "{} has not been registered as an admin", + Error::UnauthorizedAdmin => "{} does not have this permissions - {}", + Error::UnauthorizedSuper => "{} is not the authorized super admin", + Error::NoPermissions => "There are not permissions for {}", + Error::IsShutdown => { + "Contract is currently shutdown. It must be turned on for any changes to be made or any permissions to be validates" + } + Error::IsUnderMaintenance => { + "Contract is under maintenance. Oly registry updated may be made. Permission validation is disabled." + } + Error::InvalidPermissionFormat => { + "{} must be > 10 characters and only contains 0-9, A-Z, and underscores" + } + }, + context, + ) + } +} + +const ADMIN_TARGET: &str = "admin"; + +pub fn unregistered_admin(address: &str) -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::UnregisteredAdmin, vec![address]).to_error() +} + +pub fn unauthorized_admin(address: &str, permission: &str) -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::UnauthorizedAdmin, vec![ + address, permission, + ]) + .to_error() +} +pub fn unauthorized_super(super_admin: &str) -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::UnauthorizedSuper, vec![super_admin]).to_error() +} +pub fn no_permission(user: &str) -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::NoPermissions, vec![user]).to_error() +} +pub fn is_shutdown() -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::IsShutdown, vec![]).to_error() +} +pub fn is_under_maintenance() -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::IsUnderMaintenance, vec![]).to_error() +} +pub fn invalid_permission_format(permission: &str) -> StdError { + DetailedError::from_code(ADMIN_TARGET, Error::InvalidPermissionFormat, vec![ + permission, + ]) + .to_error() +} diff --git a/packages/shade_protocol/src/contract_interfaces/admin/helpers.rs b/packages/shade_protocol/src/contract_interfaces/admin/helpers.rs new file mode 100644 index 0000000..e6a3286 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/admin/helpers.rs @@ -0,0 +1,80 @@ +use crate::{ + admin::{errors::unauthorized_admin, QueryMsg, ValidateAdminPermissionResponse}, + utils::Query, + Contract, +}; +use cosmwasm_std::{QuerierWrapper, StdResult}; + +pub fn validate_admin + Clone>( + querier: &QuerierWrapper, + permission: AdminPermissions, + user: T, + admin_auth: &Contract, +) -> StdResult<()> { + if admin_is_valid(querier, permission.clone(), user.clone(), admin_auth)? { + Ok(()) + } else { + Err(unauthorized_admin(&user.into(), &permission.into_string())) + } +} + +pub fn admin_is_valid>( + querier: &QuerierWrapper, + permission: AdminPermissions, + user: T, + admin_auth: &Contract, +) -> StdResult { + let admin_resp: StdResult = + QueryMsg::ValidateAdminPermission { + permission: permission.into_string(), + user: user.into(), + } + .query(querier, admin_auth); + + match admin_resp { + Ok(resp) => Ok(resp.has_permission), + Err(err) => Err(err), + } +} + +#[derive(Clone)] +pub enum AdminPermissions { + QueryAuthAdmin, + ScrtStakingAdmin, + TreasuryManager, + TreasuryAdmin, + StabilityAdmin, + SkyAdmin, + LendAdmin, + OraclesAdmin, + OraclesPriceBot, + SilkAdmin, + ShadeSwapAdmin, + StakingAdmin, + DerivativeAdmin, + Snip20MigrationAdmin, +} + +// NOTE: SHADE_{CONTRACT_NAME}_{CONTRACT_ROLE}_{POTENTIAL IDs} + +impl AdminPermissions { + pub fn into_string(self) -> String { + match self { + AdminPermissions::QueryAuthAdmin => "SHADE_QUERY_AUTH_ADMIN", + AdminPermissions::ScrtStakingAdmin => "SHADE_SCRT_STAKING_ADMIN", + AdminPermissions::TreasuryManager => "SHADE_TREASURY_MANAGER", + AdminPermissions::TreasuryAdmin => "SHADE_TREASURY_ADMIN", + AdminPermissions::StabilityAdmin => "SHADE_STABILITY_ADMIN", + AdminPermissions::SkyAdmin => "SHADE_SKY_ADMIN", + AdminPermissions::LendAdmin => "SHADE_LEND_ADMIN", + AdminPermissions::OraclesAdmin => "SHADE_ORACLES_ADMIN", + AdminPermissions::OraclesPriceBot => "SHADE_ORACLES_PRICE_BOT", + AdminPermissions::SilkAdmin => "SHADE_SILK_ADMIN", + AdminPermissions::ShadeSwapAdmin => "SHADE_SWAP_ADMIN", + AdminPermissions::StakingAdmin => "SHADE_STAKING_ADMIN", + AdminPermissions::DerivativeAdmin => "SHADE_DERIVATIVE_ADMIN", + AdminPermissions::Snip20MigrationAdmin => "SNIP20_MIGRATION_ADMIN", + } + .to_string() + } +} diff --git a/packages/shade_protocol/src/contract_interfaces/admin/mod.rs b/packages/shade_protocol/src/contract_interfaces/admin/mod.rs new file mode 100644 index 0000000..4c6b8ae --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/admin/mod.rs @@ -0,0 +1,112 @@ +use crate::{ + admin::errors::{is_shutdown, is_under_maintenance}, + utils::{ExecuteCallback, InstantiateCallback, Query}, +}; +use cosmwasm_schema::{cw_serde, QueryResponses}; +use cosmwasm_std::{Addr, StdResult}; + +pub mod errors; +pub mod helpers; + +#[cw_serde] +pub enum AdminAuthStatus { + Active, + Maintenance, + Shutdown, +} + +impl AdminAuthStatus { + // Throws an error if status is under maintenance + pub fn not_under_maintenance(&self) -> StdResult<&Self> { + if self.eq(&AdminAuthStatus::Maintenance) { + return Err(is_under_maintenance()); + } + Ok(self) + } + + // Throws an error if status is shutdown + pub fn not_shutdown(&self) -> StdResult<&Self> { + if self.eq(&AdminAuthStatus::Shutdown) { + return Err(is_shutdown()); + } + Ok(self) + } +} + +#[cw_serde] +pub struct InstantiateMsg { + pub super_admin: Option, +} + +impl InstantiateCallback for InstantiateMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteMsg { + UpdateRegistry { action: RegistryAction }, + UpdateRegistryBulk { actions: Vec }, + TransferSuper { new_super: String }, + SelfDestruct {}, + ToggleStatus { new_status: AdminAuthStatus }, +} + +#[cw_serde] +pub enum RegistryAction { + RegisterAdmin { + user: String, + }, + GrantAccess { + permissions: Vec, + user: String, + }, + RevokeAccess { + permissions: Vec, + user: String, + }, + DeleteAdmin { + user: String, + }, +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +#[derive(QueryResponses)] +pub enum QueryMsg { + #[returns(ConfigResponse)] + GetConfig {}, + #[returns(AdminsResponse)] + GetAdmins {}, + #[returns(PermissionsResponse)] + GetPermissions { user: String }, + #[returns(ValidateAdminPermissionResponse)] + ValidateAdminPermission { permission: String, user: String }, +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub struct ConfigResponse { + pub super_admin: Addr, + pub status: AdminAuthStatus, +} + +#[cw_serde] +pub struct PermissionsResponse { + pub permissions: Vec, +} + +#[cw_serde] +pub struct AdminsResponse { + pub admins: Vec, +} + +#[cw_serde] +pub struct ValidateAdminPermissionResponse { + pub has_permission: bool, +} diff --git a/packages/shade_protocol/src/contract_interfaces/airdrop/account.rs b/packages/shade_protocol/src/contract_interfaces/airdrop/account.rs new file mode 100644 index 0000000..3599a36 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/airdrop/account.rs @@ -0,0 +1,105 @@ +use crate::contract_interfaces::airdrop::errors::permit_rejected; +use crate::c_std::Uint128; +use crate::c_std::{Addr, StdResult, Api}; +use crate::query_authentication::{ + permit::{bech32_to_canonical, Permit}, + viewing_keys::ViewingKey, +}; + +use cosmwasm_schema::{cw_serde}; + +#[cw_serde] +pub struct Account { + pub addresses: Vec, + pub total_claimable: Uint128, + pub eth_pubkey: String, + pub eth_sig: String, + // pub claimed: bool, +} + +impl Default for Account { + fn default() -> Self { + Self { + addresses: vec![], + total_claimable: Uint128::zero(), + eth_pubkey: "".to_string(), + eth_sig: "".to_string(), + // claimed: false, + } + } +} + +// Used for querying account information +pub type AccountPermit = Permit; + +#[remain::sorted] +#[cw_serde] +pub struct AccountPermitMsg { + pub contract: Addr, + pub key: String, +} + +#[remain::sorted] +#[cw_serde] +pub struct FillerMsg { + pub coins: Vec, + pub contract: String, + pub execute_msg: EmptyMsg, + pub sender: String, +} + +impl Default for FillerMsg { + fn default() -> Self { + Self { + coins: vec![], + contract: "".to_string(), + sender: "".to_string(), + execute_msg: EmptyMsg {}, + } + } +} + +#[remain::sorted] +#[cw_serde] +pub struct EmptyMsg {} + +// Used to prove ownership over IBC addresses +pub type AddressProofPermit = Permit; + +pub fn authenticate_ownership(api: &dyn Api, permit: &AddressProofPermit, permit_address: &str) -> StdResult<()> { + let signer_address = permit + .validate(api, Some("wasm/MsgExecuteContract".to_string()))? + .as_canonical(); + + if signer_address != bech32_to_canonical(permit_address) { + return Err(permit_rejected()); + } + + Ok(()) +} + +#[remain::sorted] +#[cw_serde] +pub struct AddressProofMsg { + // Address is necessary since we have other network permits present + pub address: Addr, + // Reward amount + pub amount: Uint128, + // Used to prevent permits from being used elsewhere + pub contract: Addr, + // Index of the address in the leaves array + pub index: u32, + // Used to identify permits + pub key: String, +} + +#[cw_serde] +pub struct AccountKey(pub String); + +impl ToString for AccountKey { + fn to_string(&self) -> String { + self.0.clone() + } +} + +impl ViewingKey<32> for AccountKey {} diff --git a/packages/shade_protocol/src/contract_interfaces/airdrop/claim_info.rs b/packages/shade_protocol/src/contract_interfaces/airdrop/claim_info.rs new file mode 100644 index 0000000..64e05a1 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/airdrop/claim_info.rs @@ -0,0 +1,8 @@ +use crate::c_std::{Uint128, Addr}; +use cosmwasm_schema::{cw_serde}; + +#[cw_serde] +pub struct RequiredTask { + pub address: Addr, + pub percent: Uint128, +} diff --git a/packages/shade_protocol/src/contract_interfaces/airdrop/errors.rs b/packages/shade_protocol/src/contract_interfaces/airdrop/errors.rs new file mode 100644 index 0000000..1e2f423 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/airdrop/errors.rs @@ -0,0 +1,182 @@ +use crate::{ + c_std::StdError, + impl_into_u8, + utils::errors::{build_string, CodeType, DetailedError}, +}; + +use cosmwasm_schema::cw_serde; + +#[cw_serde] +#[repr(u8)] +pub enum Error { + InvalidTaskPercentage, + InvalidDates, + PermitContractMismatch, + PermitKeyRevoked, + PermitRejected, + NotAdmin, + AccountAlreadyCreated, + AccountDoesntExist, + NothingToClaim, + DecayClaimed, + NoDecaySet, + ClaimAmountTooHigh, + AddressInAccount, + ExpectedMemo, + InvalidPartialTree, + AirdropNotStarted, + AirdropEnded, + InvalidViewingKey, + UnexpectedError, + WrongLength, + FailedVerification, + AlreadyClaimed, +} + +impl_into_u8!(Error); + +impl CodeType for Error { + fn to_verbose(&self, context: &Vec<&str>) -> String { + match self { + Error::InvalidTaskPercentage => { + build_string("Task total exceeds maximum of 100%, got {}", context) + } + Error::InvalidDates => build_string("{} ({}) cannot happen {} {} ({})", context), + Error::PermitContractMismatch => { + build_string("Permit is valid for {}, expected {}", context) + } + Error::PermitKeyRevoked => build_string("Permit key {} revoked", context), + Error::PermitRejected => build_string("Permit was rejected", context), + Error::NotAdmin => build_string("Can only be accessed by {}", context), + Error::AccountAlreadyCreated => build_string("Account already exists", context), + Error::AccountDoesntExist => build_string("Account does not exist", context), + Error::NothingToClaim => build_string("Amount to claim is 0", context), + Error::DecayClaimed => build_string("Decay already claimed", context), + Error::NoDecaySet => build_string("Decay has not been set", context), + Error::ClaimAmountTooHigh => { + build_string("Claim {} is higher than the maximum claim of {}", context) + } + Error::AddressInAccount => build_string("{} has already been claimed", context), + Error::ExpectedMemo => build_string("Expected a memo", context), + Error::InvalidPartialTree => build_string("Partial tree is not valid", context), + Error::AirdropNotStarted => { + build_string("Airdrop starts in {}, its currently {}", context) + } + Error::AirdropEnded => build_string("Airdrop ended on {}, its currently {}", context), + Error::InvalidViewingKey => build_string("Provided viewing key is invalid", context), + Error::UnexpectedError => build_string("Something unexpected happened", context), + Error::WrongLength => build_string("Wrong length", context), + Error::FailedVerification => build_string("Failed to verify merkle proofs", context), + Error::AlreadyClaimed => build_string("Already claimed", context), + } + } +} + +const AIRDROP_TARGET: &str = "airdrop"; + +pub fn invalid_task_percentage(percentage: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::InvalidTaskPercentage, vec![ + percentage, + ]) + .to_error() +} + +pub fn invalid_dates( + item_a: &str, + item_a_amount: &str, + precedence: &str, + item_b: &str, + item_b_amount: &str, +) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::InvalidDates, vec![ + item_a, + item_a_amount, + precedence, + item_b, + item_b_amount, + ]) + .to_error() +} + +pub fn permit_contract_mismatch(contract: &str, expected: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::PermitContractMismatch, vec![ + contract, expected, + ]) + .to_error() +} + +pub fn permit_key_revoked(key: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::PermitKeyRevoked, vec![key]).to_error() +} + +pub fn permit_rejected() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::PermitRejected, vec![]).to_error() +} + +pub fn not_admin(admin: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::NotAdmin, vec![admin]).to_error() +} + +pub fn account_already_created() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AccountAlreadyCreated, vec![]).to_error() +} + +pub fn account_does_not_exist() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AccountDoesntExist, vec![]).to_error() +} + +pub fn nothing_to_claim() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::NothingToClaim, vec![]).to_error() +} + +pub fn decay_claimed() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::DecayClaimed, vec![]).to_error() +} + +pub fn decay_not_set() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::NoDecaySet, vec![]).to_error() +} + +pub fn claim_too_high(claim: &str, max: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::ClaimAmountTooHigh, vec![claim, max]).to_error() +} + +pub fn address_already_in_account(address: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AddressInAccount, vec![address]).to_error() +} + +pub fn expected_memo() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::ExpectedMemo, vec![]).to_error() +} + +pub fn invalid_partial_tree() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::InvalidPartialTree, vec![]).to_error() +} + +pub fn airdrop_not_started(start: &str, current: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AirdropNotStarted, vec![ + start, current, + ]) + .to_error() +} + +pub fn airdrop_ended(end: &str, current: &str) -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AirdropEnded, vec![end, current]).to_error() +} + +pub fn invalid_viewing_key() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::InvalidViewingKey, vec![]).to_error() +} + +pub fn unexpected_error() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::UnexpectedError, vec![]).to_error() +} +pub fn wrong_length() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::WrongLength, vec![]).to_error() +} +pub fn failed_verification() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::FailedVerification, vec![]).to_error() +} +pub fn already_claimed() -> StdError { + DetailedError::from_code(AIRDROP_TARGET, Error::AlreadyClaimed, vec![]).to_error() +} \ No newline at end of file diff --git a/packages/shade_protocol/src/contract_interfaces/airdrop/mod.rs b/packages/shade_protocol/src/contract_interfaces/airdrop/mod.rs new file mode 100644 index 0000000..b2f4432 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/airdrop/mod.rs @@ -0,0 +1,233 @@ +pub mod account; +pub mod claim_info; +pub mod errors; + +use crate::{ + c_std::{Addr, Binary, Uint128}, + contract_interfaces::airdrop::{ + account::{AccountPermit, AddressProofPermit}, + claim_info::RequiredTask, + }, + utils::{asset::Contract, generic_response::ResponseStatus}, +}; + +use crate::utils::{ExecuteCallback, InstantiateCallback, Query}; +use cosmwasm_schema::cw_serde; + +#[cw_serde] +pub struct Config { + pub admin: Addr, + // Used for permit validation when querying + pub contract: Addr, + // Where the decayed tokens will be dumped, if none then nothing happens + pub dump_address: Option, + // The snip20 to be minted + pub airdrop_snip20: Contract, + // An optional, second snip20 to be minted + pub airdrop_snip20_optional: Option, + // Airdrop amount + pub airdrop_amount: Uint128, + // Required tasks + pub task_claim: Vec, + // Checks if airdrop has started / ended + pub start_date: u64, + // Airdrop stops at end date if there is one + pub end_date: Option, + // Starts to decay at this date + pub decay_start: Option, + // This is necessary to validate the airdrop information + // tree root + pub merkle_root: Binary, + // tree height + pub total_accounts: u32, + // {wallet} + pub claim_msg_plaintext: String, + // max possible reward amount; used to prevent collision possibility + pub max_amount: Uint128, + // Protects from leaking user information by limiting amount detail + pub query_rounding: Uint128, +} + +#[cw_serde] +pub struct InstantiateMsg { + pub admin: Option, + // Where the decayed tokens will be dumped, if none then nothing happens + pub dump_address: Option, + pub airdrop_token: Contract, + // Airdrop amount + pub airdrop_amount: Uint128, + // an optional, second snip20 to be minted + pub airdrop_2: Option, + // The airdrop time limit + pub start_date: Option, + // Can be set to never end + pub end_date: Option, + // Starts to decay at this date + pub decay_start: Option, + // Base64 encoded version of the tree root + pub merkle_root: Binary, + // Root height + pub total_accounts: u32, + // Max possible reward amount + pub max_amount: Uint128, + // Default gifted amount + pub default_claim: Uint128, + // The task related claims + pub task_claim: Vec, + /// {wallet} + pub claim_msg_plaintext: String, + // Protects from leaking user information by limiting amount detail + pub query_rounding: Uint128, +} + +impl InstantiateCallback for InstantiateMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteMsg { + UpdateConfig { + admin: Option, + dump_address: Option, + query_rounding: Option, + start_date: Option, + end_date: Option, + decay_start: Option, + padding: Option, + }, + AddTasks { + tasks: Vec, + padding: Option, + }, + CompleteTask { + address: Addr, + padding: Option, + }, + Account { + addresses: Vec, + eth_pubkey: String, + eth_sig: String, + partial_tree: Vec, + padding: Option, + }, + DisablePermitKey { + key: String, + padding: Option, + }, + SetViewingKey { + key: String, + padding: Option, + }, + Claim { + padding: Option, + }, + ClaimDecay { + padding: Option, + }, +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteAnswer { + UpdateConfig { + status: ResponseStatus, + }, + AddTask { + status: ResponseStatus, + }, + CompleteTask { + status: ResponseStatus, + }, + Account { + status: ResponseStatus, + // Total eligible + total: Uint128, + // Total claimed + claimed: Uint128, + finished_tasks: Vec, + // Addresses claimed + addresses: Vec, + eth_pubkey: String, + eth_sig: String, + }, + DisablePermitKey { + status: ResponseStatus, + }, + SetViewingKey { + status: ResponseStatus, + }, + Claim { + status: ResponseStatus, + // Total eligible + total: Uint128, + // Total claimed + claimed: Uint128, + finished_tasks: Vec, + // Addresses claimed + addresses: Vec, + eth_pubkey: String, + eth_sig: String, + }, + ClaimDecay { + status: ResponseStatus, + }, +} + +#[cw_serde] +pub enum QueryMsg { + Config {}, + Dates { + current_date: Option, + }, + TotalClaimed {}, + Account { + permit: AccountPermit, + current_date: Option, + }, + AccountWithKey { + account: Addr, + key: String, + current_date: Option, + }, +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum QueryAnswer { + Config { + config: Config, + }, + Dates { + start: u64, + end: Option, + decay_start: Option, + decay_factor: Option, + }, + TotalClaimed { + claimed: Uint128, + }, + Account { + // Total eligible + total: Uint128, + // Total claimed + claimed: Uint128, + // Total unclaimed but available + unclaimed: Uint128, + finished_tasks: Vec, + // Addresses claimed + addresses: Vec, + }, +} + +#[cw_serde] +pub struct AccountVerification { + // pub eth_pubkey: String, + pub account: Addr, + pub claimed: bool, +} diff --git a/packages/shade_protocol/src/contract_interfaces/mod.rs b/packages/shade_protocol/src/contract_interfaces/mod.rs new file mode 100644 index 0000000..c29d272 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/mod.rs @@ -0,0 +1,12 @@ +#[cfg(feature = "snip20")] +pub mod snip20; + +// Protocol init libraries +#[cfg(feature = "airdrop")] +pub mod airdrop; + +#[cfg(feature = "query_auth")] +pub mod query_auth; + +#[cfg(feature = "admin")] +pub mod admin; diff --git a/packages/shade_protocol/src/contract_interfaces/query_auth/auth.rs b/packages/shade_protocol/src/contract_interfaces/query_auth/auth.rs new file mode 100644 index 0000000..b77ea24 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/query_auth/auth.rs @@ -0,0 +1,78 @@ +use cosmwasm_std::MessageInfo; +use crate::c_std::{Env, Addr, StdResult, Storage}; +use cosmwasm_schema::{cw_serde}; + +use crate::query_authentication::viewing_keys::ViewingKey; +use secret_storage_plus::Map; +use crate::utils::crypto::{Prng, sha_256}; +use crate::utils::storage::plus::MapStorage; + +#[cw_serde] +pub struct Key(pub String); + +impl Key { + pub fn generate(info: &MessageInfo, env: &Env, seed: &[u8], entropy: &[u8]) -> Self { + // 16 here represents the lengths in bytes of the block height and time. + let entropy_len = 16 + info.sender.as_str().len() + entropy.len(); + let mut rng_entropy = Vec::with_capacity(entropy_len); + rng_entropy.extend_from_slice(&env.block.height.to_be_bytes()); + rng_entropy.extend_from_slice(&env.block.time.seconds().to_be_bytes()); + rng_entropy.extend_from_slice(&info.sender.as_bytes()); + rng_entropy.extend_from_slice(entropy); + + let mut rng = Prng::new(seed, &rng_entropy); + + let rand_slice = rng.rand_bytes(); + + let key = sha_256(&rand_slice); + + Self(base64::encode(key)) + } + + pub fn verify(storage: &dyn Storage, address: Addr, key: String) -> StdResult { + Ok(match HashedKey::may_load(storage, address)? { + None => { + // Empty compare for security reasons + Key(key).compare(&[0u8; KEY_SIZE]); + false + } + Some(hashed) => Key(key).compare(&hashed.0) + }) + } +} + +impl ToString for Key { + fn to_string(&self) -> String { + self.0.clone() + } +} +const KEY_SIZE: usize = 32; +impl ViewingKey for Key{} + +#[cw_serde] +pub struct HashedKey(pub [u8; KEY_SIZE]); + +impl MapStorage<'static, Addr> for HashedKey { + const MAP: Map<'static, Addr, Self> = Map::new("hashed-viewing-key-"); +} + + +#[cw_serde] +pub struct PermitKey(pub bool); + +impl MapStorage<'static, (Addr, String)> for PermitKey { + const MAP: Map<'static, (Addr, String), Self> = Map::new("permit-key-"); +} + +impl PermitKey { + pub fn revoke(storage: &mut dyn Storage, key: String, user: Addr) -> StdResult<()> { + PermitKey(true).save(storage, (user, key)) + } + + pub fn is_revoked(storage: &mut dyn Storage, key: String, user: Addr) -> StdResult { + Ok(match PermitKey::may_load(storage, (user, key))? { + None => false, + Some(_) => true + }) + } +} \ No newline at end of file diff --git a/packages/shade_protocol/src/contract_interfaces/query_auth/helpers.rs b/packages/shade_protocol/src/contract_interfaces/query_auth/helpers.rs new file mode 100644 index 0000000..d16ae68 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/query_auth/helpers.rs @@ -0,0 +1,56 @@ +use cosmwasm_std::{Addr, from_binary, QuerierWrapper, StdError, StdResult}; +use serde::de::DeserializeOwned; +use crate::{Contract, query_auth}; +use crate::query_auth::QueryPermit; +use crate::utils::Query; + +pub struct PermitAuthentication { + pub sender: Addr, + pub revoked: bool, + pub data: T +} + +pub fn authenticate_permit( + permit: QueryPermit, + querier: &QuerierWrapper, + authenticator: Contract +) -> StdResult> { + let res: query_auth::QueryAnswer = query_auth::QueryMsg::ValidatePermit { permit: permit.clone() } + .query(querier, &authenticator)?; + + let sender: Addr; + let revoked: bool; + + match res { + query_auth::QueryAnswer::ValidatePermit { user, is_revoked } => { + sender = user; + revoked = is_revoked; + } + _ => return Err(StdError::generic_err("Wrong query response")), + } + + Ok(PermitAuthentication { + sender, + revoked, + data: from_binary(&permit.params.data)? + }) +} + +pub fn authenticate_vk( + address: Addr, + key: String, + querier: &QuerierWrapper, + authenticator: &Contract +) -> StdResult { + let res: query_auth::QueryAnswer = query_auth::QueryMsg::ValidateViewingKey { + user: address, + key, + }.query(querier, authenticator)?; + + match res { + query_auth::QueryAnswer::ValidateViewingKey { is_valid } => { + Ok(is_valid) + } + _ => Err(StdError::generic_err("Unauthorized")), + } +} \ No newline at end of file diff --git a/packages/shade_protocol/src/contract_interfaces/query_auth/mod.rs b/packages/shade_protocol/src/contract_interfaces/query_auth/mod.rs new file mode 100644 index 0000000..29413af --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/query_auth/mod.rs @@ -0,0 +1,145 @@ +#[cfg(feature = "query_auth_impl")] +pub mod auth; +pub mod helpers; + +use crate::c_std::{Addr, Binary}; + +#[cfg(feature = "query_auth_impl")] +use crate::utils::storage::plus::ItemStorage; +use crate::{ + query_authentication::permit::Permit, + utils::{ + asset::Contract, + crypto::sha_256, + generic_response::ResponseStatus, + ExecuteCallback, + InstantiateCallback, + Query, + }, +}; +use cosmwasm_schema::cw_serde; +#[cfg(feature = "query_auth_impl")] +use secret_storage_plus::Item; + +#[cfg(feature = "query_auth_impl")] +#[cw_serde] +pub struct Admin(pub Contract); + +#[cfg(feature = "query_auth_impl")] +impl ItemStorage for Admin { + const ITEM: Item<'static, Self> = Item::new("admin-"); +} + +#[cfg(feature = "query_auth_impl")] +#[cw_serde] +pub struct RngSeed(pub Vec); + +#[cfg(feature = "query_auth_impl")] +impl ItemStorage for RngSeed { + const ITEM: Item<'static, Self> = Item::new("rng-seed-"); +} + +#[cfg(feature = "query_auth_impl")] +impl RngSeed { + pub fn new(seed: Binary) -> Self { + Self(sha_256(&seed.0).to_vec()) + } +} + +#[cw_serde] +pub struct InstantiateMsg { + pub admin_auth: Contract, + pub prng_seed: Binary, +} + +impl InstantiateCallback for InstantiateMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ContractStatus { + Default, + DisablePermit, + DisableVK, + DisableAll, +} + +#[cfg(feature = "query_auth_impl")] +impl ItemStorage for ContractStatus { + const ITEM: Item<'static, Self> = Item::new("contract-status-"); +} + +#[cw_serde] +pub enum ExecuteMsg { + SetAdminAuth { + admin: Contract, + padding: Option, + }, + SetRunState { + state: ContractStatus, + padding: Option, + }, + + SetViewingKey { + key: String, + padding: Option, + }, + CreateViewingKey { + entropy: String, + padding: Option, + }, + + BlockPermitKey { + key: String, + padding: Option, + }, +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteAnswer { + SetAdminAuth { status: ResponseStatus }, + SetRunState { status: ResponseStatus }, + SetViewingKey { status: ResponseStatus }, + CreateViewingKey { key: String }, + BlockPermitKey { status: ResponseStatus }, +} + +pub type QueryPermit = Permit; + +#[remain::sorted] +#[cw_serde] +pub struct PermitData { + pub data: Binary, + pub key: String, +} + +#[cw_serde] +pub enum QueryMsg { + Config {}, + + ValidateViewingKey { user: Addr, key: String }, + ValidatePermit { permit: QueryPermit }, +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum QueryAnswer { + Config { + admin: Contract, + state: ContractStatus, + }, + ValidateViewingKey { + is_valid: bool, + }, + ValidatePermit { + user: Addr, + is_revoked: bool, + }, +} diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/batch.rs b/packages/shade_protocol/src/contract_interfaces/snip20/batch.rs new file mode 100644 index 0000000..36e4bf7 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/batch.rs @@ -0,0 +1,52 @@ +use crate::c_std::Binary; + +use crate::c_std::Uint128; +use cosmwasm_schema::cw_serde; + +#[cw_serde] +pub struct TransferAction { + pub recipient: String, + pub amount: Uint128, + pub memo: Option, +} + +#[cw_serde] +pub struct SendAction { + pub recipient: String, + pub recipient_code_hash: Option, + pub amount: Uint128, + pub msg: Option, + pub memo: Option, +} + +#[cw_serde] +pub struct TransferFromAction { + pub owner: String, + pub recipient: String, + pub amount: Uint128, + pub memo: Option, +} + +#[cw_serde] +pub struct SendFromAction { + pub owner: String, + pub recipient: String, + pub recipient_code_hash: Option, + pub amount: Uint128, + pub msg: Option, + pub memo: Option, +} + +#[cw_serde] +pub struct MintAction { + pub recipient: String, + pub amount: Uint128, + pub memo: Option, +} + +#[cw_serde] +pub struct BurnFromAction { + pub owner: String, + pub amount: Uint128, + pub memo: Option, +} diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/errors.rs b/packages/shade_protocol/src/contract_interfaces/snip20/errors.rs new file mode 100644 index 0000000..092f357 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/errors.rs @@ -0,0 +1,199 @@ +use crate::{ + impl_into_u8, + utils::errors::{build_string, CodeType, DetailedError}, +}; +use crate::c_std::{Addr, StdError}; + +use cosmwasm_schema::{cw_serde}; +use crate::c_std::Uint128; +use crate::contract_interfaces::snip20::Permission; + +#[cw_serde]#[repr(u8)] +pub enum Error { + // Init Errors + InvalidNameFormat, + InvalidSymbolFormat, + InvalidDecimals, + + // User errors + NoFunds, + NotEnoughFunds, + AllowanceExpired, + InsufficientAllowance, + + // Auth errors + NotAdmin, + PermitRevoked, + PermitNotFound, + UnauthorisedPermit, + InvalidViewingKey, + + // Config errors + TransfersDisabled, + MintingDisabled, + NotMinter, + BurningDisabled, + RedeemDisabled, + DepositDisabled, + NotEnoughTokens, + NoTokensReceived, + UnsupportedToken, + + // Run state errors + ActionDisabled, + + NotAuthenticatedMsg, + + // Errors that shouldnt happen + ContractStatusLevelInvalidConversion, + TxCodeInvalidConversion, + LegacyCannotConvertFromTx, +} + +impl_into_u8!(Error); + +impl CodeType for Error { + fn to_verbose(&self, context: &Vec<&str>) -> String { + match self { + Error::InvalidNameFormat => build_string("{} is not in the expected name format (3-30 UTF-8 bytes)", context), + Error::InvalidSymbolFormat => build_string("{} is not in the expected symbol format [A-Z]{3,6}", context), + Error::InvalidDecimals => build_string("Decimals must not exceed 18", context), + Error::NoFunds => build_string("Account has no funds", context), + Error::NotEnoughFunds => build_string("Account doesnt have enough funds", context), + Error::AllowanceExpired => build_string("Allowance expired on {}", context), + Error::InsufficientAllowance => build_string("Insufficient allowance", context), + Error::NotAdmin => build_string("Only admin is allowed to do this action", context), + Error::PermitRevoked => build_string("Permit key {} is revoked", context), + Error::UnauthorisedPermit => build_string("Permit lacks the required authorisation, expecting {}", context), + Error::PermitNotFound => build_string("No permit was included in this query.", context), + Error::InvalidViewingKey => build_string("Viewing key is invalid", context), + Error::TransfersDisabled => build_string("Transfers are disabled", context), + Error::MintingDisabled => build_string("Minting is disabled", context), + Error::NotMinter => build_string("{} is not an allowed minter", context), + Error::BurningDisabled => build_string("Burning is disabled", context), + Error::RedeemDisabled => build_string("Redemptions are disabled", context), + Error::DepositDisabled => build_string("Deposits are disabled", context), + Error::NotEnoughTokens => build_string("Asking to redeem {} when theres only {} held by the reserve", context), + Error::NoTokensReceived => build_string("Found no tokens to deposit", context), + Error::UnsupportedToken => build_string("Sent tokens are not supported", context), + Error::ActionDisabled => build_string("This action has been disabled", context), + Error::NotAuthenticatedMsg => build_string("Message doesnt require authentication", context), + Error::ContractStatusLevelInvalidConversion => build_string("Stored enum id {} is greater than total supported enum items", context), + Error::TxCodeInvalidConversion => build_string("Stored action id {} is greater than total supported enum items", context), + Error::LegacyCannotConvertFromTx => build_string("Legacy Txs only supports Transfer", context), + } + } +} + +const TARGET: &str = "snip20"; + +pub fn invalid_name_format(name: &str) -> StdError { + DetailedError::from_code(TARGET, Error::InvalidNameFormat, vec![name]).to_error() +} + +pub fn invalid_symbol_format(symbol: &str) -> StdError { + DetailedError::from_code(TARGET, Error::InvalidSymbolFormat, vec![symbol]).to_error() +} + +pub fn invalid_decimals() -> StdError { + DetailedError::from_code(TARGET, Error::InvalidDecimals, vec![]).to_error() +} + +pub fn no_funds() -> StdError { + DetailedError::from_code(TARGET, Error::NoFunds, vec![]).to_error() +} + +pub fn not_enough_funds() -> StdError { + DetailedError::from_code(TARGET, Error::NotEnoughFunds, vec![]).to_error() +} + +pub fn allowance_expired(date: u64) -> StdError { + DetailedError::from_code(TARGET, Error::AllowanceExpired, vec![&date.to_string()]).to_error() +} + +pub fn not_admin() -> StdError { + DetailedError::from_code(TARGET, Error::NotAdmin, vec![]).to_error() +} + +pub fn permit_revoked(key: String) -> StdError { + DetailedError::from_code(TARGET, Error::PermitRevoked, vec![&key]).to_error() +} + +pub fn permit_not_found() -> StdError { + DetailedError::from_code(TARGET, Error::PermitNotFound, vec![]).to_error() +} + +pub fn unauthorized_permit(auth: Permission) -> StdError { + let perm = match auth { + Permission::Allowance => String::from("allowance"), + Permission::Balance => String::from("balance"), + Permission::History => String::from("history"), + Permission::Owner => String::from("owner"), + }; + DetailedError::from_code(TARGET, Error::UnauthorisedPermit, vec![&perm]).to_error() +} + +pub fn invalid_viewing_key() -> StdError { + DetailedError::from_code(TARGET, Error::InvalidViewingKey, vec![]).to_error() +} + +pub fn transfer_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::TransfersDisabled, vec![]).to_error() +} + +pub fn minting_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::MintingDisabled, vec![]).to_error() +} + +pub fn not_minter(user: &Addr) -> StdError { + DetailedError::from_code(TARGET, Error::NotMinter, vec![user.as_str()]).to_error() +} + +pub fn burning_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::BurningDisabled, vec![]).to_error() +} + +pub fn redeem_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::RedeemDisabled, vec![]).to_error() +} + +pub fn deposit_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::DepositDisabled, vec![]).to_error() +} + +pub fn not_enough_tokens(sent: Uint128, max: Uint128) -> StdError { + DetailedError::from_code(TARGET, Error::NotEnoughTokens, vec![&sent.to_string(), &max.to_string()]).to_error() +} + +pub fn no_tokens_received() -> StdError { + DetailedError::from_code(TARGET, Error::NoTokensReceived, vec![]).to_error() +} + +pub fn unsupported_token() -> StdError { + DetailedError::from_code(TARGET, Error::UnsupportedToken, vec![]).to_error() +} + +pub fn action_disabled() -> StdError { + DetailedError::from_code(TARGET, Error::ActionDisabled, vec![]).to_error() +} + +pub fn not_authenticated_msg() -> StdError { + DetailedError::from_code(TARGET, Error::NotAuthenticatedMsg, vec![]).to_error() +} + +pub fn insufficient_allowance() -> StdError { + DetailedError::from_code(TARGET, Error::InsufficientAllowance, vec![]).to_error() +} + +pub fn contract_status_level_invalid(id: u8) -> StdError { + DetailedError::from_code(TARGET, Error::ContractStatusLevelInvalidConversion, vec![&id.to_string()]).to_error() +} + +pub fn tx_code_invalid_conversion(id: u8) -> StdError { + DetailedError::from_code(TARGET, Error::TxCodeInvalidConversion, vec![&id.to_string()]).to_error() +} + +pub fn legacy_cannot_convert_from_tx() -> StdError { + DetailedError::from_code(TARGET, Error::LegacyCannotConvertFromTx, vec![]).to_error() +} + diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/helpers.rs b/packages/shade_protocol/src/contract_interfaces/snip20/helpers.rs new file mode 100644 index 0000000..89d19e8 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/helpers.rs @@ -0,0 +1,345 @@ +use super::{batch, manager::AllowanceResponse, ExecuteMsg, QueryAnswer, QueryMsg}; +use crate::{ + c_std::{Addr, Binary, CosmosMsg, QuerierWrapper, StdError, StdResult, Uint128}, + utils::{asset::Contract, ExecuteCallback, Query}, +}; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::Coin; + +#[cw_serde] +pub struct Snip20Asset { + pub contract: Contract, + pub token_info: TokenInfo, + pub token_config: Option, +} + +pub fn fetch_snip20(contract: &Contract, querier: &QuerierWrapper) -> StdResult { + Ok(Snip20Asset { + contract: contract.clone(), + token_info: token_info(querier, contract)?, + token_config: Some(token_config(querier, contract)?), + }) +} + +/// Returns a StdResult used to execute Send +#[allow(clippy::too_many_arguments)] +pub fn send_msg( + recipient: Addr, + amount: Uint128, + msg: Option, + memo: Option, + padding: Option, + contract: &Contract, +) -> StdResult { + Ok(ExecuteMsg::Send { + recipient: recipient.to_string(), + recipient_code_hash: None, + amount, + msg, + memo, + padding, + } + .to_cosmos_msg(contract, vec![])?) +} + +/// Returns a StdResult used to execute Redeem +pub fn redeem_msg( + amount: Uint128, + denom: Option, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::Redeem { + amount, + denom, + padding, + } + .to_cosmos_msg(contract, vec![]) +} + +/// Returns a StdResult used to execute Deposit +pub fn deposit_msg( + amount: Uint128, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::Deposit { padding }.to_cosmos_msg(contract, vec![Coin { + denom: "uscrt".to_string(), + amount, + }]) +} + +/// Returns a StdResult used to execute Mint +pub fn mint_msg( + recipient: Addr, + amount: Uint128, + memo: Option, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::Mint { + recipient: recipient.to_string(), + amount, + memo, + padding, + } + .to_cosmos_msg(contract, vec![]) +} + +/// Returns a StdResult used to execute Burn +pub fn burn_msg( + amount: Uint128, + memo: Option, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::Burn { + amount, + memo, + padding, + } + .to_cosmos_msg(contract, vec![]) +} + +/// Returns a StdResult used to execute RegisterReceive +pub fn register_receive( + register_hash: String, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::RegisterReceive { + code_hash: register_hash, + padding, + } + .to_cosmos_msg(contract, vec![]) +} + +pub fn set_viewing_key_msg( + viewing_key: String, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::SetViewingKey { + key: viewing_key, + padding, + } + .to_cosmos_msg(contract, vec![]) +} + +pub fn batch_send_msg( + actions: Vec, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::BatchSend { actions, padding }.to_cosmos_msg(contract, vec![]) +} + +pub fn batch_send_from_msg( + actions: Vec, + padding: Option, + contract: &Contract, +) -> StdResult { + ExecuteMsg::BatchSendFrom { actions, padding }.to_cosmos_msg(contract, vec![]) +} + +/// TokenInfo response +#[cw_serde] +pub struct TokenInfo { + pub name: String, + pub symbol: String, + pub decimals: u8, + #[serde(skip_serializing_if = "Option::is_none")] + pub total_supply: Option, +} +/// Returns a StdResult from performing TokenInfo query +pub fn token_info(querier: &QuerierWrapper, contract: &Contract) -> StdResult { + let answer: QueryAnswer = QueryMsg::TokenInfo {}.query(querier, contract)?; + + match answer { + QueryAnswer::TokenInfo { + name, + symbol, + decimals, + total_supply, + } => Ok(TokenInfo { + name, + symbol, + decimals, + total_supply, + }), + _ => Err(StdError::generic_err("Wrong answer")), //TODO: better error + } +} + +/// Returns a StdResult from performing a Balance query +pub fn balance_query( + querier: &QuerierWrapper, + address: Addr, + key: String, + contract: &Contract, +) -> StdResult { + let answer: QueryAnswer = QueryMsg::Balance { + address: address.to_string(), + key, + } + .query(querier, contract)?; + + match answer { + QueryAnswer::Balance { amount, .. } => Ok(amount), + _ => Err(StdError::generic_err("Invalid Balance Response")), //TODO: better error + } +} + +/// TokenConfig response +#[cw_serde] +pub struct TokenConfig { + pub public_total_supply: bool, + pub deposit_enabled: bool, + pub redeem_enabled: bool, + pub mint_enabled: bool, + pub burn_enabled: bool, + // Optionals only relevant to some snip20a + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_enabled: Option, +} +/// Returns a StdResult from performing TokenConfig query +pub fn token_config(querier: &QuerierWrapper, contract: &Contract) -> StdResult { + let answer: QueryAnswer = QueryMsg::TokenConfig {}.query(querier, contract)?; + + match answer { + QueryAnswer::TokenConfig { + public_total_supply, + deposit_enabled, + redeem_enabled, + mint_enabled, + burn_enabled, + .. + } => Ok(TokenConfig { + public_total_supply, + deposit_enabled, + redeem_enabled, + mint_enabled, + burn_enabled, + transfer_enabled: None, + }), + _ => Err(StdError::generic_err("Wrong answer")), //TODO: better error + } +} + +/// Returns a StdResult used to execute IncreaseAllowance +/// +/// # Arguments +/// +/// * `spender` - the address of the allowed spender +/// * `amount` - Uint128 additional amount the spender is allowed to send/burn +/// * `expiration` - Optional u64 denoting the epoch time in seconds that the allowance will expire +/// * `padding` - Optional String used as padding if you don't want to use block padding +/// * `block_size` - pad the message to blocks of this size +/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `contract_addr` - address of the contract being called +pub fn increase_allowance_msg( + spender: Addr, + amount: Uint128, + expiration: Option, + padding: Option, + block_size: usize, + contract: &Contract, + funds: Vec, +) -> StdResult { + ExecuteMsg::IncreaseAllowance { + spender: spender.to_string(), + amount, + expiration, + padding, + } + .to_cosmos_msg(contract, funds) +} + +/// Returns a StdResult used to execute DecreaseAllowance +/// +/// # Arguments +/// +/// * `spender` - the address of the allowed spender +/// * `amount` - Uint128 amount the spender is no longer allowed to send/burn +/// * `expiration` - Optional u64 denoting the epoch time in seconds that the allowance will expire +/// * `padding` - Optional String used as padding if you don't want to use block padding +/// * `block_size` - pad the message to blocks of this size +/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `contract_addr` - address of the contract being called +pub fn decrease_allowance_msg( + spender: Addr, + amount: Uint128, + expiration: Option, + padding: Option, + block_size: usize, + contract: &Contract, + funds: Vec, +) -> StdResult { + ExecuteMsg::DecreaseAllowance { + spender: spender.to_string(), + amount, + expiration, + padding, + } + .to_cosmos_msg(contract, funds) +} + +/// Returns a StdResult from performing Allowance query +/// +/// # Arguments +/// +/// * `querier` - a reference to the Querier dependency of the querying contract +/// * `owner` - the address that owns the tokens +/// * `spender` - the address allowed to send/burn tokens +/// * `key` - String holding the authentication key needed to view the allowance +/// * `block_size` - pad the message to blocks of this size +/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `contract_addr` - address of the contract being queried +#[allow(clippy::too_many_arguments)] +pub fn allowance_query( + querier: &QuerierWrapper, + owner: Addr, + spender: Addr, + key: String, + block_size: usize, + contract: &Contract, +) -> StdResult { + let answer: QueryAnswer = QueryMsg::Allowance { + owner: owner.to_string(), + spender: spender.to_string(), + key, + } + .query(querier, contract)?; + match answer { + QueryAnswer::Allowance { + spender, + owner, + allowance, + expiration, + } => Ok(AllowanceResponse { + spender, + owner, + allowance, + expiration, + }), + QueryAnswer::ViewingKeyError { .. } => Err(StdError::generic_err("Unauthorized")), + _ => Err(StdError::generic_err("Invalid Allowance query response")), + } +} + +pub fn transfer_from_msg( + owner: String, + recipient: String, + amount: Uint128, + memo: Option, + padding: Option, + contract: &Contract +) -> StdResult { + ExecuteMsg::TransferFrom { + owner, + recipient, + amount, + memo, + padding, + }.to_cosmos_msg(contract, vec![]) +} \ No newline at end of file diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/manager.rs b/packages/shade_protocol/src/contract_interfaces/snip20/manager.rs new file mode 100644 index 0000000..9e927d9 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/manager.rs @@ -0,0 +1,345 @@ +use crate::c_std::{Addr, BlockInfo, StdResult, Storage}; +use cosmwasm_std::Timestamp; + +#[cfg(feature = "snip20-impl")] +use crate::utils::storage::plus::{ItemStorage, MapStorage, NaiveItemStorage}; +use crate::{ + c_std::Uint128, + contract_interfaces::snip20::errors::{ + allowance_expired, + contract_status_level_invalid, + insufficient_allowance, + no_funds, + not_enough_funds, + }, + impl_into_u8, + Contract, +}; +use cosmwasm_schema::cw_serde; +#[cfg(feature = "snip20-impl")] +use secret_storage_plus::{Item, Map}; + +#[cw_serde] +#[repr(u8)] +pub enum ContractStatusLevel { + NormalRun, + StopAllButRedeems, + StopAll, +} + +#[cfg(feature = "snip20-impl")] +impl ContractStatusLevel { + pub fn save(self, storage: &mut dyn Storage) -> StdResult<()> { + ContractStatus(self.into()).save(storage) + } + + pub fn load(storage: &dyn Storage) -> StdResult { + let i = ContractStatus::load(storage)?.0; + let item = match i { + 0 => ContractStatusLevel::NormalRun, + 1 => ContractStatusLevel::StopAllButRedeems, + 2 => ContractStatusLevel::StopAll, + _ => return Err(contract_status_level_invalid(i)), + }; + Ok(item) + } +} +impl_into_u8!(ContractStatusLevel); + +// TODO: group all of these snip20-impl features into its own package + +#[cw_serde] +pub struct ContractStatus(pub u8); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for ContractStatus { + const ITEM: Item<'static, Self> = Item::new("contract-status-level-"); +} + +#[cw_serde] +pub struct CoinInfo { + pub name: String, + pub symbol: String, + pub decimals: u8, +} + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for CoinInfo { + const ITEM: Item<'static, Self> = Item::new("coin-info-"); +} + +#[cw_serde] +pub struct Admin(pub Addr); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for Admin { + const ITEM: Item<'static, Self> = Item::new("admin-"); +} + +#[cw_serde] +pub struct QueryAuth(pub Contract); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for QueryAuth { + const ITEM: Item<'static, Self> = Item::new("query_auth-"); +} + +#[cw_serde] +pub struct RandSeed(pub Vec); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for RandSeed { + const ITEM: Item<'static, Self> = Item::new("rand-seed-"); +} + +#[cw_serde] +pub struct Setting(pub bool); + +#[cfg(feature = "snip20-impl")] +impl NaiveItemStorage for Setting {} + +#[cfg(feature = "snip20-impl")] +const PUBLIC_TOTAL_SUPPLY: Item<'static, Setting> = Item::new("public-total-supply-"); +#[cfg(feature = "snip20-impl")] +const ENABLE_DEPOSIT: Item<'static, Setting> = Item::new("enable-deposit-"); +#[cfg(feature = "snip20-impl")] +const ENABLE_REDEEM: Item<'static, Setting> = Item::new("enable-redeem-"); +#[cfg(feature = "snip20-impl")] +const ENABLE_MINT: Item<'static, Setting> = Item::new("enable-mint-"); +#[cfg(feature = "snip20-impl")] +const ENABLE_BURN: Item<'static, Setting> = Item::new("enable-burn-"); +#[cfg(feature = "snip20-impl")] +const ENABLE_TRANSFER: Item<'static, Setting> = Item::new("enable-transfer-"); + +#[cw_serde] +pub struct Config { + pub public_total_supply: bool, + pub enable_deposit: bool, + pub enable_redeem: bool, + pub enable_mint: bool, + pub enable_burn: bool, + pub enable_transfer: bool, +} + +#[cfg(feature = "snip20-impl")] +impl Config { + pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { + Self::set_public_total_supply(storage, self.public_total_supply)?; + Self::set_deposit_enabled(storage, self.enable_deposit)?; + Self::set_redeem_enabled(storage, self.enable_redeem)?; + Self::set_mint_enabled(storage, self.enable_mint)?; + Self::set_burn_enabled(storage, self.enable_burn)?; + Self::set_transfer_enabled(storage, self.enable_transfer)?; + Ok(()) + } + + pub fn public_total_supply(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, PUBLIC_TOTAL_SUPPLY)?.0) + } + + pub fn set_public_total_supply(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, PUBLIC_TOTAL_SUPPLY)?; + Ok(()) + } + + pub fn deposit_enabled(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, ENABLE_DEPOSIT)?.0) + } + + pub fn set_deposit_enabled(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, ENABLE_DEPOSIT)?; + Ok(()) + } + + pub fn redeem_enabled(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, ENABLE_REDEEM)?.0) + } + + pub fn set_redeem_enabled(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, ENABLE_REDEEM)?; + Ok(()) + } + + pub fn mint_enabled(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, ENABLE_MINT)?.0) + } + + pub fn set_mint_enabled(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, ENABLE_MINT)?; + Ok(()) + } + + pub fn burn_enabled(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, ENABLE_BURN)?.0) + } + + pub fn set_burn_enabled(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, ENABLE_BURN)?; + Ok(()) + } + + pub fn transfer_enabled(storage: &dyn Storage) -> StdResult { + Ok(Setting::load(storage, ENABLE_TRANSFER)?.0) + } + + pub fn set_transfer_enabled(storage: &mut dyn Storage, setting: bool) -> StdResult<()> { + Setting(setting).save(storage, ENABLE_TRANSFER)?; + Ok(()) + } +} + +#[cw_serde] +pub struct TotalSupply(pub Uint128); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for TotalSupply { + const ITEM: Item<'static, Self> = Item::new("total-supply-"); +} + +#[cfg(feature = "snip20-impl")] +impl TotalSupply { + pub fn set(storage: &mut dyn Storage, amount: Uint128) -> StdResult<()> { + TotalSupply(amount).save(storage) + } + + pub fn add(storage: &mut dyn Storage, amount: Uint128) -> StdResult { + let supply = TotalSupply::load(storage)?.0.checked_add(amount)?; + TotalSupply::set(storage, supply)?; + Ok(supply) + } + + pub fn sub(storage: &mut dyn Storage, amount: Uint128) -> StdResult { + let supply = TotalSupply::load(storage)?.0.checked_sub(amount)?; + TotalSupply::set(storage, supply)?; + Ok(supply) + } +} + +#[cw_serde] +pub struct Balance(pub Uint128); + +#[cfg(feature = "snip20-impl")] +impl MapStorage<'static, Addr> for Balance { + const MAP: Map<'static, Addr, Self> = Map::new("balance-"); +} + +#[cfg(feature = "snip20-impl")] +impl Balance { + pub fn set(storage: &mut dyn Storage, amount: Uint128, addr: &Addr) -> StdResult<()> { + Balance(amount).save(storage, addr.clone()) + } + + pub fn add(storage: &mut dyn Storage, amount: Uint128, addr: &Addr) -> StdResult { + let supply = Self::may_load(storage, addr.clone())? + .unwrap_or(Self(Uint128::zero())) + .0 + .checked_add(amount)?; + + Balance::set(storage, supply, addr)?; + Ok(supply) + } + + pub fn sub(storage: &mut dyn Storage, amount: Uint128, addr: &Addr) -> StdResult { + let subtractee = match Self::load(storage, addr.clone()) { + Ok(amount) => amount.0, + Err(_) => return Err(no_funds()), + }; + let supply = match subtractee.checked_sub(amount) { + Ok(supply) => supply, + Err(_) => return Err(not_enough_funds()), + }; + Balance::set(storage, supply, addr)?; + Ok(supply) + } + + pub fn transfer( + storage: &mut dyn Storage, + amount: Uint128, + sender: &Addr, + recipient: &Addr, + ) -> StdResult<()> { + Self::sub(storage, amount, sender)?; + Self::add(storage, amount, recipient)?; + Ok(()) + } +} + +#[cw_serde] +pub struct Minters(pub Vec); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for Minters { + const ITEM: Item<'static, Self> = Item::new("minters-"); +} + +#[cw_serde] +pub struct AllowanceResponse { + pub spender: Addr, + pub owner: Addr, + pub allowance: Uint128, + pub expiration: Option, +} + +#[cw_serde] +pub struct Allowance { + pub amount: Uint128, + pub expiration: Option, +} + +impl Default for Allowance { + fn default() -> Self { + Self { + amount: Uint128::zero(), + expiration: None, + } + } +} + +#[cfg(feature = "snip20-impl")] +impl Allowance { + pub fn is_expired(&self, block: &BlockInfo) -> bool { + match self.expiration { + Some(time) => block.time >= Timestamp::from_seconds(time), + None => false, + } + } + + pub fn spend( + storage: &mut dyn Storage, + owner: &Addr, + spender: &Addr, + amount: Uint128, + block: &BlockInfo, + ) -> StdResult<()> { + let mut allowance = Allowance::load(storage, (owner.clone(), spender.clone()))?; + + if allowance.is_expired(block) { + return Err(allowance_expired(allowance.expiration.unwrap())); + } + if let Ok(new_allowance) = allowance.amount.checked_sub(amount) { + allowance.amount = new_allowance; + } else { + return Err(insufficient_allowance()); + } + + allowance.save(storage, (owner.clone(), spender.clone()))?; + + Ok(()) + } +} +// (Owner, Spender) +#[cfg(feature = "snip20-impl")] +impl MapStorage<'static, (Addr, Addr)> for Allowance { + const MAP: Map<'static, (Addr, Addr), Self> = Map::new("allowance-"); +} + +#[cw_serde] +pub struct ReceiverHash(pub String); + +#[cfg(feature = "snip20-impl")] +impl MapStorage<'static, Addr> for ReceiverHash { + const MAP: Map<'static, Addr, Self> = Map::new("receiver-hash-"); +} + +// Auth +pub use crate::contract_interfaces::query_auth::auth::{HashedKey, Key, PermitKey}; diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/mod.rs b/packages/shade_protocol/src/contract_interfaces/snip20/mod.rs new file mode 100644 index 0000000..47a23f2 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/mod.rs @@ -0,0 +1,649 @@ +pub mod batch; +pub mod errors; +pub mod helpers; +pub mod manager; +pub mod transaction_history; + +use crate::{ + c_std::{Addr, Binary, Env, StdResult, Storage}, + query_authentication::permit::Permit, +}; +use cosmwasm_std::{Api, MessageInfo}; + +#[cfg(feature = "snip20-impl")] +use crate::contract_interfaces::snip20::transaction_history::store_mint; +#[cfg(feature = "snip20-impl")] +use crate::utils::storage::plus::ItemStorage; +use crate::{ + c_std::Uint128, + contract_interfaces::{ + query_auth::QueryPermit as AuthQueryPermit, + snip20::{ + errors::{invalid_decimals, invalid_name_format, invalid_symbol_format}, + manager::{ + Admin, + Balance, + CoinInfo, + Config, + ContractStatusLevel, + Minters, + RandSeed, + TotalSupply, + }, + transaction_history::{RichTx, Tx}, + }, + }, + snip20::manager::QueryAuth, + utils::{ + crypto::sha_256, + generic_response::ResponseStatus, + ExecuteCallback, + InstantiateCallback, + Query, + }, + Contract, +}; +use cosmwasm_schema::cw_serde; + +pub const VERSION: &str = "SNIP24"; + +#[cw_serde] +pub struct InitialBalance { + pub address: String, + pub amount: Uint128, +} + +#[cw_serde] +pub struct InstantiateMsg { + pub name: String, + pub admin: Option, + pub symbol: String, + pub decimals: u8, + pub initial_balances: Option>, + pub prng_seed: Binary, + pub config: Option, + pub query_auth: Option, +} + +fn is_valid_name(name: &str) -> bool { + let len = name.len(); + (3..=30).contains(&len) +} + +fn is_valid_symbol(symbol: &str) -> bool { + let len = symbol.len(); + let len_is_valid = (3..=6).contains(&len); + + len_is_valid && symbol.bytes().all(|byte| (b'A'..=b'Z').contains(&byte)) +} + +#[cfg(feature = "snip20-impl")] +impl InstantiateMsg { + pub fn save( + &self, + storage: &mut dyn Storage, + api: &dyn Api, + env: Env, + info: MessageInfo, + ) -> StdResult<()> { + if !is_valid_name(&self.name) { + return Err(invalid_name_format(&self.name)); + } + + if !is_valid_symbol(&self.symbol) { + return Err(invalid_symbol_format(&self.symbol)); + } + + if self.decimals > 18 { + return Err(invalid_decimals()); + } + + let config = self.config.clone().unwrap_or_default(); + config.save(storage)?; + + CoinInfo { + name: self.name.clone(), + symbol: self.symbol.clone(), + decimals: self.decimals, + } + .save(storage)?; + + let admin_addr; + if let Some(admin) = &self.admin { + admin_addr = api.addr_validate(admin.as_str())? + } else { + admin_addr = info.sender; + } + + Admin(admin_addr.clone()).save(storage)?; + RandSeed(sha_256(&self.prng_seed.0).to_vec()).save(storage)?; + + let mut total_supply = Uint128::zero(); + + if let Some(initial_balances) = &self.initial_balances { + for balance in initial_balances.iter() { + let address = api.addr_validate(balance.address.as_str())?; + Balance::set(storage, balance.amount.clone(), &address)?; + total_supply = total_supply.checked_add(balance.amount)?; + + store_mint( + storage, + &admin_addr, + &address, + balance.amount, + self.symbol.clone(), + Some("Initial Balance".to_string()), + &env.block, + )?; + } + } + + TotalSupply::set(storage, total_supply)?; + + ContractStatusLevel::NormalRun.save(storage)?; + + Minters(vec![]).save(storage)?; + + if let Some(query_auth) = self.query_auth.clone() { + QueryAuth(query_auth).save(storage)?; + } + + Ok(()) + } +} + +#[cw_serde] +pub struct InitConfig { + /// Indicates whether the total supply is public or should be kept secret. + /// default: False + pub public_total_supply: Option, + /// Indicates whether deposit functionality should be enabled + /// default: False + pub enable_deposit: Option, + /// Indicates whether redeem functionality should be enabled + /// default: False + pub enable_redeem: Option, + /// Indicates whether mint functionality should be enabled + /// default: False + pub enable_mint: Option, + /// Indicates whether burn functionality should be enabled + /// default: False + pub enable_burn: Option, + /// Indicates whether transferring tokens should be enables + /// default: True + pub enable_transfer: Option, +} + +impl Default for InitConfig { + fn default() -> Self { + Self { + public_total_supply: None, + enable_deposit: None, + enable_redeem: None, + enable_mint: None, + enable_burn: None, + enable_transfer: None, + } + } +} + +#[cfg(feature = "snip20-impl")] +impl InitConfig { + pub fn save(self, storage: &mut dyn Storage) -> StdResult<()> { + Config { + public_total_supply: self.public_total_supply(), + enable_deposit: self.deposit_enabled(), + enable_redeem: self.redeem_enabled(), + enable_mint: self.mint_enabled(), + enable_burn: self.burn_enabled(), + enable_transfer: self.transfer_enabled(), + } + .save(storage)?; + Ok(()) + } + + pub fn public_total_supply(&self) -> bool { + self.public_total_supply.unwrap_or(false) + } + + pub fn deposit_enabled(&self) -> bool { + self.enable_deposit.unwrap_or(false) + } + + pub fn redeem_enabled(&self) -> bool { + self.enable_redeem.unwrap_or(false) + } + + pub fn mint_enabled(&self) -> bool { + self.enable_mint.unwrap_or(false) + } + + pub fn burn_enabled(&self) -> bool { + self.enable_burn.unwrap_or(false) + } + + pub fn transfer_enabled(&self) -> bool { + self.enable_transfer.unwrap_or(true) + } +} + +impl InstantiateCallback for InstantiateMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteMsg { + // Native coin interactions + Redeem { + amount: Uint128, + denom: Option, + padding: Option, + }, + Deposit { + padding: Option, + }, + + // Base ERC-20 stuff + Transfer { + recipient: String, + amount: Uint128, + memo: Option, + padding: Option, + }, + Send { + recipient: String, + recipient_code_hash: Option, + amount: Uint128, + msg: Option, + memo: Option, + padding: Option, + }, + BatchTransfer { + actions: Vec, + padding: Option, + }, + BatchSend { + actions: Vec, + padding: Option, + }, + Burn { + amount: Uint128, + memo: Option, + padding: Option, + }, + RegisterReceive { + code_hash: String, + padding: Option, + }, + CreateViewingKey { + entropy: String, + padding: Option, + }, + SetViewingKey { + key: String, + padding: Option, + }, + + // Allowance + IncreaseAllowance { + spender: String, + amount: Uint128, + expiration: Option, + padding: Option, + }, + DecreaseAllowance { + spender: String, + amount: Uint128, + expiration: Option, + padding: Option, + }, + TransferFrom { + owner: String, + recipient: String, + amount: Uint128, + memo: Option, + padding: Option, + }, + SendFrom { + owner: String, + recipient: String, + recipient_code_hash: Option, + amount: Uint128, + msg: Option, + memo: Option, + padding: Option, + }, + BatchTransferFrom { + actions: Vec, + padding: Option, + }, + BatchSendFrom { + actions: Vec, + padding: Option, + }, + BurnFrom { + owner: String, + amount: Uint128, + memo: Option, + padding: Option, + }, + BatchBurnFrom { + actions: Vec, + padding: Option, + }, + + // Mint + Mint { + recipient: String, + amount: Uint128, + memo: Option, + padding: Option, + }, + BatchMint { + actions: Vec, + padding: Option, + }, + AddMinters { + minters: Vec, + padding: Option, + }, + RemoveMinters { + minters: Vec, + padding: Option, + }, + SetMinters { + minters: Vec, + padding: Option, + }, + + // Admin + ChangeAdmin { + address: String, + padding: Option, + }, + SetContractStatus { + level: ContractStatusLevel, + padding: Option, + }, + // Updated the auth setting + UpdateQueryAuth { + auth: Option, + }, + + // Permit + RevokePermit { + permit_name: String, + padding: Option, + }, +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub struct Snip20ReceiveMsg { + pub sender: String, + pub from: String, + pub amount: Uint128, + #[serde(skip_serializing_if = "Option::is_none")] + pub memo: Option, + pub msg: Option, +} + +#[cw_serde] +pub enum ReceiverHandleMsg { + Receive(Snip20ReceiveMsg), +} + +impl ReceiverHandleMsg { + pub fn new( + sender: String, + from: String, + amount: Uint128, + memo: Option, + msg: Option, + ) -> Self { + Self::Receive(Snip20ReceiveMsg { + sender, + from, + amount, + memo, + msg, + }) + } +} + +impl ExecuteCallback for ReceiverHandleMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteAnswer { + // Native + Deposit { + status: ResponseStatus, + }, + Redeem { + status: ResponseStatus, + }, + + // Base + Transfer { + status: ResponseStatus, + }, + Send { + status: ResponseStatus, + }, + BatchTransfer { + status: ResponseStatus, + }, + BatchSend { + status: ResponseStatus, + }, + Burn { + status: ResponseStatus, + }, + RegisterReceive { + status: ResponseStatus, + }, + CreateViewingKey { + key: String, + }, + SetViewingKey { + status: ResponseStatus, + }, + + // Allowance + IncreaseAllowance { + spender: Addr, + owner: Addr, + allowance: Uint128, + }, + DecreaseAllowance { + spender: Addr, + owner: Addr, + allowance: Uint128, + }, + TransferFrom { + status: ResponseStatus, + }, + SendFrom { + status: ResponseStatus, + }, + BatchTransferFrom { + status: ResponseStatus, + }, + BatchSendFrom { + status: ResponseStatus, + }, + BurnFrom { + status: ResponseStatus, + }, + BatchBurnFrom { + status: ResponseStatus, + }, + + // Mint + Mint { + status: ResponseStatus, + }, + BatchMint { + status: ResponseStatus, + }, + AddMinters { + status: ResponseStatus, + }, + RemoveMinters { + status: ResponseStatus, + }, + SetMinters { + status: ResponseStatus, + }, + + // Other + ChangeAdmin { + status: ResponseStatus, + }, + SetContractStatus { + status: ResponseStatus, + }, + UpdateQueryAuth { + status: ResponseStatus, + }, + + // Permit + RevokePermit { + status: ResponseStatus, + }, +} + +pub type QueryPermit = Permit; + +#[cw_serde] +pub struct PermitParams { + pub allowed_tokens: Vec, + pub permit_name: String, + pub permissions: Vec, +} + +impl PermitParams { + pub fn contains(&self, perm: Permission) -> bool { + self.permissions.contains(&perm) + } +} + +#[cw_serde] +pub enum Permission { + /// Allowance for SNIP-20 - Permission to query allowance of the owner & spender + Allowance, + /// Balance for SNIP-20 - Permission to query balance + Balance, + /// History for SNIP-20 - Permission to query transfer_history & transaction_hisotry + History, + /// Owner permission indicates that the bearer of this permit should be granted all + /// the access of the creator/signer of the permit. SNIP-721 uses this to grant + /// viewing access to all data that the permit creator owns and is whitelisted for. + /// For SNIP-721 use, a permit with Owner permission should NEVER be given to + /// anyone else. If someone wants to share private data, they should whitelist + /// the address they want to share with via a SetWhitelistedApproval tx, and that + /// address will view the data by creating their own permit with Owner permission + Owner, +} + +#[cw_serde] +pub enum QueryMsg { + TokenInfo {}, + TokenConfig {}, + ContractStatus {}, + ExchangeRate {}, + Allowance { + owner: String, + spender: String, + key: String, + }, + Balance { + address: String, + key: String, + }, + TransferHistory { + address: String, + key: String, + page: Option, + page_size: u32, + }, + TransactionHistory { + address: String, + key: String, + page: Option, + page_size: u32, + }, + Minters {}, + WithPermit { + permit: Option, + // Extra parameter because of snip20s standards + auth_permit: Option, + query: QueryWithPermit, + }, +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum QueryWithPermit { + Allowance { owner: String, spender: String }, + Balance {}, + TransferHistory { page: Option, page_size: u32 }, + TransactionHistory { page: Option, page_size: u32 }, +} + +#[cw_serde] +pub enum QueryAnswer { + TokenInfo { + name: String, + symbol: String, + decimals: u8, + total_supply: Option, + }, + TokenConfig { + // TODO: add other config items as optionals so they can be ignored in other snip20s + public_total_supply: bool, + deposit_enabled: bool, + redeem_enabled: bool, + mint_enabled: bool, + burn_enabled: bool, + transfer_enabled: bool, + }, + ContractStatus { + status: ContractStatusLevel, + }, + ExchangeRate { + rate: Uint128, + denom: String, + }, + Allowance { + spender: Addr, + owner: Addr, + allowance: Uint128, + expiration: Option, + }, + Balance { + amount: Uint128, + }, + TransferHistory { + txs: Vec, + total: Option, + }, + TransactionHistory { + txs: Vec, + total: Option, + }, + ViewingKeyError { + msg: String, + }, + Minters { + minters: Vec, + }, +} diff --git a/packages/shade_protocol/src/contract_interfaces/snip20/transaction_history.rs b/packages/shade_protocol/src/contract_interfaces/snip20/transaction_history.rs new file mode 100644 index 0000000..f9fc7f8 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20/transaction_history.rs @@ -0,0 +1,496 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::Timestamp; + +use crate::{ + c_std::{Addr, BlockInfo, Coin, StdError, StdResult, Storage, Uint128}, + contract_interfaces::snip20::errors::{ + legacy_cannot_convert_from_tx, + tx_code_invalid_conversion, + }, +}; + +#[cfg(feature = "snip20-impl")] +use crate::utils::storage::plus::{ItemStorage, MapStorage}; +#[cfg(feature = "snip20-impl")] +use secret_storage_plus::{Item, Map}; + +// Note that id is a globally incrementing counter. +// Since it's 64 bits long, even at 50 tx/s it would take +// over 11 billion years for it to rollback. I'm pretty sure +// we'll have bigger issues by then. +#[cw_serde] +pub struct Tx { + pub id: u64, + pub from: Addr, + pub sender: Addr, + pub receiver: Addr, + pub coins: Coin, + #[serde(skip_serializing_if = "Option::is_none")] + pub memo: Option, + // The block time and block height are optional so that the JSON schema + // reflects that some SNIP-20 contracts may not include this info. + pub block_time: Option, + pub block_height: Option, +} + +#[cfg(feature = "snip20-impl")] +impl Tx { + // Inefficient but compliant, not recommended to use deprecated features + pub fn get( + storage: &dyn Storage, + for_address: &Addr, + page: u32, + page_size: u32, + ) -> StdResult<(Vec, u64)> { + let id = UserTXTotal::load(storage, for_address.clone())?.0; + let start_index = page as u64 * page_size as u64; + + // Since we dont know where the legacy txs are then we iterate over everything + let mut total = 0u64; + let mut txs = vec![]; + for i in 0..id { + match StoredRichTx::load(storage, (for_address.clone(), i))?.into_legacy() { + Ok(tx) => { + total += 1; + if total >= (start_index + page_size as u64) { + break; + } else if total >= start_index { + txs.push(tx); + } + } + Err(_) => {} + } + } + + let length = txs.len() as u64; + Ok((txs, length)) + } +} + +#[cw_serde] +pub enum TxAction { + Transfer { + from: Addr, + sender: Addr, + recipient: Addr, + }, + Mint { + minter: Addr, + recipient: Addr, + }, + Burn { + burner: Addr, + owner: Addr, + }, + Deposit {}, + Redeem {}, +} + +// Note that id is a globally incrementing counter. +// Since it's 64 bits long, even at 50 tx/s it would take +// over 11 billion years for it to rollback. I'm pretty sure +// we'll have bigger issues by then. +#[cw_serde] +pub struct RichTx { + pub id: u64, + pub action: TxAction, + pub coins: Coin, + #[serde(skip_serializing_if = "Option::is_none")] + pub memo: Option, + pub block_time: Timestamp, + pub block_height: u64, +} + +#[cfg(feature = "snip20-impl")] +impl RichTx { + pub fn get( + storage: &dyn Storage, + for_address: &Addr, + page: u32, + page_size: u32, + ) -> StdResult<(Vec, u64)> { + let id = UserTXTotal::load(storage, for_address.clone())?.0; + let start_index = page as u64 * page_size as u64; + let size: u64; + if (start_index + page_size as u64) > id { + size = id; + } else { + size = page_size as u64 + start_index; + } + + let mut txs = vec![]; + for index in start_index..size { + let stored_tx = StoredRichTx::load(storage, (for_address.clone(), index))?; + txs.push(stored_tx.into_humanized()?); + } + + let length = txs.len() as u64; + Ok((txs, length)) + } +} + +// Stored types: +#[derive(Clone, Copy, Debug)] +#[repr(u8)] +enum TxCode { + Transfer = 0, + Mint = 1, + Burn = 2, + Deposit = 3, + Redeem = 4, +} + +impl TxCode { + fn to_u8(self) -> u8 { + self as u8 + } + + fn from_u8(n: u8) -> StdResult { + use TxCode::*; + match n { + 0 => Ok(Transfer), + 1 => Ok(Mint), + 2 => Ok(Burn), + 3 => Ok(Deposit), + 4 => Ok(Redeem), + _ => Err(tx_code_invalid_conversion(n)), + } + } +} + +#[cw_serde] +struct StoredTxAction { + tx_type: u8, + address1: Option, + address2: Option, + address3: Option, +} + +impl StoredTxAction { + fn transfer(from: Addr, sender: Addr, recipient: Addr) -> Self { + Self { + tx_type: TxCode::Transfer.to_u8(), + address1: Some(from), + address2: Some(sender), + address3: Some(recipient), + } + } + + fn mint(minter: Addr, recipient: Addr) -> Self { + Self { + tx_type: TxCode::Mint.to_u8(), + address1: Some(minter), + address2: Some(recipient), + address3: None, + } + } + + fn burn(owner: Addr, burner: Addr) -> Self { + Self { + tx_type: TxCode::Burn.to_u8(), + address1: Some(burner), + address2: Some(owner), + address3: None, + } + } + + fn deposit() -> Self { + Self { + tx_type: TxCode::Deposit.to_u8(), + address1: None, + address2: None, + address3: None, + } + } + + fn redeem() -> Self { + Self { + tx_type: TxCode::Redeem.to_u8(), + address1: None, + address2: None, + address3: None, + } + } + + fn into_humanized(self) -> StdResult { + let transfer_addr_err = || { + StdError::generic_err( + "Missing address in stored Transfer transaction. Storage is corrupt", + ) + }; + let mint_addr_err = || { + StdError::generic_err("Missing address in stored Mint transaction. Storage is corrupt") + }; + let burn_addr_err = || { + StdError::generic_err("Missing address in stored Burn transaction. Storage is corrupt") + }; + + // In all of these, we ignore fields that we don't expect to find populated + let action = match TxCode::from_u8(self.tx_type)? { + TxCode::Transfer => { + let from = self.address1.ok_or_else(transfer_addr_err)?; + let sender = self.address2.ok_or_else(transfer_addr_err)?; + let recipient = self.address3.ok_or_else(transfer_addr_err)?; + TxAction::Transfer { + from, + sender, + recipient, + } + } + TxCode::Mint => { + let minter = self.address1.ok_or_else(mint_addr_err)?; + let recipient = self.address2.ok_or_else(mint_addr_err)?; + TxAction::Mint { minter, recipient } + } + TxCode::Burn => { + let burner = self.address1.ok_or_else(burn_addr_err)?; + let owner = self.address2.ok_or_else(burn_addr_err)?; + TxAction::Burn { burner, owner } + } + TxCode::Deposit => TxAction::Deposit {}, + TxCode::Redeem => TxAction::Redeem {}, + }; + + Ok(action) + } +} + +#[cw_serde] +struct StoredRichTx { + id: u64, + action: StoredTxAction, + coins: Coin, + memo: Option, + block_time: Timestamp, + block_height: u64, +} + +impl StoredRichTx { + fn new( + id: u64, + action: StoredTxAction, + coins: Coin, + memo: Option, + block: &BlockInfo, + ) -> Self { + Self { + id, + action, + coins, + memo, + block_time: block.time, + block_height: block.height, + } + } + + fn into_humanized(self) -> StdResult { + Ok(RichTx { + id: self.id, + action: self.action.into_humanized()?, + coins: self.coins, + memo: self.memo, + block_time: self.block_time, + block_height: self.block_height, + }) + } + + fn into_legacy(self) -> StdResult { + if self.action.tx_type == 0 { + Ok(Tx { + id: self.id, + from: self.action.address1.unwrap(), + sender: self.action.address2.unwrap(), + receiver: self.action.address3.unwrap(), + coins: self.coins, + memo: self.memo, + block_time: Some(self.block_time), + block_height: Some(self.block_height), + }) + } else { + Err(legacy_cannot_convert_from_tx()) + } + } +} + +#[cfg(feature = "snip20-impl")] +impl MapStorage<'static, (Addr, u64)> for StoredRichTx { + const MAP: Map<'static, (Addr, u64), Self> = Map::new("stored-rich-tx-"); +} + +// Storage functions: +#[cw_serde] +struct TXCount(pub u64); + +#[cfg(feature = "snip20-impl")] +impl ItemStorage for TXCount { + const ITEM: Item<'static, Self> = Item::new("tx-count-"); +} + +#[cfg(feature = "snip20-impl")] +fn increment_tx_count(storage: &mut dyn Storage) -> StdResult { + let id = TXCount::may_load(storage)?.unwrap_or(TXCount(0)).0 + 1; + TXCount(id).save(storage)?; + Ok(id) +} + +// User tx index +#[cw_serde] +struct UserTXTotal(pub u64); + +#[cfg(feature = "snip20-impl")] +impl UserTXTotal { + pub fn append( + storage: &mut dyn Storage, + for_address: &Addr, + tx: &StoredRichTx, + ) -> StdResult<()> { + let id = UserTXTotal::may_load(storage, for_address.clone())? + .unwrap_or(UserTXTotal(0)) + .0; + UserTXTotal(id + 1).save(storage, for_address.clone())?; + tx.save(storage, (for_address.clone(), id))?; + + Ok(()) + } +} + +#[cfg(feature = "snip20-impl")] +impl MapStorage<'static, Addr> for UserTXTotal { + const MAP: Map<'static, Addr, Self> = Map::new("user-tx-total-"); +} + +#[cfg(feature = "snip20-impl")] +#[allow(clippy::too_many_arguments)] // We just need them +pub fn store_transfer( + storage: &mut dyn Storage, + owner: &Addr, + sender: &Addr, + receiver: &Addr, + amount: Uint128, + denom: String, + memo: Option, + block: &BlockInfo, +) -> StdResult<()> { + let id = increment_tx_count(storage)?; + let coins = Coin { + denom, + amount: amount.into(), + }; + let tx = StoredRichTx::new( + id, + StoredTxAction::transfer(owner.clone(), sender.clone(), receiver.clone()), + coins, + memo, + block, + ); + + // Write to the owners history if it's different from the other two addresses + if owner != sender && owner != receiver { + // crate::c_std::debug_print("saving transaction history for owner"); + UserTXTotal::append(storage, owner, &tx)?; + } + // Write to the sender's history if it's different from the receiver + if sender != receiver { + // crate::c_std::debug_print("saving transaction history for sender"); + UserTXTotal::append(storage, sender, &tx)?; + } + // Always write to the recipient's history + // crate::c_std::debug_print("saving transaction history for receiver"); + UserTXTotal::append(storage, receiver, &tx)?; + + Ok(()) +} + +#[cfg(feature = "snip20-impl")] +pub fn store_mint( + storage: &mut dyn Storage, + minter: &Addr, + recipient: &Addr, + amount: Uint128, + denom: String, + memo: Option, + block: &BlockInfo, +) -> StdResult<()> { + let id = increment_tx_count(storage)?; + let coins = Coin { + denom, + amount: amount.into(), + }; + let action = StoredTxAction::mint(minter.clone(), recipient.clone()); + let tx = StoredRichTx::new(id, action, coins, memo, block); + + if minter != recipient { + UserTXTotal::append(storage, recipient, &tx)?; + } + UserTXTotal::append(storage, minter, &tx)?; + + Ok(()) +} + +#[cfg(feature = "snip20-impl")] +pub fn store_burn( + storage: &mut dyn Storage, + owner: &Addr, + burner: &Addr, + amount: Uint128, + denom: String, + memo: Option, + block: &BlockInfo, +) -> StdResult<()> { + let id = increment_tx_count(storage)?; + let coins = Coin { + denom, + amount: amount.into(), + }; + let action = StoredTxAction::burn(owner.clone(), burner.clone()); + let tx = StoredRichTx::new(id, action, coins, memo, block); + + if burner != owner { + UserTXTotal::append(storage, owner, &tx)?; + } + UserTXTotal::append(storage, burner, &tx)?; + + Ok(()) +} + +#[cfg(feature = "snip20-impl")] +pub fn store_deposit( + storage: &mut dyn Storage, + recipient: &Addr, + amount: Uint128, + denom: String, + block: &BlockInfo, +) -> StdResult<()> { + let id = increment_tx_count(storage)?; + let coins = Coin { + denom, + amount: amount.into(), + }; + let action = StoredTxAction::deposit(); + let tx = StoredRichTx::new(id, action, coins, None, block); + + UserTXTotal::append(storage, recipient, &tx)?; + + Ok(()) +} + +#[cfg(feature = "snip20-impl")] +pub fn store_redeem( + storage: &mut dyn Storage, + redeemer: &Addr, + amount: Uint128, + denom: String, + block: &BlockInfo, +) -> StdResult<()> { + let id = increment_tx_count(storage)?; + let coins = Coin { + denom, + amount: amount.into(), + }; + let action = StoredTxAction::redeem(); + let tx = StoredRichTx::new(id, action, coins, None, block); + + UserTXTotal::append(storage, redeemer, &tx)?; + + Ok(()) +} diff --git a/packages/shade_protocol/src/contract_interfaces/snip20_migration/mod.rs b/packages/shade_protocol/src/contract_interfaces/snip20_migration/mod.rs new file mode 100644 index 0000000..db86cec --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/snip20_migration/mod.rs @@ -0,0 +1,89 @@ +use crate::utils::{ + asset::{Contract, RawContract}, + generic_response::ResponseStatus, + ExecuteCallback, + InstantiateCallback, + Query, +}; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, Binary, Uint128}; + +#[cw_serde] +pub struct RegisteredToken { + pub burn_token: Contract, + pub mint_token: Contract, + pub burnable: Option, +} + +#[cw_serde] +pub struct Config { + pub admin: Contract, +} + +#[cw_serde] +pub struct InstantiateMsg { + pub admin: Contract, + pub tokens: Option, +} + +impl InstantiateCallback for InstantiateMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteMsg { + UpdateConfig { + admin: RawContract, + padding: Option, + }, + RegisterMigrationTokens { + burn_token: RawContract, + mint_token: RawContract, + burnable: Option, + padding: Option, + }, + Receive { + sender: String, + from: String, + amount: Uint128, + msg: Option, + memo: Option, + padding: Option, + }, +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum ExecuteAnswer { + SetConfig { + status: ResponseStatus, + config: Config, + }, + RegisterMigrationTokens { + status: ResponseStatus, + }, + Receive { + status: ResponseStatus, + }, +} + +#[cw_serde] +pub enum QueryMsg { + Config {}, + Metrics { token: String }, + RegistrationStatus { token: String }, +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = 256; +} + +#[cw_serde] +pub enum QueryAnswer { + Config { config: Config }, + Metrics { amount_minted: Uint128 }, + RegistrationStatus { status: RegisteredToken }, +} diff --git a/packages/shade_protocol/src/lib.rs b/packages/shade_protocol/src/lib.rs new file mode 100644 index 0000000..5200bae --- /dev/null +++ b/packages/shade_protocol/src/lib.rs @@ -0,0 +1,43 @@ +// TODO: make private later +pub mod contract_interfaces; +pub use contract_interfaces::*; + +pub const BLOCK_SIZE: usize = 256; +pub mod utils; + +// Forward important libs to avoid constantly importing them in the cargo crates, could help reduce compile times +pub mod c_std { + pub use contract_derive::shd_entry_point; + pub use cosmwasm_std::*; +} + +pub mod storage { + pub use cosmwasm_storage::*; +} + +pub use cosmwasm_schema; +pub use schemars; +#[cfg(feature = "storage_plus")] +pub use secret_storage_plus; +pub use serde; +pub use thiserror; + +#[cfg(feature = "query_auth_lib")] +pub use query_authentication; + +#[cfg(feature = "ensemble")] +pub use fadroma; + +#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "multi-test")] +pub use secret_multi_test as multi_test; + +#[cfg(feature = "multi-test")] +pub use anyhow::Result as AnyResult; + +// Expose contract in root since its so used +#[cfg(feature = "utils")] +pub use utils::asset::Contract; + +#[cfg(feature = "chrono")] +pub use chrono; diff --git a/packages/shade_protocol/src/schemas.rs b/packages/shade_protocol/src/schemas.rs new file mode 100644 index 0000000..149f155 --- /dev/null +++ b/packages/shade_protocol/src/schemas.rs @@ -0,0 +1,65 @@ +use cosmwasm_schema::{export_schema, remove_schemas}; +use schemars::schema_for; +use std::{env::current_dir, fs::create_dir_all}; + +macro_rules! generate_schemas { + ($($Contract:ident),+) => { + $( + use shade_protocol::contract_interfaces::$Contract; + + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + out_dir.push(stringify!($Contract)); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!($Contract::InstantiateMsg), &out_dir); + export_schema(&schema_for!($Contract::ExecuteMsg), &out_dir); + export_schema(&schema_for!($Contract::ExecuteAnswer), &out_dir); + export_schema(&schema_for!($Contract::QueryMsg), &out_dir); + export_schema(&schema_for!($Contract::QueryAnswer), &out_dir); + )+ + }; +} + +macro_rules! generate_nested_schemas { + ($Folder:ident, $($Contract:ident),+) => { + $( + use shade_protocol::contract_interfaces::$Folder::$Contract; + + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + out_dir.push(stringify!($Folder)); + out_dir.push(stringify!($Contract)); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!($Contract::InstantiateMsg), &out_dir); + export_schema(&schema_for!($Contract::ExecuteMsg), &out_dir); + export_schema(&schema_for!($Contract::ExecuteAnswer), &out_dir); + export_schema(&schema_for!($Contract::QueryMsg), &out_dir); + export_schema(&schema_for!($Contract::QueryAnswer), &out_dir); + )+ + }; +} + +pub fn main() { + generate_schemas!(airdrop); + + // generate_nested_schemas!(mint, liability_mint, mint, mint_router); + + // generate_nested_schemas!(staking, snip20_staking); + + // TODO: make admin interface up to standard + // use shade_protocol::contract_interfaces::admin; + + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + // out_dir.push("admin"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + // export_schema(&schema_for!(admin::InstantiateMsg), &out_dir); + // export_schema(&schema_for!(admin::ExecuteMsg), &out_dir); + // export_schema(&schema_for!(admin::QueryMsg), &out_dir); +} diff --git a/packages/shade_protocol/src/utils/asset.rs b/packages/shade_protocol/src/utils/asset.rs new file mode 100644 index 0000000..013b8f2 --- /dev/null +++ b/packages/shade_protocol/src/utils/asset.rs @@ -0,0 +1,225 @@ +use std::vec; + +use crate::{ + c_std::{Addr, Api, BalanceResponse, BankQuery, ContractInfo, Deps, StdResult, Uint128}, + BLOCK_SIZE, +}; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{CosmosMsg, DepsMut, Env}; + +/// Validates an optional address. +pub fn optional_addr_validate(api: &dyn Api, addr: Option) -> StdResult> { + let addr = if let Some(addr) = addr { + Some(api.addr_validate(&addr)?) + } else { + None + }; + + Ok(addr) +} + +/// Validates an optional RawContract. +pub fn optional_raw_contract_validate( + api: &dyn Api, + contract: Option, +) -> StdResult> { + let contract = if let Some(contract) = contract { + Some(contract.into_valid(api)?) + } else { + None + }; + + Ok(contract) +} + +/// Validates an optional RawContract. +pub fn optional_validate( + api: &dyn Api, + contract: Option, +) -> StdResult> { + let contract = if let Some(contract) = contract { + Some(contract.valid(api)?) + } else { + None + }; + + Ok(contract) +} + +/// Validates a vector of Strings as Addrs +pub fn validate_vec(api: &dyn Api, unvalidated_addresses: Vec) -> StdResult> { + let items: Result, _> = unvalidated_addresses + .iter() + .map(|f| api.addr_validate(f.as_str())) + .collect(); + Ok(items?) +} + +/// A contract that does not contain a validated address. +/// Should be accepted as user input because we shouldn't assume addresses are verified Addrs. +/// https://docs.rs/cosmwasm-std/latest/cosmwasm_std/struct.Addr.html +#[derive(Hash, Eq, Default)] +#[cw_serde] +pub struct RawContract { + pub address: String, + pub code_hash: String, +} + +impl RawContract { + #[allow(clippy::ptr_arg)] + pub fn new(address: &String, code_hash: &String) -> Self { + RawContract { + address: address.clone(), + code_hash: code_hash.clone(), + } + } + + /// Being deprecated in favor of `valid` which turns this into ContractInfo + /// instead of a Contract (which we are getting rid of) + pub fn into_valid(self, api: &dyn Api) -> StdResult { + let valid_addr = api.addr_validate(self.address.as_str())?; + Ok(Contract::new(&valid_addr, &self.code_hash)) + } + + pub fn valid(self, api: &dyn Api) -> StdResult { + let valid_addr = api.addr_validate(self.address.as_str())?; + Ok(ContractInfo { + address: valid_addr, + code_hash: self.code_hash.clone(), + }) + } +} + +impl From for RawContract { + fn from(item: Contract) -> Self { + RawContract { + address: item.address.into(), + code_hash: item.code_hash, + } + } +} + +impl From for RawContract { + fn from(item: ContractInfo) -> Self { + RawContract { + address: item.address.into(), + code_hash: item.code_hash, + } + } +} + +#[derive(Hash, Eq)] +#[cw_serde] +/// In the process of being deprecated for [cosmwasm_std::ContractInfo] so use that +/// instead when possible. +pub struct Contract { + pub address: Addr, + pub code_hash: String, +} + +impl Default for Contract { + fn default() -> Self { + Self { + address: Addr::unchecked(String::default()), + code_hash: Default::default(), + } + } +} + +impl Contract { + #[allow(clippy::ptr_arg)] + pub fn new(address: &Addr, code_hash: &String) -> Self { + Contract { + address: address.clone(), + code_hash: code_hash.clone(), + } + } + + pub fn validate_new(deps: Deps, address: &str, code_hash: &String) -> StdResult { + let valid_addr = deps.api.addr_validate(address)?; + Ok(Contract::new(&valid_addr, code_hash)) + } +} + +impl From for Contract { + fn from(item: ContractInfo) -> Self { + Contract { + address: item.address, + code_hash: item.code_hash, + } + } +} + +impl Into for Contract { + fn into(self) -> ContractInfo { + ContractInfo { + address: self.address, + code_hash: self.code_hash, + } + } +} + +//TODO: move away from here +pub fn scrt_balance(deps: Deps, address: Addr) -> StdResult { + let resp: BalanceResponse = deps.querier.query( + &BankQuery::Balance { + address: address.into(), + denom: "uscrt".to_string(), + } + .into(), + )?; + + Ok(resp.amount.amount) +} + +#[cfg(feature = "snip20")] +pub fn set_allowance( + deps: DepsMut, + env: &Env, + spender: Addr, + amount: Uint128, + key: String, + asset: &Contract, + cur_allowance: Option, +) -> StdResult> { + use crate::snip20::helpers::{allowance_query, decrease_allowance_msg, increase_allowance_msg}; + + let allowance = match cur_allowance { + Some(cur) => cur, + None => { + allowance_query( + &deps.querier, + env.contract.address.clone(), + spender.clone(), + key, + 1, + asset, + )? + .allowance + } + }; + + match amount.cmp(&allowance) { + // Decrease Allowance + std::cmp::Ordering::Less => Ok(vec![decrease_allowance_msg( + spender, + allowance.checked_sub(amount)?, + None, + None, + BLOCK_SIZE, + asset, + vec![], + )?]), + // Increase Allowance + std::cmp::Ordering::Greater => Ok(vec![increase_allowance_msg( + spender, + amount.checked_sub(amount)?, + None, + None, + BLOCK_SIZE, + asset, + vec![], + )?]), + _ => Ok(vec![]), + } +} diff --git a/packages/shade_protocol/src/utils/calc.rs b/packages/shade_protocol/src/utils/calc.rs new file mode 100644 index 0000000..e6baac2 --- /dev/null +++ b/packages/shade_protocol/src/utils/calc.rs @@ -0,0 +1,25 @@ +use crate::c_std::{Uint256, StdResult}; + +// For generic purpose math formulas +pub fn sqrt(value: Uint256) -> StdResult { + let mut z = Uint256::zero(); + + if value.gt(&Uint256::from(3u128)) { + z = value; + let mut x = value + .checked_div(Uint256::from(2u128))? + .checked_add(Uint256::from(1u128))?; + + while x.lt(&z) { + z = x; + x = value + .checked_div(x)? + .checked_add(x)? + .checked_div(Uint256::from(2u128))?; + } + } else if !value.is_zero() { + z = Uint256::from(1u128); + } + + Ok(z) +} \ No newline at end of file diff --git a/packages/shade_protocol/src/utils/callback.rs b/packages/shade_protocol/src/utils/callback.rs new file mode 100644 index 0000000..6c0ebba --- /dev/null +++ b/packages/shade_protocol/src/utils/callback.rs @@ -0,0 +1,376 @@ +use super::space_pad; +#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "multi-test")] +use crate::multi_test::{App, AppResponse, Contract as MultiContract, Executor}; +#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "multi-test")] +use crate::AnyResult; +use crate::{ + c_std::{ + to_binary, Addr, Coin, ContractInfo, CosmosMsg, Empty, QuerierWrapper, QueryRequest, + StdResult, WasmMsg, WasmQuery, + }, + serde::{de::DeserializeOwned, Serialize}, + Contract, +}; + +/// A trait marking types that define the instantiation message of a contract +/// +/// This trait requires specifying a padding block size and provides a method to create the +/// CosmosMsg used to instantiate a contract +pub trait InstantiateCallback: Serialize { + /// pad the message to blocks of this size + const BLOCK_SIZE: usize; + + /// Returns StdResult + /// + /// Tries to convert the instance of the implementing type to a CosmosMsg that will trigger the + /// instantiation of a contract. The BLOCK_SIZE specified in the implementation is used when + /// padding the message + /// + /// # Arguments + /// + /// * `label` - String holding the label for the new contract instance + /// * `code_id` - code ID of the contract to be instantiated + /// * `callback_code_hash` - String holding the code hash of the contract to be instantiated + /// * `send_amount` - Optional Uint128 amount of native coin to send with instantiation message + fn to_cosmos_msg( + &self, + label: String, + code_id: u64, + code_hash: String, + funds: Vec, + ) -> StdResult { + let mut msg = to_binary(self)?; + // can not have 0 block size + let padding = if Self::BLOCK_SIZE == 0 { + 1 + } else { + Self::BLOCK_SIZE + }; + space_pad(&mut msg.0, padding); + let init = WasmMsg::Instantiate { + code_id, + code_hash, + msg, + label, + funds, + admin: None, + }; + Ok(init.into()) + } + + /// Returns ContractInfo + /// + /// Tries to instantiate a contract into the multi test app. + /// + /// # Arguments + /// + /// * `testable` - a struct implementing the MultiTestable trait + /// * `router` - mutable reference to multi test app + /// * `sender` - user performing init + /// * `label` - label used to reference this contract + /// * `send_funds` - any funds sent with this init + #[cfg(not(target_arch = "wasm32"))] + #[cfg(feature = "multi-test")] + fn test_init( + &self, + testable: impl MultiTestable, + router: &mut App, + sender: Addr, + label: &str, + send_funds: &[Coin], + ) -> AnyResult { + let stored_code = router.store_code(testable.contract()); + router.instantiate_contract(stored_code, sender, &self, send_funds, label, None) + } +} + +/// A trait marking types that define the handle message(s) of a contract +/// +/// This trait requires specifying a padding block size and provides a method to create the +/// CosmosMsg used to execute a handle method of a contract +pub trait ExecuteCallback: Serialize { + /// pad the message to blocks of this size + const BLOCK_SIZE: usize; + + /// Returns StdResult + /// + /// Tries to convert the instance of the implementing type to a CosmosMsg that will trigger a + /// handle function of a contract. The BLOCK_SIZE specified in the implementation is used when + /// padding the message + /// + /// # Arguments + /// + /// * `callback_code_hash` - String holding the code hash of the contract to be executed + /// * `contract_addr` - address of the contract being called + /// * `send_amount` - Optional Uint128 amount of native coin to send with the handle message + fn to_cosmos_msg( + &self, + contract: &(impl Into + Clone), + funds: Vec, + ) -> StdResult { + let mut msg = to_binary(self)?; + // can not have 0 block size + let padding = if Self::BLOCK_SIZE == 0 { + 1 + } else { + Self::BLOCK_SIZE + }; + let contract: Contract = contract.clone().into(); + space_pad(&mut msg.0, padding); + let execute = WasmMsg::Execute { + msg, + contract_addr: contract.address.to_string(), + code_hash: contract.code_hash, + funds, + }; + Ok(execute.into()) + } + + /// Returns AnyResult + /// + /// Tries to execute a message on a contract in the multi-test App. + /// + /// # Arguments + /// + /// * `contract` - ContractInfo of an existing contract on the multi-test App + /// * `router` - a mutable reference to the multi-test App + /// * `sender` - the user executing this message in the test env + /// * `send_funds` - any funds transferred with this exec + #[cfg(not(target_arch = "wasm32"))] + #[cfg(feature = "multi-test")] + fn test_exec( + &self, + contract: &ContractInfo, + router: &mut App, + sender: Addr, + send_funds: &[Coin], + ) -> AnyResult + where + Self: Serialize + std::fmt::Debug, + { + router.execute_contract(sender, &contract, &self, send_funds) + } +} + +/// A trait marking types that define the query message(s) of a contract +/// +/// This trait requires specifying a padding block size and provides a method to query a contract +pub trait Query: Serialize { + /// pad the message to blocks of this size + const BLOCK_SIZE: usize; + + /// Returns StdResult, where T is the type defining the query response + /// + /// Tries to query a contract and deserialize the query response. The BLOCK_SIZE specified in the + /// implementation is used when padding the message + /// + /// # Arguments + /// + /// * `querier` - a reference to the Querier dependency of the querying contract + /// * `callback_code_hash` - String holding the code hash of the contract to be queried + /// * `contract_addr` - address of the contract being queried + fn query( + &self, + querier: &QuerierWrapper, + contract: &(impl Into + Clone), + ) -> StdResult { + let mut msg = to_binary(self)?; + // can not have 0 block size + let padding = if Self::BLOCK_SIZE == 0 { + 1 + } else { + Self::BLOCK_SIZE + }; + space_pad(&mut msg.0, padding); + let contract: Contract = contract.clone().into(); + querier.query(&QueryRequest::Wasm(WasmQuery::Smart { + contract_addr: contract.address.to_string(), + msg, + code_hash: contract.code_hash, + })) + } + + /// Returns StdResult, where T is the type defining the query response + /// + /// Tries to query a contract in the multi-test App. + /// + /// # Arguments + /// + /// * `info` - contract info of instantiated contract + /// * `router` - a reference to the multi-test App + #[cfg(not(target_arch = "wasm32"))] + #[cfg(feature = "multi-test")] + fn test_query(&self, info: &ContractInfo, router: &App) -> StdResult { + let mut msg = to_binary(self)?; + // can not have 0 block size + let padding = if Self::BLOCK_SIZE == 0 { + 1 + } else { + Self::BLOCK_SIZE + }; + space_pad(&mut msg.0, padding); + router.wrap().query(&QueryRequest::Wasm(WasmQuery::Smart { + contract_addr: info.address.to_string(), + msg, + code_hash: info.code_hash.clone(), + })) + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[cfg(feature = "multi-test")] +/// Trait for making integration with multi-test easier. +pub trait MultiTestable { + fn contract(&self) -> Box>; + fn default() -> Self; +} + +#[cfg(test)] +mod tests { + use super::*; + use cosmwasm_std::{to_vec, Binary, Querier, QuerierResult}; + use serde::Deserialize; + + #[derive(Serialize)] + struct FooInit { + pub f1: i8, + pub f2: i8, + } + + impl InstantiateCallback for FooInit { + const BLOCK_SIZE: usize = 256; + } + + #[derive(Serialize)] + enum FooHandle { + Var1 { f1: i8, f2: i8 }, + } + + // All you really need to do is make people give you the padding block size. + impl ExecuteCallback for FooHandle { + const BLOCK_SIZE: usize = 256; + } + + #[derive(Serialize)] + enum FooQuery { + Query1 { f1: i8, f2: i8 }, + } + + impl Query for FooQuery { + const BLOCK_SIZE: usize = 256; + } + + #[test] + fn test_handle_callback_implementation_works() -> StdResult<()> { + let address = Addr::unchecked("secret1xyzasdf".to_string()); + let hash = "asdf".to_string(); + let amount = vec![Coin::new(1234, "uscrt")]; + let contract = Contract::new(&address, &hash); + + let cosmos_message: CosmosMsg = + FooHandle::Var1 { f1: 1, f2: 2 }.to_cosmos_msg(&contract, amount.clone())?; + + match cosmos_message { + CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr, + code_hash, + msg, + funds, + }) => { + assert_eq!(contract_addr, address); + assert_eq!(code_hash, hash); + let mut expected_msg = r#"{"Var1":{"f1":1,"f2":2}}"#.as_bytes().to_vec(); + space_pad(&mut expected_msg, 256); + assert_eq!(msg.0, expected_msg); + assert_eq!(funds, amount) + } + other => panic!("unexpected CosmosMsg variant: {:?}", other), + }; + + Ok(()) + } + + #[test] + fn test_init_callback_implementation_works() -> StdResult<()> { + let lbl = "testlabel".to_string(); + let id = 17u64; + let hash = "asdf".to_string(); + let amount = vec![Coin::new(1234, "uscrt")]; + + let cosmos_message: CosmosMsg = FooInit { f1: 1, f2: 2 }.to_cosmos_msg( + lbl.clone(), + id, + hash.clone(), + amount.clone(), + )?; + + match cosmos_message { + CosmosMsg::Wasm(WasmMsg::Instantiate { + code_id, + msg, + code_hash, + funds, + label, + admin: None, + }) => { + assert_eq!(code_id, id); + let mut expected_msg = r#"{"f1":1,"f2":2}"#.as_bytes().to_vec(); + space_pad(&mut expected_msg, 256); + assert_eq!(msg.0, expected_msg); + assert_eq!(code_hash, hash); + assert_eq!(funds, amount); + assert_eq!(label, lbl) + } + other => panic!("unexpected CosmosMsg variant: {:?}", other), + }; + + Ok(()) + } + + #[test] + fn test_query_works() -> StdResult<()> { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct QueryResponse { + bar1: i8, + bar2: i8, + } + + struct MyMockQuerier {} + + impl Querier for MyMockQuerier { + fn raw_query( + &self, + request: &[u8], + ) -> cosmwasm_std::SystemResult> + { + let mut expected_msg = r#"{"Query1":{"f1":1,"f2":2}}"#.as_bytes().to_vec(); + space_pad(&mut expected_msg, 256); + let expected_request: QueryRequest = + QueryRequest::Wasm(WasmQuery::Smart { + contract_addr: "secret1xyzasdf".to_string(), + code_hash: "asdf".to_string(), + msg: Binary(expected_msg), + }); + let test_req: &[u8] = &to_vec(&expected_request).unwrap(); + assert_eq!(request, test_req); + cosmwasm_std::SystemResult::Ok(cosmwasm_std::ContractResult::Ok( + to_binary(&QueryResponse { bar1: 1, bar2: 2 }).unwrap(), + )) + } + } + + let querier = MyMockQuerier {}; + let address = "secret1xyzasdf".to_string(); + let hash = "asdf".to_string(); + let contract = Contract::new(&Addr::unchecked(address), &hash); + + // Was getting an error here + // let response: QueryResponse = + // FooQuery::Query1 { f1: 1, f2: 2 }.query(&querier, &contract)?; + // assert_eq!(response, QueryResponse { bar1: 1, bar2: 2 }); + + Ok(()) + } +} diff --git a/packages/shade_protocol/src/utils/crypto/hash.rs b/packages/shade_protocol/src/utils/crypto/hash.rs new file mode 100644 index 0000000..c7094e7 --- /dev/null +++ b/packages/shade_protocol/src/utils/crypto/hash.rs @@ -0,0 +1,35 @@ +use sha2::{Digest, Sha256}; + +pub const SHA256_HASH_SIZE: usize = 32; + +pub fn sha_256(data: &[u8]) -> [u8; SHA256_HASH_SIZE] { + let mut hasher = Sha256::new(); + hasher.update(data); + let hash = hasher.finalize(); + + let mut result = [0u8; 32]; + result.copy_from_slice(hash.as_slice()); + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sha_256() { + let r = sha_256(b"test"); + let r_expected: [u8; SHA256_HASH_SIZE] = [ + 159, 134, 208, 129, 136, 76, 125, 101, 154, 47, 234, 160, 197, 90, 208, 21, 163, 191, + 79, 27, 43, 11, 130, 44, 209, 93, 108, 21, 176, 240, 10, 8, + ]; + assert_eq!(r, r_expected); + + let r = sha_256(b"random_string_123"); + let r_expected: [u8; SHA256_HASH_SIZE] = [ + 167, 75, 46, 161, 27, 233, 254, 146, 245, 218, 2, 19, 171, 56, 78, 166, 42, 211, 88, 7, + 205, 191, 2, 6, 226, 158, 43, 144, 8, 149, 170, 164, + ]; + assert_eq!(r, r_expected); + } +} diff --git a/packages/shade_protocol/src/utils/crypto/mod.rs b/packages/shade_protocol/src/utils/crypto/mod.rs new file mode 100644 index 0000000..bb43515 --- /dev/null +++ b/packages/shade_protocol/src/utils/crypto/mod.rs @@ -0,0 +1,5 @@ +mod hash; +mod rng; + +pub use hash::{sha_256, SHA256_HASH_SIZE}; +pub use rng::Prng; diff --git a/packages/shade_protocol/src/utils/crypto/rng.rs b/packages/shade_protocol/src/utils/crypto/rng.rs new file mode 100644 index 0000000..e094554 --- /dev/null +++ b/packages/shade_protocol/src/utils/crypto/rng.rs @@ -0,0 +1,85 @@ +use rand_chacha::ChaChaRng; +use rand_core::{RngCore, SeedableRng}; +use sha2::{Digest, Sha256}; + +pub struct Prng { + rng: ChaChaRng, +} + +impl Prng { + pub fn new(seed: &[u8], entropy: &[u8]) -> Self { + let mut hasher = Sha256::new(); + + // write input message + hasher.update(&seed); + hasher.update(&entropy); + let hash = hasher.finalize(); + + let mut hash_bytes = [0u8; 32]; + hash_bytes.copy_from_slice(hash.as_slice()); + + let rng = ChaChaRng::from_seed(hash_bytes); + + Self { rng } + } + + pub fn rand_bytes(&mut self) -> [u8; 32] { + let mut bytes = [0u8; 32]; + self.rng.fill_bytes(&mut bytes); + + bytes + } + + pub fn set_word_pos(&mut self, count: u32) { + self.rng.set_word_pos(count.into()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// This test checks that the rng is stateful and generates + /// different random bytes every time it is called. + #[test] + fn test_rng() { + let mut rng = Prng::new(b"foo", b"bar!"); + let r1: [u8; 32] = [ + 155, 11, 21, 97, 252, 65, 160, 190, 100, 126, 85, 251, 47, 73, 160, 49, 216, 182, 93, + 30, 185, 67, 166, 22, 34, 10, 213, 112, 21, 136, 49, 214, + ]; + let r2: [u8; 32] = [ + 46, 135, 19, 242, 111, 125, 59, 215, 114, 130, 122, 155, 202, 23, 36, 118, 83, 11, 6, + 180, 97, 165, 218, 136, 134, 243, 191, 191, 149, 178, 7, 149, + ]; + let r3: [u8; 32] = [ + 9, 2, 131, 50, 199, 170, 6, 68, 168, 28, 242, 182, 35, 114, 15, 163, 65, 139, 101, 221, + 207, 147, 119, 110, 81, 195, 6, 134, 14, 253, 245, 244, + ]; + let r4: [u8; 32] = [ + 68, 196, 114, 205, 225, 64, 201, 179, 18, 77, 216, 197, 211, 13, 21, 196, 11, 102, 106, + 195, 138, 250, 29, 185, 51, 38, 183, 0, 5, 169, 65, 190, + ]; + assert_eq!(r1, rng.rand_bytes()); + assert_eq!(r2, rng.rand_bytes()); + assert_eq!(r3, rng.rand_bytes()); + assert_eq!(r4, rng.rand_bytes()); + } + + #[test] + fn test_rand_bytes_counter() { + let mut rng = Prng::new(b"foo", b"bar"); + + let r1: [u8; 32] = [ + 114, 227, 179, 76, 120, 34, 236, 42, 204, 27, 153, 74, 44, 29, 158, 162, 180, 202, 165, + 46, 155, 90, 178, 252, 127, 80, 162, 79, 3, 146, 153, 88, + ]; + + rng.set_word_pos(8); + assert_eq!(r1, rng.rand_bytes()); + rng.set_word_pos(8); + assert_eq!(r1, rng.rand_bytes()); + rng.set_word_pos(9); + assert_ne!(r1, rng.rand_bytes()); + } +} diff --git a/packages/shade_protocol/src/utils/cycle.rs b/packages/shade_protocol/src/utils/cycle.rs new file mode 100644 index 0000000..15282c2 --- /dev/null +++ b/packages/shade_protocol/src/utils/cycle.rs @@ -0,0 +1,327 @@ +use crate::{ + c_std::{Env, StdError, StdResult, Timestamp, Uint128}, + chrono::prelude::*, +}; + +use cosmwasm_schema::cw_serde; +use std::convert::TryInto; + +#[cw_serde] +pub enum Cycle { + Once, + Constant, + /* + Block { + blocks: Uint128, + }, + */ + Yearly { years: Uint128 }, + Monthly { months: Uint128 }, + Daily { days: Uint128 }, + Hourly { hours: Uint128 }, + Minutes { minutes: Uint128 }, + Seconds { seconds: Uint128 }, +} + +pub fn utc_from_seconds(seconds: i64) -> DateTime { + DateTime::from_utc(NaiveDateTime::from_timestamp(seconds, 0), Utc) +} + +pub fn utc_from_timestamp(timestamp: Timestamp) -> DateTime { + DateTime::from_utc( + NaiveDateTime::from_timestamp(timestamp.seconds() as i64, 0), + Utc, + ) +} + +pub fn parse_utc_datetime(rfc3339: &String) -> StdResult> { + DateTime::parse_from_rfc3339(&rfc3339) + .map(|dt| dt.with_timezone(&Utc)) + .map_err(|_| StdError::generic_err(format!("Failed to parse rfc3339 datetime {}", rfc3339))) +} + +pub fn utc_now(env: &Env) -> DateTime { + DateTime::from_utc( + NaiveDateTime::from_timestamp(env.block.time.seconds() as i64, 0), + Utc, + ) +} + +pub fn exceeds_cycle(now: &DateTime, last_refresh: &DateTime, cycle: Cycle) -> bool { + if now.timestamp() < last_refresh.timestamp() && cycle != Cycle::Constant { + return false; + } + match cycle { + Cycle::Constant => true, + Cycle::Once => false, + Cycle::Seconds { seconds } => { + seconds <= Uint128::new((now.timestamp() - last_refresh.timestamp()) as u128) + } + Cycle::Minutes { minutes } => { + println!( + "{} >= {} -> {} - {}", + minutes, + ((now.timestamp() - last_refresh.timestamp()) / 60), + now.timestamp(), + last_refresh.timestamp() + ); + minutes + <= Uint128::new( + ((now.timestamp() - last_refresh.timestamp()) / 60) + .try_into() + .unwrap(), + ) + } + Cycle::Hourly { hours } => { + println!( + "{} >= {} -> {} - {}", + hours, + ((now.timestamp() - last_refresh.timestamp()) / 60 / 60), + now.timestamp(), + last_refresh.timestamp() + ); + hours + <= Uint128::new( + ((now.timestamp() - last_refresh.timestamp()) / 60 / 60) + .try_into() + .unwrap(), + ) + } + Cycle::Daily { days } => { + days.u128() as i32 <= now.num_days_from_ce() - last_refresh.num_days_from_ce() + } + Cycle::Monthly { months } => { + let month_diff: u32; + + if now.year() > last_refresh.year() { + month_diff = (12u32 - last_refresh.month()) + now.month(); + } else { + month_diff = now.month() - last_refresh.month(); + } + + months.u128() as u32 <= month_diff + } + Cycle::Yearly { years } => { + years.u128() as u32 <= now.year_ce().1 - last_refresh.year_ce().1 + } + } +} + +#[cfg(test)] +mod test { + + use super::*; + + fn test_exceeds_cycle(last_refresh: String, now: String, cycle: Cycle, exceeds: bool) { + let last_refresh = parse_utc_datetime(&last_refresh).unwrap(); + let now = parse_utc_datetime(&now).unwrap(); + assert_eq!(exceeds_cycle(&now, &last_refresh, cycle), exceeds); + } + + macro_rules! exceeds_cycle_tests { + ($($name:ident: $value:expr,)*) => { + $( + #[test] + fn $name() { + let (start, now, cycle, exceeds) = $value; + test_exceeds_cycle(start.to_string(), now.to_string(), cycle, exceeds); + } + )* + } + } + + exceeds_cycle_tests! { + constant_cycle: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T23:59:59.59Z", + Cycle::Constant, + true, + ), + once_cycle: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T23:59:59.59Z", + Cycle::Once, + false, + ), + seconds_cycle_well_under: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:00:05.00Z", // 5 sec diff + Cycle::Seconds { seconds: Uint128::new(10) }, + false, + ), + seconds_cycle_just_short: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:00:09.99Z", // 9.99 sec diff + Cycle::Seconds { seconds: Uint128::new(10) }, + false, + ), + seconds_cycle_exact: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:00:10.00Z", // 10 sec diff + Cycle::Seconds { seconds: Uint128::new(10) }, + true, + ), + seconds_cycle_well_over: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:20:00.00Z", // 20 min diff + Cycle::Seconds { seconds: Uint128::new(10) }, + true, + ), + seconds_cycle_overflow: ( + "2019-10-12T00:20:00.00Z", // 20 min diff + "2019-10-12T00:00:00.00Z", + Cycle::Seconds { seconds: Uint128::new(10) }, + false, + ), + minutes_cycle_well_under: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:00:30.00Z", // 30 sec diff + Cycle::Minutes { minutes: Uint128::new(1) }, + false, + ), + minutes_cycle_just_short: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:00:59.99Z", // 59.99 sec diff + Cycle::Minutes { minutes: Uint128::new(1) }, + false, + ), + minutes_cycle_exact: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:01:00.00Z", // 1 min diff + Cycle::Minutes { minutes: Uint128::new(1) }, + true, + ), + minutes_cycle_well_over: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:20:00.00Z", // 20 min diff + Cycle::Minutes { minutes: Uint128::new(1) }, + true, + ), + minutes_cycle_overflow: ( + "2019-10-12T00:20:00.00Z", // 20 min diff + "2019-10-12T00:00:00.00Z", + Cycle::Minutes { minutes: Uint128::new(1) }, + false, + ), + hours_cycle_well_under: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:30:00.00Z", // 30 min diff + Cycle::Hourly { hours: Uint128::new(1) }, + false, + ), + hours_cycle_just_short: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T00:59:59.99Z", // 59 mint 59.99 sec diff + Cycle::Hourly { hours: Uint128::new(1) }, + false, + ), + hours_cycle_exact: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T01:00:00.00Z", // 1 hour diff + Cycle::Hourly { hours: Uint128::new(1) }, + true, + ), + hours_cycle_well_over: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T01:30:00.00Z", // 1 hour 30 min diff + Cycle::Hourly { hours: Uint128::new(1) }, + true, + ), + hours_cycle_overflow: ( + "2019-10-12T01:30:00.00Z", // 1 hour 30 min diff + "2019-10-12T00:00:00.00Z", + Cycle::Hourly { hours: Uint128::new(1) }, + false, + ), + daily_cycle_well_under: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T23:00:00.00Z", // 23 hour diff + Cycle::Daily { days: Uint128::new(1)}, + false, + ), + daily_cycle_just_short: ( + "2019-10-12T00:00:00.00Z", + "2019-10-12T23:59:59.99Z", // 23 hours, 59 min, 59.99 sec diff + Cycle::Daily { days: Uint128::new(1) }, + false, + ), + daily_cycle_exact: ( + "2019-10-12T00:00:00.00Z", + "2019-10-13T00:00:00.00Z", // 1 day diff + Cycle::Daily { days: Uint128::new(1) }, + true, + ), + daily_cycle_well_over: ( + "2019-10-12T00:00:00.00Z", + "2019-10-13T12:00:00.00Z", // 1 day 12 hr diff + Cycle::Daily { days: Uint128::new(1) }, + true, + ), + daily_cycle_overflow: ( + "2019-10-13T12:00:00.00Z", // 1 day 12 hr diff + "2019-10-12T00:00:00.00Z", + Cycle::Daily { days: Uint128::new(1) }, + false, + ), + monthly_cycle_well_under: ( + "2019-10-01T00:00:00.00Z", + "2019-10-15T00:00:00.00Z", // 14 day diff + Cycle::Monthly { months: Uint128::new(1) }, + false, + ), + monthly_cycle_just_short: ( + "2019-10-01T00:00:00.00Z", + "2019-10-31T23:59:59.99Z", // 30 day, 23 hr, 59 min, 59.99 sec diff + Cycle::Monthly { months: Uint128::new(1) }, + false, + ), + monthly_cycle_exact: ( + "2019-10-01T00:00:00.00Z", + "2019-11-01T00:00:00.00Z", // 1 mo diff + Cycle::Monthly { months: Uint128::new(1) }, + true, + ), + monthly_cycle_well_over: ( + "2019-10-01T00:00:00.00Z", + "2019-11-15T00:00:00.00Z", // 1 mo, 15 day diff + Cycle::Monthly { months: Uint128::new(1) }, + true, + ), + monthly_cycle_overflow: ( + "2019-11-15T00:00:00.00Z", // 1 mo, 15 day diff + "2019-10-01T00:00:00.00Z", + Cycle::Monthly { months: Uint128::new(1) }, + false, + ), + yearly_cycle_well_under: ( + "2019-01-01T00:00:00.00Z", + "2019-10-01T00:00:00.00Z", // 9 mo diff + Cycle::Yearly { years: Uint128::new(1) }, + false, + ), + yearly_cycle_just_short: ( + "2019-01-01T00:00:00.00Z", + "2019-12-31T23:59:59.99Z", // 11 mo, 31 days, 23 hrs, 59 mins 59.99 sec diff + Cycle::Yearly { years: Uint128::new(1) }, + false, + ), + yearly_cycle_exact: ( + "2019-01-01T00:00:00.00Z", + "2020-01-01T00:00:00.00Z", // 1 yr diff + Cycle::Yearly { years: Uint128::new(1) }, + true, + ), + yearly_cycle_well_over: ( + "2019-01-01T00:00:00.00Z", + "2020-06-01T00:00:00.00Z", // 1 yr, 6 mo diff + Cycle::Yearly { years: Uint128::new(1) }, + true, + ), + yearly_cycle_overflow: ( + "2020-06-01T00:00:00.00Z", // 1 yr, 6 mo diff + "2019-01-01T00:00:00.00Z", + Cycle::Yearly { years: Uint128::new(1) }, + false, + ), + } +} diff --git a/packages/shade_protocol/src/utils/errors.rs b/packages/shade_protocol/src/utils/errors.rs new file mode 100644 index 0000000..b233ff7 --- /dev/null +++ b/packages/shade_protocol/src/utils/errors.rs @@ -0,0 +1,287 @@ +use crate::c_std::StdError; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Response, StdResult}; +use schemars::_serde_json::to_string; +use serde::Serialize; + +// TODO: make another that auto imports + +/// Generates the errors +/// Macro takes in an array of error name, error msg and error function +#[macro_export] +macro_rules! errors { + ($Target:tt; $($EnumError:ident, $VerboseError:tt, $Function:ident),+) => { + use crate::{ + c_std::StdError, + generate_errors, + impl_into_u8, + utils::errors::{build_string, CodeType, DetailedError}, + }; + use cosmwasm_schema::cw_serde; + + generate_errors!($Target; $($EnumError, $VerboseError, $Function),+); + } +} + +#[macro_export] +macro_rules! generate_errors { + ($Target:tt; $($EnumError:ident, $VerboseError:tt, $Function:ident),+) => { + #[cw_serde] + #[repr(u8)] + pub enum Error { $($EnumError,)+ } + impl_into_u8!(Error); + + impl CodeType for Error { + fn to_verbose(&self, context: &Vec<&str>) -> String { + match self { + $( + Error::$EnumError => { + build_string($VerboseError, context) + } + )+ + } + } + } + + const TARGET: &str = $Target ; + + impl Error { + $( + pub fn $Function(args: Vec<&str>) -> StdError { + DetailedError::from_code(TARGET, Error::$EnumError, args).to_error() + } + )+ + } + + }; +} + +#[macro_export] +macro_rules! impl_into_u8 { + ($error:ident) => { + impl From<$error> for u8 { + fn from(err: $error) -> u8 { + err as _ + } + } + }; +} + +#[cw_serde] +pub struct DetailedError { + pub target: String, + pub code: u8, + pub r#type: T, + pub context: Vec, + pub verbose: String, +} + +impl DetailedError { + pub fn to_full_error(&self) -> StdResult { + Err(self.to_error()) + } + + pub fn to_error(&self) -> StdError { + StdError::generic_err(self.to_string()) + } + + pub fn to_string(&self) -> String { + to_string(&self).unwrap_or("".to_string()) + } + + pub fn from_code(target: &str, code: T, context: Vec<&str>) -> Self { + let verbose = code.to_verbose(&context); + Self { + target: target.to_string(), + code: code.to_code(), + r#type: code, + context: context.iter().map(|s| s.to_string()).collect(), + verbose, + } + } +} + +pub fn build_string(verbose: &str, context: &Vec<&str>) -> String { + let mut msg = verbose.to_string(); + for arg in context.iter() { + msg = msg.replacen("{}", arg, 1); + } + msg +} + +pub trait CodeType: Into + Clone { + fn to_code(&self) -> u8 { + self.clone().into() + } + fn to_verbose(&self, context: &Vec<&str>) -> String; +} + +#[cfg(test)] +pub mod tests { + use crate::{ + c_std::{Response, StdError, StdResult}, + utils::errors::{build_string, CodeType, DetailedError}, + }; + + use cosmwasm_schema::cw_serde; + + #[cw_serde] + #[repr(u8)] + enum TestCode { + Error1, + Error2, + Error3, + } + + impl_into_u8!(TestCode); + + impl CodeType for TestCode { + fn to_verbose(&self, context: &Vec<&str>) -> String { + match self { + TestCode::Error1 => build_string("Error", context), + TestCode::Error2 => build_string("Broke in {}", context), + TestCode::Error3 => build_string("Expecting {} but got {}", context), + } + } + } + + // Because of set variables, you could implement something like this + + fn error_1() -> StdError { + DetailedError::from_code("contract", TestCode::Error1, vec![]).to_error() + } + + fn error_2(context: &[&str; 1]) -> StdError { + DetailedError::from_code("contract", TestCode::Error2, context.to_vec()).to_error() + } + + fn error_3(context: &[&str; 2]) -> StdError { + DetailedError::from_code("contract", TestCode::Error3, context.to_vec()).to_error() + } + + #[test] + fn string_builder() { + assert_eq!( + build_string("Test string {}", &vec!["arg"]), + "Test string arg".to_string() + ) + } + + #[test] + fn to_code() { + let code1 = TestCode::Error1; + assert_eq!(code1.to_code(), 0); + + let code2 = TestCode::Error2; + assert_eq!(code2.to_code(), 1); + + let code3 = TestCode::Error3; + assert_eq!(code3.to_code(), 2); + } + + #[test] + fn to_verbose() { + assert_eq!(TestCode::Error1.to_verbose(&vec![]), "Error".to_string()); + assert_eq!( + TestCode::Error2.to_verbose(&vec!["function"]), + "Broke in function".to_string() + ); + assert_eq!( + TestCode::Error3.to_verbose(&vec!["address", "amount"]), + "Expecting address but got amount".to_string() + ); + } + + #[test] + fn from_code() { + let err1 = DetailedError::from_code("contract", TestCode::Error1, vec![]); + assert_eq!(err1.code, 0); + assert_eq!(err1.r#type, TestCode::Error1); + let empty: Vec = vec![]; + assert_eq!(err1.context, empty); + assert_eq!(err1.verbose, "Error".to_string()); + + let err2 = DetailedError::from_code("contract", TestCode::Error2, vec!["function"]); + assert_eq!(err2.code, 1); + assert_eq!(err2.r#type, TestCode::Error2); + assert_eq!(err2.context, vec!["function".to_string()]); + assert_eq!(err2.verbose, "Broke in function".to_string()); + + let err3 = + DetailedError::from_code("contract", TestCode::Error3, vec!["address", "amount"]); + assert_eq!(err3.code, 2); + assert_eq!(err3.r#type, TestCode::Error3); + assert_eq!(err3.context, vec![ + "address".to_string(), + "amount".to_string() + ]); + assert_eq!(err3.verbose, "Expecting address but got amount".to_string()); + } + + #[test] + fn to_string() { + assert_eq!(DetailedError::from_code("contract", TestCode::Error1, vec![]).to_string(), + "{\"target\":\"contract\",\"code\":0,\"type\":\"error1\",\"context\":[],\"verbose\":\"Error\"}".to_string()); + assert_eq!(DetailedError::from_code("contract", TestCode::Error2, vec!["function"]).to_string(), + "{\"target\":\"contract\",\"code\":1,\"type\":\"error2\",\"context\":[\"function\"],\"verbose\":\"Broke in function\"}".to_string()); + assert_eq!(DetailedError::from_code("contract", TestCode::Error3, vec!["address", "amount"]).to_string(), + "{\"target\":\"contract\",\"code\":2,\"type\":\"error3\",\"context\":[\"address\",\"amount\"],\"verbose\":\"Expecting address but got amount\"}".to_string()); + } + + #[test] + fn to_error() { + let err1 = DetailedError::from_code("contract", TestCode::Error1, vec![]).to_error(); + match err1 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":0,\"type\":\"error1\",\"context\":[],\"verbose\":\"Error\"}".to_string()), + _ => assert!(false) + } + + let err2 = + DetailedError::from_code("contract", TestCode::Error2, vec!["function"]).to_error(); + match err2 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":1,\"type\":\"error2\",\"context\":[\"function\"],\"verbose\":\"Broke in function\"}".to_string()), + _ => assert!(false) + } + + let err3 = + DetailedError::from_code("contract", TestCode::Error3, vec!["address", "amount"]) + .to_error(); + match err3 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":2,\"type\":\"error3\",\"context\":[\"address\",\"amount\"],\"verbose\":\"Expecting address but got amount\"}".to_string()), + _ => assert!(false) + } + } + + #[test] + fn helpers() { + let err1 = error_1(); + match err1 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":0,\"type\":\"error1\",\"context\":[],\"verbose\":\"Error\"}".to_string()), + _ => assert!(false) + } + + let err2 = error_2(&["function"]); + match err2 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":1,\"type\":\"error2\",\"context\":[\"function\"],\"verbose\":\"Broke in function\"}".to_string()), + _ => assert!(false) + } + + let err3 = error_3(&["address", "amount"]); + match err3 { + StdError::GenericErr { msg, .. } => assert_eq!(msg, "{\"target\":\"contract\",\"code\":2,\"type\":\"error3\",\"context\":[\"address\",\"amount\"],\"verbose\":\"Expecting address but got amount\"}".to_string()), + _ => assert!(false) + } + } + + generate_errors!("test"; + Test1, "Verb1", Test1Func, + Test2, "Ver2", Test2Func, + Test3, "Verb3", Test3Func); + + #[test] + fn macro_errors() { + let test = Error::Test2; + + let test1 = Error::Test1Func(vec![]); + } +} diff --git a/packages/shade_protocol/src/utils/flexible_msg.rs b/packages/shade_protocol/src/utils/flexible_msg.rs new file mode 100644 index 0000000..91fc9c5 --- /dev/null +++ b/packages/shade_protocol/src/utils/flexible_msg.rs @@ -0,0 +1,34 @@ +use crate::c_std::{StdError, StdResult}; + +use cosmwasm_schema::{cw_serde}; + +#[cw_serde] +pub struct FlexibleMsg { + pub msg: String, + pub arguments: u16, +} + +impl FlexibleMsg { + pub fn new(msg: String, msg_variable: &str) -> FlexibleMsg { + FlexibleMsg { + msg: msg.clone(), + arguments: msg.matches(msg_variable).count() as u16, + } + } + + pub fn create_msg(&self, args: Vec, msg_variable: &str) -> StdResult { + if args.len() as u16 != self.arguments { + return Err(StdError::generic_err(format!( + "Msg expected {:?} arguments; received {:?}", + self.arguments, + args.len() + ))); + } + + let mut msg = self.msg.clone(); + for arg in args.iter() { + msg = msg.replacen(msg_variable, arg, 1); + } + Ok(msg) + } +} diff --git a/packages/shade_protocol/src/utils/generic_response.rs b/packages/shade_protocol/src/utils/generic_response.rs new file mode 100644 index 0000000..276894b --- /dev/null +++ b/packages/shade_protocol/src/utils/generic_response.rs @@ -0,0 +1,8 @@ + +use cosmwasm_schema::{cw_serde}; + +#[cw_serde] +pub enum ResponseStatus { + Success, + Failure, +} diff --git a/packages/shade_protocol/src/utils/mod.rs b/packages/shade_protocol/src/utils/mod.rs new file mode 100644 index 0000000..c906cb7 --- /dev/null +++ b/packages/shade_protocol/src/utils/mod.rs @@ -0,0 +1,35 @@ +// Helper libraries + +#[cfg(feature = "interface")] +pub mod callback; +#[cfg(feature = "interface")] +pub use callback::*; + +pub mod padding; +pub use padding::*; +pub mod crypto; + +#[cfg(feature = "utils")] +pub mod asset; + +#[cfg(feature = "errors")] +pub mod errors; + +#[cfg(feature = "flexible_msg")] +pub mod flexible_msg; + +#[cfg(feature = "utils")] +pub mod generic_response; + +pub mod storage; + +#[cfg(feature = "dao-utils")] +pub mod cycle; +#[cfg(feature = "dao-utils")] +pub mod wrap; + +#[cfg(feature = "math")] +pub mod price; + +#[cfg(feature = "math")] +pub mod calc; diff --git a/packages/shade_protocol/src/utils/padding.rs b/packages/shade_protocol/src/utils/padding.rs new file mode 100644 index 0000000..f2fdb6d --- /dev/null +++ b/packages/shade_protocol/src/utils/padding.rs @@ -0,0 +1,43 @@ +use crate::c_std::{Response, Binary, StdResult}; + +/// Take a Vec and pad it up to a multiple of `block_size`, using spaces at the end. +pub fn space_pad(message: &mut Vec, block_size: usize) -> &mut Vec { + let len = message.len(); + let surplus = len % block_size; + if surplus == 0 { + return message; + } + + let missing = block_size - surplus; + message.reserve(missing); + message.extend(std::iter::repeat(b' ').take(missing)); + message +} + +/// Pad the data and logs in a `Response` to the block size, with spaces. +// The big `where` clause is based on the `where` clause of `Response`. +// Users don't need to care about it as the type `T` has a default, and will +// always be known in the context of the caller. +pub fn pad_handle_result(response: StdResult, block_size: usize) -> StdResult{ + response.map(|mut response| { + response.data = response.data.map(|mut data| { + space_pad(&mut data.0, block_size); + data + }); + for log in &mut response.attributes { + // Safety: These two are safe because we know the characters that + // `space_pad` appends are valid UTF-8 + unsafe { space_pad(log.key.as_mut_vec(), block_size) }; + unsafe { space_pad(log.value.as_mut_vec(), block_size) }; + } + response + }) +} + +/// Pad a `StdResult` with spaces +pub fn pad_query_result(response: StdResult, block_size: usize) -> StdResult { + response.map(|mut response| { + space_pad(&mut response.0, block_size); + response + }) +} diff --git a/packages/shade_protocol/src/utils/price.rs b/packages/shade_protocol/src/utils/price.rs new file mode 100644 index 0000000..a9094e5 --- /dev/null +++ b/packages/shade_protocol/src/utils/price.rs @@ -0,0 +1,116 @@ +use crate::c_std::Uint128; +use std::convert::TryFrom; + +/// Returns price of `token_1` in `denom` from `token_1/token_2` pair +/// +/// Denom is whatever `token_2` is quoted in. +/// +/// ### Arguments (normalized to 10^18) +/// * `scrt_price` - amount of denom per 1 token_2 from some oracle (ex: 9.18USD per 1 SCRT) +/// * `trade_price` - amount of 1 token_2 in token_1 (ex: 0.1 SHD per 1 SCRT) +pub fn translate_price(token_2_price: Uint128, trade_amount: Uint128) -> Uint128 { + token_2_price.multiply_ratio(10u128.pow(18), trade_amount) +} + +/// Normalize the price from some amount (usually snip20) with decimals to 10^18. +/// +/// ### Arguments +/// * `amount` - unsigned quantity +/// * `decimals` - number of decimals for received quantity +pub fn normalize_price(amount: Uint128, decimals: u8) -> Uint128 { + (amount.u128() * 10u128.pow(18u32 - u32::try_from(decimals).unwrap())).into() +} + +/// Returns 1 * 10^factor. +pub fn get_precision(factor: u8) -> Uint128 { + Uint128::from(10u128.pow(factor.into())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::c_std::Uint128; + + macro_rules! normalize_price_tests { + ($($name:ident: $value:expr,)*) => { + $( + #[test] + fn $name() { + let (amount, decimals, expected) = $value; + assert_eq!(normalize_price(amount, decimals), expected) + } + )* + } + } + + normalize_price_tests! { + normalize_0: ( + Uint128::new(1_413_500_852_332_497), + 18u8, + Uint128::new(1_413_500_852_332_497) + ), + normalize_1: ( + // amount of TKN received for 1 sSCRT + Uint128::new(1_000_000), + // TKN 6 decimals + 6u8, + // price * 10^18 + Uint128::new(1_000_000_000_000_000_000) + ), + normalize_2: ( + // amount of TKN received for 1 sSCRT + Uint128::new(1_000_000), + // TKN 6 decimals + 6u8, + // price * 10^18 + Uint128::new(1_000_000_000_000_000_000) + ), + } + + macro_rules! translate_price_tests { + ($($name:ident: $value:expr,)*) => { + $( + #[test] + fn $name() { + let (scrt_price, trade_price, expected) = $value; + assert_eq!(translate_price(scrt_price, trade_price), expected) + } + )* + } + } + + translate_price_tests! { + translate_0: ( + // 1.62 USD per SCRT + Uint128::new( 1_622_110_000_000_000_000), + // 1 sSCRT -> sETH + Uint128::new( 1_413_500_852_332_497), + // sETH/USD price + Uint128::new(1_147_583_319_333_175_746_166), + ), + translate_1: ( + // 1.62 USD per SCRT + Uint128::new( 1_622_110_000_000_000_000), + // .000425 ETH per sSCRT + Uint128::new( 425_600_000_000_000), + // 3811.34 ETH per USD + Uint128::new(3_811_348_684_210_526_315_789), + ), + translate_2: ( + // 1 USD per scrt + Uint128::new( 1_000_000_000_000_000_000), + // 1 sscrt for .1 SHD + Uint128::new( 100_000_000_000_000_000), + // 10 SHD per USD + Uint128::new(10_000_000_000_000_000_000), + ), + translate_3: ( + // 1 USD per scrt + Uint128::new( 1_000_000_000_000_000_000), + // 1 sscrt for .02 SHD + Uint128::new( 20_000_000_000_000_000), + // 50 SHD per USD + Uint128::new(50_000_000_000_000_000_000), + ), + } +} diff --git a/packages/shade_protocol/src/utils/storage/default.rs b/packages/shade_protocol/src/utils/storage/default.rs new file mode 100644 index 0000000..2d75ede --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/default.rs @@ -0,0 +1,113 @@ +use crate::c_std::{StdResult, Storage}; +use crate::storage::{ + bucket, + bucket_read, + singleton, + singleton_read, + Bucket, + ReadonlyBucket, + ReadonlySingleton, + Singleton, +}; +use crate::serde::{de::DeserializeOwned, Serialize}; + +pub trait NaiveSingletonStorage: Serialize + DeserializeOwned { + fn read<'a>(storage: &'a dyn Storage, namespace: &'a [u8]) -> ReadonlySingleton<'a, Self> { + singleton_read(storage, namespace) + } + + fn load<'a>(storage: &'a dyn Storage, namespace: &'a [u8]) -> StdResult { + Self::read(storage, namespace).load() + } + + fn may_load<'a>(storage: &'a dyn Storage, namespace: &'a [u8]) -> StdResult> { + Self::read(storage, namespace).may_load() + } + + fn write<'a>(storage: &'a mut dyn Storage, namespace: &'a [u8]) -> Singleton<'a, Self> { + singleton(storage, namespace) + } + + fn save<'a>(&self, storage: &mut dyn Storage, namespace: &'a [u8]) -> StdResult<()> { + Self::write(storage, namespace).save(self) + } +} + +pub trait SingletonStorage: Serialize + DeserializeOwned { + const NAMESPACE: &'static [u8]; + + fn read(storage: &dyn Storage) -> ReadonlySingleton { + singleton_read(storage, Self::NAMESPACE) + } + + fn load(storage: &dyn Storage) -> StdResult { + Self::read(storage).load() + } + + fn may_load(storage: &dyn Storage) -> StdResult> { + Self::read(storage).may_load() + } + + fn write(storage: &mut dyn Storage) -> Singleton { + singleton(storage, Self::NAMESPACE) + } + + fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { + Self::write(storage).save(self) + } +} + +pub trait NaiveBucketStorage: Serialize + DeserializeOwned { + fn read<'a>(storage: &'a dyn Storage, namespace: &'a [u8]) -> ReadonlyBucket<'a, Self> { + bucket_read(storage, namespace) + } + + fn load<'a>(storage: &'a dyn Storage, namespace: &'a [u8], key: &'a [u8]) -> StdResult { + Self::read(storage, namespace).load(key) + } + + fn may_load<'a>( + storage: &'a dyn Storage, + namespace: &'a [u8], + key: &'a [u8], + ) -> StdResult> { + Self::read(storage, namespace).may_load(key) + } + + fn write<'a>(storage: &'a mut dyn Storage, namespace: &'a [u8]) -> Bucket<'a, Self> { + bucket(storage, namespace) + } + + fn save<'a>( + &self, + storage: &mut dyn Storage, + namespace: &'a [u8], + key: &'a [u8], + ) -> StdResult<()> { + Self::write(storage, namespace).save(key, self) + } +} + +pub trait BucketStorage: Serialize + DeserializeOwned { + const NAMESPACE: &'static [u8]; + + fn read(storage: &dyn Storage) -> ReadonlyBucket { + bucket_read(storage, Self::NAMESPACE) + } + + fn load(storage: &dyn Storage, key: &[u8]) -> StdResult { + Self::read(storage).load(key) + } + + fn may_load(storage: &dyn Storage, key: &[u8]) -> StdResult> { + Self::read(storage).may_load(key) + } + + fn write(storage: &mut dyn Storage) -> Bucket { + bucket(storage, Self::NAMESPACE) + } + + fn save(&self, storage: &mut dyn Storage, key: &[u8]) -> StdResult<()> { + Self::write(storage).save(key, self) + } +} diff --git a/packages/shade_protocol/src/utils/storage/mod.rs b/packages/shade_protocol/src/utils/storage/mod.rs new file mode 100644 index 0000000..adb15ed --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/mod.rs @@ -0,0 +1,5 @@ +#[cfg(feature = "storage_plus")] +pub mod plus; + +#[cfg(feature = "storage")] +pub mod default; diff --git a/packages/shade_protocol/src/utils/storage/plus/iter_item.rs b/packages/shade_protocol/src/utils/storage/plus/iter_item.rs new file mode 100644 index 0000000..42675b7 --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/plus/iter_item.rs @@ -0,0 +1,329 @@ +use crate::utils::storage::plus::iter_map::{Increment, IterKey}; +use cosmwasm_std::{StdError, StdResult, Storage}; +use secret_storage_plus::{Item, Map}; +use serde::{de::DeserializeOwned, Serialize}; +use std::ops::{Add, AddAssign, Sub}; + +pub struct IterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + storage: Map<'a, Vec, T>, + id_storage: Item<'a, IterKey>, +} + +#[macro_export] +macro_rules! new_iter_item { + ($StoragePath:tt) => { + IterItem::new_override( + $StoragePath, + concat!("iter-item-size-namespace-", $StoragePath), + ) + }; +} + +impl<'a, T, N> IterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + pub const fn new_override(namespace: &'a str, size_namespace: &'a str) -> Self { + IterItem { + storage: Map::new(namespace), + id_storage: Item::new(size_namespace), + } + } +} + +impl<'a, T, N> IterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + pub fn set(&self, store: &mut dyn Storage, id: N, data: &T) -> StdResult<()> { + self.storage.save(store, IterKey::new(id).to_bytes()?, data) + } + + pub fn get(&self, store: &dyn Storage, id: N) -> StdResult { + self.storage.load(store, IterKey::new(id).to_bytes()?) + } + + pub fn push(&self, store: &mut dyn Storage, data: &T) -> StdResult { + let id = IterKey::new(match self.id_storage.may_load(store)? { + None => N::zero(), + Some(id) => id.item + N::one(), + }); + + self.storage.save(store, id.to_bytes()?, data)?; + + self.id_storage.save(store, &id)?; + + Ok(id.item) + } + + pub fn remove(&self, store: &mut dyn Storage) -> StdResult<()> { + let id = match self.id_storage.may_load(store)? { + None => return Err(StdError::generic_err("Iter map is empty")), + Some(id) => id, + }; + + self.storage.remove(store, id.to_bytes()?); + + let new_id = IterKey::new(id.item - N::one()); + self.id_storage.save(store, &new_id)?; + + Ok(()) + } + + pub fn pop(&self, store: &mut dyn Storage) -> StdResult { + let id = match self.id_storage.may_load(store)? { + None => return Err(StdError::generic_err("Iter map is empty")), + Some(id) => id, + }; + + let item = self.storage.load(store, id.to_bytes()?)?; + self.storage.remove(store, id.to_bytes()?); + + let new_id = IterKey::new(id.item - N::one()); + self.id_storage.save(store, &new_id)?; + + Ok(item) + } + + pub fn size(&'a self, store: &dyn Storage) -> StdResult { + Ok(match self.id_storage.may_load(store)? { + None => N::zero(), + Some(i) => i.item + N::one(), + }) + } + + pub fn iter_from( + &'a self, + store: &'a dyn Storage, + start_from: N, + ) -> IndexableIterItem<'a, T, N> { + IndexableIterItem { + iter_map: self, + storage: store, + index: start_from, + } + } + + pub fn iter(&'a self, store: &'a dyn Storage) -> IndexableIterItem<'a, T, N> { + self.iter_from(store, N::zero()) + } +} + +// Make struct IterMapIndexable and implement the cool stuff there +pub struct IndexableIterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + iter_map: &'a IterItem<'a, T, N>, + storage: &'a dyn Storage, + index: N, +} + +impl<'a, T, N> IndexableIterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + fn next_index(&mut self) { + self.index += N::one(); + } +} + +impl<'a, T, N> Iterator for IndexableIterItem<'a, T, N> +where + T: Serialize + DeserializeOwned, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + type Item = T; + + fn next(&mut self) -> Option { + let item = self.iter_map.get(self.storage.clone(), self.index.clone()); + + self.next_index(); + + match item { + Ok(i) => Some(i), + Err(_) => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::utils::storage::plus::iter_item::IterItem; + use cosmwasm_std::{ + testing::{MockApi, MockQuerier, MockStorage}, + Addr, + CustomQuery, + OwnedDeps, + Storage, + Uint64, + }; + use serde::{ + de::{self, DeserializeOwned}, + ser, + Deserialize, + Serialize, + }; + use std::marker::PhantomData; + + #[derive(Clone, Serialize, Deserialize)] + struct MyQuery; + impl CustomQuery for MyQuery {} + + const MACRO_TEST: IterItem = new_iter_item!("MACRO_TEST"); + + #[test] + fn initialization() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + } + + fn generate(size: u8, storage: &mut dyn Storage) -> IterItem { + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..size { + iter.push(storage, &Uint64::new(i as u64)).unwrap(); + } + + iter + } + + #[test] + fn push() { + let mut storage = MockStorage::new(); + + generate(10, &mut storage); + } + + #[test] + fn remove() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + let item = iter.remove(&mut storage).unwrap(); + + assert_eq!(9, iter.size(&storage).unwrap()); + } + + #[test] + fn pop() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + let item = iter.pop(&mut storage).unwrap(); + + assert_eq!(item, Uint64::new(9)); + assert_eq!(9, iter.size(&storage).unwrap()); + } + + #[test] + fn set() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + iter.set(&mut storage, 3, &Uint64::new(5)).unwrap(); + + assert_eq!(Uint64::new(5), iter.get(&storage, 3).unwrap()) + } + + #[test] + fn get() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + assert_eq!(Uint64::new(3), iter.get(&storage, 3).unwrap()) + } + + #[test] + fn total() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + assert_eq!(10, iter.size(&storage).unwrap()) + } + + #[test] + fn iterate() { + let mut storage = MockStorage::new(); + + let iter: IterItem = IterItem::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, &Uint64::new(i as u64)).unwrap(); + } + + for (i, item) in iter.iter(&storage).enumerate() { + assert_eq!(item, Uint64::new(i as u64)) + } + } +} diff --git a/packages/shade_protocol/src/utils/storage/plus/iter_map.rs b/packages/shade_protocol/src/utils/storage/plus/iter_map.rs new file mode 100644 index 0000000..4ba9172 --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/plus/iter_map.rs @@ -0,0 +1,389 @@ +use cosmwasm_std::{to_binary, StdError, StdResult, Storage}; +use secret_storage_plus::{KeyDeserialize, Map, Prefixer, PrimaryKey}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use std::ops::{Add, AddAssign, Sub}; + +pub trait Increment { + fn one() -> Self; + fn zero() -> Self; +} + +macro_rules! impl_increment { + ($($t:ty)*) => ($( + impl Increment for $t { + fn one() -> Self { + 1 + } + + fn zero() -> Self { + 0 + } + } + )*) +} + +impl_increment! { usize u8 u16 u32 u64 u128 } + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct IterKey< + N: Add + AddAssign + Sub + Clone + Serialize + Increment, +> { + pub item: N, +} + +impl IterKey +where + N: Add + Increment + AddAssign + Sub + Clone + Serialize, +{ + pub fn new(item: N) -> Self { + Self { item } + } + + pub fn to_bytes(&self) -> StdResult> { + Ok(to_binary(self)?.0) + } +} + +pub struct IterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + storage: Map<'a, (K, Vec), T>, + id_storage: Map<'a, K, IterKey>, +} + +#[macro_export] +macro_rules! new_iter_map { + ($StoragePath:tt) => { + IterMap::new_override( + $StoragePath, + concat!("iter-map-size-namespace-", $StoragePath), + ) + }; +} + +impl<'a, K, T, N> IterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + pub const fn new_override(namespace: &'a str, size_namespace: &'a str) -> Self { + IterMap { + storage: Map::new(namespace), + id_storage: Map::new(size_namespace), + } + } +} + +impl<'a, K, T, N> IterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + pub fn set(&self, store: &mut dyn Storage, key: K, id: N, data: &T) -> StdResult<()> { + self.storage + .save(store, (key, IterKey::new(id).to_bytes()?), data) + } + + pub fn get(&self, store: &dyn Storage, key: K, id: N) -> StdResult { + self.storage + .load(store, (key, IterKey::new(id).to_bytes()?)) + } + + pub fn push(&self, store: &mut dyn Storage, key: K, data: &T) -> StdResult { + let id = IterKey::new(match self.id_storage.may_load(store, key.clone())? { + None => N::zero(), + Some(id) => id.item + N::one(), + }); + + self.storage + .save(store, (key.clone(), id.to_bytes()?), data)?; + + self.id_storage.save(store, key, &id)?; + + Ok(id.item) + } + + pub fn remove(&self, store: &mut dyn Storage, key: K) -> StdResult<()> { + let id = match self.id_storage.may_load(store, key.clone())? { + None => return Err(StdError::generic_err("Iter map is empty")), + Some(id) => id, + }; + + self.storage.remove(store, (key.clone(), id.to_bytes()?)); + + let new_id = IterKey::new(id.item - N::one()); + self.id_storage.save(store, key, &new_id)?; + + Ok(()) + } + + pub fn pop(&self, store: &mut dyn Storage, key: K) -> StdResult { + let id = match self.id_storage.may_load(store, key.clone())? { + None => return Err(StdError::generic_err("Iter map is empty")), + Some(id) => id, + }; + + let item = self.storage.load(store, (key.clone(), id.to_bytes()?))?; + self.storage.remove(store, (key.clone(), id.to_bytes()?)); + + let new_id = IterKey::new(id.item - N::one()); + self.id_storage.save(store, key, &new_id)?; + + Ok(item) + } + + pub fn size(&'a self, store: &dyn Storage, key: K) -> StdResult { + Ok(match self.id_storage.may_load(store, key)? { + None => N::zero(), + Some(i) => i.item + N::one(), + }) + } + + pub fn iter_from( + &'a self, + store: &'a dyn Storage, + key: K, + start_from: N, + ) -> IndexableIterMap<'a, K, T, N> { + IndexableIterMap { + iter_map: self, + storage: store, + key: key.clone(), + index: start_from, + } + } + + pub fn iter(&'a self, store: &'a dyn Storage, key: K) -> IndexableIterMap<'a, K, T, N> { + self.iter_from(store, key, N::zero()) + } +} + +pub struct IndexableIterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + iter_map: &'a IterMap<'a, K, T, N>, + storage: &'a dyn Storage, + key: K, + index: N, +} + +impl<'a, K, T, N> IndexableIterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + fn next_index(&mut self) { + self.index += N::one(); + } +} + +impl<'a, K, T, N> Iterator for IndexableIterMap<'a, K, T, N> +where + T: Serialize + DeserializeOwned, + K: PrimaryKey<'a> + Prefixer<'a> + KeyDeserialize, + N: Add + + AddAssign + + Increment + + Sub + + Serialize + + DeserializeOwned + + Clone, +{ + type Item = T; + + fn next(&mut self) -> Option { + let item = self + .iter_map + .get(self.storage.clone(), self.key.clone(), self.index.clone()); + + self.next_index(); + + match item { + Ok(i) => Some(i), + Err(_) => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::utils::storage::plus::iter_map::IterMap; + use cosmwasm_std::{ + testing::{MockApi, MockQuerier, MockStorage}, + Addr, + CustomQuery, + OwnedDeps, + Storage, + Uint64, + }; + use serde::{ + de::{self, DeserializeOwned}, + ser, + Deserialize, + Serialize, + }; + use std::marker::PhantomData; + + #[derive(Clone, Serialize, Deserialize)] + struct MyQuery; + impl CustomQuery for MyQuery {} + + const MACRO_TEST: IterMap<(Addr), Uint64, u64> = new_iter_map!("MACRO_TEST"); + + #[test] + fn initialization() { + let mut storage = MockStorage::new(); + + let iter: IterMap<(Addr), Uint64, u64> = IterMap::new_override("TEST", "SIZE-TEST"); + } + + fn generate(size: u8, storage: &mut dyn Storage) -> IterMap<(String), Uint64, u64> { + let iter: IterMap<(String), Uint64, u64> = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..size { + iter.push(storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + iter + } + + #[test] + fn push() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + let item = iter.pop(&mut storage, "TESTING".to_string()).unwrap(); + + assert_eq!(item, Uint64::new(9)); + assert_eq!(9, iter.size(&storage, "TESTING".to_string()).unwrap()); + } + + #[test] + fn remove() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + iter.remove(&mut storage, "TESTING".to_string()).unwrap(); + + assert_eq!(9, iter.size(&storage, "TESTING".to_string()).unwrap()); + } + + #[test] + fn set() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + iter.set(&mut storage, "TESTING".to_string(), 3, &Uint64::new(5)) + .unwrap(); + + assert_eq!( + Uint64::new(5), + iter.get(&storage, "TESTING".to_string(), 3).unwrap() + ) + } + + #[test] + fn get() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + assert_eq!( + Uint64::new(3), + iter.get(&storage, "TESTING".to_string(), 3).unwrap() + ) + } + + #[test] + fn total() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + assert_eq!(10, iter.size(&storage, "TESTING".to_string()).unwrap()) + } + + #[test] + fn iterate() { + let mut storage = MockStorage::new(); + + let iter: IterMap = IterMap::new_override("TEST", "SIZE-TEST"); + + for i in 0..10 { + iter.push(&mut storage, "TESTING".to_string(), &Uint64::new(i as u64)) + .unwrap(); + } + + for (i, item) in iter.iter(&storage, "TESTING".to_string()).enumerate() { + assert_eq!(item, Uint64::new(i as u64)) + } + } +} diff --git a/packages/shade_protocol/src/utils/storage/plus/mod.rs b/packages/shade_protocol/src/utils/storage/plus/mod.rs new file mode 100644 index 0000000..51d2dc0 --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/plus/mod.rs @@ -0,0 +1,208 @@ +pub mod iter_item; +pub mod iter_map; +pub mod period_storage; + +use crate::{ + c_std::{StdError, StdResult, Storage}, + serde::{de::DeserializeOwned, Serialize}, +}; + +pub use secret_storage_plus::{Bincode2, Item, Json, Map, PrimaryKey, Serde}; + +pub trait NaiveItemStorage: Serialize + DeserializeOwned +where + Ser: Serde, +{ + fn load(storage: &dyn Storage, item: Item) -> StdResult { + item.load(storage) + } + + fn may_load(storage: &dyn Storage, item: Item) -> StdResult> { + item.may_load(storage) + } + + fn remove(storage: &mut dyn Storage, item: Item) { + item.remove(storage) + } + + fn save(&self, storage: &mut dyn Storage, item: Item) -> StdResult<()> { + item.save(storage, self) + } + + fn update( + &self, + storage: &mut dyn Storage, + item: Item, + action: A, + ) -> Result + where + A: FnOnce(Self) -> Result, + E: From, + { + item.update(storage, action) + } +} + +pub trait ItemStorage: Serialize + DeserializeOwned +where + Ser: Serde, +{ + const ITEM: Item<'static, Self, Ser>; + + fn load(storage: &dyn Storage) -> StdResult { + Self::ITEM.load(storage) + } + + fn may_load(storage: &dyn Storage) -> StdResult> { + Self::ITEM.may_load(storage) + } + + fn remove(storage: &mut dyn Storage) { + Self::ITEM.remove(storage) + } + + fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { + Self::ITEM.save(storage, self) + } + + fn update(&self, storage: &mut dyn Storage, action: A) -> Result + where + A: FnOnce(Self) -> Result, + E: From, + { + Self::ITEM.update(storage, action) + } +} + +pub trait GenericItemStorage +where + Ser: Serde, +{ + const ITEM: Item<'static, T, Ser>; + + fn load(storage: &dyn Storage) -> StdResult { + Self::ITEM.load(storage) + } + + fn may_load(storage: &dyn Storage) -> StdResult> { + Self::ITEM.may_load(storage) + } + + fn save(storage: &mut dyn Storage, item: &T) -> StdResult<()> { + Self::ITEM.save(storage, item) + } + + fn update(storage: &mut dyn Storage, action: A) -> Result + where + A: FnOnce(T) -> Result, + E: From, + { + Self::ITEM.update(storage, action) + } +} + +pub trait NaiveMapStorage<'a, Ser = Json>: Serialize + DeserializeOwned +where + Ser: Serde, +{ + fn load>( + storage: &dyn Storage, + map: Map<'a, K, Self, Ser>, + key: K, + ) -> StdResult { + map.load(storage, key) + } + + fn may_load>( + storage: &dyn Storage, + map: Map<'a, K, Self, Ser>, + key: K, + ) -> StdResult> { + map.may_load(storage, key) + } + + fn remove>(storage: &mut dyn Storage, map: Map<'a, K, Self, Ser>, key: K) { + map.remove(storage, key) + } + + fn save>( + &self, + storage: &mut dyn Storage, + map: Map<'a, K, Self, Ser>, + key: K, + ) -> StdResult<()> { + map.save(storage, key, self) + } + + fn update>( + &self, + storage: &mut dyn Storage, + map: Map<'a, K, Self, Ser>, + key: K, + action: A, + ) -> Result + where + A: FnOnce(Option) -> Result, + E: From, + { + map.update(storage, key, action) + } +} + +pub trait MapStorage<'a, K: PrimaryKey<'a>, Ser = Json>: Serialize + DeserializeOwned +where + Ser: Serde, +{ + const MAP: Map<'static, K, Self, Ser>; + + fn load(storage: &dyn Storage, key: K) -> StdResult { + Self::MAP.load(storage, key) + } + + fn may_load(storage: &dyn Storage, key: K) -> StdResult> { + Self::MAP.may_load(storage, key) + } + + fn remove(storage: &mut dyn Storage, key: K) { + Self::MAP.remove(storage, key) + } + + fn save(&self, storage: &mut dyn Storage, key: K) -> StdResult<()> { + Self::MAP.save(storage, key, self) + } + + fn update(&self, storage: &mut dyn Storage, key: K, action: A) -> Result + where + A: FnOnce(Option) -> Result, + E: From, + { + Self::MAP.update(storage, key, action) + } +} + +pub trait GenericMapStorage<'a, K: PrimaryKey<'a>, T: Serialize + DeserializeOwned, Ser = Json> +where + Ser: Serde, +{ + const MAP: Map<'static, K, T, Ser>; + + fn load(storage: &dyn Storage, key: K) -> StdResult { + Self::MAP.load(storage, key) + } + + fn may_load(storage: &dyn Storage, key: K) -> StdResult> { + Self::MAP.may_load(storage, key) + } + + fn save(storage: &mut dyn Storage, key: K, item: &T) -> StdResult<()> { + Self::MAP.save(storage, key, item) + } + + fn update(&self, storage: &mut dyn Storage, key: K, action: A) -> Result + where + A: FnOnce(Option) -> Result, + E: From, + { + Self::MAP.update(storage, key, action) + } +} diff --git a/packages/shade_protocol/src/utils/storage/plus/period_storage.rs b/packages/shade_protocol/src/utils/storage/plus/period_storage.rs new file mode 100644 index 0000000..025b778 --- /dev/null +++ b/packages/shade_protocol/src/utils/storage/plus/period_storage.rs @@ -0,0 +1,359 @@ +use crate::{ + c_std::{StdResult, Storage, Timestamp}, + cosmwasm_schema::cw_serde, + serde::{de::DeserializeOwned, Serialize}, + utils::cycle::*, +}; +pub use secret_storage_plus::{Item, Json, Map, PrimaryKey, Serde}; + + +use strum::IntoEnumIterator; +use strum_macros::EnumIter; + +#[cw_serde] +#[derive(EnumIter)] +pub enum Period { + Hour, + Day, + Month, +} + +pub fn map_key(seconds: u64, period: Period) -> String { + let datetime = utc_from_seconds(seconds as i64); + match period { + Period::Hour => datetime.format("%Y-%m-%dT%H").to_string(), + Period::Day => datetime.format("%Y-%m-%d").to_string(), + Period::Month => datetime.format("%Y-%m").to_string(), + } +} + +pub struct PeriodStorage<'a, T, Ser = Json> +where + T: Serialize + DeserializeOwned + Clone, + Ser: Serde, +{ + all: Map<'a, u64, Vec, Ser>, + recent: Item<'a, Vec>, + + /* keys are date formatted strings "%Y-%m-%dT%h" + * right-most data is truncated to categorize by higher order + * e.g. month format is "%Y-%m" + */ + timed: Map<'a, String, Vec, Ser>, +} + +impl<'a, T, Ser> PeriodStorage<'a, T, Ser> +where + T: Serialize + DeserializeOwned + Clone, + Ser: Serde, +{ + pub const fn new(all: &'a str, recent: &'a str, timed: &'a str) -> Self { + PeriodStorage { + all: Map::new(all), + recent: Item::new(recent), + timed: Map::new(timed), + } + } + + pub fn load(&self, storage: &dyn Storage, ts: Timestamp) -> StdResult> { + self.all.load(storage, ts.seconds()) + } + + pub fn load_period( + &self, + storage: &dyn Storage, + seconds: u64, + period: Period, + ) -> StdResult> { + Ok(self + .timed + .load(storage, map_key(seconds, period)) + .unwrap_or(vec![])) + } + + pub fn may_load(&self, storage: &dyn Storage, ts: Timestamp) -> StdResult> { + Ok(self.all.may_load(storage, ts.seconds())?.unwrap_or(vec![])) + } + + pub fn push(&self, storage: &mut dyn Storage, ts: Timestamp, item: T) -> StdResult<()> { + let key = ts.seconds(); + let mut recent = self.recent.may_load(storage)?.unwrap_or(vec![]); + if !recent.contains(&key) { + recent.push(key); + self.recent.save(storage, &recent)?; + } + let mut all = self.all.may_load(storage, key)?.unwrap_or(vec![]); + all.push(item); + self.all.save(storage, key, &all)?; + self.flush(storage) + } + + pub fn append( + &self, + storage: &mut dyn Storage, + ts: Timestamp, + items: &mut Vec, + ) -> StdResult<()> { + let key = ts.seconds(); + let mut recent = self.recent.may_load(storage)?.unwrap_or(vec![]); + if !recent.contains(&key) { + recent.push(key); + self.recent.save(storage, &recent)?; + } + let mut all = self.all.may_load(storage, key)?.unwrap_or(vec![]); + all.append(items); + self.all.save(storage, key, &all)?; + + self.flush(storage) + } + + /* This will move all "recents" into the time based storage + * This should likely be called at the end of execution that adds items + */ + fn flush(&self, storage: &mut dyn Storage) -> StdResult<()> { + for seconds in self.recent.load(storage)? { + let mut items = self.all.load(storage, seconds)?; + + for period in Period::iter() { + let k = map_key(seconds, period); + let mut cur_items = self.timed.may_load(storage, k.clone())?.unwrap_or(vec![]); + cur_items.append(&mut items.clone()); + self.timed.save(storage, k, &cur_items)?; + } + } + self.recent.save(storage, &vec![]) + } +} + +#[cfg(test)] +mod test { + + use super::*; + use crate::c_std::{MemoryStorage, Timestamp, Uint128}; + + fn test_push(now: String) { + let now = parse_utc_datetime(&"1995-11-13T00:00:00.00Z".to_string()).unwrap(); + let mut storage = MemoryStorage::new(); + pub const STORAGE: PeriodStorage = PeriodStorage::new("all", "recent", "timed"); + + let data = vec![1, 2, 3, 5, 10]; + + for d in data.clone() { + STORAGE + .push( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + d, + ) + .unwrap(); + } + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Hour) + .unwrap(), + data + ); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap(), + data + ); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap(), + data + ); + } + + fn test_append(now: String) { + let now = parse_utc_datetime(&"1995-11-13T00:00:00.00Z".to_string()).unwrap(); + let mut storage = MemoryStorage::new(); + pub const STORAGE: PeriodStorage = PeriodStorage::new("all", "recent", "timed"); + + let mut data = vec![1, 2, 3, 5, 10]; + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut data.clone(), + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Hour) + .unwrap(), + data + ); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap(), + data + ); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap(), + data + ); + } + + fn test_hour_timed(now: String) { + let mut now = parse_utc_datetime(&"1995-11-13T00:00:00.00Z".to_string()).unwrap(); + + let mut storage = MemoryStorage::new(); + pub const STORAGE: PeriodStorage = PeriodStorage::new("all", "recent", "timed"); + + let mut data = vec![1, 2, 3, 5, 10]; + let mut added = vec![11, 12, 13, 15, 20]; + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut data, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Hour) + .unwrap(), + data + ); + + let now = parse_utc_datetime(&"1995-11-13T01:00:00.00Z".to_string()).unwrap(); + assert!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Hour) + .unwrap() + .is_empty(), + ); + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut added, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Hour) + .unwrap(), + added + ); + + let mut all_data = data; + all_data.append(&mut added); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap(), + all_data + ); + } + + fn test_day_timed(now: String) { + let mut now = parse_utc_datetime(&"1995-11-13T00:00:00.00Z".to_string()).unwrap(); + + let mut storage = MemoryStorage::new(); + pub const STORAGE: PeriodStorage = PeriodStorage::new("all", "recent", "timed"); + + let mut data = vec![1, 2, 3, 5, 10]; + let mut added = vec![11, 12, 13, 15, 20]; + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut data, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap(), + data + ); + + let now = parse_utc_datetime(&"1995-11-14T00:00:00.00Z".to_string()).unwrap(); + assert!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap() + .is_empty(), + ); + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut added, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Day) + .unwrap(), + added + ); + + let mut all_data = data; + all_data.append(&mut added); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap(), + all_data + ); + } + + fn test_month_timed(now: String) { + let mut now = parse_utc_datetime(&"1995-11-13T00:00:00.00Z".to_string()).unwrap(); + + let mut storage = MemoryStorage::new(); + pub const STORAGE: PeriodStorage = PeriodStorage::new("all", "recent", "timed"); + + let mut data = vec![1, 2, 3, 5, 10]; + let mut added = vec![11, 12, 13, 15, 20]; + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut data, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap(), + data + ); + + let now = parse_utc_datetime(&"1995-12-13T00:00:00.00Z".to_string()).unwrap(); + assert!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap() + .is_empty(), + ); + + STORAGE + .append( + &mut storage, + Timestamp::from_seconds(now.timestamp() as u64), + &mut added, + ) + .unwrap(); + assert_eq!( + STORAGE + .load_period(&storage, now.timestamp() as u64, Period::Month) + .unwrap(), + added + ); + } +} diff --git a/packages/shade_protocol/src/utils/wrap.rs b/packages/shade_protocol/src/utils/wrap.rs new file mode 100644 index 0000000..efbe7cb --- /dev/null +++ b/packages/shade_protocol/src/utils/wrap.rs @@ -0,0 +1,35 @@ +use crate::{ + c_std::{Addr, Binary, Coin, CosmosMsg, StdResult, Uint128}, + contract_interfaces::snip20, + snip20::helpers::{deposit_msg, redeem_msg, send_msg}, + utils::{asset::Contract, callback::ExecuteCallback}, +}; + +pub fn wrap(amount: Uint128, token: Contract) -> StdResult { + Ok(deposit_msg(amount, None, &token)?) +} + +pub fn wrap_coin(coin: Coin, token: Contract) -> StdResult { + snip20::ExecuteMsg::Deposit { padding: None }.to_cosmos_msg(&token, vec![coin]) +} + +pub fn wrap_and_send( + amount: Uint128, + recipient: Addr, + token: Contract, + //denom: Option, + msg: Option, +) -> StdResult> { + Ok(vec![ + wrap(amount, token.clone())?, + send_msg(recipient, amount, msg, None, None, &token)?, + ]) +} + +pub fn unwrap( + amount: Uint128, + token: Contract, + //denom: Option, +) -> StdResult { + Ok(redeem_msg(amount, None, None, &token)?) +} diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..4934985 --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +1.69.0 diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..de1af2a --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,15 @@ +# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md + +# Stable configurations +edition = "2018" +max_width = 100 +merge_derives = true +use_field_init_shorthand = true +use_try_shorthand = true + +# Nightly configurations +imports_layout = "HorizontalVertical" +imports_granularity = "Crate" +overflow_delimited_expr = true +reorder_impl_items = true +version = "Two" diff --git a/tools/doc2book/Cargo.toml b/tools/doc2book/Cargo.toml new file mode 100644 index 0000000..8d02b99 --- /dev/null +++ b/tools/doc2book/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "doc2book" +version = "0.1.0" +edition = "2018" + +[[bin]] +name = "doc2book" +path = "src/doc2book.rs" + +[dev-dependencies] +pretty_assertions = "1.0.0" diff --git a/tools/doc2book/README.md b/tools/doc2book/README.md new file mode 100644 index 0000000..3da4ab3 --- /dev/null +++ b/tools/doc2book/README.md @@ -0,0 +1,59 @@ +# `doc2book` +A simple tool that scrapes rustdoc comments, `doc2book`-only comments and specified Rust code from a crate's source files +and outputs them as a single file (e.g. a Markdown book chapter). + +## Usage +The usage is simple, specify the crate and the output file path +``` +USAGE: doc2book CRATE_DIR OUT_FILE_PATH +``` + +Example from Shade workspace root directory: +``` +cargo r -p doc2book --release -- packages/shade_protocol doc/book/src/smart_contracts.md +``` + +### Comments +The following comments are scraped: +- `//! `: [rustdoc][1] crate-level (inner) doc comments +- `/// `: [rustdoc][1] code-level (outer) doc comments +- `//# `: `doc2book` comments, these will be ignored by rustdoc but picked up by `doc2book` + +[1]: https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html + +### Code +The comments `// book_include_code` and `// end_book_include_code` mark a section of code to be copied verbatim and place in a Rust code block (Markdown syntax). +This code: + +```rust +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "snake_case")] +// book_include_code +pub struct Contract { + /// The address of the contract + pub address: Addr, + /// The hex encoded hash of the contract code + pub code_hash: String, +} +// end_book_include_code +``` + +Would result in this Markdown section: + +~~~ +```rust +pub struct Contract { + /// The address of the contract + pub address: Addr, + /// The hex encoded hash of the contract code + pub code_hash: String, +} +``` +~~~ + +## Limitations +As the tool is currently very simple it has a few limitations: +- The crate structure is expected to be one file per module at the same directory level as the lib.rs file. +- The tool outputs everything as a single file, it could be made to create a 'sub-chapter' file for each module. +- Due to it creating a single file, the ordering of comments, modules declarations and the code is the order it will appear output file. +- Adding whitespace between scraped sections needs to be explicit, i.e. an empty comment line needs to be inserted where you want a blank line `//! `. diff --git a/tools/doc2book/src/doc2book.rs b/tools/doc2book/src/doc2book.rs new file mode 100644 index 0000000..8a00192 --- /dev/null +++ b/tools/doc2book/src/doc2book.rs @@ -0,0 +1,326 @@ +use std::{ + fs::File, + io::{BufRead, BufReader, Error as IoError, Lines, Write}, +}; + +const USAGE: &str = "USAGE: doc2book CRATE_DIR OUT_FILE_PATH"; + +type Result = std::result::Result; + +#[derive(Debug)] +enum Error { + CrateSourceDirNotFound(String), + LibRsNotFound(String), + ModuleSourceNotFound(String), + Io(IoError), +} + +impl From for Error { + fn from(err: IoError) -> Self { + Self::Io(err) + } +} + +// source reading interface +trait ReadSource { + type Src: BufRead; + + fn lib_rs_path(&self) -> &str; + + fn module_path_from_name(&self, module: &str) -> String; + + fn lines_from_path(&self, src_path: &str) -> Result>; +} + +// source reading implementor for crates +struct CrateSource { + crate_src_dir: String, + lib_rs_path: String, +} + +impl CrateSource { + // ensure the crate is valid, + // i.e. it's src directory exists and contains a mod file + fn new(crate_dir: &str) -> Result { + let crate_src_dir = format!("{}/src", crate_dir); + let lib_rs_path = format!("{}/mod", crate_src_dir); + + if std::fs::metadata(&crate_src_dir).is_err() { + return Err(Error::CrateSourceDirNotFound(crate_src_dir)); + } + + if std::fs::metadata(&lib_rs_path).is_err() { + return Err(Error::LibRsNotFound(lib_rs_path)); + } + + Ok(CrateSource { + crate_src_dir, + lib_rs_path, + }) + } +} + +impl ReadSource for CrateSource { + type Src = BufReader; + + fn lib_rs_path(&self) -> &str { + &self.lib_rs_path + } + + fn module_path_from_name(&self, module: &str) -> String { + format!("{}/{}.rs", self.crate_src_dir, module) + } + + fn lines_from_path(&self, src_path: &str) -> Result> { + if std::fs::metadata(src_path).is_err() { + return Err(Error::ModuleSourceNotFound(src_path.to_string())); + } + + let file = File::open(src_path)?; + let lines = BufReader::new(file).lines(); + + Ok(lines) + } +} + +struct Output { + output: Vec, +} + +impl Output { + fn new() -> Output { + // allocate a decent chunk of memory at the start + let output = Vec::with_capacity(1_000_000_000); + Output { output } + } + + fn push_line(&mut self, line: &str) { + writeln!(&mut self.output, "{}", line).unwrap(); + } + + fn write_into(&self, w: &mut dyn Write) -> Result<()> { + w.write_all(&self.output)?; + Ok(()) + } +} + +fn parse_args() -> Option<(String, String)> { + let mut args = std::env::args().skip(1); + let crate_dir = args.next()?; + let out_path = args.next()?; + Some((crate_dir, out_path)) +} + +fn find_doc_comment(line: &str) -> Option<&str> { + line.strip_prefix("//! ") + .or_else(|| line.strip_prefix("//# ")) + .or_else(|| line.strip_prefix("/// ")) +} + +// scrape from code between pragmas and each type of doc comment +fn process_module(input: &I, output: &mut Output, module_name: &str) -> Result<()> +where + I: ReadSource, +{ + let module_path = input.module_path_from_name(module_name); + eprintln!("Processing module file: {}", module_path); + + let mut code_transcribe_enabled = false; + + for line in input.lines_from_path(&module_path)? { + let line = line?; + + if line.starts_with("// book_include_code") { + output.push_line("```rust"); + code_transcribe_enabled = true; + continue; + } + + if line.starts_with("// end_book_include_code") { + output.push_line("```"); + code_transcribe_enabled = false; + continue; + } + + if code_transcribe_enabled { + output.push_line(&line); + continue; + } + + if let Some(line) = find_doc_comment(&line) { + output.push_line(line); + } + } + + Ok(()) +} + +// start with the crate root, mod +// scrape code comments and with each public module inserted in the order they appear +fn process_crate(input: I, output: &mut Output) -> Result<()> +where + I: ReadSource, +{ + let lib_rs_path = input.lib_rs_path(); + eprintln!("Processing mod file: {}", lib_rs_path); + + for line in input.lines_from_path(lib_rs_path)? { + let line = line?; + + if let Some(doc) = find_doc_comment(&line) { + output.push_line(doc); + continue; + } + + if line.starts_with("pub mod ") && line.ends_with(';') { + let module = line + .strip_prefix("pub mod ") + .unwrap() + .strip_suffix(';') + .unwrap(); + + process_module(&input, output, module)?; + } + } + + Ok(()) +} + +fn main() { + let (crate_root_dir, out_path) = match parse_args() { + Some(args) => args, + _ => return eprintln!("{}", USAGE), + }; + + let input = match CrateSource::new(&crate_root_dir) { + Ok(input) => input, + Err(Error::CrateSourceDirNotFound(path)) => { + eprintln!( + "{} does not exist. Make sure the specified directory is a Rust project.", + path + ); + return eprintln!("{}", USAGE); + } + Err(Error::LibRsNotFound(path)) => { + eprintln!("{} not does not exist. The crate must be a library.", path); + return eprintln!("{}", USAGE); + } + Err(err) => panic!("unexpected err: {:?}", err), + }; + + let mut output = Output::new(); + + let result = process_crate(input, &mut output).and_then(|_| { + let mut out_file = File::create(out_path)?; + output.write_into(&mut out_file) + }); + + if let Err(err) = result { + match err { + Error::ModuleSourceNotFound(path) => { + eprintln!( + "Processing module file {} failed: file does not exist", + path + ) + } + Error::Io(err) => eprintln!("Unexpected I/O Error: {}", err), + err => panic!("unexpected err: {:?}", err), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use pretty_assertions::assert_eq; + + const LIB_RS: &str = r#"//! # Main Title +//! Some text +//! + +pub mod helper_mod; + +//# ## Common Types +//# Some more text +//# + +pub mod common_types; +"#; + + const COMMON_TYPES_RS: &str = r#"use some_dep::module; +use some_other_dep::module; + +//# ### `Contract` +/// Represents another contract on the network +/// + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "snake_case")] +// book_include_code +pub struct Contract { + /// The address of the contract + pub address: Addr, + /// The hex encoded hash of the contract code + pub code_hash: String, +} +// end_book_include_code"#; + + const EXPECTED_OUTPUT: &str = r#"# Main Title +Some text + +## Common Types +Some more text + +### `Contract` +Represents another contract on the network + +```rust +pub struct Contract { + /// The address of the contract + pub address: Addr, + /// The hex encoded hash of the contract code + pub code_hash: String, +} +``` +"#; + + struct TestInput; + + impl ReadSource for TestInput { + type Src = BufReader<&'static [u8]>; + + fn lib_rs_path(&self) -> &str { + "src/mod" + } + + fn module_path_from_name(&self, module: &str) -> String { + format!("src/{}.rs", module) + } + + fn lines_from_path(&self, src_path: &str) -> Result> { + let s: &'static str = match src_path { + "src/mod" => LIB_RS, + "src/common_types.rs" => COMMON_TYPES_RS, + "src/helper_mod.rs" => "", + _ => panic!("Unexpected path: {}", src_path), + }; + + Ok(BufReader::new(s.as_bytes()).lines()) + } + } + + #[test] + fn it_works() { + let mut output = Output::new(); + + process_crate(TestInput, &mut output).unwrap(); + + let mut actual = Vec::new(); + + output.write_into(&mut actual).unwrap(); + + let actual = String::from_utf8(actual).unwrap(); + + assert_eq!(actual, EXPECTED_OUTPUT.to_owned()) + } +} diff --git a/tools/headstash/account.js b/tools/headstash/account.js new file mode 100644 index 0000000..12c2baa --- /dev/null +++ b/tools/headstash/account.js @@ -0,0 +1,63 @@ +import { MsgExecuteContract, fromBase64, toUtf8 } from "secretjs"; +import { encodeJsonToB64 } from "@shadeprotocol/shadejs"; +import { chain_id, scrtHeadstashCodeHash, secretHeadstashContractAddr, secretjs, txEncryptionSeed, wallet, permitKey, pubkey, cosmos_sig, eth_pubkey, eth_sig, partial_tree } from "./main.js"; + +let create_account = async () => { + const addressProofMsg = { + address: wallet.address, + amount: "420", + contract: secretHeadstashContractAddr, + index: 1, + key: permitKey, + } + // encode memo to base64 string + const encoded_memo = Buffer.from(JSON.stringify(addressProofMsg)).toString('base64'); + + const fillerMsg = { + coins: [], + contract: secretHeadstashContractAddr, + execute_msg: {}, + sender: wallet.address, + } + + // account + const permitParams = { + params: fillerMsg, + signature: { + pub_key: pubkey, + signature: cosmos_sig, + }, + chain_id: chain_id, + memo: encoded_memo, + } + + const createAccount = { + account: { + addresses: [permitParams], + eth_pubkey: eth_pubkey, + eth_sig: eth_sig.slice(2), + partial_tree: partial_tree, + } + } + + const tx = await secretjs.tx.compute.executeContract({ + sender: wallet.address, + contract_address: secretHeadstashContractAddr, + msg: createAccount, + code_hash: scrtHeadstashCodeHash, + }, + { + gasLimit: 400_000, + // explicitSignerData: { + // accountNumber: 22761, + // sequence: 191, + // chainId: "pulsar-3" + // } + }) + + console.log(tx); +} +export { create_account } + + + diff --git a/tools/headstash/deploy-cw20.sh b/tools/headstash/deploy-cw20.sh new file mode 100644 index 0000000..a429863 --- /dev/null +++ b/tools/headstash/deploy-cw20.sh @@ -0,0 +1,58 @@ + + +# install secret-cli + +if ! command -v scrt &> /dev/null +then + echo "The Secret Network CLI is not installed, downloading & installing." + wget https://github.com/scrtlabs/SecretNetwork/releases/download/v1.12.2/secretcli-Linux > /root/go/bin/scrt + sudo chmod +x /root/go/bin/scrt +else + # Command exists + echo "The Secret Network CLI is installed." +fi + +# define code-id or fetch cw-20 raw wasm file +CODE_ID=123 +CW20_GIT=https://github.com/scrtlabs/snip20-reference-impl +# store or instantiate +TYPE =-i + +if ! command -v docker &> /dev/null +then + echo "Docker is not installed, downloading & installing." + snap install docker +else + # Command exists + echo "Docker is now installed." +fi + + +git clone $CW20_GIT snip20 +cd snip20 + +docker run --rm -v "$(pwd)":/contract --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry enigmampc/secret-contract-optimizer +mv contract.wasm.gz ../ && cd ../ + + +## instantiate or store and instantitate contracts +# Check if the number of arguments is less than 2 (excluding the script name) +if [ "$#" -lt 2 ]; then + echo "Usage: $0 [-s|-i] name symbol [supported_denoms]" + exit 1 +fi + +# Extract the action type (instantiate or upload) and values +action=$1 +name=$2 +symbol=$3 +supported_denoms=$4 + +# Run the Node.js script with the chosen action and values +if [ "$action" == "-i" ]; then + node your_script.js "$action" "$name" "$symbol" "$supported_denoms" +elif [ "$action" == "-s" ]; then + node your_script.js "$action" +else + echo "Invalid action type. Please provide -s or -i." +fi diff --git a/tools/headstash/index.js b/tools/headstash/index.js new file mode 100644 index 0000000..c37636d --- /dev/null +++ b/tools/headstash/index.js @@ -0,0 +1 @@ +export * from './main' \ No newline at end of file diff --git a/tools/headstash/main.js b/tools/headstash/main.js new file mode 100644 index 0000000..5b126bd --- /dev/null +++ b/tools/headstash/main.js @@ -0,0 +1,177 @@ +import { Wallet, SecretNetworkClient, EncryptionUtilsImpl, MsgExecuteContract, fromUtf8, MsgExecuteContractResponse } from "secretjs"; +import {create_account} from './account.js' +import * as fs from "fs"; + +// wallet +export const chain_id = "pulsar-3"; +export const wallet = new Wallet("goat action fuel major strategy adult kind sand draw amazing pigeon inspire antenna forget six kiss loan script west jaguar again click review have"); +export const txEncryptionSeed = EncryptionUtilsImpl.GenerateNewSeed(); +// export const contract_wasm = fs.readFileSync("./target/wasm32-unknown-unknown/release/airdrop.wasm"); + +// snip-20 +export const scrt20codeId = 5697; +export const scrt20CodeHash = "c74bc4b0406507257ed033caa922272023ab013b0c74330efc16569528fa34fe"; +export const secretTerpContractAddr = "secret1c3lj7dr9r2pe83j3yx8jt5v800zs9sq7we6wrc"; +export const secretThiolContractAddr = "secret1umh28jgcp0g9jy3qc29xk42kq92xjrcdfgvwdz"; + +// airdrop contract +export const scrtHeadstashCodeId = 6559; +export const scrtHeadstashCodeHash = "f494eda77c7816c4882d0dfde8bbd35b87975e427ea74315ed96c051d5674f82"; +export const secretHeadstashContractAddr = "secret1dx5a9ut29nv2n673hh06n0zh7z2fg63n0xylqg"; +export const merkle_root = "d599867bdb2ade1e470d9ec9456490adcd9da6e0cfd8f515e2b95d345a5cd92f"; + +// account stuff +export const cosmos_sig = "esaFDwiCoi6R5h/xdW/vPyyyFGrwfujMdR/2t65GmRczF3ZYwzQvzfVEBrOBopCa2x98dpEusml8ysi1khZLhQ=="; +export const eth_pubkey = "0x254768D47Cf8958a68242ce5AA1aDB401E1feF2B"; +export const eth_sig = "0xf7992bd3f7cb1030b5d69d3326c6e2e28bfde2e38cbb8de753d1be7b5a5ecbcf2d3eccd3fe2e1fccb2454c47dcb926bd047ecf5b74c7330584cbfd619248de811b" +export const pubkey = { type: "tendermint/PubKeySecp256k1", value: "AyZtxhLgis4Ec66OVlKDnuzEZqqV641sm46R3mbE2cpO" } +export const partial_tree = ['fbff7c66d3f610bcf8223e61ce12b10bb64a3433622ff39af83443bcec78920a'] +export const permitKey = "test123" + +// signing client +export const secretjs = new SecretNetworkClient({ + chainId: chain_id, + url: "https://api.pulsar.scrttestnet.com", + wallet: wallet, + walletAddress: wallet.address, + txEncryptionSeed: txEncryptionSeed +}); + +// stores contract, prints code hash & code id +let upload_contract = async () => { + let tx = await secretjs.tx.compute.storeCode( + { + sender: wallet.address, + wasm_byte_code: contract_wasm, + source: "", + builder: "", + }, + { + gasLimit: 4_000_000, + } + ); + + if (tx.code == 0) { + const codeId = Number( + tx.arrayLog.find((log) => log.type === "message" && log.key === "code_id").value + ); + console.log("codeId: ", codeId); + const contractCodeHash = (await secretjs.query.compute.codeHashByCodeId({ code_id: codeId })).code_hash; + console.log(`Contract hash: ${contractCodeHash}`); + } +} + + +// initialize a new headstash contract +let instantiate_headstash_contract = async () => { + let initMsg = { + admin: wallet.address, + dump_address: wallet.address, + airdrop_token: { + address: secretTerpContractAddr, + code_hash: scrt20CodeHash + }, + airdrop_2: { + address: secretThiolContractAddr, + code_hash: scrt20CodeHash + }, + start_date: 1713386815, + end_date: 1744922815, + decay_start: 1723927615, + merkle_root: merkle_root, + airdrop_amount: "840", + total_accounts: 2, + max_amount: "420", + default_claim: "50", + task_claim: [{ + address: secretHeadstashContractAddr, + percent: "50", + }], + claim_msg_plaintext: "{wallet}", + query_rounding: "1" + }; + + let tx = await secretjs.tx.compute.instantiateContract( + { + code_id: scrtHeadstashCodeId, + sender: wallet.address, + code_hash: scrtHeadstashCodeHash, + init_msg: initMsg, + label: "Secret Headstash Patch" + Math.ceil(Math.random() * 10000), + }, + { + gasLimit: 400_000, + } + ); + + console.log(tx); + //Find the contract_address in the logs + const contractAddress = tx.arrayLog.find( + (log) => log.type === "message" && log.key === "contract_address" + ).value; + + console.log(contractAddress); +} + + +// initiates a new snip-20 +let instantiate_contract = async (name, synbol, supported_denom) => { + const initMsg = { + name: "Terp Network Gas Token", + symbol: "THIOL", + decimals: 6, + prng_seed: Buffer.from("dezayum").toString("base64"), + admin: wallet.address, + supported_denoms: [supported_denom] + }; + let tx = await secretjs.tx.compute.instantiateContract( + { + code_id: codeId, + sender: wallet.address, + code_hash: contractCodeHash, + init_msg: initMsg, + label: " Secret Wrapped Terp Network Gas Tokens (THIOL)" + Math.ceil(Math.random() * 10000), + }, + { + gasLimit: 400_000, + } + ); + if (tx.code == 0) { + //Find the contract_address in the logs + const contractAddress = tx.arrayLog.find( + (log) => log.type === "message" && log.key === "contract_address" + ).value; + + console.log(contractAddress); + } +}; + + +// Process command line arguments +const args = process.argv.slice(2); + +// Determine which function to run based on the first argument +if (args.length < 1) { + console.error('Invalid option. Please provide -s to store the contract, -i to instantiate the snip20 tokens followed by expected values [name] [symbol] [ibc-hash], -h to instantiate the headstash airdrop contract, -a to create the account,'); +} else if (args[0] === '-s') { + upload_contract(args[1]); +} else if (args[0] === '-h') { + instantiate_headstash_contract(); +} else if (args[0] === '-a') { + create_account(args[1]) +} else if (args[0] === '-i') { + if (args.length < 4) { + console.error('Usage: -i name symbol [supported_denoms]'); + process.exit(1); + } + const [, name, symbol, supported_denoms] = args; // Extracting values + instantiate_contract(name, symbol, supported_denoms) + .then(() => { + console.log("Upload completed!"); + }) + .catch((error) => { + console.error("Upload failed:", error); + }); +} else { + console.error('Invalid option. Please provide -s to store the contract, or -i to instantiate the contract, followed by expected values [name] [symbol] [ibc-hash].'); +} \ No newline at end of file diff --git a/tools/headstash/merkle-gen.sh b/tools/headstash/merkle-gen.sh new file mode 100644 index 0000000..e69de29 diff --git a/tools/headstash/package.json b/tools/headstash/package.json new file mode 100644 index 0000000..2df2167 --- /dev/null +++ b/tools/headstash/package.json @@ -0,0 +1,17 @@ +{ + "name": "scripts", + "version": "1.0.0", + "description": "", + "main": "index.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "@shadeprotocol/shadejs": "^1.1.7", + "secretjs": "^1.12.5" + } +} diff --git a/tools/headstash/permit-sig-example.json b/tools/headstash/permit-sig-example.json new file mode 100644 index 0000000..c9307e7 --- /dev/null +++ b/tools/headstash/permit-sig-example.json @@ -0,0 +1,22 @@ + { + "account_number": "0", + "chain_id": "pulsar-3", + "fee": { + "amount": [{ + "amount": "0", + "denom": "uscrt" + }], + "gas": "1" + }, + "memo": "", + "msgs": [{ + "type": "signature_proof", + "value": { + "coins": [], + "contract": "secret1dx5a9ut29nv2n673hh06n0zh7z2fg63n0xylqg", + "execute_msg": {}, + "sender": "secret13uazul89dp0lypuxcz0upygpjy0ftdah4lnrs4" + } + }], + "sequence": "0" + } \ No newline at end of file diff --git a/tools/headstash/yarn.lock b/tools/headstash/yarn.lock new file mode 100644 index 0000000..b213ca3 --- /dev/null +++ b/tools/headstash/yarn.lock @@ -0,0 +1,709 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@cosmjs/encoding@0.27.1": + version "0.27.1" + resolved "https://registry.yarnpkg.com/@cosmjs/encoding/-/encoding-0.27.1.tgz#3cd5bc0af743485eb2578cdb08cfa84c86d610e1" + integrity sha512-rayLsA0ojHeniaRfWWcqSsrE/T1rl1gl0OXVNtXlPwLJifKBeLEefGbOUiAQaT0wgJ8VNGBazVtAZBpJidfDhw== + dependencies: + base64-js "^1.3.0" + bech32 "^1.1.4" + readonly-date "^1.0.0" + +"@cosmjs/math@0.27.1": + version "0.27.1" + resolved "https://registry.yarnpkg.com/@cosmjs/math/-/math-0.27.1.tgz#be78857b008ffc6b1ed6fecaa1c4cd5bc38c07d7" + integrity sha512-cHWVjmfIjtRc7f80n7x+J5k8pe+vTVTQ0lA82tIxUgqUvgS6rogPP/TmGtTiZ4+NxWxd11DUISY6gVpr18/VNQ== + dependencies: + bn.js "^5.2.0" + +"@esbuild/android-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.18.20.tgz#984b4f9c8d0377443cc2dfcef266d02244593622" + integrity sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ== + +"@esbuild/android-arm@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.18.20.tgz#fedb265bc3a589c84cc11f810804f234947c3682" + integrity sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw== + +"@esbuild/android-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.18.20.tgz#35cf419c4cfc8babe8893d296cd990e9e9f756f2" + integrity sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg== + +"@esbuild/darwin-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.18.20.tgz#08172cbeccf95fbc383399a7f39cfbddaeb0d7c1" + integrity sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA== + +"@esbuild/darwin-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.18.20.tgz#d70d5790d8bf475556b67d0f8b7c5bdff053d85d" + integrity sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ== + +"@esbuild/freebsd-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.18.20.tgz#98755cd12707f93f210e2494d6a4b51b96977f54" + integrity sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw== + +"@esbuild/freebsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.18.20.tgz#c1eb2bff03915f87c29cece4c1a7fa1f423b066e" + integrity sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ== + +"@esbuild/linux-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.18.20.tgz#bad4238bd8f4fc25b5a021280c770ab5fc3a02a0" + integrity sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA== + +"@esbuild/linux-arm@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.18.20.tgz#3e617c61f33508a27150ee417543c8ab5acc73b0" + integrity sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg== + +"@esbuild/linux-ia32@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.18.20.tgz#699391cccba9aee6019b7f9892eb99219f1570a7" + integrity sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA== + +"@esbuild/linux-loong64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.18.20.tgz#e6fccb7aac178dd2ffb9860465ac89d7f23b977d" + integrity sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg== + +"@esbuild/linux-mips64el@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.18.20.tgz#eeff3a937de9c2310de30622a957ad1bd9183231" + integrity sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ== + +"@esbuild/linux-ppc64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.18.20.tgz#2f7156bde20b01527993e6881435ad79ba9599fb" + integrity sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA== + +"@esbuild/linux-riscv64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.18.20.tgz#6628389f210123d8b4743045af8caa7d4ddfc7a6" + integrity sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A== + +"@esbuild/linux-s390x@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.18.20.tgz#255e81fb289b101026131858ab99fba63dcf0071" + integrity sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ== + +"@esbuild/linux-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.18.20.tgz#c7690b3417af318a9b6f96df3031a8865176d338" + integrity sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w== + +"@esbuild/netbsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.18.20.tgz#30e8cd8a3dded63975e2df2438ca109601ebe0d1" + integrity sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A== + +"@esbuild/openbsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.18.20.tgz#7812af31b205055874c8082ea9cf9ab0da6217ae" + integrity sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg== + +"@esbuild/sunos-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.18.20.tgz#d5c275c3b4e73c9b0ecd38d1ca62c020f887ab9d" + integrity sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ== + +"@esbuild/win32-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.18.20.tgz#73bc7f5a9f8a77805f357fab97f290d0e4820ac9" + integrity sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg== + +"@esbuild/win32-ia32@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.18.20.tgz#ec93cbf0ef1085cc12e71e0d661d20569ff42102" + integrity sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g== + +"@esbuild/win32-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.18.20.tgz#786c5f41f043b07afb1af37683d7c33668858f6d" + integrity sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ== + +"@noble/hashes@1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.0.0.tgz#d5e38bfbdaba174805a4e649f13be9a9ed3351ae" + integrity sha512-DZVbtY62kc3kkBtMHqwCOfXrT/hnoORy5BJ4+HU1IR59X0KWAOqsfzQPcUl/lQLlG7qXbe/fZ3r/emxtAl+sqg== + +"@noble/secp256k1@1.7.0": + version "1.7.0" + resolved "https://registry.yarnpkg.com/@noble/secp256k1/-/secp256k1-1.7.0.tgz#d15357f7c227e751d90aa06b05a0e5cf993ba8c1" + integrity sha512-kbacwGSsH/CTout0ZnZWxnW1B+jH/7r/WAAKLBtrRJ/+CUH7lgmQzl3GTrQua3SGKWNSDsS6lmjnDpIJ5Dxyaw== + +"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf" + integrity sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ== + +"@protobufjs/base64@^1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@protobufjs/base64/-/base64-1.1.2.tgz#4c85730e59b9a1f1f349047dbf24296034bb2735" + integrity sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg== + +"@protobufjs/codegen@^2.0.4": + version "2.0.4" + resolved "https://registry.yarnpkg.com/@protobufjs/codegen/-/codegen-2.0.4.tgz#7ef37f0d010fb028ad1ad59722e506d9262815cb" + integrity sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg== + +"@protobufjs/eventemitter@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz#355cbc98bafad5978f9ed095f397621f1d066b70" + integrity sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q== + +"@protobufjs/fetch@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@protobufjs/fetch/-/fetch-1.1.0.tgz#ba99fb598614af65700c1619ff06d454b0d84c45" + integrity sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ== + dependencies: + "@protobufjs/aspromise" "^1.1.1" + "@protobufjs/inquire" "^1.1.0" + +"@protobufjs/float@^1.0.2": + version "1.0.2" + resolved "https://registry.yarnpkg.com/@protobufjs/float/-/float-1.0.2.tgz#5e9e1abdcb73fc0a7cb8b291df78c8cbd97b87d1" + integrity sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ== + +"@protobufjs/inquire@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@protobufjs/inquire/-/inquire-1.1.0.tgz#ff200e3e7cf2429e2dcafc1140828e8cc638f089" + integrity sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q== + +"@protobufjs/path@^1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@protobufjs/path/-/path-1.1.2.tgz#6cc2b20c5c9ad6ad0dccfd21ca7673d8d7fbf68d" + integrity sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA== + +"@protobufjs/pool@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@protobufjs/pool/-/pool-1.1.0.tgz#09fd15f2d6d3abfa9b65bc366506d6ad7846ff54" + integrity sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw== + +"@protobufjs/utf8@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570" + integrity sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw== + +"@shadeprotocol/shadejs@^1.1.7": + version "1.1.7" + resolved "https://registry.yarnpkg.com/@shadeprotocol/shadejs/-/shadejs-1.1.7.tgz#140f419d8ea828b3352a1b0f57da958c890b91ec" + integrity sha512-UfKBGbcDeXJtV9GsBCKN01q3hjMuGDgvhKGfHewG/WhVkd8g0uqERVXpwOuviCKg02sAiSxuXmOA0FR7MXxRfg== + dependencies: + bignumber.js "^9.1.2" + rxjs "^7.8.1" + secretjs "^1.12.1" + vite "^4.5.0" + whatwg-fetch "^3.6.19" + +"@types/node@10.12.18": + version "10.12.18" + resolved "https://registry.yarnpkg.com/@types/node/-/node-10.12.18.tgz#1d3ca764718915584fcd9f6344621b7672665c67" + integrity sha512-fh+pAqt4xRzPfqA6eh3Z2y6fyZavRIumvjhaCL753+TVkGKGhpPeyrJG2JftD0T9q4GF00KjefsQ+PQNDdWQaQ== + +"@types/node@11.11.6": + version "11.11.6" + resolved "https://registry.yarnpkg.com/@types/node/-/node-11.11.6.tgz#df929d1bb2eee5afdda598a41930fe50b43eaa6a" + integrity sha512-Exw4yUWMBXM3X+8oqzJNRqZSwUAaS4+7NdvHqQuFi/d+synz++xmX3QIf+BFqneW8N31R8Ky+sikfZUXq07ggQ== + +"@types/node@>=13.7.0": + version "20.12.2" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.12.2.tgz#9facdd11102f38b21b4ebedd9d7999663343d72e" + integrity sha512-zQ0NYO87hyN6Xrclcqp7f8ZbXNbRfoGWNcMvHTPQp9UUrwI0mI7XBz+cu7/W6/VClYo2g63B0cjull/srU7LgQ== + dependencies: + undici-types "~5.26.4" + +base-x@^3.0.2: + version "3.0.9" + resolved "https://registry.yarnpkg.com/base-x/-/base-x-3.0.9.tgz#6349aaabb58526332de9f60995e548a53fe21320" + integrity sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ== + dependencies: + safe-buffer "^5.0.1" + +base64-js@^1.3.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" + integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== + +bech32@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/bech32/-/bech32-2.0.0.tgz#078d3686535075c8c79709f054b1b226a133b355" + integrity sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg== + +bech32@^1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/bech32/-/bech32-1.1.4.tgz#e38c9f37bf179b8eb16ae3a772b40c356d4832e9" + integrity sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ== + +big-integer@1.6.51: + version "1.6.51" + resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.51.tgz#0df92a5d9880560d3ff2d5fd20245c889d130686" + integrity sha512-GPEid2Y9QU1Exl1rpO9B2IPJGHPSupF5GnVIP0blYvNOMer2bTvSWs1jGOUg04hTmu67nmLsQ9TBo1puaotBHg== + +bignumber.js@9.0.2: + version "9.0.2" + resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.0.2.tgz#71c6c6bed38de64e24a65ebe16cfcf23ae693673" + integrity sha512-GAcQvbpsM0pUb0zw1EI0KhQEZ+lRwR5fYaAp3vPOYuP7aDvGy6cVN6XHLauvF8SOga2y0dcLcjt3iQDTSEliyw== + +bignumber.js@^9.1.2: + version "9.1.2" + resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.1.2.tgz#b7c4242259c008903b13707983b5f4bbd31eda0c" + integrity sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug== + +bindings@^1.3.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + +bip32@2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/bip32/-/bip32-2.0.6.tgz#6a81d9f98c4cd57d05150c60d8f9e75121635134" + integrity sha512-HpV5OMLLGTjSVblmrtYRfFFKuQB+GArM0+XP8HGWfJ5vxYBqo+DesvJwOdC2WJ3bCkZShGf0QIfoIpeomVzVdA== + dependencies: + "@types/node" "10.12.18" + bs58check "^2.1.1" + create-hash "^1.2.0" + create-hmac "^1.1.7" + tiny-secp256k1 "^1.1.3" + typeforce "^1.11.5" + wif "^2.0.6" + +bip39@3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/bip39/-/bip39-3.0.4.tgz#5b11fed966840b5e1b8539f0f54ab6392969b2a0" + integrity sha512-YZKQlb752TrUWqHWj7XAwCSjYEgGAk+/Aas3V7NyjQeZYsztO8JnQUaCWhcnL4T+jL8nvB8typ2jRPzTlgugNw== + dependencies: + "@types/node" "11.11.6" + create-hash "^1.1.0" + pbkdf2 "^3.0.9" + randombytes "^2.0.1" + +bn.js@^4.11.8, bn.js@^4.11.9: + version "4.12.0" + resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.12.0.tgz#775b3f278efbb9718eec7361f483fb36fbbfea88" + integrity sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA== + +bn.js@^5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.1.tgz#0bc527a6a0d18d0aa8d5b0538ce4a77dccfa7b70" + integrity sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ== + +brorand@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" + integrity sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w== + +bs58@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/bs58/-/bs58-4.0.1.tgz#be161e76c354f6f788ae4071f63f34e8c4f0a42a" + integrity sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw== + dependencies: + base-x "^3.0.2" + +bs58check@<3.0.0, bs58check@^2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/bs58check/-/bs58check-2.1.2.tgz#53b018291228d82a5aa08e7d796fdafda54aebfc" + integrity sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA== + dependencies: + bs58 "^4.0.0" + create-hash "^1.1.0" + safe-buffer "^5.1.2" + +cipher-base@^1.0.1, cipher-base@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de" + integrity sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q== + dependencies: + inherits "^2.0.1" + safe-buffer "^5.0.1" + +create-hash@^1.1.0, create-hash@^1.1.2, create-hash@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.2.0.tgz#889078af11a63756bcfb59bd221996be3a9ef196" + integrity sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg== + dependencies: + cipher-base "^1.0.1" + inherits "^2.0.1" + md5.js "^1.3.4" + ripemd160 "^2.0.1" + sha.js "^2.4.0" + +create-hmac@^1.1.4, create-hmac@^1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/create-hmac/-/create-hmac-1.1.7.tgz#69170c78b3ab957147b2b8b04572e47ead2243ff" + integrity sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg== + dependencies: + cipher-base "^1.0.3" + create-hash "^1.1.0" + inherits "^2.0.1" + ripemd160 "^2.0.0" + safe-buffer "^5.0.1" + sha.js "^2.4.8" + +cross-fetch@3.1.5: + version "3.1.5" + resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-3.1.5.tgz#e1389f44d9e7ba767907f7af8454787952ab534f" + integrity sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw== + dependencies: + node-fetch "2.6.7" + +curve25519-js@0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/curve25519-js/-/curve25519-js-0.0.4.tgz#e6ad967e8cd284590d657bbfc90d8b50e49ba060" + integrity sha512-axn2UMEnkhyDUPWOwVKBMVIzSQy2ejH2xRGy1wq81dqRwApXfIzfbE3hIX0ZRFBIihf/KDqK158DLwESu4AK1w== + +elliptic@^6.4.0: + version "6.5.5" + resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.5.tgz#c715e09f78b6923977610d4c2346d6ce22e6dded" + integrity sha512-7EjbcmUm17NQFu4Pmgmq2olYMj8nwMnpcddByChSUjArp8F5DQWcIcpriwO4ZToLNAJig0yiyjswfyGNje/ixw== + dependencies: + bn.js "^4.11.9" + brorand "^1.1.0" + hash.js "^1.0.0" + hmac-drbg "^1.0.1" + inherits "^2.0.4" + minimalistic-assert "^1.0.1" + minimalistic-crypto-utils "^1.0.1" + +esbuild@^0.18.10: + version "0.18.20" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.18.20.tgz#4709f5a34801b43b799ab7d6d82f7284a9b7a7a6" + integrity sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA== + optionalDependencies: + "@esbuild/android-arm" "0.18.20" + "@esbuild/android-arm64" "0.18.20" + "@esbuild/android-x64" "0.18.20" + "@esbuild/darwin-arm64" "0.18.20" + "@esbuild/darwin-x64" "0.18.20" + "@esbuild/freebsd-arm64" "0.18.20" + "@esbuild/freebsd-x64" "0.18.20" + "@esbuild/linux-arm" "0.18.20" + "@esbuild/linux-arm64" "0.18.20" + "@esbuild/linux-ia32" "0.18.20" + "@esbuild/linux-loong64" "0.18.20" + "@esbuild/linux-mips64el" "0.18.20" + "@esbuild/linux-ppc64" "0.18.20" + "@esbuild/linux-riscv64" "0.18.20" + "@esbuild/linux-s390x" "0.18.20" + "@esbuild/linux-x64" "0.18.20" + "@esbuild/netbsd-x64" "0.18.20" + "@esbuild/openbsd-x64" "0.18.20" + "@esbuild/sunos-x64" "0.18.20" + "@esbuild/win32-arm64" "0.18.20" + "@esbuild/win32-ia32" "0.18.20" + "@esbuild/win32-x64" "0.18.20" + +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + +fsevents@~2.3.2: + version "2.3.3" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6" + integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== + +google-protobuf@^3.14.0: + version "3.21.2" + resolved "https://registry.yarnpkg.com/google-protobuf/-/google-protobuf-3.21.2.tgz#4580a2bea8bbb291ee579d1fefb14d6fa3070ea4" + integrity sha512-3MSOYFO5U9mPGikIYCzK0SaThypfGgS6bHqrUGXG3DPHCrb+txNqeEcns1W0lkGfk0rCyNXm7xB9rMxnCiZOoA== + +hash-base@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-3.1.0.tgz#55c381d9e06e1d2997a883b4a3fddfe7f0d3af33" + integrity sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA== + dependencies: + inherits "^2.0.4" + readable-stream "^3.6.0" + safe-buffer "^5.2.0" + +hash.js@^1.0.0, hash.js@^1.0.3: + version "1.1.7" + resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42" + integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA== + dependencies: + inherits "^2.0.3" + minimalistic-assert "^1.0.1" + +hmac-drbg@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" + integrity sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg== + dependencies: + hash.js "^1.0.3" + minimalistic-assert "^1.0.0" + minimalistic-crypto-utils "^1.0.1" + +inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +long@^5.0.0: + version "5.2.3" + resolved "https://registry.yarnpkg.com/long/-/long-5.2.3.tgz#a3ba97f3877cf1d778eccbcb048525ebb77499e1" + integrity sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q== + +md5.js@^1.3.4: + version "1.3.5" + resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f" + integrity sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg== + dependencies: + hash-base "^3.0.0" + inherits "^2.0.1" + safe-buffer "^5.1.2" + +minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" + integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== + +minimalistic-crypto-utils@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" + integrity sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg== + +miscreant@0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/miscreant/-/miscreant-0.3.2.tgz#a91c046566cca70bd6b5e9fbdd3f67617fa85034" + integrity sha512-fL9KxsQz9BJB2KGPMHFrReioywkiomBiuaLk6EuChijK0BsJsIKJXdVomR+/bPj5mvbFD6wM0CM3bZio9g7OHA== + +nan@^2.13.2: + version "2.19.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.19.0.tgz#bb58122ad55a6c5bc973303908d5b16cfdd5a8c0" + integrity sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw== + +nanoid@^3.3.7: + version "3.3.7" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.7.tgz#d0c301a691bc8d54efa0a2226ccf3fe2fd656bd8" + integrity sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g== + +node-fetch@2.6.7: + version "2.6.7" + resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad" + integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ== + dependencies: + whatwg-url "^5.0.0" + +pako@2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pako/-/pako-2.0.4.tgz#6cebc4bbb0b6c73b0d5b8d7e8476e2b2fbea576d" + integrity sha512-v8tweI900AUkZN6heMU/4Uy4cXRc2AYNRggVmTR+dEncawDJgCdLMximOVA2p4qO57WMynangsfGRb5WD6L1Bg== + +pbkdf2@^3.0.9: + version "3.1.2" + resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.1.2.tgz#dd822aa0887580e52f1a039dc3eda108efae3075" + integrity sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA== + dependencies: + create-hash "^1.1.2" + create-hmac "^1.1.4" + ripemd160 "^2.0.1" + safe-buffer "^5.0.1" + sha.js "^2.4.8" + +picocolors@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" + integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== + +postcss@^8.4.27: + version "8.4.38" + resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.38.tgz#b387d533baf2054288e337066d81c6bee9db9e0e" + integrity sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A== + dependencies: + nanoid "^3.3.7" + picocolors "^1.0.0" + source-map-js "^1.2.0" + +protobufjs@7.2.5: + version "7.2.5" + resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-7.2.5.tgz#45d5c57387a6d29a17aab6846dcc283f9b8e7f2d" + integrity sha512-gGXRSXvxQ7UiPgfw8gevrfRWcTlSbOFg+p/N+JVJEK5VhueL2miT6qTymqAmjr1Q5WbOCyJbyrk6JfWKwlFn6A== + dependencies: + "@protobufjs/aspromise" "^1.1.2" + "@protobufjs/base64" "^1.1.2" + "@protobufjs/codegen" "^2.0.4" + "@protobufjs/eventemitter" "^1.1.0" + "@protobufjs/fetch" "^1.1.0" + "@protobufjs/float" "^1.0.2" + "@protobufjs/inquire" "^1.1.0" + "@protobufjs/path" "^1.1.2" + "@protobufjs/pool" "^1.1.0" + "@protobufjs/utf8" "^1.1.0" + "@types/node" ">=13.7.0" + long "^5.0.0" + +randombytes@^2.0.1: + version "2.1.0" + resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" + integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== + dependencies: + safe-buffer "^5.1.0" + +readable-stream@^3.6.0: + version "3.6.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readonly-date@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/readonly-date/-/readonly-date-1.0.0.tgz#5af785464d8c7d7c40b9d738cbde8c646f97dcd9" + integrity sha512-tMKIV7hlk0h4mO3JTmmVuIlJVXjKk3Sep9Bf5OH0O+758ruuVkUy2J9SttDLm91IEX/WHlXPSpxMGjPj4beMIQ== + +ripemd160@^2.0.0, ripemd160@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.2.tgz#a1c1a6f624751577ba5d07914cbc92850585890c" + integrity sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA== + dependencies: + hash-base "^3.0.0" + inherits "^2.0.1" + +rollup@^3.27.1: + version "3.29.4" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-3.29.4.tgz#4d70c0f9834146df8705bfb69a9a19c9e1109981" + integrity sha512-oWzmBZwvYrU0iJHtDmhsm662rC15FRXmcjCk1xD771dFDx5jJ02ufAQQTn0etB2emNk4J9EZg/yWKpsn9BWGRw== + optionalDependencies: + fsevents "~2.3.2" + +rxjs@^7.8.1: + version "7.8.1" + resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.8.1.tgz#6f6f3d99ea8044291efd92e7c7fcf562c4057543" + integrity sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg== + dependencies: + tslib "^2.1.0" + +safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.2, safe-buffer@^5.2.0, safe-buffer@~5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +secretjs@^1.12.1, secretjs@^1.12.5: + version "1.12.5" + resolved "https://registry.yarnpkg.com/secretjs/-/secretjs-1.12.5.tgz#347a1593dfb97610bf4af5c4df5fa90badbeda63" + integrity sha512-JEnvJcfQRuJyu2QtsFQOZ3Vb0sQO8puKV1hK7rVsgROFWHE0s2wSmamTn9SV+hncgRwEtEtGht3Mu1WtQ5xfYA== + dependencies: + "@cosmjs/encoding" "0.27.1" + "@cosmjs/math" "0.27.1" + "@noble/hashes" "1.0.0" + "@noble/secp256k1" "1.7.0" + bech32 "2.0.0" + big-integer "1.6.51" + bignumber.js "9.0.2" + bip32 "2.0.6" + bip39 "3.0.4" + cross-fetch "3.1.5" + curve25519-js "0.0.4" + google-protobuf "^3.14.0" + miscreant "0.3.2" + pako "2.0.4" + protobufjs "7.2.5" + secure-random "1.1.2" + +secure-random@1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/secure-random/-/secure-random-1.1.2.tgz#ed103b460a851632d420d46448b2a900a41e7f7c" + integrity sha512-H2bdSKERKdBV1SwoqYm6C0y+9EA94v6SUBOWO8kDndc4NoUih7Dv6Tsgma7zO1lv27wIvjlD0ZpMQk7um5dheQ== + +sha.js@^2.4.0, sha.js@^2.4.8: + version "2.4.11" + resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.11.tgz#37a5cf0b81ecbc6943de109ba2960d1b26584ae7" + integrity sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ== + dependencies: + inherits "^2.0.1" + safe-buffer "^5.0.1" + +source-map-js@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.2.0.tgz#16b809c162517b5b8c3e7dcd315a2a5c2612b2af" + integrity sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg== + +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + +tiny-secp256k1@^1.1.3: + version "1.1.6" + resolved "https://registry.yarnpkg.com/tiny-secp256k1/-/tiny-secp256k1-1.1.6.tgz#7e224d2bee8ab8283f284e40e6b4acb74ffe047c" + integrity sha512-FmqJZGduTyvsr2cF3375fqGHUovSwDi/QytexX1Se4BPuPZpTE5Ftp5fg+EFSuEf3lhZqgCRjEG3ydUQ/aNiwA== + dependencies: + bindings "^1.3.0" + bn.js "^4.11.8" + create-hmac "^1.1.7" + elliptic "^6.4.0" + nan "^2.13.2" + +tr46@~0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" + integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw== + +tslib@^2.1.0: + version "2.6.2" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.6.2.tgz#703ac29425e7b37cd6fd456e92404d46d1f3e4ae" + integrity sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q== + +typeforce@^1.11.5: + version "1.18.0" + resolved "https://registry.yarnpkg.com/typeforce/-/typeforce-1.18.0.tgz#d7416a2c5845e085034d70fcc5b6cc4a90edbfdc" + integrity sha512-7uc1O8h1M1g0rArakJdf0uLRSSgFcYexrVoKo+bzJd32gd4gDy2L/Z+8/FjPnU9ydY3pEnVPtr9FyscYY60K1g== + +undici-types@~5.26.4: + version "5.26.5" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" + integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== + +util-deprecate@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== + +vite@^4.5.0: + version "4.5.3" + resolved "https://registry.yarnpkg.com/vite/-/vite-4.5.3.tgz#d88a4529ea58bae97294c7e2e6f0eab39a50fb1a" + integrity sha512-kQL23kMeX92v3ph7IauVkXkikdDRsYMGTVl5KY2E9OY4ONLvkHf04MDTbnfo6NKxZiDLWzVpP5oTa8hQD8U3dg== + dependencies: + esbuild "^0.18.10" + postcss "^8.4.27" + rollup "^3.27.1" + optionalDependencies: + fsevents "~2.3.2" + +webidl-conversions@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" + integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ== + +whatwg-fetch@^3.6.19: + version "3.6.20" + resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz#580ce6d791facec91d37c72890995a0b48d31c70" + integrity sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg== + +whatwg-url@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" + integrity sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw== + dependencies: + tr46 "~0.0.3" + webidl-conversions "^3.0.0" + +wif@^2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/wif/-/wif-2.0.6.tgz#08d3f52056c66679299726fade0d432ae74b4704" + integrity sha512-HIanZn1zmduSF+BQhkE+YXIbEiH0xPr1012QbFEGB0xsKqJii0/SqJjyn8dFv6y36kOznMgMB+LGcbZTJ1xACQ== + dependencies: + bs58check "<3.0.0" diff --git a/contracts/headstash-contract/helpers/.eslintignore b/tools/merkleTree/.eslintignore similarity index 100% rename from contracts/headstash-contract/helpers/.eslintignore rename to tools/merkleTree/.eslintignore diff --git a/contracts/headstash-contract/helpers/.eslintrc b/tools/merkleTree/.eslintrc similarity index 100% rename from contracts/headstash-contract/helpers/.eslintrc rename to tools/merkleTree/.eslintrc diff --git a/contracts/headstash-contract/helpers/.gitignore b/tools/merkleTree/.gitignore similarity index 100% rename from contracts/headstash-contract/helpers/.gitignore rename to tools/merkleTree/.gitignore diff --git a/contracts/headstash-contract/helpers/README.md b/tools/merkleTree/README.md similarity index 100% rename from contracts/headstash-contract/helpers/README.md rename to tools/merkleTree/README.md diff --git a/contracts/headstash-contract/helpers/bin/run b/tools/merkleTree/bin/run old mode 100644 new mode 100755 similarity index 100% rename from contracts/headstash-contract/helpers/bin/run rename to tools/merkleTree/bin/run diff --git a/contracts/headstash-contract/helpers/bin/run.cmd b/tools/merkleTree/bin/run.cmd similarity index 100% rename from contracts/headstash-contract/helpers/bin/run.cmd rename to tools/merkleTree/bin/run.cmd diff --git a/contracts/headstash-contract/helpers/package.json b/tools/merkleTree/package.json similarity index 100% rename from contracts/headstash-contract/helpers/package.json rename to tools/merkleTree/package.json diff --git a/contracts/headstash-contract/helpers/src/airdrop.ts b/tools/merkleTree/src/airdrop.ts similarity index 100% rename from contracts/headstash-contract/helpers/src/airdrop.ts rename to tools/merkleTree/src/airdrop.ts diff --git a/contracts/headstash-contract/helpers/src/commands/generateProofs.ts b/tools/merkleTree/src/commands/generateProofs.ts similarity index 100% rename from contracts/headstash-contract/helpers/src/commands/generateProofs.ts rename to tools/merkleTree/src/commands/generateProofs.ts diff --git a/contracts/headstash-contract/helpers/src/commands/generateRoot.ts b/tools/merkleTree/src/commands/generateRoot.ts similarity index 100% rename from contracts/headstash-contract/helpers/src/commands/generateRoot.ts rename to tools/merkleTree/src/commands/generateRoot.ts diff --git a/contracts/headstash-contract/helpers/src/commands/verifyProofs.ts b/tools/merkleTree/src/commands/verifyProofs.ts similarity index 100% rename from contracts/headstash-contract/helpers/src/commands/verifyProofs.ts rename to tools/merkleTree/src/commands/verifyProofs.ts diff --git a/contracts/headstash-contract/helpers/src/index.ts b/tools/merkleTree/src/index.ts similarity index 100% rename from contracts/headstash-contract/helpers/src/index.ts rename to tools/merkleTree/src/index.ts diff --git a/contracts/headstash-contract/helpers/tsconfig.json b/tools/merkleTree/tsconfig.json similarity index 100% rename from contracts/headstash-contract/helpers/tsconfig.json rename to tools/merkleTree/tsconfig.json diff --git a/contracts/headstash-contract/helpers/yarn.lock b/tools/merkleTree/yarn.lock similarity index 100% rename from contracts/headstash-contract/helpers/yarn.lock rename to tools/merkleTree/yarn.lock diff --git a/tools/multisig/broadcast_multi.sh b/tools/multisig/broadcast_multi.sh new file mode 100755 index 0000000..97b2ecd --- /dev/null +++ b/tools/multisig/broadcast_multi.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +# GUIDE: +# Organize all the signatures and the tx to be signed in one directory +# Pass that directory as $1 +# Pass the name of the file to be signed as $2 + + + +cd $1 +res=`ls` +signatures="" +for files in $res +do + if [ $files == signedMultiTx.json ] + then + rm signedMultiTx.json + fi + if [ $files == $2 ] + then + continue + else + signatures=$signatures" "$files + fi +done + +secretd tx multisign $2 ss_multisig $signatures --chain-id secret-4 > signedMultiTx.json +secretd tx broadcast signedMultiTx.json diff --git a/tools/multisig/sign_mutli.sh b/tools/multisig/sign_mutli.sh new file mode 100755 index 0000000..f0b059c --- /dev/null +++ b/tools/multisig/sign_mutli.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# example: ./multisig.sh secret1y277c499f44nxe7geeaqw8t6gpge68rcpla9lf ~/json/output.json jsledger + +secretd config node https://rpc.scrt.network:443 +secretd config chain-id secret-4 +res=`secretd q account $1` +eval sequence=`echo $res | jq ".sequence"` +eval acc_num=`echo $res | jq ".account_number"` +outputdoc="signature_$3.json" +secretd tx sign $2 --multisig ss_multisig --from $3 --output-document $outputdoc --chain-id secret-4 --offline --sequence $sequence --account-number $acc_num --sign-mode amino-json diff --git a/tools/multisig/sign_permit.py b/tools/multisig/sign_permit.py new file mode 100644 index 0000000..6cd8c57 --- /dev/null +++ b/tools/multisig/sign_permit.py @@ -0,0 +1,36 @@ +import argparse +import os + +parser = argparse.ArgumentParser(description="Create a cosmwasm msg for offline signing") + +parser.add_argument("msg", type=str, help="Permit data") +parser.add_argument("account", type=str, help="Permit signer") +parser.add_argument("--account_number", type=str, help="Account number", default="0") +parser.add_argument("--chain_id", type=str, help="Chain id to which this permit is written for", default="secret-4") +parser.add_argument("--memo", type=str, help="Memo for the permit", default="") +parser.add_argument("--msg_type", type=str, help="Msg type used on the signed msg", default="signature_proof") +parser.add_argument("--sequence", type=str, help="Signature sequence number", default="0") + +parser.add_argument("-o", "--output", type=str, help="Output message") +parser.add_argument("--use_old", action="store_true", help="Uses secretcli instead of secretd") +args = parser.parse_args() + +bin = "secretd" + +if args.use_old: + bin = "secretcli" + +output = "signed.json" + +if args.output: + output = args.output + +unsigned_permit = f'echo \' {{ "account_number": "{args.account_number}", ' \ + f'"chain_id": "{args.chain_id}", ' \ + f'"fee": {{ "amount": [{{ "amount": "0", "denom": "uscrt"}}], "gas": "1" }}, ' \ + f'"memo": "{args.memo}", "msgs": [{{ "type": "{args.msg_type}", "value": {args.msg} }}], ' \ + f'"sequence": "{args.sequence}"}} \'> unsigned.json' +os.system(unsigned_permit) + +command = f'{bin} tx sign-doc unsigned.json --from {args.account} > {output}' +os.system(command) \ No newline at end of file diff --git a/tools/multisig/wasm_msg.py b/tools/multisig/wasm_msg.py new file mode 100644 index 0000000..197461a --- /dev/null +++ b/tools/multisig/wasm_msg.py @@ -0,0 +1,25 @@ +import argparse +import os + +parser = argparse.ArgumentParser(description="Create a cosmwasm msg for offline signing") +parser.add_argument("contract_address", type=str, help="Smart contract's address") +parser.add_argument("contract_codehash", type=str, help="Smart contract's code hash") +parser.add_argument("msg", type=str, help="Smart contract's msg to execute") +parser.add_argument("sender", type=str, help="The msg sender") +parser.add_argument("key", type=str, help="Enclave key certificate") +parser.add_argument("-o", "--output", type=str, help="Output message") +parser.add_argument("--use_old", action="store_true", help="Uses secretcli instead of secretd") +args = parser.parse_args() + +bin = "secretd" + +if args.use_old: + bin = "secretcli" + +output = "output.json" + +if args.output: + output = args.output + +command = f"{bin} tx compute execute {args.contract_address} '{args.msg}' --from {args.sender} --generate-only --enclave-key {args.key} --code-hash {args.contract_codehash} --offline --sign-mode amino-json > {output}" +os.system(command) \ No newline at end of file