diff --git a/.github/workflows/cargo-audit.yml b/.github/workflows/cargo-audit.yml index 5ced91529c..86dc1b0f78 100644 --- a/.github/workflows/cargo-audit.yml +++ b/.github/workflows/cargo-audit.yml @@ -13,7 +13,7 @@ concurrency: jobs: cargo-audit: name: cargo audit - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-cargo-audit') }} steps: - name: Check-out repositoroy under $GITHUB_WORKSPACE @@ -21,8 +21,13 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -38,12 +43,6 @@ jobs: - name: cargo audit run: | - cargo audit --ignore RUSTSEC-2024-0336 \ - --ignore RUSTSEC-2021-0127 \ - --ignore RUSTSEC-2024-0370 \ - --ignore RUSTSEC-2022-0080 \ - --ignore RUSTSEC-2022-0061 \ - --ignore RUSTSEC-2020-0168 \ - --ignore RUSTSEC-2024-0384 \ - --ignore RUSTSEC-2024-0388 \ - --ignore RUSTSEC-2024-0421 + cargo audit --ignore RUSTSEC-2023-0091 \ + --ignore RUSTSEC-2025-0009 \ + --ignore RUSTSEC-2024-0438 diff --git a/.github/workflows/check-bittensor-e2e-tests.yml.yml b/.github/workflows/check-bittensor-e2e-tests.yml.yml index fcaaf9ff0f..54ca03e775 100644 --- a/.github/workflows/check-bittensor-e2e-tests.yml.yml +++ b/.github/workflows/check-bittensor-e2e-tests.yml.yml @@ -26,10 +26,15 @@ env: jobs: check-label: - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] outputs: skip-bittensor-e2e-tests: ${{ steps.get-labels.outputs.skip-bittensor-e2e-tests }} steps: + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" gh jq + - name: Check out repository uses: actions/checkout@v4 with: @@ -52,10 +57,15 @@ jobs: find-btcli-e2e-tests: needs: check-label if: needs.check-label.outputs.skip-bittensor-e2e-tests == 'false' - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] outputs: test-files: ${{ steps.get-btcli-tests.outputs.test-files }} steps: + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" jq + - name: Research preparation working-directory: ${{ github.workspace }} run: git clone https://github.com/opentensor/btcli.git @@ -64,9 +74,6 @@ jobs: working-directory: ${{ github.workspace }}/btcli run: git checkout staging - - name: Install dependencies - run: sudo apt-get install -y jq - - name: Find e2e test files id: get-btcli-tests run: | @@ -77,10 +84,15 @@ jobs: find-sdk-e2e-tests: needs: check-label if: needs.check-label.outputs.skip-bittensor-e2e-tests == 'false' - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] outputs: test-files: ${{ steps.get-sdk-tests.outputs.test-files }} steps: + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" jq + - name: Research preparation working-directory: ${{ github.workspace }} run: git clone https://github.com/opentensor/bittensor.git @@ -89,9 +101,6 @@ jobs: working-directory: ${{ github.workspace }}/bittensor run: git checkout staging - - name: Install dependencies - run: sudo apt-get install -y jq - - name: Find e2e test files id: get-sdk-tests run: | @@ -101,7 +110,7 @@ jobs: build-image-with-current-branch: needs: check-label - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Checkout code uses: actions/checkout@v4 @@ -139,7 +148,7 @@ jobs: - find-btcli-e2e-tests - build-image-with-current-branch if: needs.check-label.outputs.skip-bittensor-e2e-tests == 'false' - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] strategy: fail-fast: false max-parallel: 16 @@ -175,7 +184,7 @@ jobs: - name: Create Python virtual environment working-directory: ${{ github.workspace }} - run: uv venv ${{ github.workspace }}/venv + run: uv venv --seed ${{ github.workspace }}/venv - name: Clone Bittensor CLI repo working-directory: ${{ github.workspace }} @@ -239,7 +248,7 @@ jobs: - find-sdk-e2e-tests - build-image-with-current-branch if: needs.check-label.outputs.skip-bittensor-e2e-tests == 'false' - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] strategy: fail-fast: false max-parallel: 16 @@ -275,7 +284,7 @@ jobs: - name: Create Python virtual environment working-directory: ${{ github.workspace }} - run: uv venv ${{ github.workspace }}/venv + run: uv venv --seed ${{ github.workspace }}/venv - name: Clone Bittensor SDK repo working-directory: ${{ github.workspace }} diff --git a/.github/workflows/check-devnet.yml b/.github/workflows/check-devnet.yml index 867102a315..8d3db55001 100644 --- a/.github/workflows/check-devnet.yml +++ b/.github/workflows/check-devnet.yml @@ -4,6 +4,10 @@ on: pull_request: branches: [devnet, devnet-ready] types: [labeled, unlabeled, synchronize, opened] + +concurrency: + group: check-devnet-${{ github.ref }} + cancel-in-progress: true env: CARGO_TERM_COLOR: always @@ -11,14 +15,18 @@ env: jobs: check-spec-version: name: Check spec_version bump - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] if: ${{ !contains(github.event.pull_request.labels.*.name, 'no-spec-version-bump') }} steps: - name: Dependencies run: | - sudo apt-get update && - sudo apt-get install -y curl clang curl libssl-dev llvm \ - libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Check-out repository under $GITHUB_WORKSPACE uses: actions/checkout@v4 @@ -38,7 +46,7 @@ jobs: spec_version=$(PATH=$PATH:$HOME/.cargo/.bin substrate-spec-version wss://dev.chain.opentensor.ai:443 | tr -d '\n') echo "network spec_version: $spec_version" : ${spec_version:?bad spec version} - local_spec_version=$(cargo run -p node-subtensor-runtime --bin spec_version | tr -d '\n') + local_spec_version=$(cargo run -p subtensor-tools --bin spec-version | tr -d '\n') echo "local spec_version: $local_spec_version" echo "network spec_version: $spec_version" if (( $(echo "$local_spec_version <= $spec_version" | bc -l) )); then echo "$local_spec_version ≯ $spec_version ❌"; exit 1; fi diff --git a/.github/workflows/check-docker.yml b/.github/workflows/check-docker.yml index 0cf17bfcf8..da5054fd6d 100644 --- a/.github/workflows/check-docker.yml +++ b/.github/workflows/check-docker.yml @@ -2,10 +2,14 @@ name: Build Docker Image on: pull_request: + +concurrency: + group: check-docker-${{ github.ref }} + cancel-in-progress: true jobs: build: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Checkout code diff --git a/.github/workflows/check-finney.yml b/.github/workflows/check-finney.yml index 4a99df7868..6b056ef97e 100644 --- a/.github/workflows/check-finney.yml +++ b/.github/workflows/check-finney.yml @@ -4,6 +4,10 @@ on: pull_request: branches: [finney, main] types: [labeled, unlabeled, synchronize, opened] + +concurrency: + group: check-finney-${{ github.ref }} + cancel-in-progress: true env: CARGO_TERM_COLOR: always @@ -11,14 +15,18 @@ env: jobs: check-spec-version: name: Check spec_version bump - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] if: ${{ !contains(github.event.pull_request.labels.*.name, 'no-spec-version-bump') }} steps: - name: Dependencies run: | - sudo apt-get update && - sudo apt-get install -y curl clang curl libssl-dev llvm \ - libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Check-out repository under $GITHUB_WORKSPACE uses: actions/checkout@v4 @@ -36,7 +44,7 @@ jobs: spec_version=$(PATH=$PATH:$HOME/.cargo/.bin substrate-spec-version wss://entrypoint-finney.opentensor.ai:443 | tr -d '\n') echo "network spec_version: $spec_version" : ${spec_version:?bad spec version} - local_spec_version=$(cargo run -p node-subtensor-runtime --bin spec_version | tr -d '\n') + local_spec_version=$(cargo run -p subtensor-tools --bin spec-version | tr -d '\n') echo "local spec_version: $local_spec_version" echo "network spec_version: $spec_version" if (( $(echo "$local_spec_version <= $spec_version" | bc -l) )); then echo "$local_spec_version ≯ $spec_version ❌"; exit 1; fi diff --git a/.github/workflows/check-rust.yml b/.github/workflows/check-rust.yml index 6206f7efa2..6cdc56f26a 100644 --- a/.github/workflows/check-rust.yml +++ b/.github/workflows/check-rust.yml @@ -23,7 +23,7 @@ jobs: # runs cargo fmt cargo-fmt: name: cargo fmt - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] env: RUST_BACKTRACE: full steps: @@ -31,12 +31,15 @@ jobs: uses: actions/checkout@v4 - name: Install dependencies - run: sudo apt-get update && sudo apt-get install -y build-essential + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential - name: Install Rust Nightly - run: | - rustup install nightly - rustup component add --toolchain nightly-x86_64-unknown-linux-gnu rustfmt + uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + components: rustfmt - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -49,7 +52,7 @@ jobs: cargo-clippy-default-features: name: cargo clippy - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] env: RUST_BACKTRACE: full SKIP_WASM_BUILD: 1 @@ -59,8 +62,14 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + components: clippy - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -73,7 +82,7 @@ jobs: cargo-check-lints: name: check custom lints - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] env: RUSTFLAGS: -D warnings RUST_BACKTRACE: full @@ -84,8 +93,13 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -101,7 +115,7 @@ jobs: cargo-clippy-all-features: name: cargo clippy --all-features - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] env: RUST_BACKTRACE: full SKIP_WASM_BUILD: 1 @@ -111,8 +125,14 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + components: clippy - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -126,7 +146,7 @@ jobs: # runs cargo test --workspace --all-features cargo-test: name: cargo test - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx43] env: RUST_BACKTRACE: full SKIP_WASM_BUILD: 1 @@ -136,8 +156,13 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -151,7 +176,7 @@ jobs: # ensures cargo fix has no trivial changes that can be applied cargo-fix: name: cargo fix - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] env: RUST_BACKTRACE: full SKIP_WASM_BUILD: 1 @@ -161,8 +186,13 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -185,7 +215,7 @@ jobs: check-feature-propagation: name: zepter run check - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] steps: - name: Checkout @@ -193,6 +223,16 @@ jobs: with: fetch-depth: 0 # Dont clone historic commits. + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 with: diff --git a/.github/workflows/check-testnet.yml b/.github/workflows/check-testnet.yml index 919af25637..219d99051f 100644 --- a/.github/workflows/check-testnet.yml +++ b/.github/workflows/check-testnet.yml @@ -5,20 +5,28 @@ on: branches: [testnet, testnet-ready] types: [labeled, unlabeled, synchronize, opened] +concurrency: + group: check-testnet-${{ github.ref }} + cancel-in-progress: true + env: CARGO_TERM_COLOR: always jobs: check-spec-version: name: Check spec_version bump - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] if: ${{ !contains(github.event.pull_request.labels.*.name, 'no-spec-version-bump') }} steps: - name: Dependencies run: | - sudo apt-get update && - sudo apt-get install -y curl clang curl libssl-dev llvm \ - libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Check-out repository under $GITHUB_WORKSPACE uses: actions/checkout@v4 @@ -37,7 +45,7 @@ jobs: spec_version=$(PATH=$PATH:$HOME/.cargo/.bin substrate-spec-version wss://test.finney.opentensor.ai:443 | tr -d '\n') echo "network spec_version: $spec_version" : ${spec_version:?bad spec version} - local_spec_version=$(cargo run -p node-subtensor-runtime --bin spec_version | tr -d '\n') + local_spec_version=$(cargo run -p subtensor-tools --bin spec-version | tr -d '\n') echo "local spec_version: $local_spec_version" echo "network spec_version: $spec_version" if (( $(echo "$local_spec_version <= $spec_version" | bc -l) )); then echo "$local_spec_version ≯ $spec_version ❌"; exit 1; fi diff --git a/.github/workflows/docker-localnet.yml b/.github/workflows/docker-localnet.yml index b8e2f3eb09..96f3ca56a0 100644 --- a/.github/workflows/docker-localnet.yml +++ b/.github/workflows/docker-localnet.yml @@ -15,6 +15,10 @@ on: - main - testnet - devnet + +concurrency: + group: docker-localnet-${{ github.ref }} + cancel-in-progress: true permissions: contents: read @@ -24,7 +28,7 @@ permissions: jobs: publish: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Determine Docker tag and ref diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 6bc8c03132..f0cfd84853 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -14,6 +14,10 @@ on: - devnet-ready - devnet - testnet + +concurrency: + group: docker-${{ github.ref }} + cancel-in-progress: true permissions: contents: read @@ -23,7 +27,7 @@ permissions: jobs: publish: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Determine Docker tag and ref diff --git a/.github/workflows/evm-tests.yml b/.github/workflows/evm-tests.yml index 355e2b873f..7df1eb9733 100644 --- a/.github/workflows/evm-tests.yml +++ b/.github/workflows/evm-tests.yml @@ -11,19 +11,31 @@ on: required: false default: "" +concurrency: + group: evm-tests-${{ github.ref }} + cancel-in-progress: true + env: CARGO_TERM_COLOR: always VERBOSE: ${{ github.events.input.verbose }} +permissions: + contents: read + jobs: run: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] env: RUST_BACKTRACE: full steps: - name: Check-out repository under $GITHUB_WORKSPACE uses: actions/checkout@v4 + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 @@ -34,11 +46,16 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler nodejs + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler nodejs pkg-config - name: Run tests - working-directory: ${{ github.workspace }} - run: | - npm install --global yarn - ./evm-tests/run-ci.sh + uses: nick-fields/retry@v3 + with: + timeout_minutes: 60 + max_attempts: 3 + retry_wait_seconds: 60 + command: | + cd ${{ github.workspace }} + npm install --global yarn + ./evm-tests/run-ci.sh diff --git a/.github/workflows/hotfixes.yml b/.github/workflows/hotfixes.yml index 5292747692..7fcf28efb6 100644 --- a/.github/workflows/hotfixes.yml +++ b/.github/workflows/hotfixes.yml @@ -10,7 +10,7 @@ permissions: jobs: handle-hotfix-pr: - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] steps: - name: Check if PR is a hotfix into `main` if: > @@ -19,6 +19,11 @@ jobs: run: | echo "Hotfix PR detected. Proceeding to label and comment." + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" curl jq + - name: Add `hotfix` label if: > github.event.pull_request.base.ref == 'main' && diff --git a/.github/workflows/label-triggers.yml b/.github/workflows/label-triggers.yml index bcf43e4c23..8c7803b2e3 100644 --- a/.github/workflows/label-triggers.yml +++ b/.github/workflows/label-triggers.yml @@ -13,7 +13,7 @@ permissions: jobs: comment_on_breaking_change: - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] steps: - name: Check if 'breaking change' label is added if: github.event.label.name == 'breaking-change' diff --git a/.github/workflows/require-clean-merges.yml b/.github/workflows/require-clean-merges.yml index ac0a5f31fe..dd7a8829e7 100644 --- a/.github/workflows/require-clean-merges.yml +++ b/.github/workflows/require-clean-merges.yml @@ -9,7 +9,7 @@ on: jobs: assert-clean-merges: - runs-on: ubuntu-latest + runs-on: [self-hosted, type-ccx13] steps: - name: Checkout Repository uses: actions/checkout@v4 diff --git a/.github/workflows/run-benchmarks.yml b/.github/workflows/run-benchmarks.yml index fbdcd8e5c0..4d814c766b 100644 --- a/.github/workflows/run-benchmarks.yml +++ b/.github/workflows/run-benchmarks.yml @@ -16,7 +16,7 @@ concurrency: jobs: validate-benchmarks: - runs-on: Benchmarking + runs-on: [self-hosted, type-ccx33] env: SKIP_BENCHMARKS: "0" @@ -35,8 +35,8 @@ jobs: - name: Install GitHub CLI if: ${{ env.SKIP_BENCHMARKS != '1' }} run: | - sudo apt-get update - sudo apt-get install -y gh + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" gh echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token # (1) — first skip‑label check @@ -54,8 +54,8 @@ jobs: - name: Install system dependencies if: ${{ env.SKIP_BENCHMARKS != '1' }} run: | - sudo apt-get update - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config # (2) - name: Check skip label @@ -126,9 +126,14 @@ jobs: - name: Run & validate benchmarks if: ${{ env.SKIP_BENCHMARKS != '1' }} - run: | - chmod +x scripts/benchmark_action.sh - scripts/benchmark_action.sh + uses: nick-fields/retry@v3 + with: + timeout_minutes: 180 + max_attempts: 3 + retry_wait_seconds: 60 + command: | + chmod +x scripts/benchmark_action.sh + scripts/benchmark_action.sh # (6) — final check after run - name: Check skip label after run diff --git a/.github/workflows/rustdocs.yml b/.github/workflows/rustdocs.yml index 61d23644a1..5b3b1d5baf 100644 --- a/.github/workflows/rustdocs.yml +++ b/.github/workflows/rustdocs.yml @@ -6,17 +6,26 @@ on: - main workflow_dispatch: +concurrency: + group: rustdocs-${{ github.ref }} + cancel-in-progress: true + env: CARGO_TERM_COLOR: always jobs: build: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] steps: - name: Checkout code uses: actions/checkout@v3 + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + - name: Install rustup uses: actions-rs/toolchain@v1 with: @@ -45,7 +54,7 @@ jobs: deploy: needs: build - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx13] permissions: pages: write diff --git a/.github/workflows/try-runtime.yml b/.github/workflows/try-runtime.yml index 13383feb9b..98fa613d6a 100644 --- a/.github/workflows/try-runtime.yml +++ b/.github/workflows/try-runtime.yml @@ -3,6 +3,10 @@ name: Try Runtime on: pull_request: +concurrency: + group: try-runtime-${{ github.ref }} + cancel-in-progress: true + env: CARGO_TERM_COLOR: always @@ -10,11 +14,21 @@ jobs: check-devnet: name: check devnet if: github.base_ref != 'main' - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Checkout sources uses: actions/checkout@v4 + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config unzip + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 with: @@ -31,11 +45,21 @@ jobs: check-testnet: name: check testnet if: github.base_ref != 'main' - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Checkout sources uses: actions/checkout@v4 + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config unzip + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 with: @@ -52,11 +76,21 @@ jobs: check-finney: name: check finney # if: github.base_ref == 'testnet' || github.base_ref == 'devnet' || github.base_ref == 'main' - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] steps: - name: Checkout sources uses: actions/checkout@v4 + - name: Install dependencies + run: | + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler pkg-config unzip + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 with: diff --git a/.github/workflows/update-chainspec.yml b/.github/workflows/update-chainspec.yml index 1aedfeaa4a..ad7f0fc943 100644 --- a/.github/workflows/update-chainspec.yml +++ b/.github/workflows/update-chainspec.yml @@ -5,8 +5,6 @@ concurrency: cancel-in-progress: true on: - pull_request: - workflow_dispatch: inputs: verbose: @@ -20,7 +18,7 @@ env: jobs: update-chainspecs: - runs-on: SubtensorCI + runs-on: [self-hosted, type-ccx33] permissions: contents: write if: > @@ -37,8 +35,13 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update + sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" build-essential clang curl libssl-dev llvm libudev-dev protobuf-compiler pkg-config + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable - name: Utilize Shared Rust Cache uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index 2e8bd3f74f..f70c3dc20c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -246,7 +246,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb00293ba84f51ce3bd026bd0de55899c4e68f0a39a5728cebae3a73ffdc0a4f" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-std 0.4.0", ] @@ -258,7 +258,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20c7021f180a0cbea0380eba97c2af3c57074cdaffe0eef7e840e1c9f2841e55" dependencies = [ "ark-bls12-377", - "ark-ec", + "ark-ec 0.4.2", "ark-models-ext", "ark-std 0.4.0", ] @@ -269,20 +269,32 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c775f0d12169cba7aae4caeb547bb6a50781c7449a8aa53793827c9ec4abf488" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", ] +[[package]] +name = "ark-bls12-381" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", +] + [[package]] name = "ark-bls12-381-ext" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1dc4b3d08f19e8ec06e949712f95b8361e43f1391d94f65e4234df03480631c" dependencies = [ - "ark-bls12-381", - "ark-ec", + "ark-bls12-381 0.4.0", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-models-ext", "ark-serialize 0.4.2", @@ -296,7 +308,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e0605daf0cc5aa2034b78d008aaf159f56901d92a52ee4f6ecdfdac4f426700" dependencies = [ "ark-bls12-377", - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-std 0.4.0", ] @@ -308,7 +320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccee5fba47266f460067588ee1bf070a9c760bf2050c1c509982c5719aadb4f2" dependencies = [ "ark-bw6-761", - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-models-ext", "ark-std 0.4.0", @@ -320,7 +332,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3a13b34da09176a8baba701233fdffbaa7c1b1192ce031a3da4e55ce1f1a56" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-r1cs-std", "ark-relations", @@ -341,7 +353,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "defd9a439d56ac24968cca0571f598a61bc8c55f71d50a89cda591cb750670ba" dependencies = [ "ark-ff 0.4.2", - "ark-poly", + "ark-poly 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", "derivative", @@ -352,6 +364,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" +dependencies = [ + "ahash 0.8.12", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.4", + "itertools 0.13.0", + "num-bigint", + "num-integer", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ed-on-bls12-377" version = "0.4.0" @@ -359,7 +392,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b10d901b9ac4b38f9c32beacedfadcdd64e46f8d7f8e88c1ae1060022cf6f6c6" dependencies = [ "ark-bls12-377", - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-std 0.4.0", ] @@ -370,7 +403,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524a4fb7540df2e1a8c2e67a83ba1d1e6c3947f4f9342cc2359fc2e789ad731d" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ed-on-bls12-377", "ark-ff 0.4.2", "ark-models-ext", @@ -383,20 +416,32 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9cde0f2aa063a2a5c28d39b47761aa102bda7c13c84fc118a61b87c7b2f785c" dependencies = [ - "ark-bls12-381", - "ark-ec", + "ark-bls12-381 0.4.0", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-std 0.4.0", ] +[[package]] +name = "ark-ed-on-bls12-381-bandersnatch" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1786b2e3832f6f0f7c8d62d5d5a282f6952a1ab99981c54cd52b6ac1d8f02df5" +dependencies = [ + "ark-bls12-381 0.5.0", + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-std 0.5.0", +] + [[package]] name = "ark-ed-on-bls12-381-bandersnatch-ext" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d15185f1acb49a07ff8cbe5f11a1adc5a93b19e211e325d826ae98e98e124346" dependencies = [ - "ark-ec", - "ark-ed-on-bls12-381-bandersnatch", + "ark-ec 0.4.2", + "ark-ed-on-bls12-381-bandersnatch 0.4.0", "ark-ff 0.4.2", "ark-models-ext", "ark-std 0.4.0", @@ -440,6 +485,26 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ff" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" +dependencies = [ + "ark-ff-asm 0.5.0", + "ark-ff-macros 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "arrayvec 0.7.6", + "digest 0.10.7", + "educe", + "itertools 0.13.0", + "num-bigint", + "num-traits", + "paste", + "zeroize", +] + [[package]] name = "ark-ff-asm" version = "0.3.0" @@ -460,6 +525,16 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-ff-asm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60" +dependencies = [ + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-ff-macros" version = "0.3.0" @@ -485,13 +560,26 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-ff-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-models-ext" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e9eab5d4b5ff2f228b763d38442adc9b084b0a465409b059fac5c2308835ec2" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", @@ -511,13 +599,28 @@ dependencies = [ "hashbrown 0.13.2", ] +[[package]] +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" +dependencies = [ + "ahash 0.8.12", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.4", +] + [[package]] name = "ark-r1cs-std" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de1d1472e5cb020cb3405ce2567c91c8d43f21b674aef37b0202f5c3304761db" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-relations", "ark-std 0.4.0", @@ -546,7 +649,7 @@ version = "0.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51bd73bb6ddb72630987d37fa963e99196896c0d0ea81b7c894567e74a2f83af" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", @@ -560,7 +663,7 @@ version = "0.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f69c00b3b529be29528a6f2fd5fa7b1790f8bed81b9cdca17e326538545a179" dependencies = [ - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", @@ -584,12 +687,25 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ - "ark-serialize-derive", + "ark-serialize-derive 0.4.2", "ark-std 0.4.0", "digest 0.10.7", "num-bigint", ] +[[package]] +name = "ark-serialize" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" +dependencies = [ + "ark-serialize-derive 0.5.0", + "ark-std 0.5.0", + "arrayvec 0.7.6", + "digest 0.10.7", + "num-bigint", +] + [[package]] name = "ark-serialize-derive" version = "0.4.2" @@ -601,6 +717,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-snark" version = "0.4.0" @@ -634,6 +761,49 @@ dependencies = [ "rayon", ] +[[package]] +name = "ark-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" +dependencies = [ + "num-traits", + "rand 0.8.5", +] + +[[package]] +name = "ark-transcript" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47c1c928edb9d8ff24cb5dcb7651d3a98494fff3099eee95c2404cd813a9139f" +dependencies = [ + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "digest 0.10.7", + "rand_core 0.6.4", + "sha3", +] + +[[package]] +name = "ark-vrf" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9501da18569b2afe0eb934fb7afd5a247d238b94116155af4dd068f319adfe6d" +dependencies = [ + "ark-bls12-381 0.5.0", + "ark-ec 0.5.0", + "ark-ed-on-bls12-381-bandersnatch 0.5.0", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "digest 0.10.7", + "rand_chacha 0.3.1", + "sha2 0.10.9", + "w3f-ring-proof", + "zeroize", +] + [[package]] name = "array-bytes" version = "6.2.3" @@ -663,12 +833,12 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "asn1-rs" -version = "0.5.2" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" +checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" dependencies = [ - "asn1-rs-derive 0.4.0", - "asn1-rs-impl 0.1.0", + "asn1-rs-derive 0.5.1", + "asn1-rs-impl", "displaydoc", "nom", "num-traits", @@ -684,7 +854,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" dependencies = [ "asn1-rs-derive 0.6.0", - "asn1-rs-impl 0.2.0", + "asn1-rs-impl", "displaydoc", "nom", "num-traits", @@ -695,14 +865,14 @@ dependencies = [ [[package]] name = "asn1-rs-derive" -version = "0.4.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" +checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", - "synstructure 0.12.6", + "syn 2.0.104", + "synstructure 0.13.2", ] [[package]] @@ -717,17 +887,6 @@ dependencies = [ "synstructure 0.13.2", ] -[[package]] -name = "asn1-rs-impl" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "asn1-rs-impl" version = "0.2.0" @@ -784,9 +943,9 @@ dependencies = [ [[package]] name = "async-fs" -version = "2.1.2" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebcd09b382f40fcd159c2d695175b2ae620ffa5f3bd6f664131efff4e8b9e04a" +checksum = "09f7e37c0ed80b2a977691c47dae8625cfb21e205827106c64f7c588766b2e50" dependencies = [ "async-lock", "blocking", @@ -795,9 +954,9 @@ dependencies = [ [[package]] name = "async-io" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1237c0ae75a0f3765f58910ff9cdd0a12eeb39ab2f4c7de23262f337f0aacbb3" +checksum = "19634d6336019ef220f09fd31168ce5c184b295cbf80345437cc36094ef223ca" dependencies = [ "async-lock", "cfg-if", @@ -808,8 +967,7 @@ dependencies = [ "polling", "rustix 1.0.8", "slab", - "tracing", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -836,9 +994,9 @@ dependencies = [ [[package]] name = "async-process" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde3f4e40e6021d7acffc90095cbd6dc54cb593903d1de5832f435eb274b85dc" +checksum = "65daa13722ad51e6ab1a1b9c01299142bc75135b337923cfa10e79bbbd669f00" dependencies = [ "async-channel 2.5.0", "async-io", @@ -850,14 +1008,13 @@ dependencies = [ "event-listener 5.4.0", "futures-lite", "rustix 1.0.8", - "tracing", ] [[package]] name = "async-signal" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7605a4e50d4b06df3898d5a70bf5fde51ed9059b0434b73105193bc27acce0d" +checksum = "f567af260ef69e1d52c2b560ce0ea230763e6fbb9214a85d768760a920e3e3c1" dependencies = [ "async-io", "async-lock", @@ -868,7 +1025,7 @@ dependencies = [ "rustix 1.0.8", "signal-hook-registry", "slab", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -901,6 +1058,19 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "asynchronous-codec" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" +dependencies = [ + "bytes", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite", +] + [[package]] name = "atoi" version = "2.0.0" @@ -983,12 +1153,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6107fe1be6682a68940da878d9e9f5e90ca5745b3dec9fd1bb393c8777d4f581" -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - [[package]] name = "base64" version = "0.21.7" @@ -1007,19 +1171,10 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" -[[package]] -name = "beef" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" -dependencies = [ - "serde", -] - [[package]] name = "binary-merkle-tree" version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "hash-db", "log", @@ -1079,7 +1234,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43d193de1f7487df1914d3a568b772458861d33f9c54249612cc2893d6915054" dependencies = [ - "bitcoin_hashes", + "bitcoin_hashes 0.13.0", "serde", "unicode-normalization", ] @@ -1105,6 +1260,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9425c3bf7089c983facbae04de54513cce73b41c7f9ff8c845b54e7bc64ebbfb" +[[package]] +name = "bitcoin-io" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf" + [[package]] name = "bitcoin_hashes" version = "0.13.0" @@ -1112,7 +1273,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1930a4dabfebb8d7d9992db18ebe3ae2876f0a305fab206fd168df931ede293b" dependencies = [ "bitcoin-internals", - "hex-conservative", + "hex-conservative 0.1.2", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16" +dependencies = [ + "bitcoin-io", + "hex-conservative 0.2.1", ] [[package]] @@ -1373,9 +1544,9 @@ checksum = "fd6c0e7b807d60291f42f33f58480c0bfafe28ed08286446f45e463728cf9c1c" [[package]] name = "cc" -version = "1.2.29" +version = "1.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1599538de2394445747c8cf7935946e3cc27e9625f889d979bfb2aaf569362" +checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" dependencies = [ "jobserver", "libc", @@ -1531,9 +1702,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" +checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882" dependencies = [ "clap_builder", "clap_derive", @@ -1541,14 +1712,14 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.41" +version = "4.5.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" +checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966" dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim 0.11.1", + "strsim", "terminal_size", ] @@ -1717,12 +1888,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" -[[package]] -name = "constcat" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7e35aee659887cbfb97aaf227ac12cad1a9d7c71e55ff3376839ed4e282d08" - [[package]] name = "convert_case" version = "0.4.0" @@ -1979,7 +2144,7 @@ checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array 0.14.7", "rand_core 0.6.4", - "typenum 1.18.0", + "typenum", ] [[package]] @@ -2002,6 +2167,21 @@ dependencies = [ "subtle 2.6.1", ] +[[package]] +name = "crypto_secretbox" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1" +dependencies = [ + "aead", + "cipher 0.4.4", + "generic-array 0.14.7", + "poly1305", + "salsa20", + "subtle 2.6.1", + "zeroize", +] + [[package]] name = "ctr" version = "0.9.2" @@ -2013,8 +2193,8 @@ dependencies = [ [[package]] name = "cumulus-client-parachain-inherent" -version = "0.15.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.16.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -2023,20 +2203,18 @@ dependencies = [ "cumulus-test-relay-sproof-builder", "parity-scale-codec", "sc-client-api", - "sp-api", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-inherents", "sp-runtime", "sp-state-machine", "sp-storage 22.0.0", - "sp-trie", "tracing", ] [[package]] name = "cumulus-primitives-core" -version = "0.17.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.18.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "polkadot-core-primitives", @@ -2051,8 +2229,8 @@ dependencies = [ [[package]] name = "cumulus-primitives-parachain-inherent" -version = "0.17.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.18.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "cumulus-primitives-core", @@ -2065,18 +2243,18 @@ dependencies = [ [[package]] name = "cumulus-primitives-proof-size-hostfunction" -version = "0.11.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.12.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "sp-externalities 0.30.0", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-trie", ] [[package]] name = "cumulus-primitives-storage-weight-reclaim" -version = "9.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "11.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "cumulus-primitives-core", "cumulus-primitives-proof-size-hostfunction", @@ -2092,13 +2270,13 @@ dependencies = [ [[package]] name = "cumulus-relay-chain-interface" -version = "0.21.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.22.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "cumulus-primitives-core", "futures", - "jsonrpsee-core 0.24.9", + "jsonrpsee-core", "parity-scale-codec", "polkadot-overseer", "sc-client-api", @@ -2111,8 +2289,8 @@ dependencies = [ [[package]] name = "cumulus-test-relay-sproof-builder" -version = "0.17.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.19.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "cumulus-primitives-core", "parity-scale-codec", @@ -2151,9 +2329,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.160" +version = "1.0.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be1149bab7a5580cb267215751389597c021bfad13c0bb00c54e19559333764c" +checksum = "a3523cc02ad831111491dd64b27ad999f1ae189986728e477604e61b81f828df" dependencies = [ "cc", "cxxbridge-cmd", @@ -2165,9 +2343,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.160" +version = "1.0.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aeeaf1aefae8e0f5141920a7ecbc64a22ab038d4b4ac59f2d19e0effafd5b53" +checksum = "212b754247a6f07b10fa626628c157593f0abf640a3dd04cce2760eca970f909" dependencies = [ "cc", "codespan-reporting", @@ -2180,9 +2358,9 @@ dependencies = [ [[package]] name = "cxxbridge-cmd" -version = "1.0.160" +version = "1.0.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c36ac1f9a72064b1f41fd7b49a4c1b3bf33b9ccb1274874dda6d264f57c55964" +checksum = "f426a20413ec2e742520ba6837c9324b55ffac24ead47491a6e29f933c5b135a" dependencies = [ "clap", "codespan-reporting", @@ -2194,15 +2372,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.160" +version = "1.0.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170c6ff5d009663866857a91ebee55b98ea4d4b34e7d7aba6dc4a4c95cc7b748" +checksum = "a258b6069020b4e5da6415df94a50ee4f586a6c38b037a180e940a43d06a070d" [[package]] name = "cxxbridge-macro" -version = "1.0.160" +version = "1.0.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4984a142211026786011a7e79fa22faa1eca1e9cbf0e60bffecfd57fd3db88f1" +checksum = "e8dec184b52be5008d6eaf7e62fc1802caf1ad1227d11b3b7df2c409c7ffc3f4" dependencies = [ "indexmap 2.10.0", "proc-macro2", @@ -2211,38 +2389,14 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "darling" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" -dependencies = [ - "darling_core 0.14.4", - "darling_macro 0.14.4", -] - [[package]] name = "darling" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core 0.20.11", - "darling_macro 0.20.11", -] - -[[package]] -name = "darling_core" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 1.0.109", + "darling_core", + "darling_macro", ] [[package]] @@ -2255,28 +2409,17 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim 0.11.1", + "strsim", "syn 2.0.104", ] -[[package]] -name = "darling_macro" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" -dependencies = [ - "darling_core 0.14.4", - "quote", - "syn 1.0.109", -] - [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core 0.20.11", + "darling_core", "quote", "syn 2.0.104", ] @@ -2332,11 +2475,11 @@ dependencies = [ [[package]] name = "der-parser" -version = "8.2.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" +checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553" dependencies = [ - "asn1-rs 0.5.2", + "asn1-rs 0.6.2", "displaydoc", "nom", "num-bigint", @@ -2441,6 +2584,7 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.104", + "unicode-xid", ] [[package]] @@ -2455,12 +2599,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - [[package]] name = "digest" version = "0.8.1" @@ -2510,6 +2648,15 @@ dependencies = [ "dirs-sys-next", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -2618,9 +2765,9 @@ dependencies = [ [[package]] name = "dyn-clone" -version = "1.0.19" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7a8fb8a9fbf66c1f703fe16184d10ca0ee9d23be5b4436400408ba54a95005" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "ecdsa" @@ -2678,8 +2825,20 @@ dependencies = [ ] [[package]] -name = "either" -version = "1.15.0" +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "either" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" dependencies = [ @@ -2714,23 +2873,31 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[package]] name = "enum-as-inner" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.104", ] [[package]] -name = "enum-as-inner" -version = "0.6.1" +name = "enum-ordinalize" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +checksum = "fea0dcfa4e54eeb516fe454635a95753ddd39acda650ce703031c6973e315dd5" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d28318a75d4aead5c4db25382e8ef717932d0346600cacae6357eb5941bc5ff" dependencies = [ - "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.104", @@ -2822,7 +2989,7 @@ dependencies = [ [[package]] name = "ethereum" version = "0.15.0" -source = "git+https://github.com/rust-ethereum/ethereum?rev=3be0d8fd4c2ad1ba216b69ef65b9382612efc8ba#3be0d8fd4c2ad1ba216b69ef65b9382612efc8ba" +source = "git+https://github.com/rust-ethereum/ethereum?rev=bbb544622208ef6e9890a2dbc224248f6dd13318#bbb544622208ef6e9890a2dbc224248f6dd13318" dependencies = [ "bytes", "ethereum-types 0.15.1", @@ -2872,16 +3039,6 @@ version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" -[[package]] -name = "event-listener" -version = "4.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" -dependencies = [ - "concurrent-queue", - "pin-project-lite", -] - [[package]] name = "event-listener" version = "5.4.0" @@ -2906,7 +3063,7 @@ dependencies = [ [[package]] name = "evm" version = "0.42.0" -source = "git+https://github.com/rust-ethereum/evm?rev=e81732d6bb47e3d3d68d233e43919c4522598361#e81732d6bb47e3d3d68d233e43919c4522598361" +source = "git+https://github.com/rust-ethereum/evm?branch=v0.x#6ca5a72bc8942f4860137155dd9033526fd362a5" dependencies = [ "auto_impl", "environmental", @@ -2926,7 +3083,7 @@ dependencies = [ [[package]] name = "evm-core" version = "0.42.0" -source = "git+https://github.com/rust-ethereum/evm?rev=e81732d6bb47e3d3d68d233e43919c4522598361#e81732d6bb47e3d3d68d233e43919c4522598361" +source = "git+https://github.com/rust-ethereum/evm?branch=v0.x#6ca5a72bc8942f4860137155dd9033526fd362a5" dependencies = [ "parity-scale-codec", "primitive-types 0.13.1", @@ -2937,7 +3094,7 @@ dependencies = [ [[package]] name = "evm-gasometer" version = "0.42.0" -source = "git+https://github.com/rust-ethereum/evm?rev=e81732d6bb47e3d3d68d233e43919c4522598361#e81732d6bb47e3d3d68d233e43919c4522598361" +source = "git+https://github.com/rust-ethereum/evm?branch=v0.x#6ca5a72bc8942f4860137155dd9033526fd362a5" dependencies = [ "environmental", "evm-core", @@ -2948,7 +3105,7 @@ dependencies = [ [[package]] name = "evm-runtime" version = "0.42.0" -source = "git+https://github.com/rust-ethereum/evm?rev=e81732d6bb47e3d3d68d233e43919c4522598361#e81732d6bb47e3d3d68d233e43919c4522598361" +source = "git+https://github.com/rust-ethereum/evm?branch=v0.x#6ca5a72bc8942f4860137155dd9033526fd362a5" dependencies = [ "auto_impl", "environmental", @@ -3048,7 +3205,7 @@ dependencies = [ [[package]] name = "fc-api" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "async-trait", "fp-storage", @@ -3060,7 +3217,7 @@ dependencies = [ [[package]] name = "fc-aura" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fc-rpc", "fp-storage", @@ -3076,7 +3233,7 @@ dependencies = [ [[package]] name = "fc-consensus" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "async-trait", "fp-consensus", @@ -3092,7 +3249,7 @@ dependencies = [ [[package]] name = "fc-db" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "async-trait", "ethereum", @@ -3122,7 +3279,7 @@ dependencies = [ [[package]] name = "fc-mapping-sync" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fc-db", "fc-storage", @@ -3145,7 +3302,7 @@ dependencies = [ [[package]] name = "fc-rpc" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", @@ -3159,13 +3316,13 @@ dependencies = [ "fp-storage", "futures", "hex", - "jsonrpsee 0.24.9", + "jsonrpsee", "libsecp256k1", "log", "pallet-evm", "parity-scale-codec", "prometheus", - "rand 0.9.1", + "rand 0.9.2", "rlp 0.6.1", "sc-client-api", "sc-network", @@ -3196,22 +3353,22 @@ dependencies = [ [[package]] name = "fc-rpc-core" version = "1.1.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", - "jsonrpsee 0.24.9", + "jsonrpsee", "rlp 0.6.1", "rustc-hex", "serde", "serde_json", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", ] [[package]] name = "fc-storage" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", @@ -3299,16 +3456,6 @@ dependencies = [ "scale-info", ] -[[package]] -name = "finito" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2384245d85162258a14b43567a9ee3598f5ae746a1581fb5d3d2cb780f0dbf95" -dependencies = [ - "futures-timer", - "pin-project", -] - [[package]] name = "fixed-hash" version = "0.8.0" @@ -3327,15 +3474,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" -dependencies = [ - "num-traits", -] - [[package]] name = "flume" version = "0.11.1" @@ -3377,7 +3515,7 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "fork-tree" version = "13.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", ] @@ -3404,7 +3542,7 @@ dependencies = [ [[package]] name = "fp-account" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "hex", "impl-serde 0.5.0", @@ -3416,14 +3554,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "staging-xcm", ] [[package]] name = "fp-consensus" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "parity-scale-codec", @@ -3434,7 +3572,7 @@ dependencies = [ [[package]] name = "fp-ethereum" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", @@ -3446,7 +3584,7 @@ dependencies = [ [[package]] name = "fp-evm" version = "3.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "environmental", "evm", @@ -3462,7 +3600,7 @@ dependencies = [ [[package]] name = "fp-rpc" version = "3.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", @@ -3478,7 +3616,7 @@ dependencies = [ [[package]] name = "fp-self-contained" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "frame-support", "parity-scale-codec", @@ -3490,7 +3628,7 @@ dependencies = [ [[package]] name = "fp-storage" version = "2.0.0" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "parity-scale-codec", "serde", @@ -3504,8 +3642,8 @@ checksum = "28dd6caf6059519a65843af8fe2a3ae298b14b80179855aeb4adc2c1934ee619" [[package]] name = "frame-benchmarking" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.2.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "frame-support-procedural", @@ -3521,15 +3659,15 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-storage 22.0.0", "static_assertions", ] [[package]] name = "frame-benchmarking-cli" -version = "46.2.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "47.2.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "Inflector", "array-bytes", @@ -3543,7 +3681,6 @@ dependencies = [ "frame-system", "gethostname", "handlebars", - "hex", "itertools 0.11.0", "linked-hash-map", "log", @@ -3558,7 +3695,7 @@ dependencies = [ "sc-client-api", "sc-client-db", "sc-executor", - "sc-executor-common", + "sc-runtime-utilities", "sc-service", "sc-sysinfo", "serde", @@ -3567,7 +3704,6 @@ dependencies = [ "sp-block-builder", "sp-blockchain", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", "sp-database", "sp-externalities 0.30.0", "sp-genesis-builder", @@ -3588,10 +3724,24 @@ dependencies = [ "thousands", ] +[[package]] +name = "frame-decode" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6027a409bac4fe95b4d107f965fcdbc252fc89d884a360d076b3070b6128c094" +dependencies = [ + "frame-metadata 17.0.0", + "parity-scale-codec", + "scale-decode 0.14.0", + "scale-info", + "scale-type-resolver", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "frame-executive" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "aquamarine", "frame-support", @@ -3603,25 +3753,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-tracing 17.0.1", -] - -[[package]] -name = "frame-metadata" -version = "15.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "878babb0b136e731cc77ec2fd883ff02745ff21e6fb662729953d44923df009c" -dependencies = [ - "cfg-if", - "parity-scale-codec", - "scale-info", + "sp-tracing 17.1.0", ] [[package]] name = "frame-metadata" -version = "16.0.0" +version = "17.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cf1549fba25a6fcac22785b61698317d958e96cac72a59102ea45b9ae64692" +checksum = "701bac17e9b55e0f95067c428ebcb46496587f08e8cf4ccc0fe5903bea10dbb8" dependencies = [ "cfg-if", "parity-scale-codec", @@ -3631,9 +3770,9 @@ dependencies = [ [[package]] name = "frame-metadata" -version = "18.0.0" +version = "20.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daaf440c68eb2c3d88e5760fe8c7af3f9fee9181fab6c2f2c4e7cc48dcc40bb8" +checksum = "26de808fa6461f2485dc51811aefed108850064994fb4a62b3ac21ffa62ac8df" dependencies = [ "cfg-if", "parity-scale-codec", @@ -3643,8 +3782,8 @@ dependencies = [ [[package]] name = "frame-metadata-hash-extension" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.8.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "const-hex", @@ -3659,8 +3798,8 @@ dependencies = [ [[package]] name = "frame-support" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "aquamarine", "array-bytes", @@ -3668,7 +3807,7 @@ dependencies = [ "bitflags 1.3.2", "docify", "environmental", - "frame-metadata 18.0.0", + "frame-metadata 20.0.0", "frame-support-procedural", "impl-trait-for-tuples", "k256", @@ -3679,12 +3818,11 @@ dependencies = [ "scale-info", "serde", "serde_json", - "smallvec", "sp-api", "sp-arithmetic", "sp-core", "sp-crypto-hashing-proc-macro", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -3692,18 +3830,17 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", - "sp-tracing 17.0.1", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-tracing 17.1.0", "sp-trie", "sp-weights", - "static_assertions", "tt-call", ] [[package]] name = "frame-support-procedural" -version = "31.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "33.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "Inflector", "cfg-expr", @@ -3713,10 +3850,10 @@ dependencies = [ "frame-support-procedural-tools 13.0.1", "itertools 0.11.0", "macro_magic", - "proc-macro-warning 1.84.1", + "proc-macro-warning", "proc-macro2", "quote", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "syn 2.0.104", ] @@ -3736,7 +3873,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "13.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support-procedural-tools-derive 12.0.0", "proc-macro-crate 3.3.0", @@ -3759,7 +3896,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "12.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "proc-macro2", "quote", @@ -3768,8 +3905,8 @@ dependencies = [ [[package]] name = "frame-system" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "cfg-if", "docify", @@ -3781,15 +3918,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", "sp-version", "sp-weights", ] [[package]] name = "frame-system-benchmarking" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -3802,8 +3938,8 @@ dependencies = [ [[package]] name = "frame-system-rpc-runtime-api" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "parity-scale-codec", @@ -3812,8 +3948,8 @@ dependencies = [ [[package]] name = "frame-try-runtime" -version = "0.45.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.46.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "parity-scale-codec", @@ -3863,9 +3999,9 @@ dependencies = [ [[package]] name = "futures-bounded" -version = "0.1.0" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b07bbbe7d7e78809544c6f718d875627addc73a7c3582447abc052cd3dc67e0" +checksum = "91f328e7fb845fc832912fb6a34f40cf6d1888c92f974d1893a54e97b5ff542e" dependencies = [ "futures-timer", "futures-util", @@ -3942,12 +4078,13 @@ dependencies = [ [[package]] name = "futures-rustls" -version = "0.24.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35bd3cf68c183738046838e300353e4716c674dc5e56890de4826801a6622a28" +checksum = "a8f2f12607f92c69b12ed746fabf9ca4f5c482cba46679c1a75b874ed7c26adb" dependencies = [ "futures-io", - "rustls 0.21.12", + "rustls", + "rustls-pki-types", ] [[package]] @@ -4015,7 +4152,7 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" dependencies = [ - "typenum 1.18.0", + "typenum", ] [[package]] @@ -4024,7 +4161,7 @@ version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ - "typenum 1.18.0", + "typenum", "version_check", "zeroize", ] @@ -4046,8 +4183,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", ] [[package]] @@ -4057,9 +4196,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", "wasi 0.14.2+wasi-0.2.4", + "wasm-bindgen", ] [[package]] @@ -4095,20 +4236,14 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.1" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" dependencies = [ "fallible-iterator 0.3.0", "stable_deref_trait", ] -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" - [[package]] name = "glob" version = "0.3.2" @@ -4316,12 +4451,46 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "212ab92002354b4819390025006c897e8140934349e8635c9b077f47b4dcbd20" +[[package]] +name = "hex-conservative" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd" +dependencies = [ + "arrayvec 0.7.6", +] + [[package]] name = "hex-literal" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "hickory-proto" +version = "0.24.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92652067c9ce6f66ce53cc38d1169daa36e6e7eb7dd3b63b5103bd9d97117248" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "enum-as-inner", + "futures-channel", + "futures-io", + "futures-util", + "idna", + "ipnet", + "once_cell", + "rand 0.8.5", + "socket2 0.5.10", + "thiserror 1.0.69", + "tinyvec", + "tokio", + "tracing", + "url", +] + [[package]] name = "hickory-proto" version = "0.25.2" @@ -4331,14 +4500,14 @@ dependencies = [ "async-trait", "cfg-if", "data-encoding", - "enum-as-inner 0.6.1", + "enum-as-inner", "futures-channel", "futures-io", "futures-util", - "idna 1.0.3", + "idna", "ipnet", "once_cell", - "rand 0.9.1", + "rand 0.9.2", "ring 0.17.14", "thiserror 2.0.12", "tinyvec", @@ -4347,6 +4516,27 @@ dependencies = [ "url", ] +[[package]] +name = "hickory-resolver" +version = "0.24.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb117a1ca520e111743ab2f6688eddee69db4e0ea242545a604dce8a66fd22e" +dependencies = [ + "cfg-if", + "futures-util", + "hickory-proto 0.24.4", + "ipconfig", + "lru-cache", + "once_cell", + "parking_lot 0.12.4", + "rand 0.8.5", + "resolv-conf", + "smallvec", + "thiserror 1.0.69", + "tokio", + "tracing", +] + [[package]] name = "hickory-resolver" version = "0.25.2" @@ -4355,12 +4545,12 @@ checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a" dependencies = [ "cfg-if", "futures-util", - "hickory-proto", + "hickory-proto 0.25.2", "ipconfig", "moka", "once_cell", "parking_lot 0.12.4", - "rand 0.9.1", + "rand 0.9.2", "resolv-conf", "smallvec", "thiserror 2.0.12", @@ -4526,22 +4716,6 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-rustls" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" -dependencies = [ - "futures-util", - "http 0.2.12", - "hyper 0.14.32", - "log", - "rustls 0.21.12", - "rustls-native-certs 0.6.3", - "tokio", - "tokio-rustls 0.24.1", -] - [[package]] name = "hyper-rustls" version = "0.27.7" @@ -4552,19 +4726,19 @@ dependencies = [ "hyper 1.6.0", "hyper-util", "log", - "rustls 0.23.29", - "rustls-native-certs 0.8.1", + "rustls", + "rustls-native-certs", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.2", + "tokio-rustls", "tower-service", ] [[package]] name = "hyper-util" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f66d5bd4c6f02bf0542fad85d626775bab9258cf795a4256dcaf3161114d1df" +checksum = "8d9b05277c7e8da2c93a568989bb6207bef0112e8d17df7a6eda4a3cf143bc5e" dependencies = [ "bytes", "futures-channel", @@ -4575,7 +4749,7 @@ dependencies = [ "hyper 1.6.0", "libc", "pin-project-lite", - "socket2 0.5.10", + "socket2 0.6.0", "tokio", "tower-service", "tracing", @@ -4697,27 +4871,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "idna" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" -dependencies = [ - "matches", - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "idna" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - [[package]] name = "idna" version = "1.0.3" @@ -4905,6 +5058,7 @@ checksum = "fe4cd85333e22411419a0bcae1297d25e58c9443848b11dc6a86fefe8c78a661" dependencies = [ "equivalent", "hashbrown 0.15.4", + "serde", ] [[package]] @@ -4953,9 +5107,9 @@ dependencies = [ [[package]] name = "io-uring" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b86e202f00093dcba4275d4636b93ef9dd75d025ae560d2521b45ea28ab49013" +checksum = "d93587f37623a1a17d94ef2bc9ada592f5465fe7732084ab7beefabe5c77c0c4" dependencies = [ "bitflags 2.9.1", "cfg-if", @@ -5030,6 +5184,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -5047,16 +5210,18 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jni" -version = "0.19.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" dependencies = [ "cesu8", + "cfg-if", "combine", "jni-sys", "log", "thiserror 1.0.69", "walkdir", + "windows-sys 0.45.0", ] [[package]] @@ -5085,82 +5250,40 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "jsonrpsee" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfdb12a2381ea5b2e68c3469ec604a007b367778cdb14d09612c8069ebd616ad" -dependencies = [ - "jsonrpsee-client-transport 0.22.5", - "jsonrpsee-core 0.22.5", - "jsonrpsee-http-client", - "jsonrpsee-types 0.22.5", -] - -[[package]] -name = "jsonrpsee" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b089779ad7f80768693755a031cc14a7766aba707cbe886674e3f79e9b7e47" -dependencies = [ - "jsonrpsee-core 0.23.2", - "jsonrpsee-types 0.23.2", - "jsonrpsee-ws-client", -] - [[package]] name = "jsonrpsee" version = "0.24.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b26c20e2178756451cfeb0661fb74c47dd5988cb7e3939de7e9241fd604d42" dependencies = [ - "jsonrpsee-core 0.24.9", + "jsonrpsee-client-transport", + "jsonrpsee-core", "jsonrpsee-proc-macros", "jsonrpsee-server", - "jsonrpsee-types 0.24.9", - "tokio", - "tracing", -] - -[[package]] -name = "jsonrpsee-client-transport" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4978087a58c3ab02efc5b07c5e5e2803024536106fd5506f558db172c889b3aa" -dependencies = [ - "futures-util", - "http 0.2.12", - "jsonrpsee-core 0.22.5", - "pin-project", - "rustls-native-certs 0.7.3", - "rustls-pki-types", - "soketto 0.7.1", - "thiserror 1.0.69", + "jsonrpsee-types", + "jsonrpsee-ws-client", "tokio", - "tokio-rustls 0.25.0", - "tokio-util", "tracing", - "url", ] [[package]] name = "jsonrpsee-client-transport" -version = "0.23.2" +version = "0.24.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08163edd8bcc466c33d79e10f695cdc98c00d1e6ddfb95cec41b6b0279dd5432" +checksum = "bacb85abf4117092455e1573625e21b8f8ef4dec8aff13361140b2dc266cdff2" dependencies = [ "base64 0.22.1", "futures-util", "http 1.3.1", - "jsonrpsee-core 0.23.2", + "jsonrpsee-core", "pin-project", - "rustls 0.23.29", + "rustls", "rustls-pki-types", "rustls-platform-verifier", - "soketto 0.8.1", + "soketto", "thiserror 1.0.69", "tokio", - "tokio-rustls 0.26.2", + "tokio-rustls", "tokio-util", "tracing", "url", @@ -5168,19 +5291,22 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.22.5" +version = "0.24.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b257e1ec385e07b0255dde0b933f948b5c8b8c28d42afda9587c3a967b896d" +checksum = "456196007ca3a14db478346f58c7238028d55ee15c1df15115596e411ff27925" dependencies = [ - "anyhow", "async-trait", - "beef", + "bytes", "futures-timer", "futures-util", - "hyper 0.14.32", - "jsonrpsee-types 0.22.5", + "http 1.3.1", + "http-body 1.0.1", + "http-body-util", + "jsonrpsee-types", + "parking_lot 0.12.4", "pin-project", - "rustc-hash 1.1.0", + "rand 0.8.5", + "rustc-hash 2.1.1", "serde", "serde_json", "thiserror 1.0.69", @@ -5190,75 +5316,10 @@ dependencies = [ ] [[package]] -name = "jsonrpsee-core" -version = "0.23.2" +name = "jsonrpsee-proc-macros" +version = "0.24.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79712302e737d23ca0daa178e752c9334846b08321d439fd89af9a384f8c830b" -dependencies = [ - "anyhow", - "async-trait", - "beef", - "futures-timer", - "futures-util", - "jsonrpsee-types 0.23.2", - "pin-project", - "rustc-hash 1.1.0", - "serde", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tokio-stream", - "tracing", -] - -[[package]] -name = "jsonrpsee-core" -version = "0.24.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456196007ca3a14db478346f58c7238028d55ee15c1df15115596e411ff27925" -dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http 1.3.1", - "http-body 1.0.1", - "http-body-util", - "jsonrpsee-types 0.24.9", - "parking_lot 0.12.4", - "rand 0.8.5", - "rustc-hash 2.1.1", - "serde", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tracing", -] - -[[package]] -name = "jsonrpsee-http-client" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ccf93fc4a0bfe05d851d37d7c32b7f370fe94336b52a2f0efc5f1981895c2e5" -dependencies = [ - "async-trait", - "hyper 0.14.32", - "hyper-rustls 0.24.2", - "jsonrpsee-core 0.22.5", - "jsonrpsee-types 0.22.5", - "serde", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tower", - "tracing", - "url", -] - -[[package]] -name = "jsonrpsee-proc-macros" -version = "0.24.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e65763c942dfc9358146571911b0cd1c361c2d63e2d2305622d40d36376ca80" +checksum = "5e65763c942dfc9358146571911b0cd1c361c2d63e2d2305622d40d36376ca80" dependencies = [ "heck 0.5.0", "proc-macro-crate 3.3.0", @@ -5279,13 +5340,13 @@ dependencies = [ "http-body-util", "hyper 1.6.0", "hyper-util", - "jsonrpsee-core 0.24.9", - "jsonrpsee-types 0.24.9", + "jsonrpsee-core", + "jsonrpsee-types", "pin-project", "route-recognizer", "serde", "serde_json", - "soketto 0.8.1", + "soketto", "thiserror 1.0.69", "tokio", "tokio-stream", @@ -5294,32 +5355,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "jsonrpsee-types" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150d6168405890a7a3231a3c74843f58b8959471f6df76078db2619ddee1d07d" -dependencies = [ - "anyhow", - "beef", - "serde", - "serde_json", - "thiserror 1.0.69", -] - -[[package]] -name = "jsonrpsee-types" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c465fbe385238e861fdc4d1c85e04ada6c1fd246161d26385c1b311724d2af" -dependencies = [ - "beef", - "http 1.3.1", - "serde", - "serde_json", - "thiserror 1.0.69", -] - [[package]] name = "jsonrpsee-types" version = "0.24.9" @@ -5334,14 +5369,14 @@ dependencies = [ [[package]] name = "jsonrpsee-ws-client" -version = "0.23.2" +version = "0.24.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c28759775f5cb2f1ea9667672d3fe2b0e701d1f4b7b67954e60afe7fd058b5e" +checksum = "01b3323d890aa384f12148e8d2a1fd18eb66e9e7e825f9de4fa53bcc19b93eef" dependencies = [ "http 1.3.1", - "jsonrpsee-client-transport 0.23.2", - "jsonrpsee-core 0.23.2", - "jsonrpsee-types 0.23.2", + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-types", "url", ] @@ -5380,11 +5415,11 @@ dependencies = [ [[package]] name = "keccak-hash" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b286e6b663fb926e1eeb68528e69cb70ed46c6d65871a21b2215ae8154c6d3c" +checksum = "3e1b8590eb6148af2ea2d75f38e7d29f5ca970d5a4df456b3ef19b8b415d0264" dependencies = [ - "primitive-types 0.12.2", + "primitive-types 0.13.1", "tiny-keccak", ] @@ -5455,7 +5490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", - "windows-targets 0.53.2", + "windows-targets 0.53.3", ] [[package]] @@ -5466,16 +5501,15 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libp2p" -version = "0.52.4" +version = "0.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94495eb319a85b70a68b85e2389a95bb3555c71c49025b78c691a854a7e6464" +checksum = "bbbe80f9c7e00526cd6b838075b9c171919404a4732cb2fa8ece0a093223bfc4" dependencies = [ "bytes", "either", "futures", "futures-timer", "getrandom 0.2.16", - "instant", "libp2p-allow-block-list", "libp2p-connection-limits", "libp2p-core", @@ -5492,7 +5526,6 @@ dependencies = [ "libp2p-swarm", "libp2p-tcp", "libp2p-upnp", - "libp2p-wasm-ext", "libp2p-websocket", "libp2p-yamux", "multiaddr 0.18.2", @@ -5503,9 +5536,9 @@ dependencies = [ [[package]] name = "libp2p-allow-block-list" -version = "0.2.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55b46558c5c0bf99d3e2a1a38fd54ff5476ca66dd1737b12466a1824dd219311" +checksum = "d1027ccf8d70320ed77e984f273bc8ce952f623762cb9bf2d126df73caef8041" dependencies = [ "libp2p-core", "libp2p-identity", @@ -5515,9 +5548,9 @@ dependencies = [ [[package]] name = "libp2p-connection-limits" -version = "0.2.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f5107ad45cb20b2f6c3628c7b6014b996fcb13a88053f4569c872c6e30abf58" +checksum = "8d003540ee8baef0d254f7b6bfd79bac3ddf774662ca0abf69186d517ef82ad8" dependencies = [ "libp2p-core", "libp2p-identity", @@ -5527,17 +5560,15 @@ dependencies = [ [[package]] name = "libp2p-core" -version = "0.40.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd44289ab25e4c9230d9246c475a22241e301b23e8f4061d3bdef304a1a99713" +checksum = "a61f26c83ed111104cd820fe9bc3aaabbac5f1652a1d213ed6e900b7918a1298" dependencies = [ "either", "fnv", "futures", "futures-timer", - "instant", "libp2p-identity", - "log", "multiaddr 0.18.2", "multihash 0.19.3", "multistream-select", @@ -5549,33 +5580,35 @@ dependencies = [ "rw-stream-sink", "smallvec", "thiserror 1.0.69", - "unsigned-varint 0.7.2", + "tracing", + "unsigned-varint 0.8.0", "void", + "web-time", ] [[package]] name = "libp2p-dns" -version = "0.40.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6a18db73084b4da2871438f6239fef35190b05023de7656e877c18a00541a3b" +checksum = "97f37f30d5c7275db282ecd86e54f29dd2176bd3ac656f06abf43bedb21eb8bd" dependencies = [ "async-trait", "futures", + "hickory-resolver 0.24.4", "libp2p-core", "libp2p-identity", - "log", "parking_lot 0.12.4", "smallvec", - "trust-dns-resolver", + "tracing", ] [[package]] name = "libp2p-identify" -version = "0.43.1" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45a96638a0a176bec0a4bcaebc1afa8cf909b114477209d7456ade52c61cd9cd" +checksum = "1711b004a273be4f30202778856368683bd9a83c4c7dcc8f848847606831a4e3" dependencies = [ - "asynchronous-codec", + "asynchronous-codec 0.7.0", "either", "futures", "futures-bounded", @@ -5583,12 +5616,12 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-swarm", - "log", "lru 0.12.5", "quick-protobuf", "quick-protobuf-codec", "smallvec", "thiserror 1.0.69", + "tracing", "void", ] @@ -5612,83 +5645,84 @@ dependencies = [ [[package]] name = "libp2p-kad" -version = "0.44.6" +version = "0.46.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16ea178dabba6dde6ffc260a8e0452ccdc8f79becf544946692fff9d412fc29d" +checksum = "ced237d0bd84bbebb7c2cad4c073160dacb4fe40534963c32ed6d4c6bb7702a3" dependencies = [ "arrayvec 0.7.6", - "asynchronous-codec", + "asynchronous-codec 0.7.0", "bytes", "either", "fnv", "futures", + "futures-bounded", "futures-timer", - "instant", "libp2p-core", "libp2p-identity", "libp2p-swarm", - "log", "quick-protobuf", "quick-protobuf-codec", "rand 0.8.5", "sha2 0.10.9", "smallvec", "thiserror 1.0.69", + "tracing", "uint 0.9.5", - "unsigned-varint 0.7.2", "void", + "web-time", ] [[package]] name = "libp2p-mdns" -version = "0.44.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42a2567c305232f5ef54185e9604579a894fd0674819402bb0ac0246da82f52a" +checksum = "14b8546b6644032565eb29046b42744aee1e9f261ed99671b2c93fb140dba417" dependencies = [ "data-encoding", "futures", + "hickory-proto 0.24.4", "if-watch", "libp2p-core", "libp2p-identity", "libp2p-swarm", - "log", "rand 0.8.5", "smallvec", "socket2 0.5.10", "tokio", - "trust-dns-proto 0.22.0", + "tracing", "void", ] [[package]] name = "libp2p-metrics" -version = "0.13.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239ba7d28f8d0b5d77760dc6619c05c7e88e74ec8fbbe97f856f20a56745e620" +checksum = "77ebafa94a717c8442d8db8d3ae5d1c6a15e30f2d347e0cd31d057ca72e42566" dependencies = [ - "instant", + "futures", "libp2p-core", "libp2p-identify", "libp2p-identity", "libp2p-kad", "libp2p-ping", "libp2p-swarm", - "once_cell", + "pin-project", "prometheus-client", + "web-time", ] [[package]] name = "libp2p-noise" -version = "0.43.2" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2eeec39ad3ad0677551907dd304b2f13f17208ccebe333bef194076cd2e8921" +checksum = "36b137cb1ae86ee39f8e5d6245a296518912014eaa87427d24e6ff58cfc1b28c" dependencies = [ + "asynchronous-codec 0.7.0", "bytes", "curve25519-dalek", "futures", "libp2p-core", "libp2p-identity", - "log", "multiaddr 0.18.2", "multihash 0.19.3", "once_cell", @@ -5698,33 +5732,34 @@ dependencies = [ "snow", "static_assertions", "thiserror 1.0.69", + "tracing", "x25519-dalek", "zeroize", ] [[package]] name = "libp2p-ping" -version = "0.43.1" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e702d75cd0827dfa15f8fd92d15b9932abe38d10d21f47c50438c71dd1b5dae3" +checksum = "005a34420359223b974ee344457095f027e51346e992d1e0dcd35173f4cdd422" dependencies = [ "either", "futures", "futures-timer", - "instant", "libp2p-core", "libp2p-identity", "libp2p-swarm", - "log", "rand 0.8.5", + "tracing", "void", + "web-time", ] [[package]] name = "libp2p-quic" -version = "0.9.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "130d451d83f21b81eb7b35b360bc7972aeafb15177784adc56528db082e6b927" +checksum = "46352ac5cd040c70e88e7ff8257a2ae2f891a4076abad2c439584a31c15fd24e" dependencies = [ "bytes", "futures", @@ -5733,66 +5768,68 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-tls", - "log", "parking_lot 0.12.4", "quinn", "rand 0.8.5", - "ring 0.16.20", - "rustls 0.21.12", + "ring 0.17.14", + "rustls", "socket2 0.5.10", "thiserror 1.0.69", "tokio", + "tracing", ] [[package]] name = "libp2p-request-response" -version = "0.25.3" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8e3b4d67870478db72bac87bfc260ee6641d0734e0e3e275798f089c3fecfd4" +checksum = "1356c9e376a94a75ae830c42cdaea3d4fe1290ba409a22c809033d1b7dcab0a6" dependencies = [ "async-trait", "futures", - "instant", + "futures-bounded", + "futures-timer", "libp2p-core", "libp2p-identity", "libp2p-swarm", - "log", "rand 0.8.5", "smallvec", + "tracing", "void", + "web-time", ] [[package]] name = "libp2p-swarm" -version = "0.43.7" +version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580189e0074af847df90e75ef54f3f30059aedda37ea5a1659e8b9fca05c0141" +checksum = "d7dd6741793d2c1fb2088f67f82cf07261f25272ebe3c0b0c311e0c6b50e851a" dependencies = [ "either", "fnv", "futures", "futures-timer", - "instant", "libp2p-core", "libp2p-identity", "libp2p-swarm-derive", - "log", + "lru 0.12.5", "multistream-select", "once_cell", "rand 0.8.5", "smallvec", "tokio", + "tracing", "void", + "web-time", ] [[package]] name = "libp2p-swarm-derive" -version = "0.33.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4d5ec2a3df00c7836d7696c136274c9c59705bac69133253696a6c932cd1d74" +checksum = "206e0aa0ebe004d778d79fb0966aa0de996c19894e2c0605ba2f8524dd4443d8" dependencies = [ - "heck 0.4.1", - "proc-macro-warning 0.4.2", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.104", @@ -5800,9 +5837,9 @@ dependencies = [ [[package]] name = "libp2p-tcp" -version = "0.40.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b558dd40d1bcd1aaaed9de898e9ec6a436019ecc2420dd0016e712fbb61c5508" +checksum = "ad964f312c59dcfcac840acd8c555de8403e295d39edf96f5240048b5fcaa314" dependencies = [ "futures", "futures-timer", @@ -5810,103 +5847,91 @@ dependencies = [ "libc", "libp2p-core", "libp2p-identity", - "log", "socket2 0.5.10", "tokio", + "tracing", ] [[package]] name = "libp2p-tls" -version = "0.2.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8218d1d5482b122ccae396bbf38abdcb283ecc96fa54760e1dfd251f0546ac61" +checksum = "47b23dddc2b9c355f73c1e36eb0c3ae86f7dc964a3715f0731cfad352db4d847" dependencies = [ "futures", "futures-rustls", "libp2p-core", "libp2p-identity", "rcgen", - "ring 0.16.20", - "rustls 0.21.12", + "ring 0.17.14", + "rustls", "rustls-webpki 0.101.7", "thiserror 1.0.69", - "x509-parser 0.15.1", + "x509-parser 0.16.0", "yasna", ] [[package]] name = "libp2p-upnp" -version = "0.1.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82775a47b34f10f787ad3e2a22e2c1541e6ebef4fe9f28f3ac553921554c94c1" +checksum = "01bf2d1b772bd3abca049214a3304615e6a36fa6ffc742bdd1ba774486200b8f" dependencies = [ "futures", "futures-timer", "igd-next", "libp2p-core", "libp2p-swarm", - "log", "tokio", + "tracing", "void", ] -[[package]] -name = "libp2p-wasm-ext" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e5d8e3a9e07da0ef5b55a9f26c009c8fb3c725d492d8bb4b431715786eea79c" -dependencies = [ - "futures", - "js-sys", - "libp2p-core", - "send_wrapper", - "wasm-bindgen", - "wasm-bindgen-futures", -] - [[package]] name = "libp2p-websocket" -version = "0.42.2" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "004ee9c4a4631435169aee6aad2f62e3984dc031c43b6d29731e8e82a016c538" +checksum = "888b2ff2e5d8dcef97283daab35ad1043d18952b65e05279eecbe02af4c6e347" dependencies = [ "either", "futures", "futures-rustls", "libp2p-core", "libp2p-identity", - "log", "parking_lot 0.12.4", "pin-project-lite", "rw-stream-sink", - "soketto 0.8.1", + "soketto", "thiserror 1.0.69", + "tracing", "url", - "webpki-roots 0.25.4", + "webpki-roots", ] [[package]] name = "libp2p-yamux" -version = "0.44.1" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eedcb62824c4300efb9cfd4e2a6edaf3ca097b9e68b36dabe45a44469fd6a85" +checksum = "788b61c80789dba9760d8c669a5bedb642c8267555c803fabd8396e4ca5c5882" dependencies = [ + "either", "futures", "libp2p-core", - "log", "thiserror 1.0.69", + "tracing", "yamux 0.12.1", + "yamux 0.13.6", ] [[package]] name = "libredox" -version = "0.1.4" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" +checksum = "391290121bad3d37fbddad76d8f5d1c1c314cfc646d143d7e07a3086ddff0ce3" dependencies = [ "bitflags 2.9.1", "libc", - "redox_syscall 0.5.13", + "redox_syscall 0.5.17", ] [[package]] @@ -5940,7 +5965,7 @@ dependencies = [ "rand 0.8.5", "serde", "sha2 0.9.9", - "typenum 1.18.0", + "typenum", ] [[package]] @@ -6076,10 +6101,10 @@ dependencies = [ "ed25519-dalek", "futures", "futures-timer", - "hickory-resolver", + "hickory-resolver 0.25.2", "indexmap 2.10.0", "libc", - "mockall 0.13.1", + "mockall", "multiaddr 0.17.1", "multihash 0.17.0", "network-interface", @@ -6105,7 +6130,7 @@ dependencies = [ "url", "x25519-dalek", "x509-parser 0.17.0", - "yamux 0.13.5", + "yamux 0.13.6", "yasna", "zeroize", ] @@ -6166,6 +6191,12 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "lz4" version = "1.28.1" @@ -6251,12 +6282,6 @@ dependencies = [ "regex-automata 0.1.10", ] -[[package]] -name = "matches" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" - [[package]] name = "matrixmultiply" version = "0.3.10" @@ -6320,15 +6345,15 @@ dependencies = [ [[package]] name = "merkleized-metadata" -version = "0.2.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c592efaf1b3250df14c8f3c2d952233f0302bb81d3586db2f303666c1cd607" +checksum = "dc9b7ac0ce054412d9a85ff39bac27aec27483b06cef8756b57d9c29d448d081" dependencies = [ "array-bytes", "blake3", - "frame-metadata 18.0.0", + "frame-metadata 20.0.0", "parity-scale-codec", - "scale-decode", + "scale-decode 0.13.1", "scale-info", ] @@ -6395,21 +6420,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "mockall" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" -dependencies = [ - "cfg-if", - "downcast", - "fragile", - "lazy_static", - "mockall_derive 0.11.4", - "predicates 2.1.5", - "predicates-tree", -] - [[package]] name = "mockall" version = "0.13.1" @@ -6419,23 +6429,11 @@ dependencies = [ "cfg-if", "downcast", "fragile", - "mockall_derive 0.13.1", - "predicates 3.1.3", + "mockall_derive", + "predicates", "predicates-tree", ] -[[package]] -name = "mockall_derive" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" -dependencies = [ - "cfg-if", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "mockall_derive" version = "0.13.1" @@ -6467,6 +6465,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "multi-stash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685a9ac4b61f4e728e1d2c6a7844609c16527aeb5e6c865915c08e619c16410f" + [[package]] name = "multiaddr" version = "0.17.1" @@ -6589,7 +6593,7 @@ dependencies = [ "num-rational", "num-traits", "simba", - "typenum 1.18.0", + "typenum", ] [[package]] @@ -6703,13 +6707,13 @@ dependencies = [ [[package]] name = "network-interface" -version = "2.0.1" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3329f515506e4a2de3aa6e07027a6758e22e0f0e8eaf64fa47261cec2282602" +checksum = "862f41f1276e7148fb597fc55ed8666423bebe045199a1298c3515a73ec5cdd9" dependencies = [ "cc", "libc", - "thiserror 1.0.69", + "thiserror 2.0.12", "winapi", ] @@ -6730,12 +6734,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c" -[[package]] -name = "no-std-net" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65" - [[package]] name = "node-subtensor" version = "4.0.0-dev" @@ -6760,7 +6758,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "futures", "hex", - "jsonrpsee 0.24.9", + "jsonrpsee", "memmap2 0.9.7", "node-subtensor-runtime", "num-traits", @@ -6771,7 +6769,6 @@ dependencies = [ "pallet-transaction-payment", "pallet-transaction-payment-rpc", "pallet-transaction-payment-rpc-runtime-api", - "parity-scale-codec", "sc-basic-authorship", "sc-chain-spec", "sc-chain-spec-derive", @@ -6819,7 +6816,6 @@ dependencies = [ "subtensor-custom-rpc", "subtensor-custom-rpc-runtime-api", "subtensor-runtime-common", - "thiserror 1.0.69", ] [[package]] @@ -6833,7 +6829,7 @@ dependencies = [ "fp-self-contained", "frame-benchmarking", "frame-executive", - "frame-metadata 18.0.0", + "frame-metadata 20.0.0", "frame-metadata-hash-extension", "frame-support", "frame-system", @@ -6892,9 +6888,9 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-storage 22.0.0", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "sp-transaction-pool", "sp-version", "substrate-fixed", @@ -6904,6 +6900,7 @@ dependencies = [ "subtensor-precompiles", "subtensor-runtime-common", "subtensor-swap-interface", + "subtensor-transaction-fee", "tle", "w3f-bls", ] @@ -6942,12 +6939,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -6997,6 +6988,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "num-format" version = "0.4.4" @@ -7092,15 +7094,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "object" -version = "0.32.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" -dependencies = [ - "memchr", -] - [[package]] name = "object" version = "0.36.7" @@ -7112,11 +7105,11 @@ dependencies = [ [[package]] name = "oid-registry" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" +checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9" dependencies = [ - "asn1-rs 0.5.2", + "asn1-rs 0.6.2", ] [[package]] @@ -7269,8 +7262,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", - "sp-tracing 17.0.1", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-tracing 17.1.0", "sp-weights", "substrate-fixed", "subtensor-macros", @@ -7280,8 +7273,8 @@ dependencies = [ [[package]] name = "pallet-aura" -version = "38.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "frame-system", @@ -7296,8 +7289,8 @@ dependencies = [ [[package]] name = "pallet-authorship" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "frame-system", @@ -7309,8 +7302,8 @@ dependencies = [ [[package]] name = "pallet-balances" -version = "40.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "41.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", @@ -7319,13 +7312,14 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", + "sp-core", "sp-runtime", ] [[package]] name = "pallet-base-fee" version = "1.0.0" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "frame-support", @@ -7349,7 +7343,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "subtensor-macros", ] @@ -7374,7 +7368,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "subtensor-macros", "subtensor-runtime-common", "tle", @@ -7396,7 +7390,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "subtensor-macros", ] @@ -7405,9 +7399,9 @@ name = "pallet-drand" version = "0.0.1" dependencies = [ "anyhow", - "ark-bls12-381", + "ark-bls12-381 0.4.0", "ark-crypto-primitives", - "ark-ec", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-scale 0.0.11", "ark-serialize 0.4.2", @@ -7436,7 +7430,7 @@ dependencies = [ [[package]] name = "pallet-ethereum" version = "4.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "ethereum", "ethereum-types 0.15.1", @@ -7459,7 +7453,7 @@ dependencies = [ [[package]] name = "pallet-evm" version = "6.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "cumulus-primitives-storage-weight-reclaim", "environmental", @@ -7483,7 +7477,7 @@ dependencies = [ [[package]] name = "pallet-evm-chain-id" version = "1.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "frame-support", "frame-system", @@ -7494,7 +7488,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-bn128" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "sp-core", @@ -7504,7 +7498,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-dispatch" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "frame-support", @@ -7516,7 +7510,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-modexp" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "num", @@ -7525,7 +7519,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-sha3fips" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "tiny-keccak", @@ -7534,7 +7528,7 @@ dependencies = [ [[package]] name = "pallet-evm-precompile-simple" version = "2.0.0-dev" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "fp-evm", "ripemd", @@ -7543,8 +7537,8 @@ dependencies = [ [[package]] name = "pallet-grandpa" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -7566,7 +7560,7 @@ dependencies = [ [[package]] name = "pallet-hotfix-sufficients" version = "1.0.0" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "frame-benchmarking", "frame-support", @@ -7580,21 +7574,19 @@ dependencies = [ [[package]] name = "pallet-insecure-randomness-collective-flip" -version = "27.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "28.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "frame-support", - "frame-system", "parity-scale-codec", + "polkadot-sdk-frame", "safe-mix", "scale-info", - "sp-runtime", ] [[package]] name = "pallet-membership" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -7609,8 +7601,8 @@ dependencies = [ [[package]] name = "pallet-multisig" -version = "39.1.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "log", "parity-scale-codec", @@ -7620,8 +7612,8 @@ dependencies = [ [[package]] name = "pallet-preimage" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -7653,8 +7645,8 @@ dependencies = [ [[package]] name = "pallet-proxy" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "polkadot-sdk-frame", @@ -7674,14 +7666,14 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "subtensor-macros", ] [[package]] name = "pallet-root-testing" -version = "15.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "16.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "frame-system", @@ -7694,16 +7686,16 @@ dependencies = [ [[package]] name = "pallet-safe-mode" -version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "21.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", "frame-support", "frame-system", "pallet-balances", - "pallet-proxy 39.1.0", - "pallet-utility 39.1.0", + "pallet-proxy 40.1.0", + "pallet-utility 40.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic", @@ -7712,8 +7704,8 @@ dependencies = [ [[package]] name = "pallet-scheduler" -version = "40.2.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "41.2.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", @@ -7729,8 +7721,8 @@ dependencies = [ [[package]] name = "pallet-session" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-support", "frame-system", @@ -7753,7 +7745,7 @@ name = "pallet-subtensor" version = "4.0.0-dev" dependencies = [ "approx", - "ark-bls12-381", + "ark-bls12-381 0.4.0", "ark-serialize 0.4.2", "frame-benchmarking", "frame-support", @@ -7791,8 +7783,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", - "sp-tracing 17.0.1", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-tracing 17.1.0", "sp-version", "substrate-fixed", "subtensor-macros", @@ -7821,8 +7813,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", - "sp-tracing 17.0.1", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-tracing 17.1.0", "substrate-fixed", "subtensor-macros", "subtensor-runtime-common", @@ -7833,7 +7825,7 @@ dependencies = [ name = "pallet-subtensor-swap-rpc" version = "1.0.0" dependencies = [ - "jsonrpsee 0.24.9", + "jsonrpsee", "pallet-subtensor-swap-runtime-api", "parity-scale-codec", "sp-api", @@ -7848,13 +7840,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-api", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", ] [[package]] name = "pallet-sudo" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", @@ -7868,8 +7860,8 @@ dependencies = [ [[package]] name = "pallet-timestamp" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", @@ -7887,8 +7879,8 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -7903,10 +7895,10 @@ dependencies = [ [[package]] name = "pallet-transaction-payment-rpc" -version = "42.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "43.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "jsonrpsee 0.24.9", + "jsonrpsee", "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "sp-api", @@ -7919,8 +7911,8 @@ dependencies = [ [[package]] name = "pallet-transaction-payment-rpc-runtime-api" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "pallet-transaction-payment", "parity-scale-codec", @@ -7950,8 +7942,8 @@ dependencies = [ [[package]] name = "pallet-utility" -version = "39.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "frame-benchmarking", "frame-support", @@ -7969,7 +7961,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e69bf016dc406eff7d53a7d3f7cf1c2e72c82b9088aac1118591e36dd2cd3e9" dependencies = [ - "bitcoin_hashes", + "bitcoin_hashes 0.13.0", "rand 0.8.5", "rand_core 0.6.4", "serde", @@ -8110,7 +8102,7 @@ checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.13", + "redox_syscall 0.5.17", "smallvec", "windows-targets 0.52.6", ] @@ -8145,6 +8137,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", + "hmac 0.12.1", "password-hash", ] @@ -8156,11 +8149,12 @@ checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" [[package]] name = "pem" -version = "1.1.1" +version = "3.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8" +checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3" dependencies = [ - "base64 0.13.1", + "base64 0.22.1", + "serde", ] [[package]] @@ -8284,8 +8278,8 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "polkadot-core-primitives" -version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "17.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -8295,13 +8289,12 @@ dependencies = [ [[package]] name = "polkadot-node-metrics" -version = "21.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bs58", "futures", "futures-timer", - "log", "parity-scale-codec", "polkadot-primitives", "prioritized-metered-channel", @@ -8309,13 +8302,12 @@ dependencies = [ "sc-service", "sc-tracing", "substrate-prometheus-endpoint", - "tracing-gum", ] [[package]] name = "polkadot-node-network-protocol" -version = "21.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-channel 1.9.0", "async-trait", @@ -8339,8 +8331,8 @@ dependencies = [ [[package]] name = "polkadot-node-primitives" -version = "17.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bitvec", "bounded-vec", @@ -8355,21 +8347,18 @@ dependencies = [ "sp-application-crypto", "sp-consensus-babe", "sp-consensus-slots", - "sp-core", "sp-keystore", "sp-maybe-compressed-blob", - "sp-runtime", "thiserror 1.0.69", "zstd 0.12.4", ] [[package]] name = "polkadot-node-subsystem-types" -version = "21.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", - "bitvec", "derive_more 0.99.20", "fatality", "futures", @@ -8394,21 +8383,19 @@ dependencies = [ [[package]] name = "polkadot-overseer" -version = "21.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "22.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", "futures-timer", "orchestra", - "parking_lot 0.12.4", "polkadot-node-metrics", "polkadot-node-network-protocol", "polkadot-node-primitives", "polkadot-node-subsystem-types", "polkadot-primitives", "sc-client-api", - "sp-api", "sp-core", "tikv-jemalloc-ctl", "tracing-gum", @@ -8416,8 +8403,8 @@ dependencies = [ [[package]] name = "polkadot-parachain-primitives" -version = "15.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "16.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bounded-collections", "derive_more 0.99.20", @@ -8432,8 +8419,8 @@ dependencies = [ [[package]] name = "polkadot-primitives" -version = "17.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "18.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bitvec", "hex-literal", @@ -8454,14 +8441,23 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "thiserror 1.0.69", ] +[[package]] +name = "polkadot-sdk" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb819108697967452fa6d8d96ab4c0d48cbaa423b3156499dcb24f1cf95d6775" +dependencies = [ + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "polkadot-sdk-frame" -version = "0.8.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.9.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-benchmarking", @@ -8474,6 +8470,7 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", + "serde", "sp-api", "sp-arithmetic", "sp-block-builder", @@ -8494,44 +8491,44 @@ dependencies = [ [[package]] name = "polkadot-statement-table" -version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "polkadot-primitives", - "sp-core", "tracing-gum", ] [[package]] name = "polkavm" -version = "0.9.3" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a3693e5efdb2bf74e449cd25fd777a28bd7ed87e41f5d5da75eb31b4de48b94" +checksum = "dd044ab1d3b11567ab6b98ca71259a992b4034220d5972988a0e96518e5d343d" dependencies = [ "libc", "log", "polkavm-assembler", - "polkavm-common 0.9.0", + "polkavm-common 0.18.0", "polkavm-linux-raw", ] [[package]] name = "polkavm-assembler" -version = "0.9.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa96d6d868243acc12de813dd48e756cbadcc8e13964c70d272753266deadc1" +checksum = "eaad38dc420bfed79e6f731471c973ce5ff5e47ab403e63cf40358fef8a6368f" dependencies = [ "log", ] [[package]] name = "polkavm-common" -version = "0.9.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9428a5cfcc85c5d7b9fc4b6a18c4b802d0173d768182a51cc7751640f08b92" +checksum = "31ff33982a807d8567645d4784b9b5d7ab87bcb494f534a57cadd9012688e102" dependencies = [ "log", + "polkavm-assembler", ] [[package]] @@ -8542,11 +8539,11 @@ checksum = "49a5794b695626ba70d29e66e3f4f4835767452a6723f3a0bc20884b07088fe8" [[package]] name = "polkavm-derive" -version = "0.9.1" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8c4bea6f3e11cd89bb18bcdddac10bd9a24015399bd1c485ad68a985a19606" +checksum = "c2eb703f3b6404c13228402e98a5eae063fd16b8f58afe334073ec105ee4117e" dependencies = [ - "polkavm-derive-impl-macro 0.9.0", + "polkavm-derive-impl-macro 0.18.0", ] [[package]] @@ -8560,11 +8557,11 @@ dependencies = [ [[package]] name = "polkavm-derive-impl" -version = "0.9.0" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c4fdfc49717fb9a196e74a5d28e0bc764eb394a2c803eb11133a31ac996c60c" +checksum = "2f2116a92e6e96220a398930f4c8a6cda1264206f3e2034fc9982bfd93f261f7" dependencies = [ - "polkavm-common 0.9.0", + "polkavm-common 0.18.0", "proc-macro2", "quote", "syn 2.0.104", @@ -8584,11 +8581,11 @@ dependencies = [ [[package]] name = "polkavm-derive-impl-macro" -version = "0.9.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba81f7b5faac81e528eb6158a6f3c9e0bb1008e0ffa19653bc8dea925ecb429" +checksum = "48c16669ddc7433e34c1007d31080b80901e3e8e523cb9d4b441c3910cf9294b" dependencies = [ - "polkavm-derive-impl 0.9.0", + "polkavm-derive-impl 0.18.1", "syn 2.0.104", ] @@ -8604,38 +8601,38 @@ dependencies = [ [[package]] name = "polkavm-linker" -version = "0.9.2" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c7be503e60cf56c0eb785f90aaba4b583b36bff00e93997d93fef97f9553c39" +checksum = "e9bfe793b094d9ea5c99b7c43ba46e277b0f8f48f4bbfdbabf8d3ebf701a4bd3" dependencies = [ - "gimli 0.28.1", + "dirs", + "gimli 0.31.1", "hashbrown 0.14.5", "log", - "object 0.32.2", - "polkavm-common 0.9.0", + "object 0.36.7", + "polkavm-common 0.18.0", "regalloc2 0.9.3", "rustc-demangle", ] [[package]] name = "polkavm-linux-raw" -version = "0.9.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26e85d3456948e650dff0cfc85603915847faf893ed1e66b020bb82ef4557120" +checksum = "23eff02c070c70f31878a3d915e88a914ecf3e153741e2fb572dde28cce20fde" [[package]] name = "polling" -version = "3.8.0" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b53a684391ad002dd6a596ceb6c74fd004fdce75f4be2e3f615068abbea5fd50" +checksum = "8ee9b2fa7a4517d2c91ff5bc6c297a427a96749d15f98fcdbb22c05571a4d4b7" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi 0.5.2", "pin-project-lite", "rustix 1.0.8", - "tracing", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -8694,7 +8691,7 @@ dependencies = [ [[package]] name = "precompile-utils" version = "0.1.0" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "environmental", "evm", @@ -8718,31 +8715,17 @@ dependencies = [ [[package]] name = "precompile-utils-macro" version = "0.1.0" -source = "git+https://github.com/opentensor/frontier?rev=fe6976888fda696771cd15f78dbbdd71ee6c1216#fe6976888fda696771cd15f78dbbdd71ee6c1216" +source = "git+https://github.com/opentensor/frontier?rev=c591df98c524e1599c45f93cf4685248088ac014#c591df98c524e1599c45f93cf4685248088ac014" dependencies = [ "case", "num_enum", "prettyplease", "proc-macro2", "quote", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "syn 2.0.104", ] -[[package]] -name = "predicates" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" -dependencies = [ - "difflib", - "float-cmp", - "itertools 0.10.5", - "normalize-line-endings", - "predicates-core", - "regex", -] - [[package]] name = "predicates" version = "3.1.3" @@ -8771,9 +8754,9 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.35" +version = "0.2.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "061c1221631e079b26479d25bbf2275bfe5917ae8419cd7e34f13bfc2aa7539a" +checksum = "ff24dfcda44452b9816fff4cd4227e1bb73ff5a2f1bc1105aa92fb8565ce44d2" dependencies = [ "proc-macro2", "syn 2.0.104", @@ -8789,7 +8772,6 @@ dependencies = [ "impl-codec 0.6.0", "impl-rlp 0.3.0", "impl-serde 0.4.0", - "scale-info", "uint 0.9.5", ] @@ -8868,13 +8850,24 @@ dependencies = [ ] [[package]] -name = "proc-macro-warning" -version = "0.4.2" +name = "proc-macro-error-attr2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" dependencies = [ "proc-macro2", "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", "syn 2.0.104", ] @@ -8909,11 +8902,11 @@ dependencies = [ "frame-support-procedural-tools 10.0.0", "itertools 0.10.5", "macro_magic", - "proc-macro-warning 1.84.1", + "proc-macro-warning", "proc-macro2", "quote", "regex", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "syn 2.0.104", ] @@ -8933,9 +8926,9 @@ dependencies = [ [[package]] name = "prometheus-client" -version = "0.21.2" +version = "0.22.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c99afa9a01501019ac3a14d71d9f94050346f55ca471ce90c799a15c58f61e2" +checksum = "504ee9ff529add891127c4827eb481bd69dc0ebc72e9a682e187db4caa60c3ca" dependencies = [ "dtoa", "itoa", @@ -8965,7 +8958,7 @@ dependencies = [ "bitflags 2.9.1", "lazy_static", "num-traits", - "rand 0.9.1", + "rand 0.9.2", "rand_chacha 0.9.0", "rand_xorshift", "regex-syntax 0.8.5", @@ -9090,63 +9083,71 @@ dependencies = [ [[package]] name = "quick-protobuf-codec" -version = "0.2.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ededb1cd78531627244d51dd0c7139fbe736c7d57af0092a76f0ffb2f56e98" +checksum = "15a0580ab32b169745d7a39db2ba969226ca16738931be152a3209b409de2474" dependencies = [ - "asynchronous-codec", + "asynchronous-codec 0.7.0", "bytes", "quick-protobuf", "thiserror 1.0.69", - "unsigned-varint 0.7.2", + "unsigned-varint 0.8.0", ] [[package]] name = "quinn" -version = "0.10.2" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cc2c5017e4b43d5995dcea317bc46c1e09404c0a9664d2908f7f02dfe943d75" +checksum = "626214629cda6781b6dc1d316ba307189c85ba657213ce642d9c77670f8202c8" dependencies = [ "bytes", + "cfg_aliases 0.2.1", "futures-io", "pin-project-lite", "quinn-proto", "quinn-udp", - "rustc-hash 1.1.0", - "rustls 0.21.12", - "thiserror 1.0.69", + "rustc-hash 2.1.1", + "rustls", + "socket2 0.5.10", + "thiserror 2.0.12", "tokio", "tracing", + "web-time", ] [[package]] name = "quinn-proto" -version = "0.10.6" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "141bf7dfde2fbc246bfd3fe12f2455aa24b0fbd9af535d8c86c7bd1381ff2b1a" +checksum = "49df843a9161c85bb8aae55f101bc0bac8bcafd637a620d9122fd7e0b2f7422e" dependencies = [ "bytes", - "rand 0.8.5", - "ring 0.16.20", - "rustc-hash 1.1.0", - "rustls 0.21.12", + "getrandom 0.3.3", + "lru-slab", + "rand 0.9.2", + "ring 0.17.14", + "rustc-hash 2.1.1", + "rustls", + "rustls-pki-types", "slab", - "thiserror 1.0.69", + "thiserror 2.0.12", "tinyvec", "tracing", + "web-time", ] [[package]] name = "quinn-udp" -version = "0.4.1" +version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "055b4e778e8feb9f93c4e439f71dc2156ef13360b432b799e179a8c4cdf0b1d7" +checksum = "fcebb1209ee276352ef14ff8732e24cc2b02bbac986cd74a4c81bcb2f9881970" dependencies = [ - "bytes", + "cfg_aliases 0.2.1", "libc", + "once_cell", "socket2 0.5.10", "tracing", - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] @@ -9183,9 +9184,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", @@ -9294,9 +9295,9 @@ dependencies = [ [[package]] name = "rcgen" -version = "0.10.0" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffbe84efe2f38dea12e9bfc1f65377fdf03e53a18cb3b995faedf7934c7e785b" +checksum = "52c4f3084aa3bc7dfbba4eff4fab2a54db4324965d8872ab933565e6fbd83bc6" dependencies = [ "pem", "ring 0.16.20", @@ -9304,22 +9305,6 @@ dependencies = [ "yasna", ] -[[package]] -name = "reconnecting-jsonrpsee-ws-client" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06fa4f17e09edfc3131636082faaec633c7baa269396b4004040bc6c52f49f65" -dependencies = [ - "cfg_aliases 0.2.1", - "finito", - "futures", - "jsonrpsee 0.23.2", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tracing", -] - [[package]] name = "redox_syscall" version = "0.2.16" @@ -9331,9 +9316,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.13" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ "bitflags 2.9.1", ] @@ -9598,7 +9583,7 @@ dependencies = [ "primitive-types 0.12.2", "proptest", "rand 0.8.5", - "rand 0.9.1", + "rand 0.9.2", "rlp 0.5.2", "ruint-macro", "serde", @@ -9614,9 +9599,9 @@ checksum = "48fd7bd8a6377e15ad9d42a8ec25371b94ddc67abe7c8b9127bec79bebaaae18" [[package]] name = "rustc-demangle" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "rustc-hash" @@ -9714,35 +9699,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.12" +version = "0.23.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" -dependencies = [ - "log", - "ring 0.17.14", - "rustls-webpki 0.101.7", - "sct", -] - -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring 0.17.14", - "rustls-pki-types", - "rustls-webpki 0.102.8", - "subtle 2.6.1", - "zeroize", -] - -[[package]] -name = "rustls" -version = "0.23.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2491382039b29b9b11ff08b76ff6c97cf287671dbb74f0be44bda389fffe9bd1" +checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc" dependencies = [ "log", "once_cell", @@ -9753,31 +9712,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "rustls-native-certs" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" -dependencies = [ - "openssl-probe", - "rustls-pemfile 1.0.4", - "schannel", - "security-framework 2.11.1", -] - -[[package]] -name = "rustls-native-certs" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" -dependencies = [ - "openssl-probe", - "rustls-pemfile 2.2.0", - "rustls-pki-types", - "schannel", - "security-framework 2.11.1", -] - [[package]] name = "rustls-native-certs" version = "0.8.1" @@ -9790,52 +9724,35 @@ dependencies = [ "security-framework 3.2.0", ] -[[package]] -name = "rustls-pemfile" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" -dependencies = [ - "base64 0.21.7", -] - -[[package]] -name = "rustls-pemfile" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "rustls-pki-types" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" dependencies = [ + "web-time", "zeroize", ] [[package]] name = "rustls-platform-verifier" -version = "0.3.4" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afbb878bdfdf63a336a5e63561b1835e7a8c91524f51621db870169eac84b490" +checksum = "19787cda76408ec5404443dc8b31795c87cd8fec49762dc75fa727740d34acc1" dependencies = [ - "core-foundation 0.9.4", + "core-foundation 0.10.1", "core-foundation-sys", "jni", "log", "once_cell", - "rustls 0.23.29", - "rustls-native-certs 0.7.3", + "rustls", + "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki 0.102.8", - "security-framework 2.11.1", + "rustls-webpki 0.103.4", + "security-framework 3.2.0", "security-framework-sys", - "webpki-roots 0.26.11", - "winapi", + "webpki-root-certs 0.26.11", + "windows-sys 0.59.0", ] [[package]] @@ -9854,17 +9771,6 @@ dependencies = [ "untrusted 0.9.0", ] -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "ring 0.17.14", - "rustls-pki-types", - "untrusted 0.9.0", -] - [[package]] name = "rustls-webpki" version = "0.103.4" @@ -9896,13 +9802,12 @@ dependencies = [ [[package]] name = "ruzstd" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d" +checksum = "5174a470eeb535a721ae9fdd6e291c2411a906b96592182d05217591d5c5cf7b" dependencies = [ "byteorder", "derive_more 0.99.20", - "twox-hash", ] [[package]] @@ -9928,7 +9833,7 @@ version = "0.1.0" dependencies = [ "num-traits", "sp-arithmetic", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "substrate-fixed", ] @@ -9950,6 +9855,15 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "same-file" version = "1.0.6" @@ -9961,8 +9875,8 @@ dependencies = [ [[package]] name = "sc-allocator" -version = "30.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "31.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "log", "sp-core", @@ -9972,17 +9886,15 @@ dependencies = [ [[package]] name = "sc-authority-discovery" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", "futures-timer", "ip_network", - "libp2p", "linked_hash_set", "log", - "multihash 0.19.3", "parity-scale-codec", "prost 0.12.6", "prost-build", @@ -10002,11 +9914,10 @@ dependencies = [ [[package]] name = "sc-basic-authorship" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "futures", - "futures-timer", "log", "parity-scale-codec", "sc-block-builder", @@ -10024,8 +9935,8 @@ dependencies = [ [[package]] name = "sc-block-builder" -version = "0.43.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.44.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "sp-api", @@ -10039,12 +9950,11 @@ dependencies = [ [[package]] name = "sc-chain-spec" -version = "41.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "42.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "docify", - "log", "memmap2 0.9.7", "parity-scale-codec", "sc-chain-spec-derive", @@ -10056,18 +9966,18 @@ dependencies = [ "serde_json", "sp-blockchain", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-genesis-builder", "sp-io", "sp-runtime", "sp-state-machine", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", ] [[package]] name = "sc-chain-spec-derive" version = "12.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "proc-macro-crate 3.3.0", "proc-macro2", @@ -10077,8 +9987,8 @@ dependencies = [ [[package]] name = "sc-cli" -version = "0.50.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.51.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "chrono", @@ -10119,8 +10029,8 @@ dependencies = [ [[package]] name = "sc-client-api" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "fnv", "futures", @@ -10138,7 +10048,6 @@ dependencies = [ "sp-externalities 0.30.0", "sp-runtime", "sp-state-machine", - "sp-statement-store", "sp-storage 22.0.0", "sp-trie", "substrate-prometheus-endpoint", @@ -10146,8 +10055,8 @@ dependencies = [ [[package]] name = "sc-client-db" -version = "0.45.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.46.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "hash-db", "kvdb", @@ -10172,19 +10081,18 @@ dependencies = [ [[package]] name = "sc-consensus" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", "log", - "mockall 0.11.4", + "mockall", "parking_lot 0.12.4", "sc-client-api", "sc-network-types", "sc-utils", "serde", - "sp-api", "sp-blockchain", "sp-consensus", "sp-core", @@ -10196,8 +10104,8 @@ dependencies = [ [[package]] name = "sc-consensus-aura" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", @@ -10225,8 +10133,8 @@ dependencies = [ [[package]] name = "sc-consensus-babe" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "fork-tree", @@ -10251,7 +10159,7 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-slots", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-inherents", "sp-keystore", "sp-runtime", @@ -10261,8 +10169,8 @@ dependencies = [ [[package]] name = "sc-consensus-epochs" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "fork-tree", "parity-scale-codec", @@ -10275,7 +10183,7 @@ dependencies = [ [[package]] name = "sc-consensus-grandpa" version = "0.33.0" -source = "git+https://github.com/opentensor/grandpa.git?rev=b3ba2f67d510559edfb4963523de86ed89439d74#b3ba2f67d510559edfb4963523de86ed89439d74" +source = "git+https://github.com/opentensor/grandpa.git?rev=67ff75e915bd44586b8f8443e457b5b101920da8#67ff75e915bd44586b8f8443e457b5b101920da8" dependencies = [ "ahash 0.8.12", "array-bytes", @@ -10309,7 +10217,7 @@ dependencies = [ "sp-consensus", "sp-consensus-grandpa", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-keystore", "sp-runtime", "substrate-prometheus-endpoint", @@ -10318,12 +10226,12 @@ dependencies = [ [[package]] name = "sc-consensus-grandpa-rpc" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.34.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "finality-grandpa", "futures", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "sc-client-api", @@ -10338,14 +10246,14 @@ dependencies = [ [[package]] name = "sc-consensus-manual-seal" -version = "0.49.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.50.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "assert_matches", "async-trait", "futures", "futures-timer", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "sc-client-api", @@ -10373,8 +10281,8 @@ dependencies = [ [[package]] name = "sc-consensus-slots" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", @@ -10396,8 +10304,8 @@ dependencies = [ [[package]] name = "sc-executor" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "parking_lot 0.12.4", @@ -10410,7 +10318,7 @@ dependencies = [ "sp-externalities 0.30.0", "sp-io", "sp-panic-handler", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-trie", "sp-version", "sp-wasm-interface 21.0.1", @@ -10419,8 +10327,8 @@ dependencies = [ [[package]] name = "sc-executor-common" -version = "0.36.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.38.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "polkavm", "sc-allocator", @@ -10432,8 +10340,8 @@ dependencies = [ [[package]] name = "sc-executor-polkavm" -version = "0.33.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.35.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "log", "polkavm", @@ -10443,26 +10351,24 @@ dependencies = [ [[package]] name = "sc-executor-wasmtime" -version = "0.36.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.38.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "anyhow", - "cfg-if", - "libc", "log", "parking_lot 0.12.4", "rustix 0.36.17", "sc-allocator", "sc-executor-common", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-wasm-interface 21.0.1", "wasmtime", ] [[package]] name = "sc-informant" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "console", "futures", @@ -10470,7 +10376,6 @@ dependencies = [ "log", "sc-client-api", "sc-network", - "sc-network-common", "sc-network-sync", "sp-blockchain", "sp-runtime", @@ -10478,8 +10383,8 @@ dependencies = [ [[package]] name = "sc-keystore" -version = "34.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "35.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "parking_lot 0.12.4", @@ -10492,8 +10397,8 @@ dependencies = [ [[package]] name = "sc-mixnet" -version = "0.18.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.19.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "arrayvec 0.7.6", @@ -10503,7 +10408,6 @@ dependencies = [ "futures-timer", "log", "mixnet", - "multiaddr 0.18.2", "parity-scale-codec", "parking_lot 0.12.4", "sc-client-api", @@ -10521,13 +10425,13 @@ dependencies = [ [[package]] name = "sc-network" -version = "0.48.4" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.2" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "async-channel 1.9.0", "async-trait", - "asynchronous-codec", + "asynchronous-codec 0.6.2", "bytes", "cid 0.9.0", "either", @@ -10539,8 +10443,7 @@ dependencies = [ "linked_hash_set", "litep2p", "log", - "mockall 0.11.4", - "once_cell", + "mockall", "parity-scale-codec", "parking_lot 0.12.4", "partial_sort", @@ -10572,26 +10475,18 @@ dependencies = [ [[package]] name = "sc-network-common" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "async-trait", "bitflags 1.3.2", - "futures", - "libp2p-identity", "parity-scale-codec", - "prost-build", - "sc-consensus", - "sc-network-types", - "sp-consensus", - "sp-consensus-grandpa", "sp-runtime", ] [[package]] name = "sc-network-gossip" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "ahash 0.8.12", "futures", @@ -10609,8 +10504,8 @@ dependencies = [ [[package]] name = "sc-network-light" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "async-channel 1.9.0", @@ -10630,17 +10525,16 @@ dependencies = [ [[package]] name = "sc-network-sync" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "async-channel 1.9.0", "async-trait", "fork-tree", "futures", - "futures-timer", "log", - "mockall 0.11.4", + "mockall", "parity-scale-codec", "prost 0.12.6", "prost-build", @@ -10666,8 +10560,8 @@ dependencies = [ [[package]] name = "sc-network-transactions" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "futures", @@ -10685,12 +10579,14 @@ dependencies = [ [[package]] name = "sc-network-types" -version = "0.15.2" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.15.4" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bs58", + "bytes", "ed25519-dalek", "libp2p-identity", + "libp2p-kad", "litep2p", "log", "multiaddr 0.18.2", @@ -10702,28 +10598,25 @@ dependencies = [ [[package]] name = "sc-offchain" -version = "43.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "44.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "array-bytes", "bytes", "fnv", "futures", "futures-timer", "http-body-util", "hyper 1.6.0", - "hyper-rustls 0.27.7", + "hyper-rustls", "hyper-util", - "log", "num_cpus", "once_cell", "parity-scale-codec", "parking_lot 0.12.4", "rand 0.8.5", - "rustls 0.23.29", + "rustls", "sc-client-api", "sc-network", - "sc-network-common", "sc-network-types", "sc-transaction-pool-api", "sc-utils", @@ -10739,8 +10632,8 @@ dependencies = [ [[package]] name = "sc-proposer-metrics" -version = "0.18.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.20.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "log", "substrate-prometheus-endpoint", @@ -10748,11 +10641,11 @@ dependencies = [ [[package]] name = "sc-rpc" -version = "43.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "44.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "futures", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.4", @@ -10780,10 +10673,10 @@ dependencies = [ [[package]] name = "sc-rpc-api" -version = "0.47.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.48.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "jsonrpsee 0.24.9", + "jsonrpsee", "parity-scale-codec", "sc-chain-spec", "sc-mixnet", @@ -10800,8 +10693,8 @@ dependencies = [ [[package]] name = "sc-rpc-server" -version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "21.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "dyn-clone", "forwarded-header-value", @@ -10811,7 +10704,7 @@ dependencies = [ "http-body-util", "hyper 1.6.0", "ip_network", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "sc-rpc-api", "serde", @@ -10824,15 +10717,15 @@ dependencies = [ [[package]] name = "sc-rpc-spec-v2" -version = "0.48.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.49.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "futures", "futures-util", "hex", "itertools 0.11.0", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.4", @@ -10854,17 +10747,32 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "sc-runtime-utilities" +version = "0.2.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" +dependencies = [ + "parity-scale-codec", + "sc-executor", + "sc-executor-common", + "sp-core", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-state-machine", + "sp-wasm-interface 21.0.1", + "thiserror 1.0.69", +] + [[package]] name = "sc-service" -version = "0.49.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.50.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "directories", "exit-future", "futures", "futures-timer", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.4", @@ -10920,8 +10828,8 @@ dependencies = [ [[package]] name = "sc-state-db" -version = "0.37.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.38.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "log", "parity-scale-codec", @@ -10931,8 +10839,8 @@ dependencies = [ [[package]] name = "sc-sysinfo" -version = "41.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "42.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "derive_more 0.99.20", "futures", @@ -10945,15 +10853,14 @@ dependencies = [ "serde", "serde_json", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-io", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", ] [[package]] name = "sc-telemetry" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "28.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "chrono", "futures", @@ -10962,7 +10869,6 @@ dependencies = [ "parking_lot 0.12.4", "pin-project", "rand 0.8.5", - "sc-network", "sc-utils", "serde", "serde_json", @@ -10972,8 +10878,8 @@ dependencies = [ [[package]] name = "sc-tracing" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "chrono", "console", @@ -10991,7 +10897,7 @@ dependencies = [ "sp-core", "sp-rpc", "sp-runtime", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "thiserror 1.0.69", "tracing", "tracing-log", @@ -11000,8 +10906,8 @@ dependencies = [ [[package]] name = "sc-tracing-proc-macro" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "11.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "proc-macro-crate 3.3.0", "proc-macro2", @@ -11011,8 +10917,8 @@ dependencies = [ [[package]] name = "sc-transaction-pool" -version = "38.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", @@ -11030,23 +10936,25 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-runtime", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "sp-transaction-pool", "substrate-prometheus-endpoint", "thiserror 1.0.69", "tokio", "tokio-stream", + "tracing", ] [[package]] name = "sc-transaction-pool-api" -version = "38.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", + "indexmap 2.10.0", "log", "parity-scale-codec", "serde", @@ -11058,8 +10966,8 @@ dependencies = [ [[package]] name = "sc-utils" -version = "18.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "18.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-channel 1.9.0", "futures", @@ -11090,7 +10998,20 @@ checksum = "e98f3262c250d90e700bb802eb704e1f841e03331c2eb815e46516c4edbf5b27" dependencies = [ "derive_more 0.99.20", "parity-scale-codec", - "primitive-types 0.12.2", + "scale-bits", + "scale-type-resolver", + "smallvec", +] + +[[package]] +name = "scale-decode" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ae9cc099ae85ff28820210732b00f019546f36f33225f509fe25d5816864a0" +dependencies = [ + "derive_more 1.0.0", + "parity-scale-codec", + "primitive-types 0.13.1", "scale-bits", "scale-decode-derive", "scale-type-resolver", @@ -11099,25 +11020,25 @@ dependencies = [ [[package]] name = "scale-decode-derive" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb22f574168103cdd3133b19281639ca65ad985e24612728f727339dcaf4021" +checksum = "5ed9401effa946b493f9f84dc03714cca98119b230497df6f3df6b84a2b03648" dependencies = [ - "darling 0.14.4", + "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.104", ] [[package]] name = "scale-encode" -version = "0.7.2" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "528464e6ae6c8f98e2b79633bf79ef939552e795e316579dab09c61670d56602" +checksum = "5f9271284d05d0749c40771c46180ce89905fd95aa72a2a2fddb4b7c0aa424db" dependencies = [ - "derive_more 0.99.20", + "derive_more 1.0.0", "parity-scale-codec", - "primitive-types 0.12.2", + "primitive-types 0.13.1", "scale-bits", "scale-encode-derive", "scale-type-resolver", @@ -11126,11 +11047,11 @@ dependencies = [ [[package]] name = "scale-encode-derive" -version = "0.7.2" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef2618f123c88da9cd8853b69d766068f1eddc7692146d7dfe9b89e25ce2efd" +checksum = "102fbc6236de6c53906c0b262f12c7aa69c2bdc604862c12728f5f4d370bc137" dependencies = [ - "darling 0.20.11", + "darling", "proc-macro-crate 3.3.0", "proc-macro2", "quote", @@ -11175,9 +11096,9 @@ dependencies = [ [[package]] name = "scale-typegen" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "498d1aecf2ea61325d4511787c115791639c0fd21ef4f8e11e49dd09eff2bbac" +checksum = "0dc4c70c7fea2eef1740f0081d3fe385d8bee1eef11e9272d3bec7dc8e5438e0" dependencies = [ "proc-macro2", "quote", @@ -11188,18 +11109,17 @@ dependencies = [ [[package]] name = "scale-value" -version = "0.16.3" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cd6ab090d823e75cfdb258aad5fe92e13f2af7d04b43a55d607d25fcc38c811" +checksum = "f5e0ef2a0ee1e02a69ada37feb87ea1616ce9808aca072befe2d3131bf28576e" dependencies = [ "base58", "blake2 0.10.6", - "derive_more 0.99.20", + "derive_more 1.0.0", "either", - "frame-metadata 15.1.0", "parity-scale-codec", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-type-resolver", @@ -11216,6 +11136,30 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "schnellru" version = "0.2.4" @@ -11265,13 +11209,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f6280af86e5f559536da57a45ebc84948833b3bee313a7dd25232e09c878a52" [[package]] -name = "sct" -version = "0.7.1" +name = "scrypt" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" dependencies = [ - "ring 0.17.14", - "untrusted 0.9.0", + "password-hash", + "pbkdf2", + "salsa20", + "sha2 0.10.9", ] [[package]] @@ -11307,6 +11253,17 @@ dependencies = [ "secp256k1-sys 0.9.2", ] +[[package]] +name = "secp256k1" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" +dependencies = [ + "bitcoin_hashes 0.14.0", + "rand 0.8.5", + "secp256k1-sys 0.10.1", +] + [[package]] name = "secp256k1-sys" version = "0.8.2" @@ -11325,6 +11282,15 @@ dependencies = [ "cc", ] +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + [[package]] name = "secrecy" version = "0.8.0" @@ -11334,6 +11300,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secrecy" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" +dependencies = [ + "zeroize", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -11344,7 +11319,6 @@ dependencies = [ "core-foundation 0.9.4", "core-foundation-sys", "libc", - "num-bigint", "security-framework-sys", ] @@ -11422,12 +11396,6 @@ dependencies = [ "pest", ] -[[package]] -name = "send_wrapper" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" - [[package]] name = "serde" version = "1.0.219" @@ -11478,9 +11446,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -11511,15 +11479,19 @@ dependencies = [ [[package]] name = "serde_with" -version = "2.0.0" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89df7a26519371a3cce44fbb914c2819c84d9b897890987fa3ab096491cc0ea8" +checksum = "f2c45cd61fefa9db6f254525d46e392b852e0e61d9a1fd36e5bd183450a556d5" dependencies = [ - "base64 0.13.1", + "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", + "indexmap 2.10.0", + "schemars 0.9.0", + "schemars 1.0.4", "serde", + "serde_derive", "serde_json", "serde_with_macros", "time", @@ -11527,11 +11499,11 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "2.3.3" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" +checksum = "de90945e6565ce0d9a25098082ed4ee4002e047cb59892c318d66821e14bb30f" dependencies = [ - "darling 0.20.11", + "darling", "proc-macro2", "quote", "syn 2.0.104", @@ -11547,19 +11519,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha-1" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.1", -] - [[package]] name = "sha1" version = "0.10.6" @@ -11629,7 +11588,7 @@ name = "share-pool" version = "0.1.0" dependencies = [ "safe-math", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "substrate-fixed", ] @@ -11735,14 +11694,14 @@ dependencies = [ [[package]] name = "smoldot" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d1eaa97d77be4d026a1e7ffad1bb3b78448763b357ea6f8188d3e6f736a9b9" +checksum = "966e72d77a3b2171bb7461d0cb91f43670c63558c62d7cf42809cae6c8b6b818" dependencies = [ "arrayvec 0.7.6", "async-lock", "atomic-take", - "base64 0.21.7", + "base64 0.22.1", "bip39", "blake2-rfc", "bs58", @@ -11751,18 +11710,17 @@ dependencies = [ "derive_more 0.99.20", "ed25519-zebra", "either", - "event-listener 4.0.3", + "event-listener 5.4.0", "fnv", "futures-lite", "futures-util", "hashbrown 0.14.5", "hex", "hmac 0.12.1", - "itertools 0.12.1", + "itertools 0.13.0", "libm", "libsecp256k1", "merlin", - "no-std-net", "nom", "num-bigint", "num-rational", @@ -11781,7 +11739,7 @@ dependencies = [ "siphasher 1.0.1", "slab", "smallvec", - "soketto 0.7.1", + "soketto", "twox-hash", "wasmi", "x25519-dalek", @@ -11790,27 +11748,27 @@ dependencies = [ [[package]] name = "smoldot-light" -version = "0.14.0" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5496f2d116b7019a526b1039ec2247dd172b8670633b1a64a614c9ea12c9d8c7" +checksum = "2a33b06891f687909632ce6a4e3fd7677b24df930365af3d0bcb078310129f3f" dependencies = [ "async-channel 2.5.0", "async-lock", - "base64 0.21.7", + "base64 0.22.1", "blake2-rfc", + "bs58", "derive_more 0.99.20", "either", - "event-listener 4.0.3", + "event-listener 5.4.0", "fnv", "futures-channel", "futures-lite", "futures-util", "hashbrown 0.14.5", "hex", - "itertools 0.12.1", + "itertools 0.13.0", "log", "lru 0.12.5", - "no-std-net", "parking_lot 0.12.4", "pin-project", "rand 0.8.5", @@ -11847,16 +11805,6 @@ dependencies = [ "subtle 2.6.1", ] -[[package]] -name = "socket2" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "socket2" version = "0.5.10" @@ -11868,18 +11816,13 @@ dependencies = [ ] [[package]] -name = "soketto" -version = "0.7.1" +name = "socket2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d1c5305e39e09653383c2c7244f2f78b3bcae37cf50c64cb4789c9f5096ec2" +checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807" dependencies = [ - "base64 0.13.1", - "bytes", - "futures", - "httparse", - "log", - "rand 0.8.5", - "sha-1", + "libc", + "windows-sys 0.59.0", ] [[package]] @@ -11900,8 +11843,8 @@ dependencies = [ [[package]] name = "sp-api" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "hash-db", @@ -11913,7 +11856,7 @@ dependencies = [ "sp-externalities 0.30.0", "sp-metadata-ir", "sp-runtime", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-state-machine", "sp-trie", "sp-version", @@ -11922,8 +11865,8 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" -version = "21.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "22.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "Inflector", "blake2 0.10.6", @@ -11936,8 +11879,8 @@ dependencies = [ [[package]] name = "sp-application-crypto" -version = "39.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -11948,8 +11891,8 @@ dependencies = [ [[package]] name = "sp-arithmetic" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "26.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "integer-sqrt", @@ -11971,8 +11914,8 @@ dependencies = [ [[package]] name = "sp-authority-discovery" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -11983,8 +11926,8 @@ dependencies = [ [[package]] name = "sp-block-builder" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "sp-api", "sp-inherents", @@ -11993,8 +11936,8 @@ dependencies = [ [[package]] name = "sp-blockchain" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "futures", "parity-scale-codec", @@ -12012,13 +11955,12 @@ dependencies = [ [[package]] name = "sp-consensus" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "futures", "log", - "sp-core", "sp-inherents", "sp-runtime", "sp-state-machine", @@ -12027,8 +11969,8 @@ dependencies = [ [[package]] name = "sp-consensus-aura" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "parity-scale-codec", @@ -12043,8 +11985,8 @@ dependencies = [ [[package]] name = "sp-consensus-babe" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "parity-scale-codec", @@ -12061,8 +12003,8 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" -version = "22.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "23.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "finality-grandpa", "log", @@ -12078,8 +12020,8 @@ dependencies = [ [[package]] name = "sp-consensus-slots" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -12089,9 +12031,10 @@ dependencies = [ [[package]] name = "sp-core" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ + "ark-vrf", "array-bytes", "bitflags 1.3.2", "blake2 0.10.6", @@ -12117,13 +12060,13 @@ dependencies = [ "scale-info", "schnorrkel", "secp256k1 0.28.2", - "secrecy", + "secrecy 0.8.0", "serde", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-externalities 0.30.0", - "sp-runtime-interface 29.0.0", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-runtime-interface 29.0.1", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-storage 22.0.0", "ss58-registry", "substrate-bip39", @@ -12136,18 +12079,18 @@ dependencies = [ [[package]] name = "sp-crypto-ec-utils" version = "0.10.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "ark-bls12-377", "ark-bls12-377-ext", - "ark-bls12-381", + "ark-bls12-381 0.4.0", "ark-bls12-381-ext", "ark-bw6-761", "ark-bw6-761-ext", - "ark-ec", + "ark-ec 0.4.2", "ark-ed-on-bls12-377", "ark-ed-on-bls12-377-ext", - "ark-ed-on-bls12-381-bandersnatch", + "ark-ed-on-bls12-381-bandersnatch 0.4.0", "ark-ed-on-bls12-381-bandersnatch-ext", "ark-scale 0.0.12", "sp-runtime-interface 24.0.0", @@ -12156,21 +12099,21 @@ dependencies = [ [[package]] name = "sp-crypto-ec-utils" version = "0.15.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "ark-bls12-377", "ark-bls12-377-ext", - "ark-bls12-381", + "ark-bls12-381 0.4.0", "ark-bls12-381-ext", "ark-bw6-761", "ark-bw6-761-ext", - "ark-ec", + "ark-ec 0.4.2", "ark-ed-on-bls12-377", "ark-ed-on-bls12-377-ext", - "ark-ed-on-bls12-381-bandersnatch", + "ark-ed-on-bls12-381-bandersnatch 0.4.0", "ark-ed-on-bls12-381-bandersnatch-ext", "ark-scale 0.0.12", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", ] [[package]] @@ -12190,7 +12133,7 @@ dependencies = [ [[package]] name = "sp-crypto-hashing" version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "blake2b_simd", "byteorder", @@ -12203,17 +12146,17 @@ dependencies = [ [[package]] name = "sp-crypto-hashing-proc-macro" version = "0.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "quote", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "syn 2.0.104", ] [[package]] name = "sp-database" version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "kvdb", "parking_lot 0.12.4", @@ -12222,7 +12165,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "proc-macro2", "quote", @@ -12232,7 +12175,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "proc-macro2", "quote", @@ -12242,7 +12185,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.25.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "environmental", "parity-scale-codec", @@ -12252,7 +12195,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.30.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "environmental", "parity-scale-codec", @@ -12261,8 +12204,8 @@ dependencies = [ [[package]] name = "sp-genesis-builder" -version = "0.16.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.17.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -12273,8 +12216,8 @@ dependencies = [ [[package]] name = "sp-inherents" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -12286,8 +12229,8 @@ dependencies = [ [[package]] name = "sp-io" -version = "39.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "40.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bytes", "docify", @@ -12295,16 +12238,16 @@ dependencies = [ "libsecp256k1", "log", "parity-scale-codec", - "polkavm-derive 0.9.1", + "polkavm-derive 0.18.0", "rustversion", "secp256k1 0.28.2", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-externalities 0.30.0", "sp-keystore", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "sp-state-machine", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "sp-trie", "tracing", "tracing-core", @@ -12312,8 +12255,8 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "40.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "41.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "sp-core", "sp-runtime", @@ -12322,8 +12265,8 @@ dependencies = [ [[package]] name = "sp-keystore" -version = "0.41.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.42.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "parking_lot 0.12.4", @@ -12334,7 +12277,7 @@ dependencies = [ [[package]] name = "sp-maybe-compressed-blob" version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "thiserror 1.0.69", "zstd 0.12.4", @@ -12342,18 +12285,18 @@ dependencies = [ [[package]] name = "sp-metadata-ir" -version = "0.8.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.10.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ - "frame-metadata 18.0.0", + "frame-metadata 20.0.0", "parity-scale-codec", "scale-info", ] [[package]] name = "sp-mixnet" -version = "0.13.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.14.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -12363,8 +12306,8 @@ dependencies = [ [[package]] name = "sp-offchain" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "sp-api", "sp-core", @@ -12373,8 +12316,8 @@ dependencies = [ [[package]] name = "sp-panic-handler" -version = "13.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "13.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "backtrace", "regex", @@ -12382,8 +12325,8 @@ dependencies = [ [[package]] name = "sp-rpc" -version = "33.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "34.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "rustc-hash 1.1.0", "serde", @@ -12392,8 +12335,8 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "40.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "41.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "binary-merkle-tree", "docify", @@ -12412,7 +12355,7 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-io", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-trie", "sp-weights", "tracing", @@ -12422,13 +12365,12 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "24.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "bytes", "impl-trait-for-tuples", "parity-scale-codec", "polkavm-derive 0.26.0", - "primitive-types 0.13.1", "sp-externalities 0.25.0", "sp-runtime-interface-proc-macro 17.0.0", "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", @@ -12440,19 +12382,19 @@ dependencies = [ [[package]] name = "sp-runtime-interface" -version = "29.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "29.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bytes", "impl-trait-for-tuples", "parity-scale-codec", - "polkavm-derive 0.9.1", + "polkavm-derive 0.18.0", "primitive-types 0.13.1", "sp-externalities 0.30.0", "sp-runtime-interface-proc-macro 18.0.0", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-storage 22.0.0", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "sp-wasm-interface 21.0.1", "static_assertions", ] @@ -12460,7 +12402,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "Inflector", "expander", @@ -12473,7 +12415,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "18.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "Inflector", "expander", @@ -12485,8 +12427,8 @@ dependencies = [ [[package]] name = "sp-session" -version = "37.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "38.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "scale-info", @@ -12499,8 +12441,8 @@ dependencies = [ [[package]] name = "sp-staking" -version = "37.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "38.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -12512,8 +12454,8 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.44.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.45.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "hash-db", "log", @@ -12532,8 +12474,8 @@ dependencies = [ [[package]] name = "sp-statement-store" -version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "20.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "aes-gcm", "curve25519-dalek", @@ -12546,10 +12488,10 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-crypto-hashing 0.1.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-externalities 0.30.0", "sp-runtime", - "sp-runtime-interface 29.0.0", + "sp-runtime-interface 29.0.1", "thiserror 1.0.69", "x25519-dalek", ] @@ -12557,17 +12499,17 @@ dependencies = [ [[package]] name = "sp-std" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" [[package]] name = "sp-std" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" [[package]] name = "sp-storage" version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "impl-serde 0.5.0", "parity-scale-codec", @@ -12579,19 +12521,19 @@ dependencies = [ [[package]] name = "sp-storage" version = "22.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "impl-serde 0.5.0", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", ] [[package]] name = "sp-timestamp" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "parity-scale-codec", @@ -12603,7 +12545,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "parity-scale-codec", "regex", @@ -12614,8 +12556,8 @@ dependencies = [ [[package]] name = "sp-tracing" -version = "17.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "17.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", "tracing", @@ -12625,8 +12567,8 @@ dependencies = [ [[package]] name = "sp-transaction-pool" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "sp-api", "sp-runtime", @@ -12634,8 +12576,8 @@ dependencies = [ [[package]] name = "sp-transaction-storage-proof" -version = "35.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "36.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "async-trait", "parity-scale-codec", @@ -12648,8 +12590,8 @@ dependencies = [ [[package]] name = "sp-trie" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "ahash 0.8.12", "hash-db", @@ -12670,8 +12612,8 @@ dependencies = [ [[package]] name = "sp-version" -version = "38.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "39.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "impl-serde 0.5.0", "parity-scale-codec", @@ -12680,7 +12622,7 @@ dependencies = [ "serde", "sp-crypto-hashing-proc-macro", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "sp-version-proc-macro", "thiserror 1.0.69", ] @@ -12688,10 +12630,10 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "15.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "parity-scale-codec", - "proc-macro-warning 1.84.1", + "proc-macro-warning", "proc-macro2", "quote", "syn 2.0.104", @@ -12700,7 +12642,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#495d5a24c8078a0da1eb5e0fe8742a09f1f1bd5c" +source = "git+https://github.com/paritytech/polkadot-sdk#177b03958c766fe053f28424ee6f6748644bb794" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -12711,7 +12653,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "21.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -12722,8 +12664,8 @@ dependencies = [ [[package]] name = "sp-weights" -version = "31.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "31.1.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "bounded-collections", "parity-scale-codec", @@ -12731,7 +12673,7 @@ dependencies = [ "serde", "smallvec", "sp-arithmetic", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", ] [[package]] @@ -12896,12 +12838,12 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "staging-xcm" -version = "15.1.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "16.2.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "bounded-collections", - "derivative", + "derive-where", "environmental", "frame-support", "hex-literal", @@ -12950,10 +12892,14 @@ dependencies = [ ] [[package]] -name = "strsim" -version = "0.10.0" +name = "string-interner" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "1c6a0d765f5807e98a091107bae0a56ea3799f66a5de47b2c84c94a39c09974e" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", +] [[package]] name = "strsim" @@ -13005,7 +12951,7 @@ dependencies = [ [[package]] name = "substrate-bip39" version = "0.6.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "hmac 0.12.1", "pbkdf2", @@ -13030,28 +12976,28 @@ dependencies = [ [[package]] name = "substrate-build-script-utils" version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" [[package]] name = "substrate-fixed" -version = "0.5.9" -source = "git+https://github.com/opentensor/substrate-fixed.git?tag=v0.5.9#a4fb461aae6205ffc55bed51254a40c52be04e5d" +version = "0.6.0" +source = "git+https://github.com/encointer/substrate-fixed.git?tag=v0.6.0#d5f70362f2e05b5f33fb51cd7baa825323e4e6c5" dependencies = [ "parity-scale-codec", "scale-info", "serde", - "typenum 1.16.0", + "substrate-typenum", ] [[package]] name = "substrate-frame-rpc-system" -version = "42.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "43.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "docify", "frame-system-rpc-runtime-api", "futures", - "jsonrpsee 0.24.9", + "jsonrpsee", "log", "parity-scale-codec", "sc-rpc-api", @@ -13065,8 +13011,8 @@ dependencies = [ [[package]] name = "substrate-prometheus-endpoint" -version = "0.17.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "0.17.2" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "http-body-util", "hyper 1.6.0", @@ -13077,17 +13023,27 @@ dependencies = [ "tokio", ] +[[package]] +name = "substrate-typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cd64d3efe988228b8496698197ee60cfbfcedbf226961300e559870c1a3e8e0" +dependencies = [ + "parity-scale-codec", + "scale-info", +] + [[package]] name = "substrate-wasm-builder" -version = "25.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "26.0.1" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "array-bytes", "build-helper", "cargo_metadata", "console", "filetime", - "frame-metadata 18.0.0", + "frame-metadata 20.0.0", "jobserver", "merkleized-metadata", "parity-scale-codec", @@ -13098,7 +13054,7 @@ dependencies = [ "sp-core", "sp-io", "sp-maybe-compressed-blob", - "sp-tracing 17.0.1", + "sp-tracing 17.1.0", "sp-version", "strum 0.26.3", "tempfile", @@ -13111,8 +13067,6 @@ dependencies = [ name = "subtensor" version = "0.1.0" dependencies = [ - "node-subtensor", - "node-subtensor-runtime", "proc-macro2", "quote", "rayon", @@ -13125,7 +13079,7 @@ dependencies = [ name = "subtensor-custom-rpc" version = "0.0.2" dependencies = [ - "jsonrpsee 0.24.9", + "jsonrpsee", "pallet-subtensor", "parity-scale-codec", "serde", @@ -13196,7 +13150,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6)", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", "substrate-fixed", "subtensor-runtime-common", "subtensor-swap-interface", @@ -13234,10 +13188,45 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", + "node-subtensor-runtime", "semver 1.0.26", "toml_edit", ] +[[package]] +name = "subtensor-transaction-fee" +version = "0.1.0" +dependencies = [ + "frame-executive", + "frame-support", + "frame-system", + "log", + "pallet-balances", + "pallet-crowdloan", + "pallet-drand", + "pallet-evm-chain-id", + "pallet-grandpa", + "pallet-preimage", + "pallet-scheduler", + "pallet-subtensor", + "pallet-subtensor-swap", + "pallet-transaction-payment", + "parity-scale-codec", + "scale-info", + "smallvec", + "sp-consensus-aura", + "sp-consensus-grandpa", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6)", + "sp-tracing 17.1.0", + "sp-weights", + "substrate-fixed", + "subtensor-runtime-common", + "subtensor-swap-interface", +] + [[package]] name = "subtle" version = "1.0.0" @@ -13252,50 +13241,47 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "subxt" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a160cba1edbf3ec4fbbeaea3f1a185f70448116a6bccc8276bb39adb3b3053bd" +checksum = "1c17d7ec2359d33133b63c97e28c8b7cd3f0a5bc6ce567ae3aef9d9e85be3433" dependencies = [ "async-trait", "derive-where", "either", - "frame-metadata 16.0.0", + "frame-metadata 17.0.0", "futures", "hex", - "impl-serde 0.4.0", - "instant", - "jsonrpsee 0.22.5", + "impl-serde 0.5.0", + "jsonrpsee", "parity-scale-codec", - "primitive-types 0.12.2", - "reconnecting-jsonrpsee-ws-client", + "polkadot-sdk", + "primitive-types 0.13.1", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-value", "serde", "serde_json", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "subxt-core", "subxt-lightclient", "subxt-macro", "subxt-metadata", "thiserror 1.0.69", + "tokio", "tokio-util", "tracing", "url", + "web-time", ] [[package]] name = "subxt-codegen" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d703dca0905cc5272d7cc27a4ac5f37dcaae7671acc7fef0200057cc8c317786" +checksum = "6550ef451c77db6e3bc7c56fb6fe1dca9398a2c8fc774b127f6a396a769b9c5b" dependencies = [ - "frame-metadata 16.0.0", "heck 0.5.0", - "hex", - "jsonrpsee 0.22.5", "parity-scale-codec", "proc-macro2", "quote", @@ -13304,41 +13290,42 @@ dependencies = [ "subxt-metadata", "syn 2.0.104", "thiserror 1.0.69", - "tokio", ] [[package]] name = "subxt-core" -version = "0.37.1" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3af3b36405538a36b424d229dc908d1396ceb0994c90825ce928709eac1a159a" +checksum = "cb7a1bc6c9c1724971636a66e3225a7253cdb35bb6efb81524a6c71c04f08c59" dependencies = [ "base58", "blake2 0.10.6", "derive-where", - "frame-metadata 16.0.0", + "frame-decode", + "frame-metadata 17.0.0", "hashbrown 0.14.5", "hex", - "impl-serde 0.4.0", + "impl-serde 0.5.0", + "keccak-hash", "parity-scale-codec", - "primitive-types 0.12.2", + "polkadot-sdk", + "primitive-types 0.13.1", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-value", "serde", "serde_json", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "subxt-metadata", "tracing", ] [[package]] name = "subxt-lightclient" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d9406fbdb9548c110803cb8afa750f8b911d51eefdf95474b11319591d225d9" +checksum = "89ebc9131da4d0ba1f7814495b8cc79698798ccd52cacd7bcefe451e415bd945" dependencies = [ "futures", "futures-util", @@ -13353,56 +13340,74 @@ dependencies = [ [[package]] name = "subxt-macro" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c195f803d70687e409aba9be6c87115b5da8952cd83c4d13f2e043239818fcd" +checksum = "7819c5e09aae0319981ee853869f2fcd1fac4db8babd0d004c17161297aadc05" dependencies = [ - "darling 0.20.11", + "darling", "parity-scale-codec", - "proc-macro-error", + "proc-macro-error2", "quote", "scale-typegen", "subxt-codegen", + "subxt-utils-fetchmetadata", "syn 2.0.104", ] [[package]] name = "subxt-metadata" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "738be5890fdeff899bbffff4d9c0f244fe2a952fb861301b937e3aa40ebb55da" +checksum = "aacd4e7484fef58deaa2dcb32d94753a864b208a668c0dd0c28be1d8abeeadb2" dependencies = [ - "frame-metadata 16.0.0", + "frame-decode", + "frame-metadata 17.0.0", "hashbrown 0.14.5", "parity-scale-codec", + "polkadot-sdk", "scale-info", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "subxt-signer" -version = "0.37.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49888ae6ae90fe01b471193528eea5bd4ed52d8eecd2d13f4a2333b87388850" +checksum = "d680352d04665b1e4eb6f9d2a54b800c4d8e1b20478e69be1b7d975b08d9fc34" dependencies = [ + "base64 0.22.1", "bip32", "bip39", "cfg-if", + "crypto_secretbox", "hex", "hmac 0.12.1", "keccak-hash", "parity-scale-codec", "pbkdf2", + "polkadot-sdk", "regex", "schnorrkel", - "secp256k1 0.28.2", - "secrecy", + "scrypt", + "secp256k1 0.30.0", + "secrecy 0.10.3", + "serde", + "serde_json", "sha2 0.10.9", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "subxt-core", "zeroize", ] +[[package]] +name = "subxt-utils-fetchmetadata" +version = "0.38.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3c53bc3eeaacc143a2f29ace4082edd2edaccab37b69ad20befba9fb00fdb3d" +dependencies = [ + "hex", + "parity-scale-codec", + "thiserror 1.0.69", +] + [[package]] name = "syn" version = "1.0.109" @@ -13682,10 +13687,10 @@ source = "git+https://github.com/ideal-lab5/timelock?rev=5416406cfd32799e31e1795 dependencies = [ "aes-gcm", "ark-bls12-377", - "ark-bls12-381", - "ark-ec", + "ark-bls12-381 0.4.0", + "ark-ec 0.4.2", "ark-ff 0.4.2", - "ark-poly", + "ark-poly 0.4.2", "ark-serialize 0.4.2", "ark-std 0.4.0", "array-bytes", @@ -13705,9 +13710,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.46.1" +version = "1.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17" +checksum = "43864ed400b6043a4757a25c7a64a8efde741aed79a056a2fb348a406701bb35" dependencies = [ "backtrace", "bytes", @@ -13718,9 +13723,9 @@ dependencies = [ "pin-project-lite", "signal-hook-registry", "slab", - "socket2 0.5.10", + "socket2 0.6.0", "tokio-macros", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -13734,34 +13739,13 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "tokio-rustls" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" -dependencies = [ - "rustls 0.21.12", - "tokio", -] - -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls 0.22.4", - "rustls-pki-types", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" dependencies = [ - "rustls 0.23.29", + "rustls", "tokio", ] @@ -13785,11 +13769,11 @@ checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" dependencies = [ "futures-util", "log", - "rustls 0.23.29", - "rustls-native-certs 0.8.1", + "rustls", + "rustls-native-certs", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.2", + "tokio-rustls", "tungstenite", ] @@ -13945,8 +13929,8 @@ dependencies = [ [[package]] name = "tracing-gum" -version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "19.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "coarsetime", "polkadot-primitives", @@ -13957,7 +13941,7 @@ dependencies = [ [[package]] name = "tracing-gum-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "expander", "proc-macro-crate 3.3.0", @@ -14008,9 +13992,9 @@ dependencies = [ [[package]] name = "trie-db" -version = "0.29.1" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c992b4f40c234a074d48a757efeabb1a6be88af84c0c23f7ca158950cb0ae7f" +checksum = "6c0670ab45a6b7002c7df369fee950a27cf29ae0474343fd3a15aa15f691e7a6" dependencies = [ "hash-db", "log", @@ -14027,78 +14011,6 @@ dependencies = [ "hash-db", ] -[[package]] -name = "trust-dns-proto" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f7f83d1e4a0e4358ac54c5c3681e5d7da5efc5a7a632c90bb6d6669ddd9bc26" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "enum-as-inner 0.5.1", - "futures-channel", - "futures-io", - "futures-util", - "idna 0.2.3", - "ipnet", - "lazy_static", - "rand 0.8.5", - "smallvec", - "socket2 0.4.10", - "thiserror 1.0.69", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "trust-dns-proto" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3119112651c157f4488931a01e586aa459736e9d6046d3bd9105ffb69352d374" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "enum-as-inner 0.6.1", - "futures-channel", - "futures-io", - "futures-util", - "idna 0.4.0", - "ipnet", - "once_cell", - "rand 0.8.5", - "smallvec", - "thiserror 1.0.69", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "trust-dns-resolver" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a3e6c3aff1718b3c73e395d1f35202ba2ffa847c6a62eea0db8fb4cfe30be6" -dependencies = [ - "cfg-if", - "futures-util", - "ipconfig", - "lru-cache", - "once_cell", - "parking_lot 0.12.4", - "rand 0.8.5", - "resolv-conf", - "smallvec", - "thiserror 1.0.69", - "tokio", - "tracing", - "trust-dns-proto 0.23.2", -] - [[package]] name = "try-lock" version = "0.2.5" @@ -14122,8 +14034,8 @@ dependencies = [ "http 1.3.1", "httparse", "log", - "rand 0.9.1", - "rustls 0.23.29", + "rand 0.9.2", + "rustls", "rustls-pki-types", "sha1", "thiserror 2.0.12", @@ -14149,15 +14061,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "typenum" -version = "1.16.0" -source = "git+https://github.com/encointer/typenum?tag=v1.16.0#4c8dddaa8bdd13130149e43b4085ad14e960617f" -dependencies = [ - "parity-scale-codec", - "scale-info", -] - [[package]] name = "typenum" version = "1.18.0" @@ -14200,12 +14103,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - [[package]] name = "unicode-ident" version = "1.0.18" @@ -14255,7 +14152,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6889a77d49f1f013504cec6bf97a2c730394adedaeb1deb5ea08949a50541105" dependencies = [ - "asynchronous-codec", + "asynchronous-codec 0.6.2", "bytes", "futures-io", "futures-util", @@ -14290,7 +14187,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" dependencies = [ "form_urlencoded", - "idna 1.0.3", + "idna", "percent-encoding", ] @@ -14350,27 +14247,70 @@ checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "w3f-bls" version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7335e4c132c28cc43caef6adb339789e599e39adbe78da0c4d547fad48cbc331" +source = "git+https://github.com/opentensor/bls?branch=fix-no-std#4ac443d11a6c9fdebe329d113702ad7387ba1688" dependencies = [ "ark-bls12-377", - "ark-bls12-381", - "ark-ec", + "ark-bls12-381 0.4.0", + "ark-ec 0.4.2", "ark-ff 0.4.2", "ark-serialize 0.4.2", - "ark-serialize-derive", + "ark-serialize-derive 0.4.2", "arrayref", - "constcat", "digest 0.10.7", "rand 0.8.5", "rand_chacha 0.3.1", "rand_core 0.6.4", "sha2 0.10.9", "sha3", - "thiserror 1.0.69", "zeroize", ] +[[package]] +name = "w3f-pcs" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbe7a8d5c914b69392ab3b267f679a2e546fe29afaddce47981772ac71bd02e1" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "merlin", +] + +[[package]] +name = "w3f-plonk-common" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aca389e494fe08c5c108b512e2328309036ee1c0bc7bdfdb743fef54d448c8c" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "getrandom_or_panic", + "rand_core 0.6.4", + "w3f-pcs", +] + +[[package]] +name = "w3f-ring-proof" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a639379402ad51504575dbd258740383291ac8147d3b15859bdf1ea48c677de" +dependencies = [ + "ark-ec 0.5.0", + "ark-ff 0.5.0", + "ark-poly 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "ark-transcript", + "w3f-pcs", + "w3f-plonk-common", +] + [[package]] name = "wait-timeout" version = "0.2.1" @@ -14560,28 +14500,37 @@ dependencies = [ [[package]] name = "wasmi" -version = "0.31.2" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8281d1d660cdf54c76a3efa9ddd0c270cada1383a995db3ccb43d166456c7" +checksum = "50386c99b9c32bd2ed71a55b6dd4040af2580530fae8bdb9a6576571a80d0cca" dependencies = [ + "arrayvec 0.7.6", + "multi-stash", + "num-derive", + "num-traits", "smallvec", "spin 0.9.8", - "wasmi_arena", + "wasmi_collections", "wasmi_core", "wasmparser-nostd", ] [[package]] -name = "wasmi_arena" -version = "0.4.1" +name = "wasmi_collections" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "104a7f73be44570cac297b3035d76b169d6599637631cf37a1703326a0727073" +checksum = "9c128c039340ffd50d4195c3f8ce31aac357f06804cfc494c8b9508d4b30dca4" +dependencies = [ + "ahash 0.8.12", + "hashbrown 0.14.5", + "string-interner", +] [[package]] name = "wasmi_core" -version = "0.13.0" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf1a7db34bff95b85c261002720c00c3a6168256dcb93041d3fa2054d19856a" +checksum = "a23b3a7f6c8c3ceeec6b83531ee61f0013c56e51cbf2b14b0f213548b23a4b41" dependencies = [ "downcast-rs", "libm", @@ -14824,29 +14773,29 @@ dependencies = [ ] [[package]] -name = "webpki-roots" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" - -[[package]] -name = "webpki-roots" +name = "webpki-root-certs" version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +checksum = "75c7f0ef91146ebfb530314f5f1d24528d7f0767efbfd31dce919275413e393e" dependencies = [ - "webpki-roots 1.0.1", + "webpki-root-certs 1.0.2", ] [[package]] -name = "webpki-roots" -version = "1.0.1" +name = "webpki-root-certs" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8782dd5a41a24eed3a4f40b606249b3e236ca61adf1f25ea4d45c73de122b502" +checksum = "4e4ffd8df1c57e87c325000a3d6ef93db75279dc3a231125aac571650f22b12a" dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + [[package]] name = "wide" version = "0.7.33" @@ -15067,7 +15016,7 @@ version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets 0.53.2", + "windows-targets 0.53.3", ] [[package]] @@ -15118,10 +15067,11 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.2" +version = "0.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" dependencies = [ + "windows-link", "windows_aarch64_gnullvm 0.53.0", "windows_aarch64_msvc 0.53.0", "windows_i686_gnu 0.53.0", @@ -15378,16 +15328,16 @@ dependencies = [ [[package]] name = "x509-parser" -version = "0.15.1" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" +checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69" dependencies = [ - "asn1-rs 0.5.2", + "asn1-rs 0.6.2", "data-encoding", - "der-parser 8.2.0", + "der-parser 9.0.0", "lazy_static", "nom", - "oid-registry 0.6.1", + "oid-registry 0.7.1", "rusticata-macros", "thiserror 1.0.69", "time", @@ -15412,8 +15362,8 @@ dependencies = [ [[package]] name = "xcm-procedural" -version = "11.0.1" -source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2412-6#bbc435c7667d3283ba280a8fec44676357392753" +version = "11.0.2" +source = "git+https://github.com/paritytech/polkadot-sdk.git?tag=polkadot-stable2503-6#598feddb893f5ad3923a62e41a2f179b6e10c30c" dependencies = [ "Inflector", "proc-macro2", @@ -15453,16 +15403,16 @@ dependencies = [ [[package]] name = "yamux" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3da1acad1c2dc53f0dde419115a38bd8221d8c3e47ae9aeceaf453266d29307e" +checksum = "2b2dd50a6d6115feb3e5d7d0efd45e8ca364b6c83722c1e9c602f5764e0e9597" dependencies = [ "futures", "log", "nohash-hasher", "parking_lot 0.12.4", "pin-project", - "rand 0.9.1", + "rand 0.9.2", "static_assertions", "web-time", ] diff --git a/Cargo.toml b/Cargo.toml index 32ec158a85..33df163f67 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,15 +9,17 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" -[dependencies] -node-subtensor = { path = "node", version = "4.0.0-dev" } -node-subtensor-runtime = { path = "runtime", version = "4.0.0-dev" } - [build-dependencies] subtensor-linting = { path = "support/linting", version = "0.1.0" } -syn.workspace = true +syn = { workspace = true, features = [ + "full", + "visit-mut", + "visit", + "extra-traits", + "parsing", +] } quote.workspace = true -proc-macro2.workspace = true +proc-macro2 = { workspace = true, features = ["span-locations"] } walkdir.workspace = true rayon = "1.10" @@ -56,22 +58,22 @@ pallet-subtensor = { default-features = false, path = "pallets/subtensor" } pallet-subtensor-swap = { default-features = false, path = "pallets/swap" } pallet-subtensor-swap-runtime-api = { default-features = false, path = "pallets/swap/runtime-api" } pallet-subtensor-swap-rpc = { default-features = false, path = "pallets/swap/rpc" } +procedural-fork = { path = "support/procedural-fork", default-features = false } safe-math = { default-features = false, path = "primitives/safe-math" } +share-pool = { path = "primitives/share-pool", default-features = false } +subtensor-macros = { path = "support/macros", default-features = false } subtensor-custom-rpc = { default-features = false, path = "pallets/subtensor/rpc" } subtensor-custom-rpc-runtime-api = { default-features = false, path = "pallets/subtensor/runtime-api" } subtensor-precompiles = { default-features = false, path = "precompiles" } subtensor-runtime-common = { default-features = false, path = "common" } subtensor-swap-interface = { default-features = false, path = "pallets/swap-interface" } +subtensor-transaction-fee = { default-features = false, path = "pallets/transaction-fee" } +ed25519-dalek = { version = "2.1.0", default-features = false } async-trait = "0.1" cargo-husky = { version = "1", default-features = false } clap = "4.5.4" -codec = { package = "parity-scale-codec", version = "3.7.5", default-features = false, features = [ - "derive", -] } -ed25519-dalek = { version = "2.1.0", default-features = false, features = [ - "alloc", -] } +codec = { package = "parity-scale-codec", version = "3.7.5", default-features = false } enumflags2 = "0.7.9" futures = "0.3.30" hex = { version = "0.4", default-features = false } @@ -83,183 +85,172 @@ memmap2 = "0.9.4" ndarray = { version = "0.15.6", default-features = false } parity-util-mem = "0.12.0" rand = "0.8.5" -scale-codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ - "derive", -] } scale-info = { version = "2.11.2", default-features = false } serde = { version = "1.0.214", default-features = false } serde-tuple-vec-map = { version = "1.0.1", default-features = false } serde_bytes = { version = "0.11.14", default-features = false } -serde_json = { version = "1.0.121", default-features = false } -serde_with = { version = "=2.0.0", default-features = false } +serde_json = { version = "1.0.141", default-features = false } +serde_with = { version = "3.14.0", default-features = false } smallvec = "1.13.2" -litep2p = { git = "https://github.com/paritytech/litep2p", tag = "v0.7.0" } -syn = { version = "2.0.87", features = [ - "full", - "visit-mut", - "visit", - "extra-traits", - "parsing", -] } -quote = "1" -proc-macro2 = { version = "1", features = ["span-locations"] } -thiserror = "1.0" +litep2p = { git = "https://github.com/paritytech/litep2p", tag = "v0.7.0", default-features = false } +syn = { version = "2.0.87", default-features = false } +quote = { version = "1", default-features = false } +proc-macro2 = { version = "1", default-features = false } walkdir = "2" approx = "0.5" alloy-primitives = { version = "0.8.23", default-features = false } +num-traits = { version = "0.2.19", default-features = false } +semver = "1.0" +toml_edit = "0.22" +derive-syn-parse = "0.2" +Inflector = "0.11" +cfg-expr = "0.15" +itertools = "0.10" +macro_magic = { version = "0.5", default-features = false } +frame-support-procedural-tools = { version = "10.0.0", default-features = false } +proc-macro-warning = { version = "1", default-features = false } +expander = "2" +ahash = { version = "0.8", default-features = false } +regex = { version = "1.11.1", default-features = false } -subtensor-macros = { path = "support/macros" } -frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -frame-executive = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -frame-metadata = "18.0.0" +frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-executive = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +frame-metadata = { version = "20.0.0", default-features = false } -pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-insecure-randomness-collective-flip = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-multisig = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-preimage = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } pallet-proxy = { path = "pallets/proxy", default-features = false } -pallet-safe-mode = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-scheduler = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } pallet-utility = { path = "pallets/utility", default-features = false } -pallet-root-testing = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } +pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-insecure-randomness-collective-flip = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-multisig = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-preimage = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-safe-mode = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-scheduler = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +pallet-root-testing = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } -sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-cli = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-consensus-grandpa-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-chain-spec-derive = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-consensus-slots = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-executor = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-network = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-service = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } +sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-cli = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus-grandpa-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-chain-spec-derive = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus-slots = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-executor = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-network = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-service = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-consensus-manual-seal = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } -sp-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-consensus = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-session = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-storage = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-version = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sp-weights = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } +sp-api = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-consensus = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-rpc = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-session = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-storage = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-version = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-weights = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +sp-crypto-hashing = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } -substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -substrate-fixed = { git = "https://github.com/opentensor/substrate-fixed.git", tag = "v0.5.9" } -substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } -substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6" } +substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +substrate-fixed = { git = "https://github.com/encointer/substrate-fixed.git", tag = "v0.6.0", default-features = false } +substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } -sc-consensus-manual-seal = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } +cumulus-primitives-proof-size-hostfunction = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } # Frontier -fp-evm = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fp-rpc = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fp-self-contained = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false, features = [ - "serde", -] } -fp-account = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-storage = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-db = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-consensus = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fp-consensus = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fp-dynamic-fee = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-api = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-rpc = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false, features = [ - "rpc-binary-search-estimate", -] } -fc-rpc-core = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-aura = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -fc-mapping-sync = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -precompile-utils = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } +fp-evm = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fp-rpc = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fp-self-contained = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fp-account = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-storage = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-db = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-consensus = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fp-consensus = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fp-dynamic-fee = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-api = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-rpc = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-rpc-core = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-aura = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +fc-mapping-sync = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +precompile-utils = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } # Frontier FRAME -pallet-base-fee = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-dynamic-fee = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-ethereum = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-precompile-dispatch = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-chain-id = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-precompile-modexp = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-precompile-sha3fips = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-precompile-simple = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-evm-precompile-bn128 = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } -pallet-hotfix-sufficients = { git = "https://github.com/opentensor/frontier", rev = "fe6976888fda696771cd15f78dbbdd71ee6c1216", default-features = false } +pallet-base-fee = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-dynamic-fee = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-ethereum = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-precompile-dispatch = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-chain-id = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-precompile-modexp = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-precompile-sha3fips = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-precompile-simple = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-evm-precompile-bn128 = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } +pallet-hotfix-sufficients = { git = "https://github.com/opentensor/frontier", rev = "c591df98c524e1599c45f93cf4685248088ac014", default-features = false } #DRAND pallet-drand = { path = "pallets/drand", default-features = false } -sp-crypto-ec-utils = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", features = [ - "bls12-381", -] } -getrandom = { version = "0.2.15", features = [ +sp-crypto-ec-utils = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +getrandom = { version = "0.2.15", default-features = false, features = [ "custom", -], default-features = false } -sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", default-features = false } -w3f-bls = { version = "=0.1.3", default-features = false } -ark-crypto-primitives = { version = "0.4.0", default-features = false, features = [ - "r1cs", - "snark", -] } -ark-scale = { version = "0.0.11", default-features = false, features = [ - "hazmat", ] } +sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2503-6", default-features = false } +w3f-bls = { git = "https://github.com/opentensor/bls", branch = "fix-no-std", default-features = false } +ark-crypto-primitives = { version = "0.4.0", default-features = false } +ark-scale = { version = "0.0.11", default-features = false } sp-ark-bls12-381 = { git = "https://github.com/paritytech/substrate-curves", default-features = false } -ark-bls12-381 = { version = "0.4.0", features = [ - "curve", -], default-features = false } -ark-serialize = { version = "0.4.0", features = [ - "derive", -], default-features = false } +ark-bls12-381 = { version = "0.4.0", default-features = false } +ark-serialize = { version = "0.4.0", default-features = false } ark-ff = { version = "0.4.0", default-features = false } ark-ec = { version = "0.4.0", default-features = false } ark-std = { version = "0.4.0", default-features = false } -anyhow = "1.0.81" +anyhow = { version = "1.0.81", default-features = false } sha2 = { version = "0.10.8", default-features = false } rand_chacha = { version = "0.3.1", default-features = false } tle = { git = "https://github.com/ideal-lab5/timelock", rev = "5416406cfd32799e31e1795393d4916894de4468", default-features = false } -cumulus-primitives-proof-size-hostfunction = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2412-6", package = "cumulus-primitives-proof-size-hostfunction", default-features = false } +# Primitives [profile.release] panic = "unwind" @@ -274,16 +265,10 @@ codegen-units = 1 [features] default = [] -try-runtime = [ - "node-subtensor/try-runtime", - "node-subtensor-runtime/try-runtime", -] -runtime-benchmarks = [ - "node-subtensor/runtime-benchmarks", - "node-subtensor-runtime/runtime-benchmarks", -] -metadata-hash = ["node-subtensor-runtime/metadata-hash"] pow-faucet = [] [patch."https://github.com/paritytech/polkadot-sdk.git"] -sc-consensus-grandpa = { git = "https://github.com/opentensor/grandpa.git", rev = "b3ba2f67d510559edfb4963523de86ed89439d74" } +sc-consensus-grandpa = { git = "https://github.com/opentensor/grandpa.git", rev = "67ff75e915bd44586b8f8443e457b5b101920da8" } + +[patch.crates-io] +w3f-bls = { git = "https://github.com/opentensor/bls", branch = "fix-no-std" } diff --git a/common/Cargo.toml b/common/Cargo.toml index c0de294180..b1b0f1bbf2 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-runtime-common" version = "0.1.0" -edition = "2024" +edition.workspace = true authors = ["Opentensor Foundation "] homepage = "https://opentensor.ai/" publish = false @@ -11,16 +11,15 @@ repository = "https://github.com/opentensor/subtensor/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true } -frame-support = { workspace = true } -scale-info = { workspace = true } -serde = { workspace = true } -sp-core = { workspace = true } -sp-runtime = { workspace = true } -substrate-fixed = { workspace = true } -subtensor-macros = { workspace = true } - -approx = {workspace = true, optional = true} +codec = { workspace = true, features = ["derive"] } +frame-support.workspace = true +scale-info.workspace = true +serde.workspace = true +sp-core.workspace = true +sp-runtime.workspace = true +substrate-fixed.workspace = true +subtensor-macros.workspace = true +approx = { workspace = true, optional = true } [lints] workspace = true diff --git a/common/src/currency.rs b/common/src/currency.rs index f50e2bc9a1..8233383e95 100644 --- a/common/src/currency.rs +++ b/common/src/currency.rs @@ -3,14 +3,16 @@ use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; #[cfg(feature = "approx")] use approx::AbsDiffEq; -use codec::{Compact, CompactAs, Decode, Encode, Error as CodecError, MaxEncodedLen}; +use codec::{ + Compact, CompactAs, Decode, DecodeWithMemTracking, Encode, Error as CodecError, MaxEncodedLen, +}; use frame_support::pallet_prelude::*; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use substrate_fixed::traits::{Fixed, ToFixed}; use subtensor_macros::freeze_struct; -#[freeze_struct("b21dcd0434b67c67")] +#[freeze_struct("40205476b6d995b2")] #[repr(transparent)] #[derive( Deserialize, @@ -18,6 +20,7 @@ use subtensor_macros::freeze_struct; Clone, Copy, Decode, + DecodeWithMemTracking, Default, Encode, Eq, @@ -30,103 +33,101 @@ use subtensor_macros::freeze_struct; )] pub struct AlphaCurrency(u64); -impl TypeInfo for AlphaCurrency { - type Identity = ::Identity; - fn type_info() -> scale_info::Type { - ::type_info() - } -} - -impl Display for AlphaCurrency { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0, f) - } -} - -impl CompactAs for AlphaCurrency { - type As = u64; - - fn encode_as(&self) -> &Self::As { - &self.0 - } - - fn decode_from(v: Self::As) -> Result { - Ok(Self(v)) - } -} - -impl From> for AlphaCurrency { - fn from(c: Compact) -> Self { - c.0 - } -} - -impl From for u64 { - fn from(val: AlphaCurrency) -> Self { - val.0 - } -} +#[freeze_struct("4d1bcb31c40c2594")] +#[repr(transparent)] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Default, + Encode, + Eq, + Hash, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, + RuntimeDebug, +)] +pub struct TaoCurrency(u64); -impl From for AlphaCurrency { - fn from(value: u64) -> Self { - Self(value) - } -} +// implements traits required by the Currency trait (ToFixed + Into + From) and CompactAs, +// TypeInfo and Display. It expects a wrapper structure for u64 (CurrencyT(u64)). +macro_rules! impl_currency_reqs { + ($currency_type:ident) => { + impl $currency_type { + pub const fn new(inner: u64) -> Self { + Self(inner) + } + } -impl ToFixed for AlphaCurrency { - fn to_fixed(self) -> F { - self.0.to_fixed() - } + impl TypeInfo for $currency_type { + type Identity = ::Identity; + fn type_info() -> scale_info::Type { + ::type_info() + } + } - fn checked_to_fixed(self) -> Option { - self.0.checked_to_fixed() - } + impl Display for $currency_type { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Display::fmt(&self.0, f) + } + } - fn saturating_to_fixed(self) -> F { - self.0.saturating_to_fixed() - } - fn wrapping_to_fixed(self) -> F { - self.0.wrapping_to_fixed() - } + impl CompactAs for $currency_type { + type As = u64; - fn overflowing_to_fixed(self) -> (F, bool) { - self.0.overflowing_to_fixed() - } -} + fn encode_as(&self) -> &Self::As { + &self.0 + } -impl Currency for AlphaCurrency { - const MAX: Self = Self(u64::MAX); - const ZERO: Self = Self(0); -} + fn decode_from(v: Self::As) -> Result { + Ok(Self(v)) + } + } -pub trait Currency: ToFixed + Into + From + Clone + Copy { - const MAX: Self; - const ZERO: Self; + impl From> for $currency_type { + fn from(c: Compact<$currency_type>) -> Self { + c.0 + } + } - fn is_zero(&self) -> bool { - Into::::into(*self) == 0 - } + impl From<$currency_type> for u64 { + fn from(val: $currency_type) -> Self { + val.0 + } + } - fn to_u64(&self) -> u64 { - (*self).into() - } + impl From for $currency_type { + fn from(value: u64) -> Self { + Self(value) + } + } - fn saturating_add(&self, rhv: Self) -> Self { - Into::::into(*self).saturating_add(rhv.into()).into() - } + impl ToFixed for $currency_type { + fn to_fixed(self) -> F { + self.0.to_fixed() + } - #[allow(clippy::arithmetic_side_effects)] - fn saturating_div(&self, rhv: Self) -> Self { - Into::::into(*self).saturating_div(rhv.into()).into() - } + fn checked_to_fixed(self) -> Option { + self.0.checked_to_fixed() + } - fn saturating_sub(&self, rhv: Self) -> Self { - Into::::into(*self).saturating_sub(rhv.into()).into() - } + fn saturating_to_fixed(self) -> F { + self.0.saturating_to_fixed() + } + fn wrapping_to_fixed(self) -> F { + self.0.wrapping_to_fixed() + } - fn saturating_mul(&self, rhv: Self) -> Self { - Into::::into(*self).saturating_mul(rhv.into()).into() - } + fn overflowing_to_fixed(self) -> (F, bool) { + self.0.overflowing_to_fixed() + } + } + }; } macro_rules! impl_arithmetic_operators { @@ -205,8 +206,6 @@ macro_rules! impl_arithmetic_operators { }; } -impl_arithmetic_operators!(AlphaCurrency); - macro_rules! impl_approx { ($currency_type:ident) => { #[cfg(feature = "approx")] @@ -228,4 +227,50 @@ macro_rules! impl_approx { }; } +pub trait Currency: ToFixed + Into + From + Clone + Copy { + const MAX: Self; + const ZERO: Self; + + fn is_zero(&self) -> bool { + Into::::into(*self) == 0 + } + + fn to_u64(&self) -> u64 { + (*self).into() + } + + fn saturating_add(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_add(rhv.into()).into() + } + + #[allow(clippy::arithmetic_side_effects)] + fn saturating_div(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_div(rhv.into()).into() + } + + fn saturating_sub(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_sub(rhv.into()).into() + } + + fn saturating_mul(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_mul(rhv.into()).into() + } +} + +impl_arithmetic_operators!(AlphaCurrency); impl_approx!(AlphaCurrency); +impl_currency_reqs!(AlphaCurrency); + +impl_arithmetic_operators!(TaoCurrency); +impl_approx!(TaoCurrency); +impl_currency_reqs!(TaoCurrency); + +impl Currency for AlphaCurrency { + const MAX: Self = Self(u64::MAX); + const ZERO: Self = Self(0); +} + +impl Currency for TaoCurrency { + const MAX: Self = Self(u64::MAX); + const ZERO: Self = Self(0); +} diff --git a/common/src/lib.rs b/common/src/lib.rs index 44b7fb879a..abec6ed7c8 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -1,7 +1,9 @@ #![cfg_attr(not(feature = "std"), no_std)] use core::fmt::{self, Display, Formatter}; -use codec::{Compact, CompactAs, Decode, Encode, Error as CodecError, MaxEncodedLen}; +use codec::{ + Compact, CompactAs, Decode, DecodeWithMemTracking, Encode, Error as CodecError, MaxEncodedLen, +}; use frame_support::pallet_prelude::*; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; @@ -39,7 +41,7 @@ pub type Nonce = u32; /// Transfers below SMALL_TRANSFER_LIMIT are considered small transfers pub const SMALL_TRANSFER_LIMIT: Balance = 500_000_000; // 0.5 TAO -#[freeze_struct("9b6be98fb98e9b17")] +#[freeze_struct("c972489bff40ae48")] #[repr(transparent)] #[derive( Deserialize, @@ -47,6 +49,7 @@ pub const SMALL_TRANSFER_LIMIT: Balance = 500_000_000; // 0.5 TAO Clone, Copy, Decode, + DecodeWithMemTracking, Default, Encode, Eq, @@ -124,7 +127,18 @@ impl TypeInfo for NetUid { } #[derive( - Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo, + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + DecodeWithMemTracking, + Debug, + MaxEncodedLen, + TypeInfo, )] pub enum ProxyType { Any, @@ -154,7 +168,7 @@ impl Default for ProxyType { } pub trait SubnetInfo { - fn tao_reserve(netuid: NetUid) -> u64; + fn tao_reserve(netuid: NetUid) -> TaoCurrency; fn alpha_reserve(netuid: NetUid) -> AlphaCurrency; fn exists(netuid: NetUid) -> bool; fn mechanism(netuid: NetUid) -> u16; @@ -162,10 +176,13 @@ pub trait SubnetInfo { } pub trait BalanceOps { - fn tao_balance(account_id: &AccountId) -> u64; + fn tao_balance(account_id: &AccountId) -> TaoCurrency; fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> AlphaCurrency; - fn increase_balance(coldkey: &AccountId, tao: u64); - fn decrease_balance(coldkey: &AccountId, tao: u64) -> Result; + fn increase_balance(coldkey: &AccountId, tao: TaoCurrency); + fn decrease_balance( + coldkey: &AccountId, + tao: TaoCurrency, + ) -> Result; fn increase_stake( coldkey: &AccountId, hotkey: &AccountId, @@ -178,8 +195,8 @@ pub trait BalanceOps { netuid: NetUid, alpha: AlphaCurrency, ) -> Result; - fn increase_provided_tao_reserve(netuid: NetUid, tao: u64); - fn decrease_provided_tao_reserve(netuid: NetUid, tao: u64); + fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency); + fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency); fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency); fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency); } diff --git a/evm-tests/test/crowdloan.precompile.test.ts b/evm-tests/test/crowdloan.precompile.test.ts index 314e19e82d..70c93ca5f4 100644 --- a/evm-tests/test/crowdloan.precompile.test.ts +++ b/evm-tests/test/crowdloan.precompile.test.ts @@ -1,3 +1,5 @@ +import * as assert from "assert"; + import { PublicClient } from "viem"; import { ETH_LOCAL_URL } from "../src/config"; import { generateRandomEthersWallet, getPublicClient } from "../src/utils"; @@ -9,7 +11,6 @@ import { getAliceSigner, getDevnetApi, waitForFinalizedBlock } from "../src/subs import { forceSetBalanceToEthAddress } from "../src/subtensor"; import { decodeAddress } from "@polkadot/util-crypto"; import { u8aToHex } from "@polkadot/util"; -import { assert } from "chai"; import { convertH160ToSS58 } from "../src/address-utils"; describe("Test Crowdloan precompile", () => { @@ -50,7 +51,7 @@ describe("Test Crowdloan precompile", () => { const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); const crowdloanInfo = await crowdloanContract.getCrowdloan(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloanInfo[0], u8aToHex(decodeAddress(crowdloan.creator))); assert.equal(crowdloanInfo[1], crowdloan.deposit); assert.equal(crowdloanInfo[2], crowdloan.min_contribution); @@ -83,7 +84,7 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.creator, convertH160ToSS58(wallet1.address)); assert.equal(crowdloan.deposit, deposit); assert.equal(crowdloan.min_contribution, minContribution); @@ -123,7 +124,7 @@ describe("Test Crowdloan precompile", () => { }).signAndSubmit(alice); let crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit); assert.equal(crowdloan.contributors_count, 1); @@ -138,10 +139,10 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); let balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(wallet1.address)); - assert.approximately(Number(balanceBefore.data.free - balanceAfter.data.free), Number(contribution), 1_000_000); + assert.ok(Number(balanceBefore.data.free - balanceAfter.data.free) - Number(contribution) < 1_000_000); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit + contribution); assert.equal(crowdloan.contributors_count, 2); @@ -155,10 +156,10 @@ describe("Test Crowdloan precompile", () => { await tx2.wait(); balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(wallet1.address)); - assert.approximately(Number(balanceAfter.data.free), Number(balanceBefore.data.free + contribution), 1_000_000); + assert.ok(Number(balanceAfter.data.free) - Number(balanceBefore.data.free + contribution) < 1_000_000); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit); assert.equal(crowdloan.contributors_count, 1); @@ -188,10 +189,10 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); let balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(wallet1.address)); - assert.approximately(Number(balanceBefore.data.free - balanceAfter.data.free), Number(deposit), 1_000_000); + assert.ok(Number(balanceBefore.data.free - balanceAfter.data.free) - Number(deposit) < 1_000_000); let crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit); assert.equal(crowdloan.contributors_count, 1); @@ -207,10 +208,10 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(wallet2.address)); - assert.approximately(Number(balanceBefore.data.free - balanceAfter.data.free), Number(contribution), 1_000_000); + assert.ok(Number(balanceBefore.data.free - balanceAfter.data.free) - Number(contribution) < 1_000_000); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit + contribution); assert.equal(crowdloan.contributors_count, 2); @@ -224,10 +225,10 @@ describe("Test Crowdloan precompile", () => { await tx2.wait(); balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(wallet2.address)); - assert.approximately(Number(balanceAfter.data.free), Number(balanceBefore.data.free + contribution), 1_000_000); + assert.ok(Number(balanceAfter.data.free) - Number(balanceBefore.data.free + contribution) < 1_000_000); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit); assert.equal(crowdloan.contributors_count, 1); @@ -268,11 +269,11 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); - assert.isTrue(crowdloan.finalized); + assert.ok(crowdloan); + assert.equal(crowdloan.finalized, true); const crowdloanInfo = await crowdloanContract.getCrowdloan(nextId); - assert.isTrue(crowdloanInfo[9]); + assert.equal(crowdloanInfo[9], true); const balanceAfter = await api.query.System.Account.getValue(convertH160ToSS58(targetAddress.address)); assert.equal(balanceAfter.data.free, cap); @@ -316,7 +317,7 @@ describe("Test Crowdloan precompile", () => { await waitForFinalizedBlock(api, end); let crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit + contribution * BigInt(3)); assert.equal(crowdloan.contributors_count, 4); @@ -328,14 +329,14 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const balanceAfter2 = await api.query.System.Account.getValue(convertH160ToSS58(wallet2.address)); - assert.approximately(Number(balanceAfter2.data.free), Number(balanceBefore2.data.free), 1_000_000); + assert.ok(Number(balanceAfter2.data.free) - Number(balanceBefore2.data.free) < 1_000_000); const balanceAfter3 = await api.query.System.Account.getValue(convertH160ToSS58(wallet3.address)); - assert.approximately(Number(balanceAfter3.data.free), Number(balanceBefore3.data.free), 1_000_000); + assert.ok(Number(balanceAfter3.data.free) - Number(balanceBefore3.data.free) < 1_000_000); const balanceAfter4 = await api.query.System.Account.getValue(convertH160ToSS58(wallet4.address)); - assert.approximately(Number(balanceAfter4.data.free), Number(balanceBefore4.data.free), 1_000_000); + assert.ok(Number(balanceAfter4.data.free) - Number(balanceBefore4.data.free) < 1_000_000); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.raised, deposit); assert.equal(crowdloan.contributors_count, 1); @@ -347,10 +348,10 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isUndefined(crowdloan); + assert.equal(crowdloan, undefined); const balanceAfter1 = await api.query.System.Account.getValue(convertH160ToSS58(wallet1.address)); - assert.approximately(Number(balanceAfter1.data.free), Number(balanceBefore1.data.free), 2_000_000); + assert.ok(Number(balanceAfter1.data.free) - Number(balanceBefore1.data.free) < 2_000_000); }); it("updates the min contribution", async () => { @@ -372,7 +373,7 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.min_contribution, BigInt(1_000_000_000)); const newMinContribution = BigInt(2_000_000_000); @@ -380,7 +381,7 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const updatedCrowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(updatedCrowdloan); + assert.ok(updatedCrowdloan); assert.equal(updatedCrowdloan.min_contribution, newMinContribution); const updatedCrowdloanInfo = await crowdloanContract.getCrowdloan(nextId); @@ -406,7 +407,7 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.end, end); const newEnd = end + 200; @@ -414,7 +415,7 @@ describe("Test Crowdloan precompile", () => { await tx2.wait(); const updatedCrowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(updatedCrowdloan); + assert.ok(updatedCrowdloan); assert.equal(updatedCrowdloan.end, newEnd); const updatedCrowdloanInfo = await crowdloanContract.getCrowdloan(nextId); @@ -440,7 +441,7 @@ describe("Test Crowdloan precompile", () => { await tx.wait(); const crowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(crowdloan); + assert.ok(crowdloan); assert.equal(crowdloan.cap, BigInt(200_000_000_000)); const newCap = BigInt(300_000_000_000); @@ -448,7 +449,7 @@ describe("Test Crowdloan precompile", () => { await tx2.wait(); const updatedCrowdloan = await api.query.Crowdloan.Crowdloans.getValue(nextId); - assert.isDefined(updatedCrowdloan); + assert.ok(updatedCrowdloan); assert.equal(updatedCrowdloan.cap, newCap); const updatedCrowdloanInfo = await crowdloanContract.getCrowdloan(nextId); diff --git a/evm-tests/test/leasing.precompile.test.ts b/evm-tests/test/leasing.precompile.test.ts index 53bbbf8334..7ea45c0509 100644 --- a/evm-tests/test/leasing.precompile.test.ts +++ b/evm-tests/test/leasing.precompile.test.ts @@ -1,3 +1,5 @@ +import * as assert from "assert"; + import { PublicClient } from "viem"; import { ETH_LOCAL_URL } from "../src/config"; import { generateRandomEthersWallet, getPublicClient } from "../src/utils"; @@ -11,7 +13,6 @@ import { u8aToHex } from "@polkadot/util"; import { ILEASING_ADDRESS, ILeasingABI } from "../src/contracts/leasing"; import { ICROWDLOAN_ADDRESS, ICrowdloanABI } from "../src/contracts/crowdloan"; import { INEURON_ADDRESS, INeuronABI } from "../src/contracts/neuron"; -import { assert } from "chai"; import { convertH160ToPublicKey, convertH160ToSS58 } from "../src/address-utils"; describe("Test Leasing precompile", () => { @@ -20,7 +21,6 @@ describe("Test Leasing precompile", () => { let wallet1: ethers.Wallet; let wallet2: ethers.Wallet; - let wallet3: ethers.Wallet; let leaseContract: ethers.Contract; let crowdloanContract: ethers.Contract; let neuronContract: ethers.Contract; @@ -34,22 +34,18 @@ describe("Test Leasing precompile", () => { wallet1 = generateRandomEthersWallet(); wallet2 = generateRandomEthersWallet(); - wallet3 = generateRandomEthersWallet(); leaseContract = new ethers.Contract(ILEASING_ADDRESS, ILeasingABI, wallet1); crowdloanContract = new ethers.Contract(ICROWDLOAN_ADDRESS, ICrowdloanABI, wallet1); neuronContract = new ethers.Contract(INEURON_ADDRESS, INeuronABI, wallet1); await forceSetBalanceToEthAddress(api, wallet1.address); await forceSetBalanceToEthAddress(api, wallet2.address); - await forceSetBalanceToEthAddress(api, wallet3.address); - await neuronContract.burnedRegister(1, convertH160ToPublicKey(wallet3.address)); - await forceSetBalanceToEthAddress(api, wallet1.address); }); it("gets an existing lease created on substrate side, its subnet id and its contributor shares", async () => { const nextCrowdloanId = await api.query.Crowdloan.NextCrowdloanId.getValue(); const crowdloanDeposit = BigInt(100_000_000_000); // 100 TAO - const crowdloanCap = BigInt(10_000_000_000_000); // 10000 TAO + const crowdloanCap = await api.query.SubtensorModule.NetworkLastLockCost.getValue() * BigInt(2); const crowdloanEnd = await api.query.System.Number.getValue() + 100; const leaseEmissionsShare = 15; const leaseEnd = await api.query.System.Number.getValue() + 300; @@ -79,7 +75,7 @@ describe("Test Leasing precompile", () => { const lease = await api.query.SubtensorModule.SubnetLeases.getValue(nextLeaseId); const leaseInfo = await leaseContract.getLease(nextLeaseId); - assert.isDefined(lease); + assert.ok(lease); assert.equal(leaseInfo[0], u8aToHex(decodeAddress(lease.beneficiary))); assert.equal(leaseInfo[1], u8aToHex(decodeAddress(lease.coldkey))); assert.equal(leaseInfo[2], u8aToHex(decodeAddress(lease.hotkey))); @@ -104,7 +100,7 @@ describe("Test Leasing precompile", () => { const nextCrowdloanId = await api.query.Crowdloan.NextCrowdloanId.getValue(); const crowdloanDeposit = BigInt(100_000_000_000); // 100 TAO const crowdloanMinContribution = BigInt(1_000_000_000); // 1 TAO - const crowdloanCap = BigInt(10_000_000_000_000); // 10000 TAO + const crowdloanCap = await api.query.SubtensorModule.NetworkLastLockCost.getValue() * BigInt(2); const crowdloanEnd = await api.query.System.Number.getValue() + 100; const leasingEmissionsShare = 15; const leasingEndBlock = await api.query.System.Number.getValue() + 300; @@ -131,7 +127,7 @@ describe("Test Leasing precompile", () => { await tx.wait(); const lease = await api.query.SubtensorModule.SubnetLeases.getValue(nextLeaseId); - assert.isDefined(lease); + assert.ok(lease); assert.equal(lease.beneficiary, convertH160ToSS58(wallet1.address)); assert.equal(lease.emissions_share, leasingEmissionsShare); assert.equal(lease.end_block, leasingEndBlock); @@ -158,15 +154,19 @@ describe("Test Leasing precompile", () => { }); it("terminates a lease", async () => { + const hotkey = generateRandomEthersWallet(); + let tx = await neuronContract.burnedRegister(1, convertH160ToPublicKey(hotkey.address)); + await tx.wait(); + const nextCrowdloanId = await api.query.Crowdloan.NextCrowdloanId.getValue(); const crowdloanDeposit = BigInt(100_000_000_000); // 100 TAO const crowdloanMinContribution = BigInt(1_000_000_000); // 1 TAO - const crowdloanCap = BigInt(10_000_000_000_000); // 10000 TAO + const crowdloanCap = await api.query.SubtensorModule.NetworkLastLockCost.getValue() * BigInt(2); const crowdloanEnd = await api.query.System.Number.getValue() + 100; const leasingEmissionsShare = 15; const leasingEndBlock = await api.query.System.Number.getValue() + 200; - let tx = await leaseContract.createLeaseCrowdloan( + tx = await leaseContract.createLeaseCrowdloan( crowdloanDeposit, crowdloanMinContribution, crowdloanCap, @@ -190,19 +190,19 @@ describe("Test Leasing precompile", () => { await waitForFinalizedBlock(api, leasingEndBlock); let lease = await api.query.SubtensorModule.SubnetLeases.getValue(nextLeaseId); - assert.isDefined(lease); + assert.ok(lease); const netuid = lease.netuid; - tx = await leaseContract.terminateLease(nextLeaseId, convertH160ToPublicKey(wallet3.address)); + tx = await leaseContract.terminateLease(nextLeaseId, convertH160ToPublicKey(hotkey.address)); await tx.wait(); lease = await api.query.SubtensorModule.SubnetLeases.getValue(nextLeaseId); - assert.isUndefined(lease); + assert.strictEqual(lease, undefined); // Ensure that the subnet ownership has been transferred const ownerColdkey = await api.query.SubtensorModule.SubnetOwner.getValue(netuid); const ownerHotkey = await api.query.SubtensorModule.SubnetOwnerHotkey.getValue(netuid); assert.equal(ownerColdkey, convertH160ToSS58(wallet1.address)); - assert.equal(ownerHotkey, convertH160ToSS58(wallet3.address)); + assert.equal(ownerHotkey, convertH160ToSS58(hotkey.address)); }); }) \ No newline at end of file diff --git a/evm-tests/yarn.lock b/evm-tests/yarn.lock index 043a97f2ef..38c4c5bde2 100644 --- a/evm-tests/yarn.lock +++ b/evm-tests/yarn.lock @@ -26,10 +26,10 @@ resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz" integrity sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow== -"@commander-js/extra-typings@^13.1.0": - version "13.1.0" - resolved "https://registry.npmjs.org/@commander-js/extra-typings/-/extra-typings-13.1.0.tgz" - integrity sha512-q5P52BYb1hwVWE6dtID7VvuJWrlfbCv4klj7BjUUOqMz4jbSZD4C9fJ9lRjL2jnBGTg+gDDlaXN51rkWcLk4fg== +"@commander-js/extra-typings@^14.0.0": + version "14.0.0" + resolved "https://registry.yarnpkg.com/@commander-js/extra-typings/-/extra-typings-14.0.0.tgz#a48b73e8e9c80d5c7538d361f9c1fb9b231643d7" + integrity sha512-hIn0ncNaJRLkZrxBIp5AsW/eXEHNKYQBh0aPdoUqNgD+Io3NIykQqpKFyKcuasZhicGaEZJX/JBSIkZ4e5x8Dg== "@cspotcode/source-map-support@^0.8.0": version "0.8.1" @@ -80,12 +80,12 @@ "@esbuild/darwin-arm64@0.21.5": version "0.21.5" - resolved "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz#e495b539660e51690f3928af50a76fb0a6ccff2a" integrity sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ== "@esbuild/darwin-arm64@0.25.5": version "0.25.5" - resolved "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz#49d8bf8b1df95f759ac81eb1d0736018006d7e34" integrity sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ== "@esbuild/darwin-x64@0.21.5": @@ -200,12 +200,12 @@ "@esbuild/linux-x64@0.21.5": version "0.21.5" - resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz#6d8f0c768e070e64309af8004bb94e68ab2bb3b0" + resolved "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz" integrity sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ== "@esbuild/linux-x64@0.25.5": version "0.25.5" - resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz#b2357dd153aa49038967ddc1ffd90c68a9d2a0d4" + resolved "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz" integrity sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw== "@esbuild/netbsd-arm64@0.25.5": @@ -381,60 +381,60 @@ resolved "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz" integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== -"@polkadot-api/cli@0.13.0": - version "0.13.0" - resolved "https://registry.npmjs.org/@polkadot-api/cli/-/cli-0.13.0.tgz" - integrity sha512-uumqacO1+YxuhHYOr75czxvV0KmRxm3DaZtRKzxIf2zpICnj/QnBTpJwlxU56g+pQDU5P/hTR0Thh0vrnUTNVw== +"@polkadot-api/cli@0.14.5": + version "0.14.5" + resolved "https://registry.yarnpkg.com/@polkadot-api/cli/-/cli-0.14.5.tgz#e87cef726d6844d720170e917d00d86b7b4955d8" + integrity sha512-510nvNWsOOYQJZq1ZJKPlvQ81sNXmwlmb8Ww9UI5THgarFJcuUvPe7W/kCRAUBdrK5yp5hziVrxuy84p55pWDQ== dependencies: - "@commander-js/extra-typings" "^13.1.0" - "@polkadot-api/codegen" "0.16.0" - "@polkadot-api/ink-contracts" "0.3.2" + "@commander-js/extra-typings" "^14.0.0" + "@polkadot-api/codegen" "0.17.1" + "@polkadot-api/ink-contracts" "0.3.7" "@polkadot-api/json-rpc-provider" "0.0.4" - "@polkadot-api/known-chains" "0.7.6" - "@polkadot-api/metadata-compatibility" "0.2.3" - "@polkadot-api/observable-client" "0.11.0" + "@polkadot-api/known-chains" "0.9.3" + "@polkadot-api/metadata-compatibility" "0.3.2" + "@polkadot-api/observable-client" "0.13.4" "@polkadot-api/polkadot-sdk-compat" "2.3.2" "@polkadot-api/sm-provider" "0.1.7" - "@polkadot-api/smoldot" "0.3.8" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/substrate-client" "0.3.0" - "@polkadot-api/utils" "0.1.2" - "@polkadot-api/wasm-executor" "^0.1.2" - "@polkadot-api/ws-provider" "0.4.0" - "@types/node" "^22.15.18" - commander "^13.1.0" - execa "^9.5.3" + "@polkadot-api/smoldot" "0.3.10" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/substrate-client" "0.4.2" + "@polkadot-api/utils" "0.2.0" + "@polkadot-api/wasm-executor" "^0.2.1" + "@polkadot-api/ws-provider" "0.4.1" + "@types/node" "^24.0.14" + commander "^14.0.0" + execa "^9.6.0" fs.promises.exists "^1.1.4" ora "^8.2.0" read-pkg "^9.0.1" rxjs "^7.8.2" tsc-prog "^2.3.0" - tsup "^8.4.0" + tsup "^8.5.0" typescript "^5.8.3" write-package "^7.1.0" -"@polkadot-api/codegen@0.16.0": - version "0.16.0" - resolved "https://registry.npmjs.org/@polkadot-api/codegen/-/codegen-0.16.0.tgz" - integrity sha512-2Sq/fkB7a9Oi3t7nGc0EbTt1Nd8Pb8XGiKKS9i/wwFAdCLN2oXd33DxmRQTX0Hm2/nrBzXYh1zBuyxRUb9+Sdw== +"@polkadot-api/codegen@0.17.1": + version "0.17.1" + resolved "https://registry.yarnpkg.com/@polkadot-api/codegen/-/codegen-0.17.1.tgz#53af24167656cbf327ec7a0e418225957f438108" + integrity sha512-JAbKbnqNH5W/siIA2tYJqCsDehzXOVStTrSgiWuIjfly+6fvXig/tKqoreNpY6NAmAe9BBkVw8kSfZs4mm/UfA== dependencies: - "@polkadot-api/ink-contracts" "0.3.2" - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/metadata-compatibility" "0.2.3" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/ink-contracts" "0.3.7" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/metadata-compatibility" "0.3.2" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/descriptors@file:.papi/descriptors": - version "0.1.0-autogenerated.9294084971075542043" + version "0.1.0-autogenerated.1186735750961316967" -"@polkadot-api/ink-contracts@0.3.2": - version "0.3.2" - resolved "https://registry.npmjs.org/@polkadot-api/ink-contracts/-/ink-contracts-0.3.2.tgz" - integrity sha512-ipWuClaySrPI7XHIomiswXhIZfU4q/EmHmLFIwLdn9iNhLd7YLuUtGF6kacSQu76YtWd3tkLe2rGx4cRRaLjOA== +"@polkadot-api/ink-contracts@0.3.7": + version "0.3.7" + resolved "https://registry.yarnpkg.com/@polkadot-api/ink-contracts/-/ink-contracts-0.3.7.tgz#d3f3800c542a8bfd149373686a5190397d450e30" + integrity sha512-n72H9xu7E7gvVB3+YhRRcYuD5ozc5u2Camv/NyYRrKg+omoL3qtn6k9ucPb1j77GbrZA1dLXpBYmjd9fVuQ4Xg== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/json-rpc-provider-proxy@0.2.4": version "0.2.4" @@ -456,10 +456,15 @@ resolved "https://registry.npmjs.org/@polkadot-api/json-rpc-provider/-/json-rpc-provider-0.0.4.tgz" integrity sha512-9cDijLIxzHOBuq6yHqpqjJ9jBmXrctjc1OFqU+tQrS96adQze3mTIH6DTgfb/0LMrqxzxffz1HQGrIlEH00WrA== -"@polkadot-api/known-chains@0.7.6": - version "0.7.6" - resolved "https://registry.npmjs.org/@polkadot-api/known-chains/-/known-chains-0.7.6.tgz" - integrity sha512-em+p9AVfTYulC4U10I+nO42wdczN9ZSAEyb5ppQsxxsKAxaJVPVe4xsDkWzlhheheEN6OBojNHnoYNBVG6X2bg== +"@polkadot-api/json-rpc-provider@workspace:*": + version "0.0.4" + resolved "https://registry.yarnpkg.com/@polkadot-api/json-rpc-provider/-/json-rpc-provider-0.0.4.tgz#15d0c6a7ec14aa6d0dd64039f931bebea83ffdb3" + integrity sha512-9cDijLIxzHOBuq6yHqpqjJ9jBmXrctjc1OFqU+tQrS96adQze3mTIH6DTgfb/0LMrqxzxffz1HQGrIlEH00WrA== + +"@polkadot-api/known-chains@0.9.3": + version "0.9.3" + resolved "https://registry.yarnpkg.com/@polkadot-api/known-chains/-/known-chains-0.9.3.tgz#e0a65be93fef367cc27cd4dfc3cef3b877846547" + integrity sha512-zP+6R8JrrkDfFa5p6pBtRGCxuc0vJlzbgJ/EXokpe+FHl4HyVobj0fgo9UXklOXXbV2iTQnNXOsXiE8QfLBwIQ== "@polkadot-api/logs-provider@0.0.6": version "0.0.6" @@ -468,22 +473,22 @@ dependencies: "@polkadot-api/json-rpc-provider" "0.0.4" -"@polkadot-api/merkleize-metadata@1.1.17": - version "1.1.17" - resolved "https://registry.npmjs.org/@polkadot-api/merkleize-metadata/-/merkleize-metadata-1.1.17.tgz" - integrity sha512-3wlLrYjpBluN5l8M1H9zgXlFHfJhqIXYvSVXTvkBYcEVKxZt0PO0f43Zgskeabg29Lx83OiPINcEHFWF8ndAzg== +"@polkadot-api/merkleize-metadata@1.1.20": + version "1.1.20" + resolved "https://registry.yarnpkg.com/@polkadot-api/merkleize-metadata/-/merkleize-metadata-1.1.20.tgz#bcda511fa3fdc7f9c465396f4843987e4e1dd575" + integrity sha512-biHRZbMJkKhmzBegiOk4W+iwiVNgNQ1YV5QzMrgmFwFeGBhm8iaNILnz0iB7t48+IaiWczQYnT3ZqYMTJslXwg== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" -"@polkadot-api/metadata-builders@0.12.1": - version "0.12.1" - resolved "https://registry.npmjs.org/@polkadot-api/metadata-builders/-/metadata-builders-0.12.1.tgz" - integrity sha512-heGt+WgcxrS1CqMm9XwD2DC+fI6azMKJf2ToMP+H12yw6FAy++nijASDZ3MlV/0ZpA/QGZpuZmgQmxKh6jbxVg== +"@polkadot-api/metadata-builders@0.13.1": + version "0.13.1" + resolved "https://registry.yarnpkg.com/@polkadot-api/metadata-builders/-/metadata-builders-0.13.1.tgz#9c78bffa3f28bbb0da0c059b95c012de2efb9638" + integrity sha512-a0vnN/BmSBnpsC/rD52Uej8dIiwWwdVy0K67NKw8jmRgl2LXYbsy4YSLB49WDwCD6p9AGm5chydNDCGYq4wOMw== dependencies: - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/metadata-builders@0.3.2": version "0.3.2" @@ -493,22 +498,22 @@ "@polkadot-api/substrate-bindings" "0.6.0" "@polkadot-api/utils" "0.1.0" -"@polkadot-api/metadata-compatibility@0.2.3": - version "0.2.3" - resolved "https://registry.npmjs.org/@polkadot-api/metadata-compatibility/-/metadata-compatibility-0.2.3.tgz" - integrity sha512-rtym491RA2yl8qGdEDJVujiCya+DK0CW5AwB6InSo85Um04/WWMq7oboRiXQZmspwLkfm2vYBusl/Q9k4Rxshw== +"@polkadot-api/metadata-compatibility@0.3.2": + version "0.3.2" + resolved "https://registry.yarnpkg.com/@polkadot-api/metadata-compatibility/-/metadata-compatibility-0.3.2.tgz#940c5ae355edc2fa17d8eef36668d467bbf9ccf0" + integrity sha512-3RE2e4hyeucx1uSvYt5sVQozjLLAEX3RDBM0XWqjHHjTqomihF8c+ozuoXtprR2h92x9UdiHg/jYuDT6/cL24w== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/substrate-bindings" "0.13.0" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/substrate-bindings" "0.15.1" -"@polkadot-api/observable-client@0.11.0": - version "0.11.0" - resolved "https://registry.npmjs.org/@polkadot-api/observable-client/-/observable-client-0.11.0.tgz" - integrity sha512-cyXyih+RI73vPcUQ6GxyMelm1Z3bGDvBIow8W3MqBdpUy4mZ87QGQXGpyBC0Op/qnIxrUFP1cLyT38fUe0i6KQ== +"@polkadot-api/observable-client@0.13.4": + version "0.13.4" + resolved "https://registry.yarnpkg.com/@polkadot-api/observable-client/-/observable-client-0.13.4.tgz#d9a913469e042211c1d3461e76ee2dade24b07a6" + integrity sha512-UYdssmUSMS0YKBtoQx9hFeSYDKg27iYx0FQZKmPHRfZ9Mk8EYZq4Mls71sTjuqXTl34GwYMgjrPUaSpK7jBL0w== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/observable-client@^0.3.0": version "0.3.2" @@ -519,16 +524,16 @@ "@polkadot-api/substrate-bindings" "0.6.0" "@polkadot-api/utils" "0.1.0" -"@polkadot-api/pjs-signer@0.6.8": - version "0.6.8" - resolved "https://registry.npmjs.org/@polkadot-api/pjs-signer/-/pjs-signer-0.6.8.tgz" - integrity sha512-YBp+uF2mPZFH4VjT5xgIU462EXbdLrFz09D6vY4SgoS2FRbPV7ktnqiNK2BykKJPGV4TiqpEjNB4OtX6ZLzafg== +"@polkadot-api/pjs-signer@0.6.11": + version "0.6.11" + resolved "https://registry.yarnpkg.com/@polkadot-api/pjs-signer/-/pjs-signer-0.6.11.tgz#0dd235c8d37c9ee411df92ba1d4e250418f66b66" + integrity sha512-tgv4l/PsCzOxJ8TXXd4x1QEZPow7Mt8WaUSIt+dUFLMKO+ZPWS0WEsBc0oMvHbriJuDSILmEi7YVXPFukF5OIA== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" + "@polkadot-api/metadata-builders" "0.13.1" "@polkadot-api/polkadot-signer" "0.1.6" - "@polkadot-api/signers-common" "0.1.9" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/signers-common" "0.1.12" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/polkadot-sdk-compat@2.3.2": version "2.3.2" @@ -542,27 +547,34 @@ resolved "https://registry.npmjs.org/@polkadot-api/polkadot-signer/-/polkadot-signer-0.1.6.tgz" integrity sha512-X7ghAa4r7doETtjAPTb50IpfGtrBmy3BJM5WCfNKa1saK04VFY9w+vDn+hwEcM4p0PcDHt66Ts74hzvHq54d9A== -"@polkadot-api/signer@0.2.1": - version "0.2.1" - resolved "https://registry.npmjs.org/@polkadot-api/signer/-/signer-0.2.1.tgz" - integrity sha512-z3BPDIglLh/hghQExQVVHR3xgIijjEVcIA2P+xLan5vO4cglGm4U6vIBXgKBuU2oxKlG494ixH8BkXSv5F79zw== +"@polkadot-api/raw-client@0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@polkadot-api/raw-client/-/raw-client-0.1.0.tgz#495c9cd65c2e34927bf4a737051c21e09db296ed" + integrity sha512-gHhPxTy9jbpoX3MBKT5QwPKX4gNmapJ+dC+ACZ5AXuqMraAUnFR1lu0QeUWH04Tc2gykVH1Eigz1kTDCSpN+zA== + dependencies: + "@polkadot-api/json-rpc-provider" "workspace:*" + +"@polkadot-api/signer@0.2.4": + version "0.2.4" + resolved "https://registry.yarnpkg.com/@polkadot-api/signer/-/signer-0.2.4.tgz#36a36bb4f7f0f2c1d1477798fff1ba4eb0da4d01" + integrity sha512-DOTUCnVwvWWEnJ1u/oyPbVk/RplDKJpRKJUOUGraoYh+J0PBicLvdVQF8680Guo/GJf7GBQpSFnev3mIcma6Pg== dependencies: "@noble/hashes" "^1.8.0" - "@polkadot-api/merkleize-metadata" "1.1.17" + "@polkadot-api/merkleize-metadata" "1.1.20" "@polkadot-api/polkadot-signer" "0.1.6" - "@polkadot-api/signers-common" "0.1.9" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/signers-common" "0.1.12" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" -"@polkadot-api/signers-common@0.1.9": - version "0.1.9" - resolved "https://registry.npmjs.org/@polkadot-api/signers-common/-/signers-common-0.1.9.tgz" - integrity sha512-eOAPfnNpa0kJrtM/OPHOt+jlFP97c4CWZmzfcPzOqfrLUgyyLzVCFzgBipffpzPXNPQsToM6FM+7DQEgQmoDuA== +"@polkadot-api/signers-common@0.1.12": + version "0.1.12" + resolved "https://registry.yarnpkg.com/@polkadot-api/signers-common/-/signers-common-0.1.12.tgz#e3e08dcad3f7ec356e0dd726c7ac2cf1621e82ed" + integrity sha512-wnNe08BbH1nG6XUy3hNbpRKsbAXFU0m4YovXp74hEDw0ycyjni0RnO2sUEV/vaghej8xFtD+7abjzE/lzmnHRA== dependencies: - "@polkadot-api/metadata-builders" "0.12.1" + "@polkadot-api/metadata-builders" "0.13.1" "@polkadot-api/polkadot-signer" "0.1.6" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/sm-provider@0.1.7": version "0.1.7" @@ -572,22 +584,22 @@ "@polkadot-api/json-rpc-provider" "0.0.4" "@polkadot-api/json-rpc-provider-proxy" "0.2.4" -"@polkadot-api/smoldot@0.3.8": - version "0.3.8" - resolved "https://registry.npmjs.org/@polkadot-api/smoldot/-/smoldot-0.3.8.tgz" - integrity sha512-dbJSMRFtELDW+rZIWRwKE/K8oy7+gYaGl+DvaOjARoBW2n80rJ7RAMOCCu+b5h2zgl3elftFBwMNAuAWgHT/Zg== +"@polkadot-api/smoldot@0.3.10": + version "0.3.10" + resolved "https://registry.yarnpkg.com/@polkadot-api/smoldot/-/smoldot-0.3.10.tgz#e7d9316546f5c214d4ce083b5458f3fc5cc69531" + integrity sha512-oL0Qsq2p3h2mU1/+gNq4h2rC/S99WoDiqkpmxg/phzknjXcbYXouYLSvhGbECygE1vWPVPl3IWAOjW/gcKdYKw== dependencies: - "@types/node" "^22.9.0" - smoldot "2.0.34" + "@types/node" "^22.15.30" + smoldot "2.0.36" -"@polkadot-api/substrate-bindings@0.13.0": - version "0.13.0" - resolved "https://registry.npmjs.org/@polkadot-api/substrate-bindings/-/substrate-bindings-0.13.0.tgz" - integrity sha512-M/60lXtHr4flwx4K7L4xv2jLk44EhD8UB4jvah+jbZM195I89nZGXKo2JOkgyR5DHoLj//TAoBkLedZmaaAiaQ== +"@polkadot-api/substrate-bindings@0.15.1": + version "0.15.1" + resolved "https://registry.yarnpkg.com/@polkadot-api/substrate-bindings/-/substrate-bindings-0.15.1.tgz#d6fbd758eb87fb4b3617ea170ef4ca326f4b9ac9" + integrity sha512-zQqgjjEqx7aQtssu5OMm+nLOGDQXvPZUrWGwtbT6rWJNDB5s3FcMhG5RBiBB2HUwjWPrC28XO/A2c8dNUtRKOw== dependencies: "@noble/hashes" "^1.8.0" - "@polkadot-api/utils" "0.1.2" - "@scure/base" "^1.2.5" + "@polkadot-api/utils" "0.2.0" + "@scure/base" "^1.2.6" scale-ts "^1.6.1" "@polkadot-api/substrate-bindings@0.6.0": @@ -600,13 +612,14 @@ "@scure/base" "^1.1.1" scale-ts "^1.6.0" -"@polkadot-api/substrate-client@0.3.0": - version "0.3.0" - resolved "https://registry.npmjs.org/@polkadot-api/substrate-client/-/substrate-client-0.3.0.tgz" - integrity sha512-0hEvQLKH2zhaFzE8DPkWehvJilec8u2O2wbIEUStm0OJ8jIFtJ40MFjXQfB01dXBWUz1KaVBqS6xd3sZA90Dpw== +"@polkadot-api/substrate-client@0.4.2": + version "0.4.2" + resolved "https://registry.yarnpkg.com/@polkadot-api/substrate-client/-/substrate-client-0.4.2.tgz#74fda584e9646066233a80eec5eccc3248ab1257" + integrity sha512-RXOqIy0h1EsiHiubPxZedVNbwBJR3Z/+bBlDFIxS81CSjP8eohs8xHQ/SDUm+4279XATwHdb8qeWnotFNcpl8A== dependencies: "@polkadot-api/json-rpc-provider" "0.0.4" - "@polkadot-api/utils" "0.1.2" + "@polkadot-api/raw-client" "0.1.0" + "@polkadot-api/utils" "0.2.0" "@polkadot-api/substrate-client@^0.1.2": version "0.1.4" @@ -621,24 +634,24 @@ resolved "https://registry.npmjs.org/@polkadot-api/utils/-/utils-0.1.0.tgz" integrity sha512-MXzWZeuGxKizPx2Xf/47wx9sr/uxKw39bVJUptTJdsaQn/TGq+z310mHzf1RCGvC1diHM8f593KrnDgc9oNbJA== -"@polkadot-api/utils@0.1.2": - version "0.1.2" - resolved "https://registry.npmjs.org/@polkadot-api/utils/-/utils-0.1.2.tgz" - integrity sha512-yhs5k2a8N1SBJcz7EthZoazzLQUkZxbf+0271Xzu42C5AEM9K9uFLbsB+ojzHEM72O5X8lPtSwGKNmS7WQyDyg== +"@polkadot-api/utils@0.2.0": + version "0.2.0" + resolved "https://registry.yarnpkg.com/@polkadot-api/utils/-/utils-0.2.0.tgz#812d4c4ee282691440aed4b6ddf863651e804444" + integrity sha512-nY3i5fQJoAxU4n3bD7Fs208/KR2J95SGfVc58kDjbRYN5a84kWaGEqzjBNtP9oqht49POM8Bm9mbIrkvC1Bzuw== -"@polkadot-api/wasm-executor@^0.1.2": - version "0.1.2" - resolved "https://registry.npmjs.org/@polkadot-api/wasm-executor/-/wasm-executor-0.1.2.tgz" - integrity sha512-a5wGenltB3EFPdf72u8ewi6HsUg2qubUAf3ekJprZf24lTK3+w8a/GUF/y6r08LJF35MALZ32SAtLqtVTIOGnQ== +"@polkadot-api/wasm-executor@^0.2.1": + version "0.2.1" + resolved "https://registry.yarnpkg.com/@polkadot-api/wasm-executor/-/wasm-executor-0.2.1.tgz#632b2ebc243b55eda4b1dd71cc457b51406a229e" + integrity sha512-EN3qtu9Aurz1PoEjvrvL/Z9lSMrLkRU2K1fOjzWFpI5siBgQ2eN/tMLbX1VjaSk1VhvXmbXPaqBrkfdMCxLdsg== -"@polkadot-api/ws-provider@0.4.0": - version "0.4.0" - resolved "https://registry.npmjs.org/@polkadot-api/ws-provider/-/ws-provider-0.4.0.tgz" - integrity sha512-ZurjUHHAlQ1Ux8HiZz7mtkg1qjq6LmqxcHljcZxne0U7foCZrXdWHsohwlV8kUQUir5kXuDsNvdZN/MFCUMaVw== +"@polkadot-api/ws-provider@0.4.1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/@polkadot-api/ws-provider/-/ws-provider-0.4.1.tgz#8e0eb0e189cfa6c1fa2d0282ad5ab9fc8a11fc60" + integrity sha512-C4SM3IExBghHAaNIGL7Xi1Pg8+1dJCOgYQ4HmdYUqqP2rcNtUUN68jx5vTfPFtCPw4z7kldP4DvL0BU0YtmauQ== dependencies: "@polkadot-api/json-rpc-provider" "0.0.4" "@polkadot-api/json-rpc-provider-proxy" "0.2.4" - ws "^8.18.1" + ws "^8.18.3" "@polkadot-labs/hdkd-helpers@0.0.10": version "0.0.10" @@ -733,20 +746,20 @@ tslib "^2.8.0" "@polkadot/keyring@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/keyring/-/keyring-13.4.3.tgz" - integrity sha512-2ePNcvBTznDN2luKbZM5fdxgAnj7V8m276qSTgrHlqKVvg9FsQpRCR6CAU+AjhnHzpe7uiZO+UH+jlXWefI3AA== + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/keyring/-/keyring-13.5.4.tgz" + integrity sha512-dQ/yq2OAl6jvjH+drxyqcfprsU2J9h74GSy5X4499W6YNwCt/2pxAJbmsM3lDWUlGOV1Wnp/aNHHs9kjb8GaJw== dependencies: - "@polkadot/util" "13.4.3" - "@polkadot/util-crypto" "13.4.3" + "@polkadot/util" "13.5.4" + "@polkadot/util-crypto" "13.5.4" tslib "^2.8.0" -"@polkadot/networks@13.4.3", "@polkadot/networks@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/networks/-/networks-13.4.3.tgz" - integrity sha512-Z+YZkltBt//CtkVH8ZYJ1z66qYxdI0yPamzkzZAqw6gj3gjgSxKtxB4baA/rcAw05QTvN2R3dLkkmKr2mnHovQ== +"@polkadot/networks@13.5.4", "@polkadot/networks@^13.2.3": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/networks/-/networks-13.5.4.tgz" + integrity sha512-JD7brNZsWTWbT3bDnEsAYkJfESvmn1XcoFMLoivVrg8dPXqYxoWcYveKPORjPyMPP6wgJ498vJGq7Ce0ihZ8ig== dependencies: - "@polkadot/util" "13.4.3" + "@polkadot/util" "13.5.4" "@substrate/ss58-registry" "^1.51.0" tslib "^2.8.0" @@ -855,31 +868,31 @@ rxjs "^7.8.1" tslib "^2.8.0" -"@polkadot/util-crypto@13.4.3", "@polkadot/util-crypto@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/util-crypto/-/util-crypto-13.4.3.tgz" - integrity sha512-Ml0mjhKVetMrRCIosmVNMa6lbFPa3fSAeOggf34NsDIIQOKt9FL644iGz1ZSMOnBwN9qk2qHYmcFMTDXX2yKVQ== +"@polkadot/util-crypto@13.5.4", "@polkadot/util-crypto@^13.2.3": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/util-crypto/-/util-crypto-13.5.4.tgz" + integrity sha512-XkKtiUi6I60DxT0dblGajZsqX4jWTnMpj4Pqxddz61KbpmvyybtAUqgmXOmO/Mob6TgGTutPuFeE7uMNEdFdJw== dependencies: "@noble/curves" "^1.3.0" "@noble/hashes" "^1.3.3" - "@polkadot/networks" "13.4.3" - "@polkadot/util" "13.4.3" + "@polkadot/networks" "13.5.4" + "@polkadot/util" "13.5.4" "@polkadot/wasm-crypto" "^7.4.1" "@polkadot/wasm-util" "^7.4.1" - "@polkadot/x-bigint" "13.4.3" - "@polkadot/x-randomvalues" "13.4.3" + "@polkadot/x-bigint" "13.5.4" + "@polkadot/x-randomvalues" "13.5.4" "@scure/base" "^1.1.7" tslib "^2.8.0" -"@polkadot/util@13.4.3", "@polkadot/util@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/util/-/util-13.4.3.tgz" - integrity sha512-6v2zvg8l7W22XvjYf7qv9tPQdYl2E6aXY94M4TZKsXZxmlS5BoG+A9Aq0+Gw8zBUjupjEmUkA6Y//msO8Zisug== +"@polkadot/util@13.5.4", "@polkadot/util@^13.2.3": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/util/-/util-13.5.4.tgz" + integrity sha512-w/D7tqfx5a+yHcVBTb+CWGwpJTwcFRNJaVIBxl/MjF3x8JUZCtcKNwklpWJH5HtwaXT1Mt2aBKjoxlNdnd6FYg== dependencies: - "@polkadot/x-bigint" "13.4.3" - "@polkadot/x-global" "13.4.3" - "@polkadot/x-textdecoder" "13.4.3" - "@polkadot/x-textencoder" "13.4.3" + "@polkadot/x-bigint" "13.5.4" + "@polkadot/x-global" "13.5.4" + "@polkadot/x-textdecoder" "13.5.4" + "@polkadot/x-textencoder" "13.5.4" "@types/bn.js" "^5.1.6" bn.js "^5.2.1" tslib "^2.8.0" @@ -937,60 +950,60 @@ dependencies: tslib "^2.7.0" -"@polkadot/x-bigint@13.4.3", "@polkadot/x-bigint@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-bigint/-/x-bigint-13.4.3.tgz" - integrity sha512-8NbjF5Q+5lflhvDFve58wULjCVcvXa932LKFtI5zL2gx5VDhMgyfkNcYRjHB18Ecl21963JuGzvGVTZNkh/i6g== +"@polkadot/x-bigint@13.5.4", "@polkadot/x-bigint@^13.2.3": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-bigint/-/x-bigint-13.5.4.tgz" + integrity sha512-vA4vjHWDUAnoAxzp1kSQMCzaArdagGXCNlooI2EOZ0pcFnEf4NkKCVjYg8i5L1QOYRAeJjgoKjKwCFBx63vtRw== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" tslib "^2.8.0" "@polkadot/x-fetch@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-fetch/-/x-fetch-13.4.3.tgz" - integrity sha512-EwhcwROqWa7mvNTbLVNH71Hbyp5PW5j9lV2UpII5MZzRO95eYwV4oP/xgtTxC+60nC8lrvzAw0JxEHrmNzmtlg== + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-fetch/-/x-fetch-13.5.4.tgz" + integrity sha512-VVhmfPaQwFVopgtMUCNhodyZXBy9P4wkQwwYWpkQv2KqYOEQVck/Hhq8IVhGdbtPJxCAWsj/EyYTzUIHZ9aBlw== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" node-fetch "^3.3.2" tslib "^2.8.0" -"@polkadot/x-global@13.4.3", "@polkadot/x-global@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-global/-/x-global-13.4.3.tgz" - integrity sha512-6c98kxZdoGRct3ua9Dz6/qz8wb3XFRUkaY+4+RzIgehKMPhu19pGWTrzmbJSyY9FtIpThuWKuDaBEvd5KgSxjA== +"@polkadot/x-global@13.5.4", "@polkadot/x-global@^13.2.3": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-global/-/x-global-13.5.4.tgz" + integrity sha512-oRUdO8/uKOEmLoPUFYgGascE/nyjT2ObRdf7jgwXOd9f+uUHPiE3K/MNAEi9t9sRKs8dbqgyaGWLTRYCDyzMag== dependencies: tslib "^2.8.0" -"@polkadot/x-randomvalues@13.4.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-randomvalues/-/x-randomvalues-13.4.3.tgz" - integrity sha512-pskXP/S2jROZ6aASExsUFlNp7GbJvQikKogvyvMMCzNIbUYLxpLuquLRa3MOORx2c0SNsENg90cx/zHT+IjPRQ== +"@polkadot/x-randomvalues@13.5.4": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-randomvalues/-/x-randomvalues-13.5.4.tgz" + integrity sha512-jKVEj+wVO83drbFFGGxhHJqwsOZCzyy6HVwQ/M9G6zhNXHrT46OWK+myd3dB4KbHoxWuH03Nvh540vMC3ah8Fw== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" tslib "^2.8.0" -"@polkadot/x-textdecoder@13.4.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-textdecoder/-/x-textdecoder-13.4.3.tgz" - integrity sha512-k7Wg6csAPxfNtpBt3k5yUuPHYmRl/nl7H2OMr40upMjbZXbQ1RJW9Z3GBkLmQczG7NwwfAXHwQE9FYOMUtbuRQ== +"@polkadot/x-textdecoder@13.5.4": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-textdecoder/-/x-textdecoder-13.5.4.tgz" + integrity sha512-+5rWIs+mhvBR2D7+/gWQyKKDoQzyHRIUrygphxdpBsFSvsJkTTGeGXLiD/ls0gTTE31Kb6StQJi1b9h6ywOvfg== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" tslib "^2.8.0" -"@polkadot/x-textencoder@13.4.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-textencoder/-/x-textencoder-13.4.3.tgz" - integrity sha512-byl2LbN1rnEXKmnsCzEDaIjSIHAr+1ciSe2yj3M0K+oWEEcaFZEovJaf/uoyzkcjn+/l8rDv3nget6mPuQ/DSw== +"@polkadot/x-textencoder@13.5.4": + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-textencoder/-/x-textencoder-13.5.4.tgz" + integrity sha512-GQ4kVJLtiirjI3NAKCnXCSIRudpTKog5SFPqouImV4X5rSsxnLf2xOqLwgYobdv3SIpTHBA1vy2RpQqUQUF6vw== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" tslib "^2.8.0" "@polkadot/x-ws@^13.2.3": - version "13.4.3" - resolved "https://registry.npmjs.org/@polkadot/x-ws/-/x-ws-13.4.3.tgz" - integrity sha512-GS0I6MYLD/xNAAjODZi/pbG7Ba0e/5sbvDIrT01iKH3SPGN+PZoyAsc04t2IOXA6QmPa1OBHnaU3N4K8gGmJ+w== + version "13.5.4" + resolved "https://registry.npmjs.org/@polkadot/x-ws/-/x-ws-13.5.4.tgz" + integrity sha512-tznbRjPnb3QW8v6+7zUoJINL84DW2dHJjwd0rkU0dtwzc9Y92faxz3bgOrCpgC2oVDpyUUg2PsyjokVBQHqLSA== dependencies: - "@polkadot/x-global" "13.4.3" + "@polkadot/x-global" "13.5.4" tslib "^2.8.0" ws "^8.18.0" @@ -1066,12 +1079,12 @@ "@rollup/rollup-linux-x64-gnu@4.34.8": version "4.34.8" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.34.8.tgz#5783fc0adcab7dc069692056e8ca8d83709855ce" + resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.34.8.tgz" integrity sha512-8y7ED8gjxITUltTUEJLQdgpbPh1sUQ0kMTmufRF/Ns5tI9TNMNlhWtmPKKHCU0SilX+3MJkZ0zERYYGIVBYHIA== "@rollup/rollup-linux-x64-musl@4.34.8": version "4.34.8" - resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.34.8.tgz#00b6c29b298197a384e3c659910b47943003a678" + resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.34.8.tgz" integrity sha512-SCXcP0ZpGFIe7Ge+McxY5zKxiEI5ra+GT3QRxL0pMMtxPfpyLAKleZODi1zdRHkz5/BhueUrYtYVgubqe9JBNQ== "@rollup/rollup-win32-arm64-msvc@4.34.8": @@ -1094,11 +1107,16 @@ resolved "https://registry.npmjs.org/@rx-state/core/-/core-0.1.4.tgz" integrity sha512-Z+3hjU2xh1HisLxt+W5hlYX/eGSDaXXP+ns82gq/PLZpkXLu0uwcNUh9RLY3Clq4zT+hSsA3vcpIGt6+UAb8rQ== -"@scure/base@^1.1.1", "@scure/base@^1.1.7", "@scure/base@^1.2.1", "@scure/base@^1.2.4", "@scure/base@^1.2.5", "@scure/base@~1.2.2", "@scure/base@~1.2.4": +"@scure/base@^1.1.1", "@scure/base@^1.1.7", "@scure/base@^1.2.1", "@scure/base@^1.2.4", "@scure/base@~1.2.2", "@scure/base@~1.2.4": version "1.2.5" resolved "https://registry.npmjs.org/@scure/base/-/base-1.2.5.tgz" integrity sha512-9rE6EOVeIQzt5TSu4v+K523F8u6DhBsoZWPGKlnCshhlDhy0kJzUX4V+tr2dWmzF1GdekvThABoEQBGBQI7xZw== +"@scure/base@^1.2.6": + version "1.2.6" + resolved "https://registry.yarnpkg.com/@scure/base/-/base-1.2.6.tgz#ca917184b8231394dd8847509c67a0be522e59f6" + integrity sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg== + "@scure/bip32@1.6.2", "@scure/bip32@^1.5.0": version "1.6.2" resolved "https://registry.npmjs.org/@scure/bip32/-/bip32-1.6.2.tgz" @@ -1132,9 +1150,9 @@ integrity sha512-t66jwrXA0s5Goq82ZtjagLNd7DPGCNjHeehRlE/gcJmJ+G56C0W+2plqOMRicJ8XGR1/YFnUSEqUFiSNbjGrAA== "@substrate/connect-known-chains@^1.1.5": - version "1.9.2" - resolved "https://registry.npmjs.org/@substrate/connect-known-chains/-/connect-known-chains-1.9.2.tgz" - integrity sha512-uEmm+rKJQQhhbforvmcg74TsDHKFVBkstjPwblGT1RdHMxUKR7Gq7F8vbkGnr5ce9tMK2Ylil760Z7vtX013hw== + version "1.10.3" + resolved "https://registry.npmjs.org/@substrate/connect-known-chains/-/connect-known-chains-1.10.3.tgz" + integrity sha512-OJEZO1Pagtb6bNE3wCikc2wrmvEU5x7GxFFLqqbz1AJYYxSlrPCGu4N2og5YTExo4IcloNMQYFRkBGue0BKZ4w== "@substrate/connect@0.8.11": version "0.8.11" @@ -1185,9 +1203,9 @@ integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== "@types/bn.js@^5.1.6": - version "5.1.6" - resolved "https://registry.npmjs.org/@types/bn.js/-/bn.js-5.1.6.tgz" - integrity sha512-Xh8vSwUeMKeYYrj3cX4lGQgFSF/N03r+tv4AiLl1SucqV+uTQpxRcnM8AkXKHwYP9ZPXOYXRr2KPXpVlIvqh9w== + version "5.2.0" + resolved "https://registry.npmjs.org/@types/bn.js/-/bn.js-5.2.0.tgz" + integrity sha512-DLbJ1BPqxvQhIGbeu8VbUC1DiAiahHtAYvA0ZEAa4P31F7IaArc8z3C3BRQdWX4mtLQuABG4yzp76ZrS02Ui1Q== dependencies: "@types/node" "*" @@ -1220,7 +1238,7 @@ resolved "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz" integrity sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q== -"@types/node@*", "@types/node@^22.15.18", "@types/node@^22.9.0": +"@types/node@*": version "22.15.21" resolved "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz" integrity sha512-EV/37Td6c+MgKAbkcLG6vqZ2zEYHD7bvSrzqqs2RIhbA6w3x+Dqz8MZM3sP6kGTeLrdoOgKZe+Xja7tUB2DNkQ== @@ -1234,6 +1252,20 @@ dependencies: undici-types "~6.19.2" +"@types/node@^22.15.30": + version "22.17.0" + resolved "https://registry.yarnpkg.com/@types/node/-/node-22.17.0.tgz#e8c9090e957bd4d9860efb323eb92d297347eac7" + integrity sha512-bbAKTCqX5aNVryi7qXVMi+OkB3w/OyblodicMbvE38blyAz7GxXf6XYhklokijuPwwVg9sDLKRxt0ZHXQwZVfQ== + dependencies: + undici-types "~6.21.0" + +"@types/node@^24.0.14": + version "24.2.0" + resolved "https://registry.yarnpkg.com/@types/node/-/node-24.2.0.tgz#cde712f88c5190006d6b069232582ecd1f94a760" + integrity sha512-3xyG3pMCq3oYCNg7/ZP+E1ooTaGB4cG8JWRsqqOYQdbWNY4zbaV0Ennrd7stjiJEFZCaybcIgpTjJWHRfBSIDw== + dependencies: + undici-types "~7.10.0" + "@types/normalize-package-data@^2.4.3": version "2.4.4" resolved "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz" @@ -1352,9 +1384,9 @@ binary-extensions@^2.0.0: integrity sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw== bn.js@^5.2.1: - version "5.2.1" - resolved "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz" - integrity sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ== + version "5.2.2" + resolved "https://registry.npmjs.org/bn.js/-/bn.js-5.2.2.tgz" + integrity sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw== brace-expansion@^2.0.1: version "2.0.1" @@ -1510,10 +1542,10 @@ color-name@~1.1.4: resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== -commander@^13.1.0: - version "13.1.0" - resolved "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz" - integrity sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw== +commander@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-14.0.0.tgz#f244fc74a92343514e56229f16ef5c5e22ced5e9" + integrity sha512-2uM9rYjPvyq39NwLRqaiLtWHyDC1FvryJDa2ATTVims5YAS4PupsEQsDvP14FqhFr0P49CYDugi59xaxJlTXRA== commander@^4.0.0: version "4.1.1" @@ -1748,9 +1780,9 @@ eventemitter3@5.0.1, eventemitter3@^5.0.1: resolved "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz" integrity sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA== -execa@^9.5.3: +execa@^9.6.0: version "9.6.0" - resolved "https://registry.npmjs.org/execa/-/execa-9.6.0.tgz" + resolved "https://registry.yarnpkg.com/execa/-/execa-9.6.0.tgz#38665530e54e2e018384108322f37f35ae74f3bc" integrity sha512-jpWzZ1ZhwUmeWRhS7Qv3mhpOhLfwI+uAX4e5fOcXqwMR7EcJ0pj2kV1CVzHVMX/LphnKWD3LObjZCoJ71lKpHw== dependencies: "@sindresorhus/merge-streams" "^4.0.0" @@ -2502,28 +2534,28 @@ pkg-types@^1.3.0: pathe "^2.0.1" polkadot-api@^1.9.5: - version "1.12.0" - resolved "https://registry.npmjs.org/polkadot-api/-/polkadot-api-1.12.0.tgz" - integrity sha512-CstKp0ySE3JRVnG4nzl6hDhYLf4Qs/XpVk1xJrypYMqVbTu8FwjBK3l3j4pHhEttVudlEjK2hoVzQ1MdxMLeEg== + version "1.15.3" + resolved "https://registry.yarnpkg.com/polkadot-api/-/polkadot-api-1.15.3.tgz#c8d02c9d79536669c50d17b2426f9fb905825804" + integrity sha512-ikv7+3SvIXE03NBEi3Otn10c5L80TXimAvRnbZKugO0lilE9+uW1JXkMemaP13qlkoH5jrZbvz6xOEcz0ali9Q== dependencies: - "@polkadot-api/cli" "0.13.0" - "@polkadot-api/ink-contracts" "0.3.2" + "@polkadot-api/cli" "0.14.5" + "@polkadot-api/ink-contracts" "0.3.7" "@polkadot-api/json-rpc-provider" "0.0.4" - "@polkadot-api/known-chains" "0.7.6" + "@polkadot-api/known-chains" "0.9.3" "@polkadot-api/logs-provider" "0.0.6" - "@polkadot-api/metadata-builders" "0.12.1" - "@polkadot-api/metadata-compatibility" "0.2.3" - "@polkadot-api/observable-client" "0.11.0" - "@polkadot-api/pjs-signer" "0.6.8" + "@polkadot-api/metadata-builders" "0.13.1" + "@polkadot-api/metadata-compatibility" "0.3.2" + "@polkadot-api/observable-client" "0.13.4" + "@polkadot-api/pjs-signer" "0.6.11" "@polkadot-api/polkadot-sdk-compat" "2.3.2" "@polkadot-api/polkadot-signer" "0.1.6" - "@polkadot-api/signer" "0.2.1" + "@polkadot-api/signer" "0.2.4" "@polkadot-api/sm-provider" "0.1.7" - "@polkadot-api/smoldot" "0.3.8" - "@polkadot-api/substrate-bindings" "0.13.0" - "@polkadot-api/substrate-client" "0.3.0" - "@polkadot-api/utils" "0.1.2" - "@polkadot-api/ws-provider" "0.4.0" + "@polkadot-api/smoldot" "0.3.10" + "@polkadot-api/substrate-bindings" "0.15.1" + "@polkadot-api/substrate-client" "0.4.2" + "@polkadot-api/utils" "0.2.0" + "@polkadot-api/ws-provider" "0.4.1" "@rx-state/core" "^0.1.4" possible-typed-array-names@^1.0.0: @@ -2719,10 +2751,10 @@ smoldot@2.0.26: dependencies: ws "^8.8.1" -smoldot@2.0.34: - version "2.0.34" - resolved "https://registry.npmjs.org/smoldot/-/smoldot-2.0.34.tgz" - integrity sha512-mw9tCbGEhEp0koMqLL0jBEixVY1MIN/xI3pE6ZY1TuOPU+LnYy8FloODVyzkvzQPaBYrETXJdRlmA/+k6g3gow== +smoldot@2.0.36: + version "2.0.36" + resolved "https://registry.yarnpkg.com/smoldot/-/smoldot-2.0.36.tgz#3d4216b7fe33130fcf276f691d37f7503485ab78" + integrity sha512-0GtHgxOs1VGs+WzpUgTQ52Zg92/q4mnIPEl+smArI4pis6aduQ6ZiXRllbDafsIb18wWYsxaBLNjBkNOB8xBrw== dependencies: ws "^8.8.1" @@ -2955,9 +2987,9 @@ tslib@^2.1.0, tslib@^2.7.0, tslib@^2.8.0: resolved "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz" integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== -tsup@^8.4.0: +tsup@^8.5.0: version "8.5.0" - resolved "https://registry.npmjs.org/tsup/-/tsup-8.5.0.tgz" + resolved "https://registry.yarnpkg.com/tsup/-/tsup-8.5.0.tgz#4b1e25b1a8f4e4f89b764207bf37cfe2d7411d31" integrity sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ== dependencies: bundle-require "^5.1.0" @@ -3003,6 +3035,11 @@ undici-types@~6.21.0: resolved "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz" integrity sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ== +undici-types@~7.10.0: + version "7.10.0" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.10.0.tgz#4ac2e058ce56b462b056e629cc6a02393d3ff350" + integrity sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag== + unicorn-magic@^0.1.0: version "0.1.0" resolved "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz" @@ -3171,10 +3208,10 @@ ws@8.18.0: resolved "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz" integrity sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw== -ws@^8.18.0, ws@^8.18.1, ws@^8.18.2, ws@^8.8.1: - version "8.18.2" - resolved "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz" - integrity sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ== +ws@^8.18.0, ws@^8.18.2, ws@^8.18.3, ws@^8.8.1: + version "8.18.3" + resolved "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz" + integrity sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg== y18n@^5.0.5: version "5.0.8" diff --git a/node/Cargo.toml b/node/Cargo.toml index 0ee30ab9f3..3696e78f21 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "A fresh FRAME-based Substrate node, ready for hacking." authors = ["Substrate DevHub "] homepage = "https://substrate.io/" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" @@ -20,91 +20,91 @@ targets = ["x86_64-unknown-linux-gnu"] name = "node-subtensor" [dependencies] -async-trait = { workspace = true } +async-trait.workspace = true clap = { workspace = true, features = ["derive"] } futures = { workspace = true, features = ["thread-pool"] } -scale-codec = { workspace = true } serde = { workspace = true, features = ["derive"] } -hex = { workspace = true } +hex.workspace = true # Storage import -memmap2 = { workspace = true } -serde_json = { workspace = true } - -sc-cli = { workspace = true } -sp-core = { workspace = true } -sc-executor = { workspace = true } -sc-service = { workspace = true } -sc-telemetry = { workspace = true } -sc-keystore = { workspace = true } -sc-transaction-pool = { workspace = true } -sc-transaction-pool-api = { workspace = true } -sc-offchain = { workspace = true } -sc-network = { workspace = true } -sc-consensus-aura = { workspace = true } -sp-consensus-aura = { workspace = true } -sp-consensus = { workspace = true } -sc-consensus = { workspace = true } -sc-consensus-grandpa = { workspace = true } -sc-consensus-grandpa-rpc = { workspace = true } -sp-consensus-grandpa = { workspace = true } -sc-chain-spec-derive = { workspace = true } -sc-chain-spec = { workspace = true } -sc-consensus-slots = { workspace = true } -sc-client-api = { workspace = true } -sp-runtime = { workspace = true } -sp-io = { workspace = true } -sp-timestamp = { workspace = true } +memmap2.workspace = true +serde_json.workspace = true + +sc-cli.workspace = true +sp-core.workspace = true +sc-executor.workspace = true +sc-service.workspace = true +sc-telemetry.workspace = true +sc-keystore.workspace = true +sc-transaction-pool.workspace = true +sc-transaction-pool-api.workspace = true +sc-offchain.workspace = true +sc-network.workspace = true +sc-consensus-aura.workspace = true +sp-consensus-aura.workspace = true +sp-consensus.workspace = true +sc-consensus.workspace = true +sc-consensus-grandpa.workspace = true +sc-consensus-grandpa-rpc.workspace = true +sp-consensus-grandpa.workspace = true +sc-chain-spec-derive.workspace = true +sc-chain-spec.workspace = true +sc-consensus-slots.workspace = true +sc-client-api.workspace = true +sp-runtime.workspace = true +sp-io.workspace = true +sp-timestamp.workspace = true sp-transaction-pool = { workspace = true, features = ["default"] } -sp-inherents = { workspace = true } -sp-keyring = { workspace = true } -sp-offchain = { workspace = true } -sp-session = { workspace = true } -frame-metadata-hash-extension = { workspace = true } -frame-system = { workspace = true } -pallet-transaction-payment = { workspace = true } -pallet-commitments = { path = "../pallets/commitments" } -pallet-drand = { workspace = true } -sp-crypto-ec-utils = { workspace = true } -sp-keystore = { workspace = true, default-features = false } -cumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = false } +sp-inherents.workspace = true +sp-keyring.workspace = true +sp-offchain.workspace = true +sp-session.workspace = true +frame-metadata-hash-extension.workspace = true +frame-system.workspace = true +pallet-transaction-payment.workspace = true +pallet-commitments.workspace = true +pallet-drand.workspace = true +sp-crypto-ec-utils = { workspace = true, default-features = true, features = [ + "bls12-381", +] } +sp-keystore.workspace = true +cumulus-primitives-proof-size-hostfunction.workspace = true # These dependencies are used for the subtensor's RPCs jsonrpsee = { workspace = true, features = ["server"] } -sc-rpc = { workspace = true } -sp-api = { workspace = true } -sc-rpc-api = { workspace = true } -sp-blockchain = { workspace = true } -sp-block-builder = { workspace = true } -sc-basic-authorship = { workspace = true } -substrate-frame-rpc-system = { workspace = true } -pallet-transaction-payment-rpc = { workspace = true } -frame-system-rpc-runtime-api = { workspace = true } -pallet-transaction-payment-rpc-runtime-api = { workspace = true } +sc-rpc.workspace = true +sp-api.workspace = true +sc-rpc-api.workspace = true +sp-blockchain.workspace = true +sp-block-builder.workspace = true +sc-basic-authorship.workspace = true +substrate-frame-rpc-system.workspace = true +pallet-transaction-payment-rpc.workspace = true +frame-system-rpc-runtime-api.workspace = true +pallet-transaction-payment-rpc-runtime-api.workspace = true # These dependencies are used for runtime benchmarking -frame-benchmarking = { workspace = true } -frame-benchmarking-cli = { workspace = true } +frame-benchmarking.workspace = true +frame-benchmarking-cli.workspace = true # Needed for Frontier -sc-consensus-manual-seal = { workspace = true } -sc-network-sync = { workspace = true } -substrate-prometheus-endpoint = { workspace = true } +sc-consensus-manual-seal.workspace = true +sc-network-sync.workspace = true +substrate-prometheus-endpoint.workspace = true # Frontier -fc-storage = { workspace = true } -fc-db = { workspace = true } -fc-consensus = { workspace = true } -fc-api = { workspace = true } -fc-rpc = { workspace = true } -fc-rpc-core = { workspace = true } -fp-rpc = { workspace = true } -fc-aura = { workspace = true } -fc-mapping-sync = { workspace = true } -fp-consensus = { workspace = true } -thiserror = { workspace = true } -num-traits = { version = "0.2", features = ["std"] } +fc-storage.workspace = true +fc-db.workspace = true +fc-consensus.workspace = true +fc-api.workspace = true +fc-rpc = { workspace = true, features = ["rpc-binary-search-estimate"] } +fc-rpc-core.workspace = true +fp-rpc.workspace = true +fc-aura.workspace = true +fc-mapping-sync.workspace = true +fp-consensus.workspace = true +num-traits = { workspace = true, features = ["std"] } # Local Dependencies node-subtensor-runtime = { workspace = true, features = ["std"] } @@ -115,7 +115,7 @@ pallet-subtensor-swap-rpc = { workspace = true, features = ["std"] } pallet-subtensor-swap-runtime-api = { workspace = true, features = ["std"] } [build-dependencies] -substrate-build-script-utils = { workspace = true } +substrate-build-script-utils.workspace = true [features] default = ["rocksdb", "sql", "txpool"] @@ -126,6 +126,8 @@ rocksdb = [ "fc-db/rocksdb", "fc-mapping-sync/rocksdb", "fc-rpc/rocksdb", + "frame-benchmarking-cli/rocksdb", + "sc-cli/rocksdb", ] txpool = ["fc-rpc/txpool", "fc-rpc-core/txpool"] diff --git a/node/src/benchmarking.rs b/node/src/benchmarking.rs index 1590422c08..df21d5bef4 100644 --- a/node/src/benchmarking.rs +++ b/node/src/benchmarking.rs @@ -174,6 +174,6 @@ pub fn inherent_benchmark_data() -> Result { let timestamp = sp_timestamp::InherentDataProvider::new(d.into()); futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data)) - .map_err(|e| format!("creating inherent data: {:?}", e))?; + .map_err(|e| format!("creating inherent data: {e:?}"))?; Ok(inherent_data) } diff --git a/node/src/chain_spec/finney.rs b/node/src/chain_spec/finney.rs index be35c4e901..4b47c29473 100644 --- a/node/src/chain_spec/finney.rs +++ b/node/src/chain_spec/finney.rs @@ -21,7 +21,7 @@ pub fn finney_mainnet_config() -> Result { }; let old_state: ColdkeyHotkeys = - json::from_slice(&bytes).map_err(|e| format!("Error parsing genesis file: {}", e))?; + json::from_slice(&bytes).map_err(|e| format!("Error parsing genesis file: {e}"))?; let mut processed_stakes: Vec<( sp_runtime::AccountId32, diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index e8efbb1647..733f416e69 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -38,7 +38,7 @@ pub type ChainSpec = sc_service::GenericChainSpec; /// Generate a crypto pair from seed. pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) + TPublic::Pair::from_string(&format!("//{seed}"), None) .expect("static values are valid; qed") .public() } diff --git a/node/src/command.rs b/node/src/command.rs index f8f4990d0f..f35664f8b0 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -134,8 +134,7 @@ pub fn run() -> sc_cli::Result<()> { } Err(err) => { return Err(format!( - "Cannot purge `{:?}` database: {:?}", - db_path, err, + "Cannot purge `{db_path:?}` database: {err:?}", ) .into()); } diff --git a/node/src/service.rs b/node/src/service.rs index 2dc9cbd479..ca23ddb03b 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -161,7 +161,7 @@ where std::num::NonZeroU32::new(eth_config.frontier_sql_backend_num_ops_timeout), storage_override.clone(), )) - .unwrap_or_else(|err| panic!("failed creating sql backend: {:?}", err)); + .unwrap_or_else(|err| panic!("failed creating sql backend: {err:?}")); FrontierBackend::Sql(Arc::new(backend)) } }; @@ -424,7 +424,7 @@ where Some(WarpSyncConfig::WithProvider(warp_sync)) }; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, net_config, @@ -453,7 +453,7 @@ where log::debug!("Offchain worker key generated"); } Err(e) => { - log::error!("Failed to create SR25519 key for offchain worker: {:?}", e); + log::error!("Failed to create SR25519 key for offchain worker: {e:?}"); } } } else { @@ -632,7 +632,6 @@ where commands_stream, )?; - network_starter.start_network(); log::info!("Manual Seal Ready"); return Ok(task_manager); } @@ -729,7 +728,6 @@ where .spawn_blocking("grandpa-voter", None, grandpa_voter); } - network_starter.start_network(); Ok(task_manager) } @@ -739,16 +737,12 @@ pub async fn build_full( sealing: Option, ) -> Result { match config.network.network_backend { - Some(sc_network::config::NetworkBackendType::Libp2p) => { + sc_network::config::NetworkBackendType::Libp2p => { new_full::>(config, eth_config, sealing).await } - Some(sc_network::config::NetworkBackendType::Litep2p) => { + sc_network::config::NetworkBackendType::Litep2p => { new_full::(config, eth_config, sealing).await } - _ => { - log::debug!("no network backend selected, falling back to libp2p"); - new_full::>(config, eth_config, sealing).await - } } } diff --git a/pallets/admin-utils/Cargo.toml b/pallets/admin-utils/Cargo.toml index c0abc67ad2..61cdba4cbf 100644 --- a/pallets/admin-utils/Cargo.toml +++ b/pallets/admin-utils/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "FRAME pallet for extending admin utilities." authors = ["Bittensor Nucleus Team"] homepage = "https://bittensor.com" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" @@ -16,37 +16,35 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -subtensor-macros = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ - "derive", -] } +subtensor-macros.workspace = true +codec = { workspace = true, features = ["derive"] } scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-runtime = { workspace = true } -log = { workspace = true } -pallet-subtensor = { version = "4.0.0-dev", default-features = false, path = "../subtensor" } -sp-weights = { workspace = true } -substrate-fixed = { workspace = true } -pallet-evm-chain-id = { workspace = true } -pallet-drand = { workspace = true, default-features = false } -sp-consensus-grandpa = { workspace = true } -subtensor-swap-interface = { workspace = true } -subtensor-runtime-common = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +sp-runtime.workspace = true +log.workspace = true +pallet-subtensor.workspace = true +sp-weights.workspace = true +substrate-fixed.workspace = true +pallet-evm-chain-id.workspace = true +pallet-drand.workspace = true +sp-consensus-grandpa.workspace = true +subtensor-swap-interface.workspace = true +subtensor-runtime-common.workspace = true [dev-dependencies] -sp-core = { workspace = true } -sp-io = { workspace = true } -sp-tracing = { workspace = true } -sp-consensus-aura = { workspace = true } +sp-core.workspace = true +sp-io.workspace = true +sp-tracing.workspace = true +sp-consensus-aura.workspace = true pallet-balances = { workspace = true, features = ["std"] } -pallet-scheduler = { workspace = true } -pallet-grandpa = { workspace = true } -sp-std = { workspace = true } -pallet-subtensor-swap = { workspace = true } -pallet-crowdloan = { workspace = true, default-features = false } -pallet-preimage = { workspace = true, default-features = false } +pallet-scheduler.workspace = true +pallet-grandpa.workspace = true +sp-std.workspace = true +pallet-subtensor-swap.workspace = true +pallet-crowdloan.workspace = true +pallet-preimage.workspace = true [features] default = ["std"] @@ -76,7 +74,7 @@ std = [ "sp-weights/std", "substrate-fixed/std", "subtensor-swap-interface/std", - "subtensor-runtime-common/std" + "subtensor-runtime-common/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/pallets/admin-utils/src/benchmarking.rs b/pallets/admin-utils/src/benchmarking.rs index 917d9008ba..61df5d55f8 100644 --- a/pallets/admin-utils/src/benchmarking.rs +++ b/pallets/admin-utils/src/benchmarking.rs @@ -266,7 +266,7 @@ mod benchmarks { ); #[extrinsic_call] - _(RawOrigin::Root, 1u16.into()/*netuid*/, 10u64/*max_burn*/)/*sudo_set_max_burn*/; + _(RawOrigin::Root, 1u16.into()/*netuid*/, 10.into()/*max_burn*/)/*sudo_set_max_burn*/; } #[benchmark] @@ -277,7 +277,7 @@ mod benchmarks { ); #[extrinsic_call] - _(RawOrigin::Root, 1u16.into()/*netuid*/, 10u64/*min_burn*/)/*sudo_set_min_burn*/; + _(RawOrigin::Root, 1u16.into()/*netuid*/, 10.into()/*min_burn*/)/*sudo_set_min_burn*/; } #[benchmark] @@ -335,5 +335,16 @@ mod benchmarks { _(RawOrigin::Root, 1u16.into()/*netuid*/, true/*enabled*/)/*set_commit_reveal_weights_enabled*/; } + #[benchmark] + fn sudo_set_commit_reveal_version() { + pallet_subtensor::Pallet::::init_new_network( + 1u16.into(), /*netuid*/ + 1u16, /*sudo_tempo*/ + ); + + #[extrinsic_call] + _(RawOrigin::Root, 5u16/*version*/)/*sudo_set_commit_reveal_version()*/; + } + //impl_benchmark_test_suite!(AdminUtils, crate::mock::new_test_ext(), crate::mock::Test); } diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index 1be45caaee..a8d0a080b5 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -31,7 +31,7 @@ pub mod pallet { use pallet_subtensor::utils::rate_limiting::TransactionType; use sp_runtime::BoundedVec; use substrate_fixed::types::I96F32; - use subtensor_runtime_common::NetUid; + use subtensor_runtime_common::{NetUid, TaoCurrency}; /// The main data structure of the module. #[pallet::pallet] @@ -111,7 +111,9 @@ pub mod pallet { RevealPeriodOutOfBounds, } /// Enum for specifying the type of precompile operation. - #[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, Debug, Copy)] + #[derive( + Encode, Decode, DecodeWithMemTracking, TypeInfo, Clone, PartialEq, Eq, Debug, Copy, + )] pub enum PrecompileEnum { /// Enum for balance transfer precompile BalanceTransfer, @@ -159,7 +161,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Aura pallet to change the authorities. #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(5_062_000, 0) + #[pallet::weight(Weight::from_parts(3_071_000, 0) .saturating_add(::DbWeight::get().reads(0_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn swap_authorities( @@ -170,7 +172,7 @@ pub mod pallet { T::Aura::change_authorities(new_authorities.clone()); - log::debug!("Aura authorities changed: {:?}", new_authorities); + log::debug!("Aura authorities changed: {new_authorities:?}"); // Return a successful DispatchResultWithPostInfo Ok(()) @@ -180,13 +182,13 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the default take. #[pallet::call_index(1)] - #[pallet::weight(Weight::from_parts(5_831_000, 0) + #[pallet::weight(Weight::from_parts(3_590_000, 0) .saturating_add(::DbWeight::get().reads(0_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_default_take(origin: OriginFor, default_take: u16) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_max_delegate_take(default_take); - log::debug!("DefaultTakeSet( default_take: {:?} ) ", default_take); + log::debug!("DefaultTakeSet( default_take: {default_take:?} ) "); Ok(()) } @@ -198,7 +200,7 @@ pub mod pallet { pub fn sudo_set_tx_rate_limit(origin: OriginFor, tx_rate_limit: u64) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_tx_rate_limit(tx_rate_limit); - log::debug!("TxRateLimitSet( tx_rate_limit: {:?} ) ", tx_rate_limit); + log::debug!("TxRateLimitSet( tx_rate_limit: {tx_rate_limit:?} ) "); Ok(()) } @@ -206,7 +208,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the serving rate limit. #[pallet::call_index(3)] - #[pallet::weight(Weight::from_parts(6_682_000, 0) + #[pallet::weight(Weight::from_parts(4_470_000, 0) .saturating_add(::DbWeight::get().reads(0_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_serving_rate_limit( @@ -217,10 +219,7 @@ pub mod pallet { pallet_subtensor::Pallet::::ensure_subnet_owner_or_root(origin, netuid)?; pallet_subtensor::Pallet::::set_serving_rate_limit(netuid, serving_rate_limit); - log::debug!( - "ServingRateLimitSet( serving_rate_limit: {:?} ) ", - serving_rate_limit - ); + log::debug!("ServingRateLimitSet( serving_rate_limit: {serving_rate_limit:?} ) "); Ok(()) } @@ -228,7 +227,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the minimum difficulty. #[pallet::call_index(4)] - #[pallet::weight(Weight::from_parts(19_780_000, 0) + #[pallet::weight(Weight::from_parts(12_140_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_min_difficulty( @@ -244,9 +243,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_min_difficulty(netuid, min_difficulty); log::debug!( - "MinDifficultySet( netuid: {:?} min_difficulty: {:?} ) ", - netuid, - min_difficulty + "MinDifficultySet( netuid: {netuid:?} min_difficulty: {min_difficulty:?} ) " ); Ok(()) } @@ -255,7 +252,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the maximum difficulty. #[pallet::call_index(5)] - #[pallet::weight(Weight::from_parts(16750000, 0) + #[pallet::weight(Weight::from_parts(12_840_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_difficulty( @@ -271,9 +268,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_max_difficulty(netuid, max_difficulty); log::debug!( - "MaxDifficultySet( netuid: {:?} max_difficulty: {:?} ) ", - netuid, - max_difficulty + "MaxDifficultySet( netuid: {netuid:?} max_difficulty: {max_difficulty:?} ) " ); Ok(()) } @@ -282,7 +277,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the weights version key. #[pallet::call_index(6)] - #[pallet::weight(Weight::from_parts(16320000, 0) + #[pallet::weight(Weight::from_parts(12_560_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_weights_version_key( @@ -321,9 +316,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_weights_version_key(netuid, weights_version_key); log::debug!( - "WeightsVersionKeySet( netuid: {:?} weights_version_key: {:?} ) ", - netuid, - weights_version_key + "WeightsVersionKeySet( netuid: {netuid:?} weights_version_key: {weights_version_key:?} ) " ); Ok(()) } @@ -332,7 +325,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the weights set rate limit. #[pallet::call_index(7)] - #[pallet::weight(Weight::from_parts(16560000, 0) + #[pallet::weight(Weight::from_parts(12_230_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_weights_set_rate_limit( @@ -351,9 +344,7 @@ pub mod pallet { weights_set_rate_limit, ); log::debug!( - "WeightsSetRateLimitSet( netuid: {:?} weights_set_rate_limit: {:?} ) ", - netuid, - weights_set_rate_limit + "WeightsSetRateLimitSet( netuid: {netuid:?} weights_set_rate_limit: {weights_set_rate_limit:?} ) " ); Ok(()) } @@ -362,7 +353,7 @@ pub mod pallet { /// It is only callable by the root account, not changeable by the subnet owner. /// The extrinsic will call the Subtensor pallet to set the adjustment interval. #[pallet::call_index(8)] - #[pallet::weight(Weight::from_parts(16570000, 0) + #[pallet::weight(Weight::from_parts(12_200_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_adjustment_interval( @@ -378,9 +369,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_adjustment_interval(netuid, adjustment_interval); log::debug!( - "AdjustmentIntervalSet( netuid: {:?} adjustment_interval: {:?} ) ", - netuid, - adjustment_interval + "AdjustmentIntervalSet( netuid: {netuid:?} adjustment_interval: {adjustment_interval:?} ) " ); Ok(()) } @@ -408,10 +397,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_adjustment_alpha(netuid, adjustment_alpha); - log::debug!( - "AdjustmentAlphaSet( adjustment_alpha: {:?} ) ", - adjustment_alpha - ); + log::debug!("AdjustmentAlphaSet( adjustment_alpha: {adjustment_alpha:?} ) "); Ok(()) } @@ -419,7 +405,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the adjustment beta. #[pallet::call_index(12)] - #[pallet::weight(Weight::from_parts(19_240_000, 0) + #[pallet::weight(Weight::from_parts(12_210_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_weight_limit( @@ -435,9 +421,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_max_weight_limit(netuid, max_weight_limit); log::debug!( - "MaxWeightLimitSet( netuid: {:?} max_weight_limit: {:?} ) ", - netuid, - max_weight_limit + "MaxWeightLimitSet( netuid: {netuid:?} max_weight_limit: {max_weight_limit:?} ) " ); Ok(()) } @@ -446,7 +430,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the immunity period. #[pallet::call_index(13)] - #[pallet::weight(Weight::from_parts(19_380_000, 0) + #[pallet::weight(Weight::from_parts(12_330_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_immunity_period( @@ -462,9 +446,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_immunity_period(netuid, immunity_period); log::debug!( - "ImmunityPeriodSet( netuid: {:?} immunity_period: {:?} ) ", - netuid, - immunity_period + "ImmunityPeriodSet( netuid: {netuid:?} immunity_period: {immunity_period:?} ) " ); Ok(()) } @@ -473,7 +455,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the minimum allowed weights. #[pallet::call_index(14)] - #[pallet::weight(Weight::from_parts(19_770_000, 0) + #[pallet::weight(Weight::from_parts(12_200_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_min_allowed_weights( @@ -489,9 +471,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_min_allowed_weights(netuid, min_allowed_weights); log::debug!( - "MinAllowedWeightSet( netuid: {:?} min_allowed_weights: {:?} ) ", - netuid, - min_allowed_weights + "MinAllowedWeightSet( netuid: {netuid:?} min_allowed_weights: {min_allowed_weights:?} ) " ); Ok(()) } @@ -500,7 +480,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the maximum allowed UIDs for a subnet. #[pallet::call_index(15)] - #[pallet::weight(Weight::from_parts(23_820_000, 0) + #[pallet::weight(Weight::from_parts(15_500_000, 0) .saturating_add(::DbWeight::get().reads(2_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_allowed_uids( @@ -519,9 +499,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_max_allowed_uids(netuid, max_allowed_uids); log::debug!( - "MaxAllowedUidsSet( netuid: {:?} max_allowed_uids: {:?} ) ", - netuid, - max_allowed_uids + "MaxAllowedUidsSet( netuid: {netuid:?} max_allowed_uids: {max_allowed_uids:?} ) " ); Ok(()) } @@ -530,7 +508,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the kappa. #[pallet::call_index(16)] - #[pallet::weight(Weight::from_parts(16440000, 0) + #[pallet::weight(Weight::from_parts(12_530_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_kappa(origin: OriginFor, netuid: NetUid, kappa: u16) -> DispatchResult { @@ -541,7 +519,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_kappa(netuid, kappa); - log::debug!("KappaSet( netuid: {:?} kappa: {:?} ) ", netuid, kappa); + log::debug!("KappaSet( netuid: {netuid:?} kappa: {kappa:?} ) "); Ok(()) } @@ -549,7 +527,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the rho. #[pallet::call_index(17)] - #[pallet::weight(Weight::from_parts(13770000, 0) + #[pallet::weight(Weight::from_parts(10_160_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_rho(origin: OriginFor, netuid: NetUid, rho: u16) -> DispatchResult { @@ -560,7 +538,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_rho(netuid, rho); - log::debug!("RhoSet( netuid: {:?} rho: {:?} ) ", netuid, rho); + log::debug!("RhoSet( netuid: {netuid:?} rho: {rho:?} ) "); Ok(()) } @@ -568,7 +546,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the activity cutoff. #[pallet::call_index(18)] - #[pallet::weight(Weight::from_parts(22_600_000, 0) + #[pallet::weight(Weight::from_parts(14_160_000, 0) .saturating_add(::DbWeight::get().reads(2_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_activity_cutoff( @@ -590,9 +568,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_activity_cutoff(netuid, activity_cutoff); log::debug!( - "ActivityCutoffSet( netuid: {:?} activity_cutoff: {:?} ) ", - netuid, - activity_cutoff + "ActivityCutoffSet( netuid: {netuid:?} activity_cutoff: {activity_cutoff:?} ) " ); Ok(()) } @@ -602,7 +578,7 @@ pub mod pallet { /// The extrinsic will call the Subtensor pallet to set the network registration allowed. #[pallet::call_index(19)] #[pallet::weight(( - Weight::from_parts(8_696_000, 0) + Weight::from_parts(4_600_000, 0) .saturating_add(::DbWeight::get().reads(0)) .saturating_add(::DbWeight::get().writes(1)), DispatchClass::Operational, @@ -619,8 +595,7 @@ pub mod pallet { registration_allowed, ); log::debug!( - "NetworkRegistrationAllowed( registration_allowed: {:?} ) ", - registration_allowed + "NetworkRegistrationAllowed( registration_allowed: {registration_allowed:?} ) " ); Ok(()) } @@ -647,8 +622,7 @@ pub mod pallet { registration_allowed, ); log::debug!( - "NetworkPowRegistrationAllowed( registration_allowed: {:?} ) ", - registration_allowed + "NetworkPowRegistrationAllowed( registration_allowed: {registration_allowed:?} ) " ); Ok(()) } @@ -657,7 +631,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the target registrations per interval. #[pallet::call_index(21)] - #[pallet::weight(Weight::from_parts(16260000, 0) + #[pallet::weight(Weight::from_parts(12_400_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_target_registrations_per_interval( @@ -676,9 +650,7 @@ pub mod pallet { target_registrations_per_interval, ); log::debug!( - "RegistrationPerIntervalSet( netuid: {:?} target_registrations_per_interval: {:?} ) ", - netuid, - target_registrations_per_interval + "RegistrationPerIntervalSet( netuid: {netuid:?} target_registrations_per_interval: {target_registrations_per_interval:?} ) " ); Ok(()) } @@ -687,13 +659,13 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the minimum burn. #[pallet::call_index(22)] - #[pallet::weight(Weight::from_parts(19_840_000, 0) + #[pallet::weight(Weight::from_parts(12_590_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_min_burn( origin: OriginFor, netuid: NetUid, - min_burn: u64, + min_burn: TaoCurrency, ) -> DispatchResult { ensure_root(origin)?; @@ -702,11 +674,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_min_burn(netuid, min_burn); - log::debug!( - "MinBurnSet( netuid: {:?} min_burn: {:?} ) ", - netuid, - min_burn - ); + log::debug!("MinBurnSet( netuid: {netuid:?} min_burn: {min_burn:?} ) "); Ok(()) } @@ -714,13 +682,13 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the maximum burn. #[pallet::call_index(23)] - #[pallet::weight(Weight::from_parts(16250000, 0) + #[pallet::weight(Weight::from_parts(12_420_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_burn( origin: OriginFor, netuid: NetUid, - max_burn: u64, + max_burn: TaoCurrency, ) -> DispatchResult { ensure_root(origin)?; @@ -729,11 +697,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_max_burn(netuid, max_burn); - log::debug!( - "MaxBurnSet( netuid: {:?} max_burn: {:?} ) ", - netuid, - max_burn - ); + log::debug!("MaxBurnSet( netuid: {netuid:?} max_burn: {max_burn:?} ) "); Ok(()) } @@ -741,7 +705,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the difficulty. #[pallet::call_index(24)] - #[pallet::weight(Weight::from_parts(17_040_000, 0) + #[pallet::weight(Weight::from_parts(10_520_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_difficulty( @@ -755,11 +719,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_difficulty(netuid, difficulty); - log::debug!( - "DifficultySet( netuid: {:?} difficulty: {:?} ) ", - netuid, - difficulty - ); + log::debug!("DifficultySet( netuid: {netuid:?} difficulty: {difficulty:?} ) "); Ok(()) } @@ -767,7 +727,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the maximum allowed validators. #[pallet::call_index(25)] - #[pallet::weight(Weight::from_parts(25_210_000, 0) + #[pallet::weight(Weight::from_parts(13_860_000, 0) .saturating_add(::DbWeight::get().reads(2_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_allowed_validators( @@ -791,9 +751,7 @@ pub mod pallet { max_allowed_validators, ); log::debug!( - "MaxAllowedValidatorsSet( netuid: {:?} max_allowed_validators: {:?} ) ", - netuid, - max_allowed_validators + "MaxAllowedValidatorsSet( netuid: {netuid:?} max_allowed_validators: {max_allowed_validators:?} ) " ); Ok(()) } @@ -802,7 +760,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the bonds moving average. #[pallet::call_index(26)] - #[pallet::weight(Weight::from_parts(16880000, 0) + #[pallet::weight(Weight::from_parts(12_450_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_bonds_moving_average( @@ -825,9 +783,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_bonds_moving_average(netuid, bonds_moving_average); log::debug!( - "BondsMovingAverageSet( netuid: {:?} bonds_moving_average: {:?} ) ", - netuid, - bonds_moving_average + "BondsMovingAverageSet( netuid: {netuid:?} bonds_moving_average: {bonds_moving_average:?} ) " ); Ok(()) } @@ -836,7 +792,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the bonds penalty. #[pallet::call_index(60)] - #[pallet::weight(Weight::from_parts(20_030_000, 0) + #[pallet::weight(Weight::from_parts(12_940_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_bonds_penalty( @@ -851,11 +807,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_bonds_penalty(netuid, bonds_penalty); - log::debug!( - "BondsPenalty( netuid: {:?} bonds_penalty: {:?} ) ", - netuid, - bonds_penalty - ); + log::debug!("BondsPenalty( netuid: {netuid:?} bonds_penalty: {bonds_penalty:?} ) "); Ok(()) } @@ -863,7 +815,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the maximum registrations per block. #[pallet::call_index(27)] - #[pallet::weight(Weight::from_parts(19_680_000, 0) + #[pallet::weight(Weight::from_parts(12_180_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_max_registrations_per_block( @@ -882,9 +834,7 @@ pub mod pallet { max_registrations_per_block, ); log::debug!( - "MaxRegistrationsPerBlock( netuid: {:?} max_registrations_per_block: {:?} ) ", - netuid, - max_registrations_per_block + "MaxRegistrationsPerBlock( netuid: {netuid:?} max_registrations_per_block: {max_registrations_per_block:?} ) " ); Ok(()) } @@ -905,10 +855,7 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_subnet_owner_cut(subnet_owner_cut); - log::debug!( - "SubnetOwnerCut( subnet_owner_cut: {:?} ) ", - subnet_owner_cut - ); + log::debug!("SubnetOwnerCut( subnet_owner_cut: {subnet_owner_cut:?} ) "); Ok(()) } @@ -928,7 +875,7 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_network_rate_limit(rate_limit); - log::debug!("NetworkRateLimit( rate_limit: {:?} ) ", rate_limit); + log::debug!("NetworkRateLimit( rate_limit: {rate_limit:?} ) "); Ok(()) } @@ -936,7 +883,7 @@ pub mod pallet { /// It is only callable by the root account. /// The extrinsic will call the Subtensor pallet to set the tempo. #[pallet::call_index(30)] - #[pallet::weight(Weight::from_parts(16690000, 0) + #[pallet::weight(Weight::from_parts(12_310_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_tempo(origin: OriginFor, netuid: NetUid, tempo: u16) -> DispatchResult { @@ -946,7 +893,7 @@ pub mod pallet { Error::::SubnetDoesNotExist ); pallet_subtensor::Pallet::::set_tempo(netuid, tempo); - log::debug!("TempoSet( netuid: {:?} tempo: {:?} ) ", netuid, tempo); + log::debug!("TempoSet( netuid: {netuid:?} tempo: {tempo:?} ) "); Ok(()) } @@ -957,7 +904,7 @@ pub mod pallet { #[pallet::weight((0, DispatchClass::Operational, Pays::No))] pub fn sudo_set_total_issuance( origin: OriginFor, - total_issuance: u64, + total_issuance: TaoCurrency, ) -> DispatchResult { ensure_root(origin)?; @@ -984,7 +931,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_network_immunity_period(immunity_period); - log::debug!("NetworkImmunityPeriod( period: {:?} ) ", immunity_period); + log::debug!("NetworkImmunityPeriod( period: {immunity_period:?} ) "); Ok(()) } @@ -1001,13 +948,13 @@ pub mod pallet { ))] pub fn sudo_set_network_min_lock_cost( origin: OriginFor, - lock_cost: u64, + lock_cost: TaoCurrency, ) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_network_min_lock(lock_cost); - log::debug!("NetworkMinLockCost( lock_cost: {:?} ) ", lock_cost); + log::debug!("NetworkMinLockCost( lock_cost: {lock_cost:?} ) "); Ok(()) } @@ -1045,7 +992,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_lock_reduction_interval(interval); - log::debug!("NetworkLockReductionInterval( interval: {:?} ) ", interval); + log::debug!("NetworkLockReductionInterval( interval: {interval:?} ) "); Ok(()) } @@ -1058,7 +1005,7 @@ pub mod pallet { pub fn sudo_set_rao_recycled( origin: OriginFor, netuid: NetUid, - rao_recycled: u64, + rao_recycled: TaoCurrency, ) -> DispatchResult { ensure_root(origin)?; ensure!( @@ -1092,7 +1039,7 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; let prev_min_stake = pallet_subtensor::Pallet::::get_nominator_min_required_stake(); - log::trace!("Setting minimum stake to: {}", min_stake); + log::trace!("Setting minimum stake to: {min_stake}"); pallet_subtensor::Pallet::::set_nominator_min_required_stake(min_stake); if min_stake > prev_min_stake { log::trace!("Clearing small nominations if possible"); @@ -1114,8 +1061,7 @@ pub mod pallet { ensure_root(origin)?; pallet_subtensor::Pallet::::set_tx_delegate_take_rate_limit(tx_rate_limit); log::debug!( - "TxRateLimitDelegateTakeSet( tx_delegate_take_rate_limit: {:?} ) ", - tx_rate_limit + "TxRateLimitDelegateTakeSet( tx_delegate_take_rate_limit: {tx_rate_limit:?} ) " ); Ok(()) } @@ -1128,7 +1074,7 @@ pub mod pallet { pub fn sudo_set_min_delegate_take(origin: OriginFor, take: u16) -> DispatchResult { ensure_root(origin)?; pallet_subtensor::Pallet::::set_min_delegate_take(take); - log::debug!("TxMinDelegateTakeSet( tx_min_delegate_take: {:?} ) ", take); + log::debug!("TxMinDelegateTakeSet( tx_min_delegate_take: {take:?} ) "); Ok(()) } @@ -1156,7 +1102,7 @@ pub mod pallet { /// It is only callable by the root account or subnet owner. /// The extrinsic will call the Subtensor pallet to set the value. #[pallet::call_index(49)] - #[pallet::weight(Weight::from_parts(19_480_000, 0) + #[pallet::weight(Weight::from_parts(12_180_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_commit_reveal_weights_enabled( @@ -1172,7 +1118,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_commit_reveal_weights_enabled(netuid, enabled); - log::debug!("ToggleSetWeightsCommitReveal( netuid: {:?} ) ", netuid); + log::debug!("ToggleSetWeightsCommitReveal( netuid: {netuid:?} ) "); Ok(()) } @@ -1194,11 +1140,7 @@ pub mod pallet { ) -> DispatchResult { pallet_subtensor::Pallet::::ensure_subnet_owner_or_root(origin, netuid)?; pallet_subtensor::Pallet::::set_liquid_alpha_enabled(netuid, enabled); - log::debug!( - "LiquidAlphaEnableToggled( netuid: {:?}, Enabled: {:?} ) ", - netuid, - enabled - ); + log::debug!("LiquidAlphaEnableToggled( netuid: {netuid:?}, Enabled: {enabled:?} ) "); Ok(()) } @@ -1300,7 +1242,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_coldkey_swap_schedule_duration(duration); // Log the change - log::trace!("ColdkeySwapScheduleDurationSet( duration: {:?} )", duration); + log::trace!("ColdkeySwapScheduleDurationSet( duration: {duration:?} )"); Ok(()) } @@ -1332,10 +1274,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_dissolve_network_schedule_duration(duration); // Log the change - log::trace!( - "DissolveNetworkScheduleDurationSet( duration: {:?} )", - duration - ); + log::trace!("DissolveNetworkScheduleDurationSet( duration: {duration:?} )"); Ok(()) } @@ -1357,7 +1296,7 @@ pub mod pallet { /// # Weight /// Weight is handled by the `#[pallet::weight]` attribute. #[pallet::call_index(57)] - #[pallet::weight(Weight::from_parts(17160000, 0) + #[pallet::weight(Weight::from_parts(12_360_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn sudo_set_commit_reveal_weights_interval( @@ -1379,11 +1318,7 @@ pub mod pallet { ); pallet_subtensor::Pallet::::set_reveal_period(netuid, interval); - log::debug!( - "SetWeightCommitInterval( netuid: {:?}, interval: {:?} ) ", - netuid, - interval - ); + log::debug!("SetWeightCommitInterval( netuid: {netuid:?}, interval: {interval:?} ) "); Ok(()) } @@ -1426,7 +1361,7 @@ pub mod pallet { /// No change should be signaled while any change is pending. Returns an error if a change /// is already pending. #[pallet::call_index(59)] - #[pallet::weight(Weight::from_parts(9_060_000, 0) + #[pallet::weight(Weight::from_parts(6_228_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] pub fn schedule_grandpa_change( @@ -1507,7 +1442,7 @@ pub mod pallet { ensure_root(origin)?; pallet_subtensor::SubnetMovingAlpha::::set(alpha); - log::debug!("SubnetMovingAlphaSet( alpha: {:?} )", alpha); + log::debug!("SubnetMovingAlphaSet( alpha: {alpha:?} )"); Ok(()) } @@ -1533,11 +1468,7 @@ pub mod pallet { pallet_subtensor::Pallet::::ensure_subnet_owner(origin.clone(), netuid)?; pallet_subtensor::Pallet::::set_subnet_owner_hotkey(netuid, &hotkey); - log::debug!( - "SubnetOwnerHotkeySet( netuid: {:?}, hotkey: {:?} )", - netuid, - hotkey - ); + log::debug!("SubnetOwnerHotkeySet( netuid: {netuid:?}, hotkey: {hotkey:?} )"); Ok(()) } @@ -1563,9 +1494,7 @@ pub mod pallet { pallet_subtensor::EMAPriceHalvingBlocks::::set(netuid, ema_halving); log::debug!( - "EMAPriceHalvingBlocks( netuid: {:?}, ema_halving: {:?} )", - netuid, - ema_halving + "EMAPriceHalvingBlocks( netuid: {netuid:?}, ema_halving: {ema_halving:?} )" ); Ok(()) } @@ -1607,11 +1536,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_alpha_sigmoid_steepness(netuid, steepness); - log::debug!( - "AlphaSigmoidSteepnessSet( netuid: {:?}, steepness: {:?} )", - netuid, - steepness - ); + log::debug!("AlphaSigmoidSteepnessSet( netuid: {netuid:?}, steepness: {steepness:?} )"); Ok(()) } @@ -1635,11 +1560,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_yuma3_enabled(netuid, enabled); Self::deposit_event(Event::Yuma3EnableToggled { netuid, enabled }); - log::debug!( - "Yuma3EnableToggled( netuid: {:?}, Enabled: {:?} ) ", - netuid, - enabled - ); + log::debug!("Yuma3EnableToggled( netuid: {netuid:?}, Enabled: {enabled:?} ) "); Ok(()) } @@ -1663,11 +1584,7 @@ pub mod pallet { pallet_subtensor::Pallet::::set_bonds_reset(netuid, enabled); Self::deposit_event(Event::BondsResetToggled { netuid, enabled }); - log::debug!( - "BondsResetToggled( netuid: {:?} bonds_reset: {:?} ) ", - netuid, - enabled - ); + log::debug!("BondsResetToggled( netuid: {netuid:?} bonds_reset: {enabled:?} ) "); Ok(()) } @@ -1734,12 +1651,28 @@ pub mod pallet { pallet_subtensor::SubtokenEnabled::::set(netuid, subtoken_enabled); log::debug!( - "SubtokenEnabled( netuid: {:?}, subtoken_enabled: {:?} )", - netuid, - subtoken_enabled + "SubtokenEnabled( netuid: {netuid:?}, subtoken_enabled: {subtoken_enabled:?} )" ); Ok(()) } + + /// Sets the commit-reveal weights version for all subnets + #[pallet::call_index(71)] + #[pallet::weight(( + Weight::from_parts(3_940_000, 0) + .saturating_add(::DbWeight::get().writes(1)) + .saturating_add(::DbWeight::get().reads(0_u64)), + DispatchClass::Operational, + Pays::No + ))] + pub fn sudo_set_commit_reveal_version( + origin: OriginFor, + version: u16, + ) -> DispatchResult { + ensure_root(origin)?; + pallet_subtensor::Pallet::::set_commit_reveal_weights_version(version); + Ok(()) + } } } diff --git a/pallets/admin-utils/src/tests/mock.rs b/pallets/admin-utils/src/tests/mock.rs index 8ab39e50cf..35934bc846 100644 --- a/pallets/admin-utils/src/tests/mock.rs +++ b/pallets/admin-utils/src/tests/mock.rs @@ -387,6 +387,7 @@ impl pallet_scheduler::Config for Test { type WeightInfo = pallet_scheduler::weights::SubstrateWeight; type OriginPrivilegeCmp = OriginPrivilegeCmp; type Preimages = (); + type BlockNumberProvider = System; } impl pallet_evm_chain_id::Config for Test {} @@ -516,10 +517,7 @@ pub fn register_ok_neuron( ); assert_ok!(result); log::info!( - "Register ok neuron: netuid: {:?}, coldkey: {:?}, hotkey: {:?}", - netuid, - hotkey_account_id, - coldkey_account_id + "Register ok neuron: netuid: {netuid:?}, coldkey: {hotkey_account_id:?}, hotkey: {coldkey_account_id:?}" ); } diff --git a/pallets/admin-utils/src/tests/mod.rs b/pallets/admin-utils/src/tests/mod.rs index 51f2f7364c..754befc805 100644 --- a/pallets/admin-utils/src/tests/mod.rs +++ b/pallets/admin-utils/src/tests/mod.rs @@ -11,7 +11,7 @@ use pallet_subtensor::Event; use sp_consensus_grandpa::AuthorityId as GrandpaId; use sp_core::{Get, Pair, U256, ed25519}; use substrate_fixed::types::I96F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Currency, NetUid, TaoCurrency}; use crate::Error; use crate::pallet::PrecompileEnable; @@ -426,7 +426,7 @@ fn test_sudo_set_max_weight_limit() { #[test] fn test_sudo_set_issuance() { new_test_ext().execute_with(|| { - let to_be_set: u64 = 10; + let to_be_set = TaoCurrency::from(10); assert_eq!( AdminUtils::sudo_set_total_issuance( <::RuntimeOrigin>::signed(U256::from(0)), @@ -894,9 +894,9 @@ fn test_sudo_set_bonds_penalty() { fn test_sudo_set_rao_recycled() { new_test_ext().execute_with(|| { let netuid = NetUid::from(1); - let to_be_set: u64 = 10; + let to_be_set = TaoCurrency::from(10); add_network(netuid, 10); - let init_value: u64 = SubtensorModule::get_rao_recycled(netuid); + let init_value = SubtensorModule::get_rao_recycled(netuid); // Need to run from genesis block run_to_block(1); @@ -1035,7 +1035,7 @@ mod sudo_set_nominator_min_required_stake { let default_min_stake = pallet_subtensor::DefaultMinStake::::get(); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - 10 * default_min_stake / 1_000_000 + 10 * default_min_stake.to_u64() / 1_000_000 ); assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( @@ -1044,7 +1044,7 @@ mod sudo_set_nominator_min_required_stake { )); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - 5 * default_min_stake / 1_000_000 + 5 * default_min_stake.to_u64() / 1_000_000 ); }); } @@ -1060,7 +1060,7 @@ mod sudo_set_nominator_min_required_stake { )); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - to_be_set * default_min_stake / 1_000_000 + to_be_set * default_min_stake.to_u64() / 1_000_000 ); }); } @@ -1268,11 +1268,7 @@ fn test_sudo_get_set_alpha() { let (grabbed_alpha_low, grabbed_alpha_high): (u16, u16) = SubtensorModule::get_alpha_values(netuid); - log::info!( - "alpha_low: {:?} alpha_high: {:?}", - grabbed_alpha_low, - grabbed_alpha_high - ); + log::info!("alpha_low: {grabbed_alpha_low:?} alpha_high: {grabbed_alpha_high:?}"); assert_eq!(grabbed_alpha_low, alpha_low); assert_eq!(grabbed_alpha_high, alpha_high); @@ -1656,7 +1652,7 @@ fn test_sets_a_lower_value_clears_small_nominations() { )); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - initial_nominator_min_required_stake * default_min_stake / 1_000_000_u64 + initial_nominator_min_required_stake * default_min_stake.to_u64() / 1_000_000 ); // Stake to the hotkey as staker_coldkey @@ -1674,7 +1670,7 @@ fn test_sets_a_lower_value_clears_small_nominations() { )); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - nominator_min_required_stake_0 * default_min_stake / 1_000_000_u64 + nominator_min_required_stake_0 * default_min_stake.to_u64() / 1_000_000 ); // Check this nomination is not cleared @@ -1692,7 +1688,7 @@ fn test_sets_a_lower_value_clears_small_nominations() { )); assert_eq!( SubtensorModule::get_nominator_min_required_stake(), - nominator_min_required_stake_1 * default_min_stake / 1_000_000_u64 + nominator_min_required_stake_1 * default_min_stake.to_u64() / 1_000_000 ); // Check this nomination is cleared @@ -1934,3 +1930,24 @@ fn test_sudo_set_yuma3_enabled() { assert_eq!(SubtensorModule::get_yuma3_enabled(netuid), !to_be_set); }); } + +#[test] +fn test_sudo_set_commit_reveal_version() { + new_test_ext().execute_with(|| { + add_network(NetUid::from(1), 10); + + let to_be_set: u16 = 5; + let init_value: u16 = SubtensorModule::get_commit_reveal_weights_version(); + + assert_ok!(AdminUtils::sudo_set_commit_reveal_version( + <::RuntimeOrigin>::root(), + to_be_set + )); + + assert!(init_value != to_be_set); + assert_eq!( + SubtensorModule::get_commit_reveal_weights_version(), + to_be_set + ); + }); +} diff --git a/pallets/collective/Cargo.toml b/pallets/collective/Cargo.toml index 11ab2a9cb3..015d6ab709 100644 --- a/pallets/collective/Cargo.toml +++ b/pallets/collective/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-collective" version = "4.0.0-dev" authors = ["Parity Technologies , Opentensor Technologies"] -edition = "2024" +edition.workspace = true license = "Apache-2.0" homepage = "https://bittensor.com" repository = "https://github.com/opentensor/subtensor" @@ -17,18 +17,16 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] subtensor-macros.workspace = true -codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = [ - "derive", -] } -log = { workspace = true } +codec = { workspace = true, features = ["derive"] } +log.workspace = true scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-core = { workspace = true } -sp-io = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true [features] default = ["std"] @@ -53,5 +51,5 @@ runtime-benchmarks = [ try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", - "sp-runtime/try-runtime" + "sp-runtime/try-runtime", ] diff --git a/pallets/collective/src/lib.rs b/pallets/collective/src/lib.rs index baea090307..4a3aea5a30 100644 --- a/pallets/collective/src/lib.rs +++ b/pallets/collective/src/lib.rs @@ -126,7 +126,17 @@ impl DefaultVote for MoreThanMajorityThenPrimeDefaultVote { } /// Origin for the collective module. -#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[derive( + PartialEq, + Eq, + Clone, + RuntimeDebug, + Encode, + Decode, + DecodeWithMemTracking, + TypeInfo, + MaxEncodedLen, +)] #[scale_info(skip_type_params(I))] #[codec(mel_bound(AccountId: MaxEncodedLen))] pub enum RawOrigin { diff --git a/pallets/commitments/Cargo.toml b/pallets/commitments/Cargo.toml index efc1a216db..bedc0d945c 100644 --- a/pallets/commitments/Cargo.toml +++ b/pallets/commitments/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "Add the ability to commit generic hashed data for network participants." authors = ["Bittensor Nucleus Team"] homepage = "https://bittensor.com" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" @@ -17,35 +17,32 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] subtensor-macros.workspace = true -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ - "derive", - "max-encoded-len", -] } +codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -enumflags2 = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true +enumflags2.workspace = true -pallet-drand = { path = "../drand", default-features = false } -tle = { workspace = true, default-features = false } -ark-serialize = { workspace = true, default-features = false } -w3f-bls = { workspace = true, default-features = false } -rand_chacha = { workspace = true } -hex = { workspace = true } -sha2 = { workspace = true } +pallet-drand.workspace = true +tle.workspace = true +ark-serialize = { workspace = true, features = ["derive"] } +w3f-bls.workspace = true +rand_chacha.workspace = true +hex.workspace = true +sha2.workspace = true -log = { workspace = true } +log.workspace = true -pallet-subtensor = { path = "../subtensor", default-features = false } -subtensor-runtime-common = { workspace = true } +pallet-subtensor.workspace = true +subtensor-runtime-common.workspace = true [dev-dependencies] -sp-core = { workspace = true } -sp-io = { workspace = true } -pallet-balances = { workspace = true } +sp-core.workspace = true +sp-io.workspace = true +pallet-balances.workspace = true [features] default = ["std"] @@ -79,7 +76,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-drand/runtime-benchmarks", - "pallet-subtensor/runtime-benchmarks" + "pallet-subtensor/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", @@ -87,5 +84,5 @@ try-runtime = [ "pallet-balances/try-runtime", "sp-runtime/try-runtime", "pallet-drand/try-runtime", - "pallet-subtensor/try-runtime" + "pallet-subtensor/try-runtime", ] diff --git a/pallets/commitments/src/lib.rs b/pallets/commitments/src/lib.rs index c42d7a3413..12356da08d 100644 --- a/pallets/commitments/src/lib.rs +++ b/pallets/commitments/src/lib.rs @@ -205,7 +205,7 @@ pub mod pallet { /// Set the commitment for a given netuid #[pallet::call_index(0)] #[pallet::weight(( - Weight::from_parts(34_140_000, 0) + Weight::from_parts(25_070_000, 0) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)), DispatchClass::Operational, @@ -343,7 +343,7 @@ pub mod pallet { /// Sudo-set MaxSpace #[pallet::call_index(2)] #[pallet::weight(( - Weight::from_parts(2_965_000, 0) + Weight::from_parts(1_660_000, 0) .saturating_add(T::DbWeight::get().reads(0_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)), DispatchClass::Operational, @@ -360,11 +360,7 @@ pub mod pallet { impl Hooks> for Pallet { fn on_initialize(n: BlockNumberFor) -> Weight { if let Err(e) = Self::reveal_timelocked_commitments() { - log::debug!( - "Failed to unveil matured commitments on block {:?}: {:?}", - n, - e - ); + log::debug!("Failed to unveil matured commitments on block {n:?}: {e:?}"); } Weight::from_parts(0, 0) } @@ -445,9 +441,7 @@ impl Pallet { ) .map_err(|e| { log::warn!( - "Failed to deserialize drand signature for {:?}: {:?}", - who, - e + "Failed to deserialize drand signature for {who:?}: {e:?}" ) }) .ok(); @@ -460,11 +454,7 @@ impl Pallet { let reader = &mut &encrypted[..]; let commit = TLECiphertext::::deserialize_compressed(reader) .map_err(|e| { - log::warn!( - "Failed to deserialize TLECiphertext for {:?}: {:?}", - who, - e - ) + log::warn!("Failed to deserialize TLECiphertext for {who:?}: {e:?}") }) .ok(); @@ -476,13 +466,13 @@ impl Pallet { let decrypted_bytes: Vec = tld::(commit, sig) .map_err(|e| { - log::warn!("Failed to decrypt timelock for {:?}: {:?}", who, e) + log::warn!("Failed to decrypt timelock for {who:?}: {e:?}") }) .ok() .unwrap_or_default(); if decrypted_bytes.is_empty() { - log::warn!("Bytes were decrypted for {:?} but they are empty", who); + log::warn!("Bytes were decrypted for {who:?} but they are empty"); continue; } diff --git a/pallets/commitments/src/tests.rs b/pallets/commitments/src/tests.rs index 431d5e521b..6866ebdeec 100644 --- a/pallets/commitments/src/tests.rs +++ b/pallets/commitments/src/tests.rs @@ -43,7 +43,7 @@ fn manual_data_type_info() { .variants .iter() .find(|v| v.name == variant_name) - .unwrap_or_else(|| panic!("Expected to find variant {}", variant_name)); + .unwrap_or_else(|| panic!("Expected to find variant {variant_name}")); let encoded = data.encode(); assert_eq!(encoded[0], variant.index); @@ -72,15 +72,13 @@ fn manual_data_type_info() { assert_eq!( encoded.len() as u32 - 1, // Subtract variant byte expected_len, - "Encoded length mismatch for variant {}", - variant_name + "Encoded length mismatch for variant {variant_name}" ); } else { assert_eq!( encoded.len() as u32 - 1, 0, - "Expected no fields for {}", - variant_name + "Expected no fields for {variant_name}" ); } } else { @@ -1551,7 +1549,7 @@ fn revealed_commitments_keeps_only_10_items() { let mut fields = Vec::with_capacity(TOTAL_TLES); for i in 0..TOTAL_TLES { - let plaintext = format!("TLE #{}", i).into_bytes(); + let plaintext = format!("TLE #{i}").into_bytes(); let ciphertext = produce_ciphertext(&plaintext, reveal_round); let timelock = Data::TimelockEncrypted { encrypted: ciphertext, @@ -1594,7 +1592,7 @@ fn revealed_commitments_keeps_only_10_items() { // We expect them to be TLE #2..TLE #11 let expected_index = idx + 2; // since we dropped #0 and #1 - let expected_str = format!("TLE #{}", expected_index); + let expected_str = format!("TLE #{expected_index}"); assert_eq!(revealed_str, expected_str, "Check which TLE is kept"); // Also check it was revealed at block 2 @@ -1619,7 +1617,7 @@ fn revealed_commitments_keeps_only_10_newest_with_individual_single_field_commit for i in 0..12 { System::::set_block_number(i as u64 + 1); - let plaintext = format!("TLE #{}", i).into_bytes(); + let plaintext = format!("TLE #{i}").into_bytes(); let ciphertext = produce_ciphertext(&plaintext, reveal_round); let new_timelock = Data::TimelockEncrypted { @@ -1644,8 +1642,7 @@ fn revealed_commitments_keeps_only_10_newest_with_individual_single_field_commit assert_eq!( revealed.len(), expected_count, - "At iteration {}, we keep at most 10 reveals", - i + "At iteration {i}, we keep at most 10 reveals" ); } @@ -1662,19 +1659,17 @@ fn revealed_commitments_keeps_only_10_newest_with_individual_single_field_commit let revealed_str = sp_std::str::from_utf8(revealed_bytes).expect("Should be valid UTF-8"); let expected_i = idx + 2; // i=0 => "TLE #2", i=1 => "TLE #3", etc. - let expected_str = format!("TLE #{}", expected_i); + let expected_str = format!("TLE #{expected_i}"); assert_eq!( revealed_str, expected_str, - "Revealed data #{} should match the truncated TLE #{}", - idx, expected_i + "Revealed data #{idx} should match the truncated TLE #{expected_i}" ); let expected_reveal_block = expected_i as u64 + 1; assert_eq!( *reveal_block, expected_reveal_block, - "Check which block TLE #{} was revealed in", - expected_i + "Check which block TLE #{expected_i} was revealed in" ); } }); diff --git a/pallets/commitments/src/types.rs b/pallets/commitments/src/types.rs index 543eb08cd1..0467fee8f3 100644 --- a/pallets/commitments/src/types.rs +++ b/pallets/commitments/src/types.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Codec, Decode, Encode, MaxEncodedLen}; +use codec::{Codec, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use frame_support::{ BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound, traits::{ConstU32, Get}, @@ -38,7 +38,7 @@ use subtensor_macros::freeze_struct; /// - A timelock-encrypted blob with a reveal round /// - A reset flag (`ResetBondsFlag`) /// Can also be `None`. -#[derive(Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)] +#[derive(Clone, Eq, PartialEq, RuntimeDebug, DecodeWithMemTracking, MaxEncodedLen)] pub enum Data { /// No data here. None, @@ -362,9 +362,17 @@ impl Default for Data { } } -#[freeze_struct("25c84048dcc90813")] +#[freeze_struct("5ca4adbb4d2a2b20")] #[derive( - CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo, + CloneNoBound, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + MaxEncodedLen, + PartialEqNoBound, + RuntimeDebugNoBound, + TypeInfo, )] #[codec(mel_bound())] #[derive(frame_support::DefaultNoBound)] diff --git a/pallets/crowdloan/Cargo.toml b/pallets/crowdloan/Cargo.toml index e8d582fa44..dcde4504f4 100644 --- a/pallets/crowdloan/Cargo.toml +++ b/pallets/crowdloan/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "pallet-crowdloan" version = "0.1.0" -edition = "2024" +edition.workspace = true authors = ["Bittensor Nucleus Team"] license = "Apache-2.0" homepage = "https://bittensor.com" @@ -21,13 +21,13 @@ frame-support.workspace = true frame-system.workspace = true sp-runtime.workspace = true sp-std.workspace = true -log = { workspace = true } +log.workspace = true [dev-dependencies] -pallet-balances = { default-features = true, workspace = true } -pallet-preimage = { default-features = true, workspace = true } -sp-core = { default-features = true, workspace = true } -sp-io = { default-features = true, workspace = true } +pallet-balances = { workspace = true, default-features = true } +pallet-preimage = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/pallets/crowdloan/README.md b/pallets/crowdloan/README.md index 3d67fee33a..9977c782c3 100644 --- a/pallets/crowdloan/README.md +++ b/pallets/crowdloan/README.md @@ -1,5 +1,7 @@ # Crowdloan Pallet +## Overview + A pallet that enables the creation and management of generic crowdloans for transferring funds and executing an arbitrary call. Users of this pallet can create a crowdloan by providing a deposit, a cap, an end block, an optional target address and an optional call. @@ -10,10 +12,38 @@ Once the crowdloan is finalized, the funds will be transferred to the target add If the crowdloan fails to reach the cap, the creator can decide to refund all contributors and dissolve the crowdloan. The initial deposit will be refunded. -## Overview +*The call or target address provided when creating the crowdloan is guaranteed to never change. Only the minimum contribution, end block and cap can be updated from the crowdloan creator.* ## Interface -## Dispatchable Functions +- `create`: Create a crowdloan that will raise funds up to a maximum cap and if successful, will transfer funds to the target address if provided and/or dispatch the call (using creator origin). The initial deposit will be transfered to the crowdloan account and will be refunded in case the crowdloan fails to raise the cap. Additionally, the creator will pay for the execution of the call. + +- `contribute`: Contribute to an active crowdloan. The contribution will be transfered to the crowdloan account and will be refunded if the crowdloan fails to raise the cap. If the contribution would raise the amount above the cap, the contribution will be set to the amount that is left to be raised. + +- `withdraw`: Withdraw a contribution from an active (not yet finalized or dissolved) crowdloan. Only contributions over the deposit can be withdrawn by the creator. + +- `refund`: Try to refund all contributors (excluding the creator) up to the limit defined by a runtime parameter *RefundContributorsLimit* (currently set to 5). If the limit is reached, the call will stop and the crowdloan will be marked as partially refunded. It may be needed to dispatch this call multiple times to refund all contributors. + +The following functions are only callable by the creator of the crowdloan: + +- `finalize`: Finalize a successful crowdloan. The call will transfer the raised amount to the target address if it was provided when the crowdloan was created and dispatch the call that was provided using the creator origin. + +- `dissolve`: Dissolve a crowdloan. The crowdloan will be removed from the storage. All contributions must have been refunded before the crowdloan can be dissolved (except the creator's one). + +- `update_min_contribution`: Update the minimum contribution of a non-finalized crowdloan. + +- `update_end`: Update the end block of a non-finalized crowdloan. + +- `update_cap`: Update the cap of a non-finalized crowdloan. + +## Integration with subnet leasing (from the subtensor pallet) + +The `crowdloan` pallet can be used to create a crowdloan that will be used to register a new leased network through a crowdloan using the `register_leased_network` extrinsic from the `subtensor` pallet as a call parameter to the crowdloan pallet `create` extrinsic. A new subnet will be registered paying the lock cost using the crowdloan funds and a proxy will be created for the beneficiary to operate the subnet. + +When active, the lease will distribute dividends to the contributors according to their contribution to the crowdloan and the lease can be operated by the beneficiary using the proxy created `SubnetLeaseBeneficiary`. + +If the lease is perpetual, the lease will never be terminated and emissions will continue to be distributed to the contributors. + +If the lease has an end block, the lease can be terminated when end block has passed and the subnet ownership will be transferred to the beneficiary. License: Apache-2.0 diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index 78cf15717c..7f4281b538 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -38,6 +38,7 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities { (U256::from(4), 10), (U256::from(5), 3), ], + dev_accounts: None, } .assimilate_storage(&mut t) .expect("Expected to not panic"); @@ -242,6 +243,7 @@ impl TestState { .iter() .map(|(who, balance)| (*who, *balance)) .collect::>(), + dev_accounts: None, } .assimilate_storage(&mut t) .unwrap(); diff --git a/pallets/drand/Cargo.toml b/pallets/drand/Cargo.toml index 3f4b5e4c33..c6a0705627 100644 --- a/pallets/drand/Cargo.toml +++ b/pallets/drand/Cargo.toml @@ -4,7 +4,7 @@ description = "FRAME pallet for briding to drand." authors = ["Tony Riemer "] version = "0.0.1" license = "MIT-0" -edition = "2024" +edition.workspace = true homepage = "https://www.idealabs.network" publish = false @@ -12,44 +12,40 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true, default-features = false, features = [ - "derive", -] } -scale-info = { workspace = true, default-features = false, features = [ - "derive", -] } -serde = { workspace = true, features = ["derive"], default-features = false } -serde_json = { workspace = true, default-features = false } -log = { workspace = true, default-features = false } -hex = { workspace = true, features = ["serde"], default-features = false } -sha2 = { workspace = true } -anyhow = { workspace = true } +codec = { workspace = true, features = ["derive"] } +scale-info = { workspace = true, features = ["derive"] } +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +log.workspace = true +hex = { workspace = true, features = ["serde"] } +sha2.workspace = true +anyhow.workspace = true # frame deps -frame-benchmarking = { workspace = true, default-features = false, optional = true } -frame-support = { workspace = true, default-features = false } -frame-system = { workspace = true, default-features = false } -sp-core = { workspace = true, default-features = false } -sp-io = { workspace = true, default-features = false} -sp-runtime = { workspace = true, default-features = false} +frame-benchmarking = { workspace = true, optional = true } +frame-support.workspace = true +frame-system.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true # arkworks dependencies -sp-ark-bls12-381 = { workspace = true, default-features = false } -ark-bls12-381 = { workspace = true, features = ["curve"], default-features = false } -ark-serialize = { workspace = true, features = [ "derive" ], default-features = false } -ark-ff = { workspace = true, default-features = false } -ark-ec = { workspace = true, default-features = false } -ark-std = { workspace = true, default-features = false } -ark-crypto-primitives = { workspace = true, default-features = false, features = [ "r1cs", "snark" ] } -ark-scale = { workspace = true, default-features = false, features = ["hazmat"] } -w3f-bls = { workspace = true, default-features = false } -sp-keyring = { workspace = true, default-features = false } +sp-ark-bls12-381.workspace = true +ark-bls12-381 = { workspace = true, features = ["curve"] } +ark-serialize = { workspace = true, features = ["derive"] } +ark-ff.workspace = true +ark-ec.workspace = true +ark-std.workspace = true +ark-crypto-primitives = { workspace = true, features = ["r1cs", "snark"] } +ark-scale = { workspace = true, features = ["hazmat"] } +w3f-bls.workspace = true +sp-keyring.workspace = true subtensor-macros.workspace = true -tle = { workspace = true, default-features = false } +tle.workspace = true [dev-dependencies] -sp-keystore = { workspace = true, default-features = false } +sp-keystore.workspace = true [features] -default = ["std"] +default = [] std = [ "codec/std", "log/std", @@ -76,6 +72,7 @@ std = [ "ark-scale/std", "w3f-bls/std", "tle/std", + "anyhow/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/pallets/drand/src/benchmarking.rs b/pallets/drand/src/benchmarking.rs index 0abf59a478..799b9d16b2 100644 --- a/pallets/drand/src/benchmarking.rs +++ b/pallets/drand/src/benchmarking.rs @@ -79,5 +79,15 @@ mod benchmarks { assert_eq!(Pulses::::get(p.round), Some(p)); } + #[benchmark] + fn set_oldest_stored_round() { + let oldest_stored_round: u64 = 10; + + #[extrinsic_call] + set_oldest_stored_round(RawOrigin::Root, oldest_stored_round); + + assert_eq!(OldestStoredRound::::get(), oldest_stored_round); + } + impl_benchmark_test_suite!(Drand, crate::mock::new_test_ext(), crate::mock::Test); } diff --git a/pallets/drand/src/lib.rs b/pallets/drand/src/lib.rs index d82f39581a..9a0e3c04a4 100644 --- a/pallets/drand/src/lib.rs +++ b/pallets/drand/src/lib.rs @@ -58,6 +58,7 @@ use sp_runtime::{ }; pub mod bls12_381; +pub mod migrations; pub mod types; pub mod utils; pub mod verifier; @@ -91,6 +92,8 @@ pub const QUICKNET_CHAIN_HASH: &str = const CHAIN_HASH: &str = QUICKNET_CHAIN_HASH; pub const MAX_PULSES_TO_FETCH: u64 = 50; +pub const MAX_KEPT_PULSES: u64 = 216_000; // 1 week +pub const MAX_REMOVED_PULSES: u64 = 100; /// Defines application identifier for crypto keys of this module. /// @@ -212,12 +215,24 @@ pub mod pallet { } } + /// Define a maximum length for the migration key + type MigrationKeyMaxLen = ConstU32<128>; + + /// Storage for migration run status + #[pallet::storage] + pub type HasMigrationRun = + StorageMap<_, Identity, BoundedVec, bool, ValueQuery>; + /// map round number to pulse #[pallet::storage] pub type Pulses = StorageMap<_, Blake2_128Concat, RoundNumber, Pulse, OptionQuery>; #[pallet::storage] - pub(super) type LastStoredRound = StorageValue<_, RoundNumber, ValueQuery>; + pub type LastStoredRound = StorageValue<_, RoundNumber, ValueQuery>; + + /// oldest stored round + #[pallet::storage] + pub type OldestStoredRound = StorageValue<_, RoundNumber, ValueQuery>; /// Defines the block when next unsigned transaction will be accepted. /// @@ -230,11 +245,12 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { + /// Beacon Configuration has changed. BeaconConfigChanged, /// Successfully set a new pulse(s). - NewPulse { - rounds: Vec, - }, + NewPulse { rounds: Vec }, + /// Oldest Stored Round has been set. + SetOldestStoredRound(u64), } #[pallet::error] @@ -256,11 +272,19 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn offchain_worker(block_number: BlockNumberFor) { - log::debug!("Drand OCW working on block: {:?}", block_number); + log::debug!("Drand OCW working on block: {block_number:?}"); if let Err(e) = Self::fetch_drand_pulse_and_send_unsigned(block_number) { - log::debug!("Drand: Failed to fetch pulse from drand. {:?}", e); + log::debug!("Drand: Failed to fetch pulse from drand. {e:?}"); } } + fn on_runtime_upgrade() -> frame_support::weights::Weight { + /*let weight = */ + frame_support::weights::Weight::from_parts(0, 0) /*;*/ + + //weight = weight.saturating_add(migrations::migrate_set_oldest_round::()); + + //weight + } } #[pallet::validate_unsigned] @@ -307,9 +331,9 @@ pub mod pallet { impl Pallet { /// Verify and write a pulse from the beacon into the runtime #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(5_708_000_000, 0) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)))] + #[pallet::weight(Weight::from_parts(4_294_000_000, 0) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)))] pub fn write_pulse( origin: OriginFor, pulses_payload: PulsesPayload>, @@ -321,6 +345,10 @@ pub mod pallet { let mut last_stored_round = LastStoredRound::::get(); let mut new_rounds = Vec::new(); + let oldest_stored_round = OldestStoredRound::::get(); + let is_first_storage = last_stored_round == 0 && oldest_stored_round == 0; + let mut first_new_round: Option = None; + for pulse in &pulses_payload.pulses { let is_verified = T::Verifier::verify(config.clone(), pulse.clone()) .map_err(|_| Error::::PulseVerificationError)?; @@ -339,12 +367,25 @@ pub mod pallet { // Collect the new round new_rounds.push(pulse.round); + + // Set the first new round if this is the initial storage + if is_first_storage && first_new_round.is_none() { + first_new_round = Some(pulse.round); + } } } // Update LastStoredRound storage LastStoredRound::::put(last_stored_round); + // Set OldestStoredRound if this was the first storage + if let Some(first_round) = first_new_round { + OldestStoredRound::::put(first_round); + } + + // Prune old pulses + Self::prune_old_pulses(last_stored_round); + // Update the next unsigned block number let current_block = frame_system::Pallet::::block_number(); >::put(current_block); @@ -363,7 +404,7 @@ pub mod pallet { /// * `origin`: the root user /// * `config`: the beacon configuration #[pallet::call_index(1)] - #[pallet::weight(Weight::from_parts(9_878_000, 0) + #[pallet::weight(Weight::from_parts(5_450_000, 0) .saturating_add(T::DbWeight::get().reads(0_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)))] pub fn set_beacon_config( @@ -381,6 +422,18 @@ pub mod pallet { Self::deposit_event(Event::BeaconConfigChanged {}); Ok(()) } + + /// allows the root user to set the oldest stored round + #[pallet::call_index(2)] + #[pallet::weight(Weight::from_parts(3_350_000, 0) + .saturating_add(T::DbWeight::get().reads(0_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)))] + pub fn set_oldest_stored_round(origin: OriginFor, oldest_round: u64) -> DispatchResult { + ensure_root(origin)?; + OldestStoredRound::::put(oldest_round); + Self::deposit_event(Event::SetOldestStoredRound(oldest_round)); + Ok(()) + } } } @@ -462,12 +515,12 @@ impl Pallet { } fn fetch_drand_by_round(round: RoundNumber) -> Result { - let relative_path = format!("/{}/public/{}", CHAIN_HASH, round); + let relative_path = format!("/{CHAIN_HASH}/public/{round}"); Self::fetch_and_decode_from_any_endpoint(&relative_path) } fn fetch_drand_latest() -> Result { - let relative_path = format!("/{}/public/latest", CHAIN_HASH); + let relative_path = format!("/{CHAIN_HASH}/public/latest"); Self::fetch_and_decode_from_any_endpoint(&relative_path) } @@ -477,7 +530,7 @@ impl Pallet { ) -> Result { let uris: Vec = ENDPOINTS .iter() - .map(|e| format!("{}{}", e, relative_path)) + .map(|e| format!("{e}{relative_path}")) .collect(); let deadline = sp_io::offchain::timestamp().add( sp_runtime::offchain::Duration::from_millis(T::HttpFetchTimeout::get()), @@ -494,7 +547,7 @@ impl Pallet { pending_requests.push((uri.clone(), pending_req)); } Err(_) => { - log::warn!("Drand: HTTP IO Error on endpoint {}", uri); + log::warn!("Drand: HTTP IO Error on endpoint {uri}"); } } } @@ -543,7 +596,7 @@ impl Pallet { } } Ok(Err(e)) => { - log::warn!("Drand: HTTP error from {}: {:?}", uri, e); + log::warn!("Drand: HTTP error from {uri}: {e:?}"); } Err(pending_req) => { still_pending = true; @@ -628,6 +681,24 @@ impl Pallet { .propagate(true) .build() } + + fn prune_old_pulses(last_stored_round: RoundNumber) { + let mut oldest = OldestStoredRound::::get(); + if oldest == 0 { + return; + } + + let mut removed: u64 = 0; + while last_stored_round.saturating_sub(oldest).saturating_add(1) > MAX_KEPT_PULSES + && removed < MAX_REMOVED_PULSES + { + Pulses::::remove(oldest); + oldest = oldest.saturating_add(1); + removed = removed.saturating_add(1); + } + + OldestStoredRound::::put(oldest); + } } /// construct a message (e.g. signed by drand) diff --git a/pallets/drand/src/migrations/migrate_prune_old_pulses.rs b/pallets/drand/src/migrations/migrate_prune_old_pulses.rs new file mode 100644 index 0000000000..0a6697f6fd --- /dev/null +++ b/pallets/drand/src/migrations/migrate_prune_old_pulses.rs @@ -0,0 +1,63 @@ +use crate::*; +use frame_support::{traits::Get, weights::Weight}; +use log; + +pub fn migrate_prune_old_pulses() -> Weight { + let migration_name = BoundedVec::truncate_from(b"migrate_prune_old_pulses".to_vec()); + + // Initialize the weight with one read operation. + let mut weight = T::DbWeight::get().reads(1); + + // Check if the migration has already run + if HasMigrationRun::::get(&migration_name) { + log::info!( + "Migration '{:?}' has already run. Skipping.", + String::from_utf8_lossy(&migration_name) + ); + return weight; + } + log::info!( + "Running migration '{}'", + String::from_utf8_lossy(&migration_name) + ); + + // Collect all round numbers + let mut rounds: Vec = Pulses::::iter_keys().collect(); + weight = weight.saturating_add(T::DbWeight::get().reads(rounds.len() as u64)); + + if rounds.is_empty() { + OldestStoredRound::::put(0u64); + LastStoredRound::::put(0u64); + weight = weight.saturating_add(T::DbWeight::get().writes(2)); + } else { + rounds.sort(); + let num_pulses = rounds.len() as u64; + + let mut new_oldest = rounds[0]; + if num_pulses > MAX_KEPT_PULSES { + let num_to_delete = num_pulses.saturating_sub(MAX_KEPT_PULSES); + new_oldest = rounds[num_to_delete as usize]; + + for &round in &rounds[0..num_to_delete as usize] { + Pulses::::remove(round); + weight = weight.saturating_add(T::DbWeight::get().writes(1)); + } + } + + OldestStoredRound::::put(new_oldest); + LastStoredRound::::put(*rounds.last().unwrap()); + weight = weight.saturating_add(T::DbWeight::get().writes(2)); + } + + // Mark the migration as completed + HasMigrationRun::::insert(&migration_name, true); + weight = weight.saturating_add(T::DbWeight::get().writes(1)); + + log::info!( + "Migration '{:?}' completed.", + String::from_utf8_lossy(&migration_name) + ); + + // Return the migration weight. + weight +} diff --git a/pallets/drand/src/migrations/migrate_set_oldest_round.rs b/pallets/drand/src/migrations/migrate_set_oldest_round.rs new file mode 100644 index 0000000000..c1ef6b9e04 --- /dev/null +++ b/pallets/drand/src/migrations/migrate_set_oldest_round.rs @@ -0,0 +1,57 @@ +use crate::*; +use frame_support::weights::Weight; +use log; + +/// Migration to set `OldestStoredRound` to the oldest round in storage. +pub fn migrate_set_oldest_round() -> Weight { + use frame_support::traits::Get; + + let migration_name = BoundedVec::truncate_from(b"migrate_set_oldest_round".to_vec()); + + // Start with one read for HasMigrationRun + let mut weight = T::DbWeight::get().reads(1); + + // Skip if already run. + if HasMigrationRun::::get(&migration_name) { + log::info!( + "Migration '{}' has already run. Skipping.", + String::from_utf8_lossy(&migration_name) + ); + return weight; + } + log::info!( + "Running migration '{}'", + String::from_utf8_lossy(&migration_name) + ); + + // Single-pass over keys: track min and how many keys we read. + let mut reads: u64 = 0; + let mut min_round: Option = None; + + for r in Pulses::::iter_keys() { + reads = reads.saturating_add(1); + if min_round.is_none_or(|m| r < m) { + min_round = Some(r); + } + } + + // Account for all key reads + weight = weight.saturating_add(T::DbWeight::get().reads(reads)); + + let oldest = min_round.unwrap_or(0u64); + OldestStoredRound::::put(oldest); + weight = weight.saturating_add(T::DbWeight::get().writes(1)); + + // Mark as completed. + HasMigrationRun::::insert(&migration_name, true); + weight = weight.saturating_add(T::DbWeight::get().writes(1)); + + log::info!( + "Migration '{}' completed. OldestStoredRound set to {} (scanned {} rounds).", + String::from_utf8_lossy(&migration_name), + oldest, + reads + ); + + weight +} diff --git a/pallets/drand/src/migrations/mod.rs b/pallets/drand/src/migrations/mod.rs new file mode 100644 index 0000000000..7518996fc9 --- /dev/null +++ b/pallets/drand/src/migrations/mod.rs @@ -0,0 +1,4 @@ +pub mod migrate_prune_old_pulses; +pub use migrate_prune_old_pulses::*; +pub mod migrate_set_oldest_round; +pub use migrate_set_oldest_round::*; diff --git a/pallets/drand/src/tests.rs b/pallets/drand/src/tests.rs index 3f6470f04c..fdc450b5e2 100644 --- a/pallets/drand/src/tests.rs +++ b/pallets/drand/src/tests.rs @@ -16,14 +16,18 @@ use crate::{ BeaconConfig, BeaconConfigurationPayload, BeaconInfoResponse, Call, DrandResponseBody, - ENDPOINTS, Error, Pulse, Pulses, PulsesPayload, QUICKNET_CHAIN_HASH, mock::*, + ENDPOINTS, Error, HasMigrationRun, LastStoredRound, MAX_KEPT_PULSES, OldestStoredRound, Pulse, + Pulses, PulsesPayload, QUICKNET_CHAIN_HASH, migrations::migrate_prune_old_pulses, + migrations::migrate_set_oldest_round, mock::*, }; use codec::Encode; use frame_support::{ - assert_noop, assert_ok, + BoundedVec, assert_noop, assert_ok, pallet_prelude::{InvalidTransaction, TransactionSource}, + weights::RuntimeDbWeight, }; use frame_system::RawOrigin; +use sp_core::Get; use sp_runtime::{ offchain::{ OffchainWorkerExt, @@ -358,7 +362,7 @@ fn can_execute_and_handle_valid_http_responses() { for endpoint in ENDPOINTS.iter() { state.expect_request(PendingRequest { method: "GET".into(), - uri: format!("{}/{}/public/1000", endpoint, QUICKNET_CHAIN_HASH), + uri: format!("{endpoint}/{QUICKNET_CHAIN_HASH}/public/1000"), response: Some(DRAND_PULSE.as_bytes().to_vec()), sent: true, ..Default::default() @@ -368,7 +372,7 @@ fn can_execute_and_handle_valid_http_responses() { for endpoint in ENDPOINTS.iter() { state.expect_request(PendingRequest { method: "GET".into(), - uri: format!("{}/{}/public/latest", endpoint, QUICKNET_CHAIN_HASH), + uri: format!("{endpoint}/{QUICKNET_CHAIN_HASH}/public/latest"), response: Some(DRAND_PULSE.as_bytes().to_vec()), sent: true, ..Default::default() @@ -424,7 +428,7 @@ fn test_all_endpoints_fail() { for endpoint in endpoints.iter() { state.expect_request(PendingRequest { method: "GET".into(), - uri: format!("{}/{}/public/1000", endpoint, QUICKNET_CHAIN_HASH), + uri: format!("{endpoint}/{QUICKNET_CHAIN_HASH}/public/1000"), response: Some(INVALID_JSON.as_bytes().to_vec()), sent: true, ..Default::default() @@ -549,3 +553,193 @@ fn test_invalid_json_then_success() { assert_eq!(actual, expected_pulse); }); } + +#[test] +fn test_pulses_are_correctly_pruned() { + new_test_ext().execute_with(|| { + let pulse = Pulse::default(); + let last_round: u64 = MAX_KEPT_PULSES + 2; + let oldest_round: u64 = 1; + let prune_count: u64 = 2; + let new_oldest: u64 = oldest_round + prune_count; + let middle_round: u64 = MAX_KEPT_PULSES / 2; + + // Set storage bounds + OldestStoredRound::::put(oldest_round); + LastStoredRound::::put(last_round); + + // Insert pulses at boundaries + // These should be pruned + Pulses::::insert(1, pulse.clone()); + Pulses::::insert(2, pulse.clone()); + + // This should remain (new oldest) + Pulses::::insert(new_oldest, pulse.clone()); + + // Middle and last should remain + Pulses::::insert(middle_round, pulse.clone()); + Pulses::::insert(last_round, pulse.clone()); + + // Trigger prune + Drand::prune_old_pulses(last_round); + + // Assert new oldest + assert_eq!(OldestStoredRound::::get(), new_oldest); + + // Assert pruned correctly + assert!(!Pulses::::contains_key(1), "Round 1 should be pruned"); + assert!(!Pulses::::contains_key(2), "Round 2 should be pruned"); + + // Assert not pruned incorrectly + assert!( + Pulses::::contains_key(new_oldest), + "New oldest round should remain" + ); + assert!( + Pulses::::contains_key(middle_round), + "Middle round should remain" + ); + assert!( + Pulses::::contains_key(last_round), + "Last round should remain" + ); + }); +} + +#[test] +fn test_migrate_prune_old_pulses() { + new_test_ext().execute_with(|| { + let migration_name = BoundedVec::truncate_from(b"migrate_prune_old_pulses".to_vec()); + let pulse = Pulse::default(); + + assert_eq!(Pulses::::iter().count(), 0); + assert!(!HasMigrationRun::::get(&migration_name)); + assert_eq!(OldestStoredRound::::get(), 0); + assert_eq!(LastStoredRound::::get(), 0); + + // Test with more pulses than MAX_KEPT_PULSES + let excess: u64 = 9; + let total: u64 = MAX_KEPT_PULSES + excess; + for i in 1..=total { + Pulses::::insert(i, pulse.clone()); + } + + let weight_large = migrate_prune_old_pulses::(); + + let expected_oldest = excess + 1; + assert_eq!(OldestStoredRound::::get(), expected_oldest); + assert_eq!(LastStoredRound::::get(), total); + + for i in 1..=excess { + assert!(!Pulses::::contains_key(i)); + } + for i in expected_oldest..=total { + assert!(Pulses::::contains_key(i)); + } + + let db_weight: RuntimeDbWeight = ::DbWeight::get(); + let num_pulses = total; + let num_to_delete = num_pulses - MAX_KEPT_PULSES; + let expected_weight = db_weight.reads(1 + num_pulses) + db_weight.writes(num_to_delete + 3); + assert_eq!(weight_large, expected_weight); + }); +} + +#[test] +fn test_prune_maximum_of_100_pulses_per_call() { + new_test_ext().execute_with(|| { + // ------------------------------------------------------------ + // 1. Arrange – create a storage layout that exceeds MAX_KEPT_PULSES + // ------------------------------------------------------------ + const EXTRA: u64 = 250; + let oldest_round: u64 = 1; + let last_round: u64 = oldest_round + MAX_KEPT_PULSES + EXTRA; + + OldestStoredRound::::put(oldest_round); + LastStoredRound::::put(last_round); + let pulse = Pulse::default(); + + // Insert the first 150 rounds so we can check they disappear / stay + for r in oldest_round..=oldest_round + 150 { + Pulses::::insert(r, pulse.clone()); + } + let mid_round = oldest_round + 150; + Pulses::::insert(last_round, pulse.clone()); + + // ------------------------------------------------------------ + // 2. Act – run the pruning function once + // ------------------------------------------------------------ + Drand::prune_old_pulses(last_round); + + // ------------------------------------------------------------ + // 3. Assert – only the *first* 100 pulses were removed + // ------------------------------------------------------------ + let expected_new_oldest = oldest_round + 100; // 101 + + // ‣ Storage bound updated correctly + assert_eq!( + OldestStoredRound::::get(), + expected_new_oldest, + "OldestStoredRound should advance by exactly 100" + ); + + // ‣ Rounds 1‑100 are gone + for r in oldest_round..expected_new_oldest { + assert!( + !Pulses::::contains_key(r), + "Round {r} should have been pruned" + ); + } + + // ‣ Round 101 (new oldest) and later rounds remain + assert!( + Pulses::::contains_key(expected_new_oldest), + "Round {expected_new_oldest} should remain after pruning" + ); + assert!( + Pulses::::contains_key(mid_round), + "Mid-range round should remain after pruning" + ); + assert!( + Pulses::::contains_key(last_round), + "LastStoredRound should remain after pruning" + ); + }); +} + +#[test] +fn test_migrate_set_oldest_round() { + new_test_ext().execute_with(|| { + let migration_name = BoundedVec::truncate_from(b"migrate_set_oldest_round".to_vec()); + let db_weight: RuntimeDbWeight = ::DbWeight::get(); + let pulse = Pulse::default(); + + assert_eq!(Pulses::::iter().count(), 0); + assert!(!HasMigrationRun::::get(&migration_name)); + assert_eq!(OldestStoredRound::::get(), 0); + assert_eq!(LastStoredRound::::get(), 0); + + // Insert out-of-order rounds: oldest should be 5 + for r in [10u64, 7, 5].into_iter() { + Pulses::::insert(r, pulse.clone()); + } + let num_rounds = 3u64; + + // Run migration + let weight = migrate_set_oldest_round::(); + + assert_eq!(OldestStoredRound::::get(), 5); + // Migration does NOT touch LastStoredRound + assert_eq!(LastStoredRound::::get(), 0); + // Pulses untouched + assert!(Pulses::::contains_key(5)); + assert!(Pulses::::contains_key(7)); + assert!(Pulses::::contains_key(10)); + // Flag set + assert!(HasMigrationRun::::get(&migration_name)); + + // Weight: reads(1 + num_rounds) + writes(2) [Oldest + HasMigrationRun] + let expected = db_weight.reads(1 + num_rounds) + db_weight.writes(2); + assert_eq!(weight, expected); + }); +} diff --git a/pallets/drand/src/types.rs b/pallets/drand/src/types.rs index 49a0a593f5..6763787935 100644 --- a/pallets/drand/src/types.rs +++ b/pallets/drand/src/types.rs @@ -15,7 +15,7 @@ */ use alloc::{string::String, vec::Vec}; -use codec::{Decode, Encode}; +use codec::{Decode, DecodeWithMemTracking, Encode}; use frame_support::pallet_prelude::*; use serde::{Deserialize, Serialize}; use subtensor_macros::freeze_struct; @@ -116,11 +116,12 @@ impl DrandResponseBody { } } /// A drand chain configuration -#[freeze_struct("1e01e739e2a5c940")] +#[freeze_struct("e839cb287e55b4f5")] #[derive( Clone, Debug, Decode, + DecodeWithMemTracking, Default, PartialEq, Encode, @@ -141,8 +142,8 @@ pub struct BeaconConfiguration { /// Payload used by to hold the beacon /// config required to submit a transaction. -#[freeze_struct("2b7ebe4cb969cbd3")] -#[derive(Encode, Decode, Debug, Clone, PartialEq, scale_info::TypeInfo)] +#[freeze_struct("aa582bfb5fcb7d4f")] +#[derive(Encode, Decode, DecodeWithMemTracking, Debug, Clone, PartialEq, scale_info::TypeInfo)] pub struct BeaconConfigurationPayload { pub block_number: BlockNumber, pub config: BeaconConfiguration, @@ -150,11 +151,12 @@ pub struct BeaconConfigurationPayload { } /// metadata for the drand beacon configuration -#[freeze_struct("d87f51d2ad39c10e")] +#[freeze_struct("e4cfd191c043f56f")] #[derive( Clone, Debug, Decode, + DecodeWithMemTracking, Default, PartialEq, Encode, @@ -168,11 +170,12 @@ pub struct Metadata { } /// A pulse from the drand beacon -#[freeze_struct("de1a209f66f482b4")] +#[freeze_struct("3836b1f8846739fc")] #[derive( Clone, Debug, Decode, + DecodeWithMemTracking, Default, PartialEq, Encode, @@ -196,8 +199,8 @@ pub struct Pulse { /// Payload used by to hold the pulse /// data required to submit a transaction. -#[freeze_struct("4a9f01b1d8fbbe89")] -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[freeze_struct("d56228e0330b6598")] +#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] pub struct PulsesPayload { pub block_number: BlockNumber, pub pulses: Vec, diff --git a/pallets/drand/src/verifier.rs b/pallets/drand/src/verifier.rs index bdaafcec57..e24b82003a 100644 --- a/pallets/drand/src/verifier.rs +++ b/pallets/drand/src/verifier.rs @@ -68,12 +68,12 @@ impl Verifier for QuicknetVerifier { // decode public key (pk) let pk = ArkScale::::decode(&mut beacon_config.public_key.into_inner().as_slice()) - .map_err(|e| format!("Failed to decode public key: {}", e))?; + .map_err(|e| format!("Failed to decode public key: {e}"))?; // decode signature (sigma) let signature = ArkScale::::decode(&mut pulse.signature.into_inner().as_slice()) - .map_err(|e| format!("Failed to decode signature: {}", e))?; + .map_err(|e| format!("Failed to decode signature: {e}"))?; // m = sha256({} || {round}) let message = message(pulse.round, &[]); @@ -81,15 +81,15 @@ impl Verifier for QuicknetVerifier { // H(m) \in G1 let message_hash = hasher .hash(&message) - .map_err(|e| format!("Failed to hash message: {}", e))?; + .map_err(|e| format!("Failed to hash message: {e}"))?; let mut bytes = Vec::new(); message_hash .serialize_compressed(&mut bytes) - .map_err(|e| format!("Failed to serialize message hash: {}", e))?; + .map_err(|e| format!("Failed to serialize message hash: {e}"))?; let message_on_curve = ArkScale::::decode(&mut &bytes[..]) - .map_err(|e| format!("Failed to decode message on curve: {}", e))?; + .map_err(|e| format!("Failed to decode message on curve: {e}"))?; let g2 = G2AffineOpt::generator(); diff --git a/pallets/proxy/Cargo.toml b/pallets/proxy/Cargo.toml index f3a97dfedf..4f5dddfed1 100644 --- a/pallets/proxy/Cargo.toml +++ b/pallets/proxy/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-proxy" version = "38.0.0" authors = ["Bittensor Nucleus Team"] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://bittensor.com" description = "FRAME proxying pallet" @@ -15,9 +15,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { features = ["max-encoded-len"], workspace = true } -scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { optional = true, workspace = true } +codec = { workspace = true, features = ["derive", "max-encoded-len"] } +scale-info = { workspace = true, features = ["derive"] } +frame-benchmarking = { workspace = true, optional = true } frame-support.workspace = true frame-system.workspace = true sp-io.workspace = true @@ -25,9 +25,9 @@ sp-runtime.workspace = true subtensor-macros.workspace = true [dev-dependencies] -pallet-balances = { default-features = true, workspace = true } -pallet-utility = { default-features = true, workspace = true } -sp-core = { default-features = true, workspace = true } +pallet-balances = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] @@ -46,12 +46,12 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "pallet-balances/runtime-benchmarks", - "pallet-utility/runtime-benchmarks" + "pallet-utility/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", "sp-runtime/try-runtime", "pallet-balances/try-runtime", - "pallet-utility/try-runtime" + "pallet-utility/try-runtime", ] diff --git a/pallets/proxy/src/benchmarking.rs b/pallets/proxy/src/benchmarking.rs index f519c0f0c3..0e0d89f03e 100644 --- a/pallets/proxy/src/benchmarking.rs +++ b/pallets/proxy/src/benchmarking.rs @@ -23,7 +23,7 @@ use super::*; use crate::Pallet as Proxy; use alloc::{boxed::Box, vec}; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; -use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use frame_system::{RawOrigin, pallet_prelude::BlockNumberFor}; use sp_runtime::traits::{Bounded, CheckedDiv}; const SEED: u32 = 0; diff --git a/pallets/proxy/src/lib.rs b/pallets/proxy/src/lib.rs index 25bf82462c..9a7aab857a 100644 --- a/pallets/proxy/src/lib.rs +++ b/pallets/proxy/src/lib.rs @@ -39,18 +39,18 @@ use alloc::{boxed::Box, vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::pallet_prelude::{Pays, Weight}; use frame_support::{ + BoundedVec, dispatch::GetDispatchInfo, ensure, traits::{Currency, Get, InstanceFilter, IsSubType, IsType, OriginTrait, ReservableCurrency}, - BoundedVec, }; use frame_system::{self as system, ensure_signed, pallet_prelude::BlockNumberFor}; pub use pallet::*; -use scale_info::{prelude::cmp::Ordering, TypeInfo}; +use scale_info::{TypeInfo, prelude::cmp::Ordering}; use sp_io::hashing::blake2_256; use sp_runtime::{ - traits::{Dispatchable, Hash, Saturating, StaticLookup, TrailingZeroInput, Zero}, DispatchError, DispatchResult, RuntimeDebug, + traits::{Dispatchable, Hash, Saturating, StaticLookup, TrailingZeroInput, Zero}, }; use subtensor_macros::freeze_struct; pub use weights::WeightInfo; @@ -412,7 +412,7 @@ pub mod pallet { height: system::Pallet::::block_number(), }; - Announcements::::try_mutate(&who, |(ref mut pending, ref mut deposit)| { + Announcements::::try_mutate(&who, |(pending, deposit)| { pending .try_push(announcement) .map_err(|_| Error::::TooMany)?; @@ -709,7 +709,7 @@ impl Pallet { delay: BlockNumberFor, ) -> DispatchResult { ensure!(delegator != &delegatee, Error::::NoSelfProxy); - Proxies::::try_mutate(delegator, |(ref mut proxies, ref mut deposit)| { + Proxies::::try_mutate(delegator, |(proxies, deposit)| { let proxy_def = ProxyDefinition { delegate: delegatee.clone(), proxy_type: proxy_type.clone(), @@ -876,8 +876,8 @@ impl Pallet { match c.is_sub_type() { // Proxy call cannot add or remove a proxy with more permissions than it already // has. - Some(Call::add_proxy { ref proxy_type, .. }) - | Some(Call::remove_proxy { ref proxy_type, .. }) + Some(Call::add_proxy { proxy_type, .. }) + | Some(Call::remove_proxy { proxy_type, .. }) if !def.proxy_type.is_superset(proxy_type) => { false diff --git a/pallets/proxy/src/tests.rs b/pallets/proxy/src/tests.rs index d3200d2e76..e350386164 100644 --- a/pallets/proxy/src/tests.rs +++ b/pallets/proxy/src/tests.rs @@ -23,13 +23,13 @@ use super::*; use crate as proxy; use alloc::{vec, vec::Vec}; -use codec::{Decode, Encode}; +use codec::{Decode, DecodeWithMemTracking, Encode}; use frame_support::{ assert_noop, assert_ok, derive_impl, traits::{ConstU32, ConstU64, Contains}, }; use sp_core::H256; -use sp_runtime::{traits::BlakeTwo256, BuildStorage, DispatchError, RuntimeDebug}; +use sp_runtime::{BuildStorage, DispatchError, RuntimeDebug, traits::BlakeTwo256}; type Block = frame_system::mocking::MockBlock; @@ -72,6 +72,7 @@ impl pallet_utility::Config for Test { PartialOrd, Encode, Decode, + DecodeWithMemTracking, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo, @@ -142,6 +143,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { .expect("Expected to not panic"); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 3)], + dev_accounts: None, } .assimilate_storage(&mut t) .expect("Expected to not panic"); diff --git a/pallets/registry/Cargo.toml b/pallets/registry/Cargo.toml index 006c5a753b..63224aa8c1 100644 --- a/pallets/registry/Cargo.toml +++ b/pallets/registry/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "Simplified identity system for network participants." authors = ["Bittensor Nucleus Team"] homepage = "https://bittensor.com" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" @@ -17,21 +17,18 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] subtensor-macros.workspace = true -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ - "derive", - "max-encoded-len", -] } +codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -enumflags2 = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true +enumflags2.workspace = true [dev-dependencies] -sp-core = { workspace = true } -sp-io = { workspace = true } +sp-core.workspace = true +sp-io.workspace = true [features] default = ["std"] @@ -45,7 +42,7 @@ std = [ "sp-runtime/std", "enumflags2/std", "sp-core/std", - "sp-io/std" + "sp-io/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", @@ -56,5 +53,5 @@ runtime-benchmarks = [ try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", - "sp-runtime/try-runtime" + "sp-runtime/try-runtime", ] diff --git a/pallets/registry/src/types.rs b/pallets/registry/src/types.rs index 5e1b52c0d0..eb19e145d6 100644 --- a/pallets/registry/src/types.rs +++ b/pallets/registry/src/types.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Decode, Encode, MaxEncodedLen}; +use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use enumflags2::{BitFlags, bitflags}; use frame_support::{ BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound, @@ -37,7 +37,7 @@ use subtensor_macros::freeze_struct; /// than 32-bytes then it will be truncated when encoding. /// /// Can also be `None`. -#[derive(Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)] +#[derive(Clone, Eq, PartialEq, RuntimeDebug, DecodeWithMemTracking, MaxEncodedLen)] pub enum Data { /// No data here. None, @@ -280,9 +280,17 @@ impl TypeInfo for IdentityFields { /// /// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra /// fields in a backwards compatible way through a specialized `Decode` impl. -#[freeze_struct("98e2d7fc7536226b")] +#[freeze_struct("4015f12f49280ee")] #[derive( - CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo, + CloneNoBound, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + MaxEncodedLen, + PartialEqNoBound, + RuntimeDebugNoBound, + TypeInfo, )] #[codec(mel_bound())] #[derive(frame_support::DefaultNoBound)] @@ -432,7 +440,7 @@ mod tests { .variants .iter() .find(|v| v.name == variant_name) - .unwrap_or_else(|| panic!("Expected to find variant {}", variant_name)); + .unwrap_or_else(|| panic!("Expected to find variant {variant_name}")); let field_arr_len = variant .fields diff --git a/pallets/subtensor/Cargo.toml b/pallets/subtensor/Cargo.toml index 2ea43f96c1..5479789077 100644 --- a/pallets/subtensor/Cargo.toml +++ b/pallets/subtensor/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "FRAME pallet for runtime logic of Subtensor Blockchain." authors = ["Bittensor Nucleus Team"] homepage = "https://bittensor.com" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" @@ -17,64 +17,60 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] subtensor-macros.workspace = true -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ - "derive", -] } -sp-core = { workspace = true } -pallet-balances = { workspace = true } +codec = { workspace = true, features = ["derive"] } +sp-core.workspace = true +pallet-balances.workspace = true scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -sp-io = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +sp-io.workspace = true serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -serde-tuple-vec-map = { workspace = true } +serde_json.workspace = true +serde-tuple-vec-map.workspace = true serde_bytes = { workspace = true, features = ["alloc"] } serde_with = { workspace = true, features = ["macros"] } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -libsecp256k1 = { workspace = true } -log = { workspace = true } -substrate-fixed = { workspace = true } -pallet-transaction-payment = { workspace = true } -pallet-utility = { workspace = true } -ndarray = { workspace = true } -hex = { workspace = true } -share-pool = { default-features = false, path = "../../primitives/share-pool" } -safe-math = { default-features = false, path = "../../primitives/safe-math" } -approx = { workspace = true } -subtensor-swap-interface = { workspace = true } +sp-runtime.workspace = true +sp-std.workspace = true +libsecp256k1.workspace = true +log.workspace = true +substrate-fixed.workspace = true +pallet-transaction-payment.workspace = true +pallet-utility.workspace = true +ndarray.workspace = true +hex.workspace = true +share-pool.workspace = true +safe-math.workspace = true +approx.workspace = true +subtensor-swap-interface.workspace = true subtensor-runtime-common = { workspace = true, features = ["approx"] } -pallet-collective = { version = "4.0.0-dev", default-features = false, path = "../collective" } -pallet-drand = { path = "../drand", default-features = false } -pallet-membership = { workspace = true } -hex-literal = { workspace = true } -num-traits = { version = "0.2.19", default-features = false, features = [ - "libm", -] } -tle = { workspace = true, default-features = false } -ark-bls12-381 = { workspace = true, default-features = false } -ark-serialize = { workspace = true, default-features = false } -w3f-bls = { workspace = true, default-features = false } -sha2 = { workspace = true } -rand_chacha = { workspace = true } -pallet-crowdloan = { workspace = true, default-features = false } -pallet-proxy = { workspace = true, default-features = false } +pallet-drand.workspace = true +pallet-collective.workspace = true +pallet-membership.workspace = true +hex-literal.workspace = true +num-traits = { workspace = true, features = ["libm"] } +tle.workspace = true +ark-bls12-381 = { workspace = true, features = ["curve"] } +ark-serialize = { workspace = true, features = ["derive"] } +w3f-bls.workspace = true +sha2.workspace = true +rand_chacha.workspace = true +pallet-crowdloan.workspace = true +pallet-proxy.workspace = true [dev-dependencies] pallet-balances = { workspace = true, features = ["std"] } -pallet-scheduler = { workspace = true } -pallet-subtensor-swap = { workspace = true } -sp-version = { workspace = true } +pallet-scheduler.workspace = true +pallet-subtensor-swap.workspace = true +sp-version.workspace = true # Substrate -sp-tracing = { workspace = true } +sp-tracing.workspace = true parity-util-mem = { workspace = true, features = ["primitive-types"] } -rand = { workspace = true } -sp-core = { workspace = true } -sp-std = { workspace = true } -pallet-preimage = { workspace = true } +rand.workspace = true +sp-core.workspace = true +sp-std.workspace = true +pallet-preimage.workspace = true [features] std = [ diff --git a/pallets/subtensor/rpc/Cargo.toml b/pallets/subtensor/rpc/Cargo.toml index 47b63b9067..e3512b82d1 100644 --- a/pallets/subtensor/rpc/Cargo.toml +++ b/pallets/subtensor/rpc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-custom-rpc" version = "0.0.2" -edition = "2024" +edition.workspace = true authors = ['Cameron Fairchild '] repository = 'https://github.com/opentensor/subtensor' description = "A pallet that adds custom RPC calls to subtensor" @@ -12,20 +12,20 @@ publish = false workspace = true [dependencies] -codec = { workspace = true } +codec = { workspace = true, features = ["derive"] } jsonrpsee = { workspace = true, features = ["client-core", "server", "macros"] } serde = { workspace = true, features = ["derive"] } # Substrate packages -sp-api = { workspace = true } -sp-blockchain = { workspace = true } -sp-rpc = { workspace = true } -sp-runtime = { workspace = true } +sp-api.workspace = true +sp-blockchain.workspace = true +sp-rpc.workspace = true +sp-runtime.workspace = true # local packages -subtensor-runtime-common = { workspace = true } -subtensor-custom-rpc-runtime-api = { path = "../runtime-api", default-features = false } -pallet-subtensor = { path = "../../subtensor", default-features = false } +subtensor-runtime-common.workspace = true +subtensor-custom-rpc-runtime-api.workspace = true +pallet-subtensor.workspace = true [features] default = ["std"] diff --git a/pallets/subtensor/rpc/src/lib.rs b/pallets/subtensor/rpc/src/lib.rs index eb3c7b11ca..e3d5d8f1c1 100644 --- a/pallets/subtensor/rpc/src/lib.rs +++ b/pallets/subtensor/rpc/src/lib.rs @@ -9,7 +9,7 @@ use jsonrpsee::{ use sp_blockchain::HeaderBackend; use sp_runtime::{AccountId32, traits::Block as BlockT}; use std::sync::Arc; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; use sp_api::ProvideRuntimeApi; @@ -54,7 +54,7 @@ pub trait SubtensorCustomApi { fn get_subnets_info(&self, at: Option) -> RpcResult>; #[method(name = "subnetInfo_getSubnetInfo_v2")] fn get_subnet_info_v2(&self, netuid: NetUid, at: Option) -> RpcResult>; - #[method(name = "subnetInfo_getSubnetsInf_v2")] + #[method(name = "subnetInfo_getSubnetsInfo_v2")] fn get_subnets_info_v2(&self, at: Option) -> RpcResult>; #[method(name = "subnetInfo_getSubnetHyperparams")] fn get_subnet_hyperparams(&self, netuid: NetUid, at: Option) -> RpcResult>; @@ -75,7 +75,7 @@ pub trait SubtensorCustomApi { #[method(name = "subnetInfo_getSubnetState")] fn get_subnet_state(&self, netuid: NetUid, at: Option) -> RpcResult>; #[method(name = "subnetInfo_getLockCost")] - fn get_network_lock_cost(&self, at: Option) -> RpcResult; + fn get_network_lock_cost(&self, at: Option) -> RpcResult; #[method(name = "subnetInfo_getSelectiveMetagraph")] fn get_selective_metagraph( &self, @@ -139,7 +139,7 @@ where match api.get_delegates(at) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get delegates info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get delegates info: {e:?}")).into()) } } } @@ -156,14 +156,14 @@ where Ok(delegate_account) => delegate_account, Err(e) => { return Err( - Error::RuntimeError(format!("Unable to get delegates info: {:?}", e)).into(), + Error::RuntimeError(format!("Unable to get delegates info: {e:?}")).into(), ); } }; match api.get_delegate(at, delegate_account) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get delegates info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get delegates info: {e:?}")).into()) } } } @@ -180,14 +180,14 @@ where Ok(delegatee_account) => delegatee_account, Err(e) => { return Err( - Error::RuntimeError(format!("Unable to get delegates info: {:?}", e)).into(), + Error::RuntimeError(format!("Unable to get delegates info: {e:?}")).into(), ); } }; match api.get_delegated(at, delegatee_account) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get delegates info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get delegates info: {e:?}")).into()) } } } @@ -203,7 +203,7 @@ where match api.get_neurons_lite(at, netuid) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get neurons lite info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get neurons lite info: {e:?}")).into()) } } } @@ -220,7 +220,7 @@ where match api.get_neuron_lite(at, netuid, uid) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get neurons lite info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get neurons lite info: {e:?}")).into()) } } } @@ -235,9 +235,7 @@ where match api.get_neurons(at, netuid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get neurons info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get neurons info: {e:?}")).into()), } } @@ -252,9 +250,7 @@ where match api.get_neuron(at, netuid, uid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get neuron info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get neuron info: {e:?}")).into()), } } @@ -268,9 +264,7 @@ where match api.get_subnet_info(at, netuid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnet info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnet info: {e:?}")).into()), } } @@ -284,9 +278,7 @@ where match api.get_subnet_hyperparams(at, netuid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnet info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnet info: {e:?}")).into()), } } @@ -300,9 +292,7 @@ where match api.get_subnet_hyperparams_v2(at, netuid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnet info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnet info: {e:?}")).into()), } } @@ -313,8 +303,7 @@ where match api.get_all_dynamic_info(at) { Ok(result) => Ok(result.encode()), Err(e) => Err(Error::RuntimeError(format!( - "Unable to get dynamic subnets info: {:?}", - e + "Unable to get dynamic subnets info: {e:?}" )) .into()), } @@ -326,7 +315,7 @@ where match api.get_all_metagraphs(at) { Ok(result) => Ok(result.encode()), - Err(e) => Err(Error::RuntimeError(format!("Unable to get metagraps: {:?}", e)).into()), + Err(e) => Err(Error::RuntimeError(format!("Unable to get metagraps: {e:?}")).into()), } } @@ -341,8 +330,7 @@ where match api.get_dynamic_info(at, netuid) { Ok(result) => Ok(result.encode()), Err(e) => Err(Error::RuntimeError(format!( - "Unable to get dynamic subnets info: {:?}", - e + "Unable to get dynamic subnets info: {e:?}" )) .into()), } @@ -358,8 +346,7 @@ where match api.get_metagraph(at, netuid) { Ok(result) => Ok(result.encode()), Err(e) => Err(Error::RuntimeError(format!( - "Unable to get dynamic subnets info: {:?}", - e + "Unable to get dynamic subnets info: {e:?}" )) .into()), } @@ -376,7 +363,7 @@ where match api.get_subnet_state(at, netuid) { Ok(result) => Ok(result.encode()), Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnet state info: {:?}", e)).into()) + Err(Error::RuntimeError(format!("Unable to get subnet state info: {e:?}")).into()) } } } @@ -387,9 +374,7 @@ where match api.get_subnets_info(at) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnets info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnets info: {e:?}")).into()), } } @@ -403,9 +388,7 @@ where match api.get_subnet_info_v2(at, netuid) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnet info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnet info: {e:?}")).into()), } } @@ -415,18 +398,16 @@ where match api.get_subnets_info_v2(at) { Ok(result) => Ok(result.encode()), - Err(e) => { - Err(Error::RuntimeError(format!("Unable to get subnets info: {:?}", e)).into()) - } + Err(e) => Err(Error::RuntimeError(format!("Unable to get subnets info: {e:?}")).into()), } } - fn get_network_lock_cost(&self, at: Option<::Hash>) -> RpcResult { + fn get_network_lock_cost(&self, at: Option<::Hash>) -> RpcResult { let api = self.client.runtime_api(); let at = at.unwrap_or_else(|| self.client.info().best_hash); api.get_network_registration_cost(at).map_err(|e| { - Error::RuntimeError(format!("Unable to get subnet lock cost: {:?}", e)).into() + Error::RuntimeError(format!("Unable to get subnet lock cost: {e:?}")).into() }) } @@ -441,11 +422,9 @@ where match api.get_selective_metagraph(at, netuid, metagraph_index) { Ok(result) => Ok(result.encode()), - Err(e) => Err(Error::RuntimeError(format!( - "Unable to get selective metagraph: {:?}", - e - )) - .into()), + Err(e) => { + Err(Error::RuntimeError(format!("Unable to get selective metagraph: {e:?}")).into()) + } } } } diff --git a/pallets/subtensor/runtime-api/Cargo.toml b/pallets/subtensor/runtime-api/Cargo.toml index 1a95b75d16..1951f77fd3 100644 --- a/pallets/subtensor/runtime-api/Cargo.toml +++ b/pallets/subtensor/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-custom-rpc-runtime-api" version = "0.0.2" -edition = "2024" +edition.workspace = true authors = ['Cameron Fairchild '] repository = 'https://github.com/opentensor/subtensor' description = "A pallet that adds a custom runtime API to Subtensor" @@ -12,14 +12,14 @@ publish = false workspace = true [dependencies] -sp-api = { workspace = true } -sp-runtime = { workspace = true } -frame-support = { workspace = true } +sp-api.workspace = true +sp-runtime.workspace = true +frame-support.workspace = true serde = { workspace = true, features = ["derive"] } -codec = { workspace = true } -subtensor-runtime-common = { workspace = true } +codec = { workspace = true, features = ["derive"] } +subtensor-runtime-common.workspace = true # local -pallet-subtensor = { version = "4.0.0-dev", path = "../../subtensor", default-features = false } +pallet-subtensor.workspace = true [features] default = ["std"] diff --git a/pallets/subtensor/runtime-api/src/lib.rs b/pallets/subtensor/runtime-api/src/lib.rs index aa85aeffa8..42d12eb686 100644 --- a/pallets/subtensor/runtime-api/src/lib.rs +++ b/pallets/subtensor/runtime-api/src/lib.rs @@ -12,7 +12,7 @@ use pallet_subtensor::rpc_info::{ subnet_info::{SubnetHyperparams, SubnetHyperparamsV2, SubnetInfo, SubnetInfov2}, }; use sp_runtime::AccountId32; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; // Here we declare the runtime API. It is implemented it the `impl` block in // src/neuron_info.rs, src/subnet_info.rs, and src/delegate_info.rs @@ -53,6 +53,6 @@ sp_api::decl_runtime_apis! { } pub trait SubnetRegistrationRuntimeApi { - fn get_network_registration_cost() -> u64; + fn get_network_registration_cost() -> TaoCurrency; } } diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index b239adb70e..6a2a35e3c0 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -15,7 +15,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash}, }; use sp_std::vec; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; #[frame_benchmarking::v2::benchmarks] mod pallet_benchmarks { @@ -71,7 +71,7 @@ mod pallet_benchmarks { let coldkey: T::AccountId = account("Test", 0, seed); seed += 1; - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); let amount_to_be_staked: u64 = 1_000_000; Subtensor::::add_balance_to_coldkey_account(&coldkey, amount_to_be_staked); @@ -104,7 +104,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, tempo); SubtokenEnabled::::insert(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); Subtensor::::set_max_allowed_uids(netuid, 4096); Subtensor::::set_network_registration_allowed(netuid, true); @@ -131,17 +131,17 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, tempo); SubtokenEnabled::::insert(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); Subtensor::::set_network_registration_allowed(netuid, true); Subtensor::::set_max_allowed_uids(netuid, 4096); let seed: u32 = 1; let coldkey: T::AccountId = account("Test", 0, seed); let hotkey: T::AccountId = account("Alice", 0, seed); - let total_stake: u64 = 1_000_000_000; - let amount: u64 = 60_000_000; + let total_stake = TaoCurrency::from(1_000_000_000); + let amount = TaoCurrency::from(60_000_000); - Subtensor::::add_balance_to_coldkey_account(&coldkey, total_stake); + Subtensor::::add_balance_to_coldkey_account(&coldkey, total_stake.into()); assert_ok!(Subtensor::::do_burned_registration( RawOrigin::Signed(coldkey.clone()).into(), netuid, @@ -173,9 +173,9 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid, true); Subtensor::::set_max_allowed_uids(netuid, 4096); - let reg_fee: u64 = Subtensor::::get_burn_as_u64(netuid); - let deposit = reg_fee.saturating_mul(2); - Subtensor::::add_balance_to_coldkey_account(&caller, deposit); + let reg_fee = Subtensor::::get_burn(netuid); + let deposit = reg_fee.saturating_mul(2.into()); + Subtensor::::add_balance_to_coldkey_account(&caller, deposit.into()); assert_ok!(Subtensor::::do_burned_registration( RawOrigin::Signed(caller.clone()).into(), @@ -211,9 +211,9 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid, true); Subtensor::::set_max_allowed_uids(netuid, 4096); - let reg_fee: u64 = Subtensor::::get_burn_as_u64(netuid); - let deposit = reg_fee.saturating_mul(2); - Subtensor::::add_balance_to_coldkey_account(&caller, deposit); + let reg_fee = Subtensor::::get_burn(netuid); + let deposit = reg_fee.saturating_mul(2.into()); + Subtensor::::add_balance_to_coldkey_account(&caller, deposit.into()); assert_ok!(Subtensor::::do_burned_registration( RawOrigin::Signed(caller.clone()).into(), @@ -242,7 +242,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, 1); SubtokenEnabled::::insert(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); let amount: u64 = 1_000_000; Subtensor::::add_balance_to_coldkey_account(&coldkey, amount); @@ -260,7 +260,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, 1); SubtokenEnabled::::insert(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); Subtensor::::set_network_registration_allowed(netuid, true); Subtensor::::set_max_allowed_uids(netuid, 4096); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -424,9 +424,9 @@ mod pallet_benchmarks { Subtensor::::set_network_registration_allowed(netuid, true); SubtokenEnabled::::insert(netuid, true); - let reg_fee: u64 = Subtensor::::get_burn_as_u64(netuid); - let deposit = reg_fee.saturating_mul(2); - Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit); + let reg_fee = Subtensor::::get_burn(netuid); + let deposit = reg_fee.saturating_mul(2.into()); + Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit.into()); assert_ok!(Subtensor::::do_burned_registration( RawOrigin::Signed(coldkey.clone()).into(), @@ -449,14 +449,14 @@ mod pallet_benchmarks { let new_coldkey: T::AccountId = account("new_coldkey", 0, 0); let hotkey1: T::AccountId = account("hotkey1", 0, 0); let netuid = NetUid::from(1); - let swap_cost: u64 = Subtensor::::get_key_swap_cost(); - let free_balance_old: u64 = 12345 + swap_cost; + let swap_cost = Subtensor::::get_key_swap_cost(); + let free_balance_old = swap_cost + 12345.into(); Subtensor::::init_new_network(netuid, 1); Subtensor::::set_network_registration_allowed(netuid, true); Subtensor::::set_network_pow_registration_allowed(netuid, true); - let block_number: u64 = Subtensor::::get_current_block_as_u64(); + let block_number = Subtensor::::get_current_block_as_u64(); let (nonce, work) = Subtensor::::create_work_for_block_number(netuid, block_number, 3, &hotkey1); let _ = Subtensor::::register( @@ -469,7 +469,7 @@ mod pallet_benchmarks { old_coldkey.clone(), ); - Subtensor::::add_balance_to_coldkey_account(&old_coldkey, free_balance_old); + Subtensor::::add_balance_to_coldkey_account(&old_coldkey, free_balance_old.into()); let name: Vec = b"The fourth Coolest Identity".to_vec(); let identity = ChainIdentity { name, @@ -573,9 +573,9 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, 1); SubtokenEnabled::::insert(netuid, true); Subtensor::::set_network_registration_allowed(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); - let amount_to_be_staked: u64 = 1_000_000_000; + let amount_to_be_staked = 1_000_000_000; Subtensor::::add_balance_to_coldkey_account(&coldkey, amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration( RawOrigin::Signed(coldkey.clone()).into(), @@ -616,7 +616,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, 1); SubtokenEnabled::::insert(netuid, true); Subtensor::::set_network_registration_allowed(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); let amount_to_be_staked: u64 = 1_000_000_000; Subtensor::::add_balance_to_coldkey_account(&coldkey, amount_to_be_staked); @@ -658,8 +658,8 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid, true); Subtensor::::set_network_registration_allowed(netuid, true); - Subtensor::::set_burn(netuid, 1); - let amount_to_be_staked: u64 = 1_000_000; + Subtensor::::set_burn(netuid, 1.into()); + let amount_to_be_staked = 1_000_000; Subtensor::::add_balance_to_coldkey_account(&coldkey, amount_to_be_staked); SubnetOwner::::set(netuid, coldkey.clone()); @@ -703,7 +703,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid, tempo); SubtokenEnabled::::insert(netuid, true); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); Subtensor::::set_network_registration_allowed(netuid, true); Subtensor::::set_max_allowed_uids(netuid, 4096); @@ -711,11 +711,11 @@ mod pallet_benchmarks { let hotkey: T::AccountId = account("Alice", 0, seed); let amount = 900_000_000_000; - let limit: u64 = 6_000_000_000; - let amount_to_be_staked = 44_000_000_000; + let limit = TaoCurrency::from(6_000_000_000); + let amount_to_be_staked = TaoCurrency::from(44_000_000_000); Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount); - let tao_reserve = 150_000_000_000_u64; + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); @@ -747,10 +747,10 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid, true); Subtensor::::init_new_network(netuid, 1); - let burn_fee = Subtensor::::get_burn_as_u64(netuid); - let stake_tao: u64 = DefaultMinStake::::get().saturating_mul(10); - let deposit = burn_fee.saturating_mul(2).saturating_add(stake_tao); - Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit); + let burn_fee = Subtensor::::get_burn(netuid); + let stake_tao = DefaultMinStake::::get().saturating_mul(10.into()); + let deposit = burn_fee.saturating_mul(2.into()).saturating_add(stake_tao); + Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit.into()); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(coldkey.clone()).into(), @@ -759,7 +759,7 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid, deposit); - SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit)); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit.to_u64())); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -767,7 +767,7 @@ mod pallet_benchmarks { origin.clone(), netuid, stake_tao, - u64::MAX, + TaoCurrency::MAX, false )); @@ -797,7 +797,7 @@ mod pallet_benchmarks { let seed: u32 = 1; // Set our total stake to 1000 TAO - Subtensor::::increase_total_stake(1_000_000_000_000); + Subtensor::::increase_total_stake(1_000_000_000_000.into()); Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_network_registration_allowed(netuid, true); @@ -808,10 +808,10 @@ mod pallet_benchmarks { let coldkey: T::AccountId = account("Test", 0, seed); let hotkey: T::AccountId = account("Alice", 0, seed); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); - let limit: u64 = 1_000_000_000; - let tao_reserve = 150_000_000_000_u64; + let limit = TaoCurrency::from(1_000_000_000); + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); @@ -832,7 +832,7 @@ mod pallet_benchmarks { RawOrigin::Signed(coldkey.clone()).into(), hotkey.clone(), netuid, - u64_staked_amt + u64_staked_amt.into() )); let amount_unstaked = AlphaCurrency::from(30_000_000_000); @@ -864,18 +864,18 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid2, true); Subtensor::::init_new_network(netuid2, 1); - let tao_reserve = 150_000_000_000_u64; + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid1, tao_reserve); SubnetAlphaIn::::insert(netuid1, alpha_in); SubnetTAO::::insert(netuid2, tao_reserve); - Subtensor::::increase_total_stake(1_000_000_000_000); + Subtensor::::increase_total_stake(1_000_000_000_000.into()); let amount = 900_000_000_000; - let limit_stake: u64 = 6_000_000_000; - let limit_swap: u64 = 1_000_000_000; - let amount_to_be_staked = 440_000_000_000; + let limit_stake = TaoCurrency::from(6_000_000_000); + let limit_swap = TaoCurrency::from(1_000_000_000); + let amount_to_be_staked = TaoCurrency::from(440_000_000_000); let amount_swapped = AlphaCurrency::from(30_000_000_000); Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount); @@ -925,10 +925,10 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid, true); Subtensor::::init_new_network(netuid, 1); - let reg_fee = Subtensor::::get_burn_as_u64(netuid); - let stake_tao: u64 = DefaultMinStake::::get().saturating_mul(10); - let deposit = reg_fee.saturating_mul(2).saturating_add(stake_tao); - Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit); + let reg_fee = Subtensor::::get_burn(netuid); + let stake_tao = DefaultMinStake::::get().saturating_mul(10.into()); + let deposit = reg_fee.saturating_mul(2.into()).saturating_add(stake_tao); + Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit.into()); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(coldkey.clone()).into(), @@ -937,7 +937,7 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid, deposit); - SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit)); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit.to_u64())); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -945,7 +945,7 @@ mod pallet_benchmarks { hot.clone(), netuid, stake_tao, - u64::MAX, + TaoCurrency::MAX, false )); @@ -980,10 +980,10 @@ mod pallet_benchmarks { SubtokenEnabled::::insert(netuid2, true); Subtensor::::init_new_network(netuid2, 1); - let reg_fee = Subtensor::::get_burn_as_u64(netuid1); - let stake_tao: u64 = DefaultMinStake::::get().saturating_mul(10); - let deposit = reg_fee.saturating_mul(2).saturating_add(stake_tao); - Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit); + let reg_fee = Subtensor::::get_burn(netuid1); + let stake_tao = DefaultMinStake::::get().saturating_mul(10.into()); + let deposit = reg_fee.saturating_mul(2.into()).saturating_add(stake_tao); + Subtensor::::add_balance_to_coldkey_account(&coldkey, deposit.into()); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(coldkey.clone()).into(), @@ -992,9 +992,9 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid1, deposit); - SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(deposit)); + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(deposit.to_u64())); SubnetTAO::::insert(netuid2, deposit); - SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(deposit)); + SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(deposit.to_u64())); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -1002,7 +1002,7 @@ mod pallet_benchmarks { hot.clone(), netuid1, stake_tao, - u64::MAX, + TaoCurrency::MAX, false )); @@ -1034,8 +1034,8 @@ mod pallet_benchmarks { Subtensor::::set_network_pow_registration_allowed(netuid, true); SubtokenEnabled::::insert(netuid, true); - let reg_fee = Subtensor::::get_burn_as_u64(netuid); - Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.saturating_mul(2)); + let reg_fee = Subtensor::::get_burn(netuid); + Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.to_u64().saturating_mul(2)); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(hotkey.clone()).into(), @@ -1073,8 +1073,8 @@ mod pallet_benchmarks { Subtensor::::set_network_registration_allowed(netuid, true); SubtokenEnabled::::insert(netuid, true); - let reg_fee = Subtensor::::get_burn_as_u64(netuid); - Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.saturating_mul(2)); + let reg_fee = Subtensor::::get_burn(netuid); + Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.to_u64().saturating_mul(2)); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(hotkey.clone()).into(), @@ -1103,8 +1103,8 @@ mod pallet_benchmarks { Subtensor::::set_network_pow_registration_allowed(netuid, true); SubtokenEnabled::::insert(netuid, true); - let reg_fee = Subtensor::::get_burn_as_u64(netuid); - Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.saturating_mul(2)); + let reg_fee = Subtensor::::get_burn(netuid); + Subtensor::::add_balance_to_coldkey_account(&hotkey, reg_fee.to_u64().saturating_mul(2)); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(hotkey.clone()).into(), @@ -1185,9 +1185,9 @@ mod pallet_benchmarks { Subtensor::::set_network_registration_allowed(netuid, true); SubtokenEnabled::::insert(netuid, true); - let reg_fee = Subtensor::::get_burn_as_u64(netuid); - let deposit: u64 = reg_fee.saturating_mul(2); - Subtensor::::add_balance_to_coldkey_account(&caller, deposit); + let reg_fee = Subtensor::::get_burn(netuid); + let deposit = reg_fee.saturating_mul(2.into()); + Subtensor::::add_balance_to_coldkey_account(&caller, deposit.into()); assert_ok!(Subtensor::::burned_register( RawOrigin::Signed(caller.clone()).into(), @@ -1305,8 +1305,8 @@ mod pallet_benchmarks { let old: T::AccountId = account("A", 0, 7); let new: T::AccountId = account("B", 0, 8); Owner::::insert(&old, &coldkey); - let cost: u64 = Subtensor::::get_key_swap_cost(); - Subtensor::::add_balance_to_coldkey_account(&coldkey, cost); + let cost = Subtensor::::get_key_swap_cost(); + Subtensor::::add_balance_to_coldkey_account(&coldkey, cost.into()); #[extrinsic_call] _( @@ -1351,9 +1351,9 @@ mod pallet_benchmarks { let coldkey: T::AccountId = account("Test", 0, seed); let hotkey: T::AccountId = account("Alice", 0, seed); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); - SubnetTAO::::insert(netuid, 150_000_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(150_000_000_000)); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(100_000_000_000)); Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 1000000u32.into()); @@ -1371,7 +1371,7 @@ mod pallet_benchmarks { RawOrigin::Signed(coldkey.clone()).into(), hotkey.clone(), netuid, - staked_amt + staked_amt.into() )); // Remove stake limit for benchmark @@ -1388,7 +1388,7 @@ mod pallet_benchmarks { let seed: u32 = 1; // Set our total stake to 1000 TAO - Subtensor::::increase_total_stake(1_000_000_000_000); + Subtensor::::increase_total_stake(1_000_000_000_000.into()); Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_network_registration_allowed(netuid, true); @@ -1399,10 +1399,10 @@ mod pallet_benchmarks { let coldkey: T::AccountId = account("Test", 0, seed); let hotkey: T::AccountId = account("Alice", 0, seed); - Subtensor::::set_burn(netuid, 1); + Subtensor::::set_burn(netuid, 1.into()); - let limit: u64 = 1_000_000_000; - let tao_reserve = 150_000_000_000_u64; + let limit = TaoCurrency::from(1_000_000_000); + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); @@ -1423,7 +1423,7 @@ mod pallet_benchmarks { RawOrigin::Signed(coldkey.clone()).into(), hotkey.clone(), netuid, - u64_staked_amt + u64_staked_amt.into() )); StakingOperationRateLimiter::::remove((hotkey.clone(), coldkey.clone(), netuid)); @@ -1598,4 +1598,40 @@ mod pallet_benchmarks { assert_eq!(TokenSymbol::::get(netuid), new_symbol); } + + #[benchmark] + fn commit_timelocked_weights() { + let hotkey: T::AccountId = whitelisted_caller(); + let netuid = NetUid::from(1); + let vec_commit: Vec = vec![0; MAX_CRV3_COMMIT_SIZE_BYTES as usize]; + let commit: BoundedVec<_, _> = vec_commit.try_into().unwrap(); + let round: u64 = 0; + + Subtensor::::init_new_network(netuid, 1); + Subtensor::::set_network_pow_registration_allowed(netuid, true); + SubtokenEnabled::::insert(netuid, true); + + let reg_fee = Subtensor::::get_burn(netuid); + Subtensor::::add_balance_to_coldkey_account( + &hotkey, + reg_fee.saturating_mul(2.into()).into(), + ); + + assert_ok!(Subtensor::::burned_register( + RawOrigin::Signed(hotkey.clone()).into(), + netuid, + hotkey.clone() + )); + + Subtensor::::set_commit_reveal_weights_enabled(netuid, true); + + #[extrinsic_call] + _( + RawOrigin::Signed(hotkey.clone()), + netuid, + commit.clone(), + round, + Subtensor::::get_commit_reveal_weights_version(), + ); + } } diff --git a/pallets/subtensor/src/coinbase/block_emission.rs b/pallets/subtensor/src/coinbase/block_emission.rs index 4f6fb9d95f..064bab4d2a 100644 --- a/pallets/subtensor/src/coinbase/block_emission.rs +++ b/pallets/subtensor/src/coinbase/block_emission.rs @@ -5,7 +5,7 @@ use substrate_fixed::{ transcendental::log2, types::{I96F32, U96F32}, }; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; use subtensor_swap_interface::SwapHandler; impl Pallet { @@ -41,7 +41,7 @@ impl Pallet { // Get alpha price for subnet. let alpha_price = T::SwapInterface::current_alpha_price(netuid.into()); - log::debug!("{:?} - alpha_price: {:?}", netuid, alpha_price); + log::debug!("{netuid:?} - alpha_price: {alpha_price:?}"); // Get initial alpha_in let mut alpha_in_emission: U96F32 = U96F32::saturating_from_num(tao_emission) @@ -51,10 +51,7 @@ impl Pallet { // Check if we are emitting too much alpha_in if alpha_in_emission >= float_alpha_block_emission { log::debug!( - "{:?} - alpha_in_emission: {:?} > alpha_block_emission: {:?}", - netuid, - alpha_in_emission, - float_alpha_block_emission + "{netuid:?} - alpha_in_emission: {alpha_in_emission:?} > alpha_block_emission: {float_alpha_block_emission:?}" ); // Scale down tao_in @@ -76,13 +73,9 @@ impl Pallet { let alpha_out_emission = float_alpha_block_emission; // Log results. - log::debug!("{:?} - tao_in_emission: {:?}", netuid, tao_in_emission); - log::debug!("{:?} - alpha_in_emission: {:?}", netuid, alpha_in_emission); - log::debug!( - "{:?} - alpha_out_emission: {:?}", - netuid, - alpha_out_emission - ); + log::debug!("{netuid:?} - tao_in_emission: {tao_in_emission:?}"); + log::debug!("{netuid:?} - alpha_in_emission: {alpha_in_emission:?}"); + log::debug!("{netuid:?} - alpha_out_emission: {alpha_out_emission:?}"); // Return result. ( @@ -103,9 +96,9 @@ impl Pallet { /// # Returns /// * 'Result': The calculated block emission rate or error. /// - pub fn get_block_emission() -> Result { + pub fn get_block_emission() -> Result { // Convert the total issuance to a fixed-point number for calculation. - Self::get_block_emission_for_issuance(Self::get_total_issuance()) + Self::get_block_emission_for_issuance(Self::get_total_issuance().into()).map(Into::into) } /// Returns the block emission for an issuance value. diff --git a/pallets/subtensor/src/coinbase/block_step.rs b/pallets/subtensor/src/coinbase/block_step.rs index d003a698e3..6a96090b05 100644 --- a/pallets/subtensor/src/coinbase/block_step.rs +++ b/pallets/subtensor/src/coinbase/block_step.rs @@ -1,19 +1,22 @@ use super::*; use safe_math::*; use substrate_fixed::types::{U96F32, U110F18}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; impl Pallet { /// Executes the necessary operations for each block. pub fn block_step() -> Result<(), &'static str> { let block_number: u64 = Self::get_current_block_as_u64(); - log::debug!("block_step for block: {:?} ", block_number); + log::debug!("block_step for block: {block_number:?} "); // --- 1. Adjust difficulties. Self::adjust_registration_terms_for_networks(); // --- 2. Get the current coinbase emission. - let block_emission: U96F32 = - U96F32::saturating_from_num(Self::get_block_emission().unwrap_or(0)); - log::debug!("Block emission: {:?}", block_emission); + let block_emission: U96F32 = U96F32::saturating_from_num( + Self::get_block_emission() + .unwrap_or(TaoCurrency::ZERO) + .to_u64(), + ); + log::debug!("Block emission: {block_emission:?}"); // --- 3. Run emission through network. Self::run_coinbase(block_emission); // --- 4. Set pending children on the epoch; but only after the coinbase has been run. @@ -43,11 +46,7 @@ impl Pallet { let adjustment_interval: u16 = Self::get_adjustment_interval(netuid); let current_block: u64 = Self::get_current_block_as_u64(); log::debug!( - "netuid: {:?} last_adjustment_block: {:?} adjustment_interval: {:?} current_block: {:?}", - netuid, - last_adjustment_block, - adjustment_interval, - current_block + "netuid: {netuid:?} last_adjustment_block: {last_adjustment_block:?} adjustment_interval: {adjustment_interval:?} current_block: {current_block:?}" ); // --- 3. Check if we are at the adjustment interval for this network. @@ -56,7 +55,7 @@ impl Pallet { log::debug!("interval reached."); // --- 4. Get the current counters for this network w.r.t burn and difficulty values. - let current_burn: u64 = Self::get_burn_as_u64(netuid); + let current_burn = Self::get_burn(netuid); let current_difficulty: u64 = Self::get_difficulty_as_u64(netuid); let registrations_this_interval: u16 = Self::get_registrations_this_interval(netuid); @@ -228,10 +227,10 @@ impl Pallet { /// pub fn upgraded_burn( netuid: NetUid, - current_burn: u64, + current_burn: TaoCurrency, registrations_this_interval: u16, target_registrations_per_interval: u16, - ) -> u64 { + ) -> TaoCurrency { let updated_burn: U110F18 = U110F18::saturating_from_num(current_burn) .saturating_mul(U110F18::saturating_from_num( registrations_this_interval.saturating_add(target_registrations_per_interval), @@ -248,12 +247,12 @@ impl Pallet { .saturating_sub(alpha) .saturating_mul(updated_burn), ); - if next_value >= U110F18::saturating_from_num(Self::get_max_burn_as_u64(netuid)) { - Self::get_max_burn_as_u64(netuid) - } else if next_value <= U110F18::saturating_from_num(Self::get_min_burn_as_u64(netuid)) { - return Self::get_min_burn_as_u64(netuid); + if next_value >= U110F18::saturating_from_num(Self::get_max_burn(netuid)) { + Self::get_max_burn(netuid) + } else if next_value <= U110F18::saturating_from_num(Self::get_min_burn(netuid)) { + return Self::get_min_burn(netuid); } else { - return next_value.saturating_to_num::(); + return next_value.saturating_to_num::().into(); } } } diff --git a/pallets/subtensor/src/coinbase/reveal_commits.rs b/pallets/subtensor/src/coinbase/reveal_commits.rs index 9318321633..029b77227c 100644 --- a/pallets/subtensor/src/coinbase/reveal_commits.rs +++ b/pallets/subtensor/src/coinbase/reveal_commits.rs @@ -1,13 +1,14 @@ use super::*; use ark_serialize::CanonicalDeserialize; use codec::Decode; -use frame_support::dispatch; -use frame_support::traits::OriginTrait; +use frame_support::{dispatch, traits::OriginTrait}; +use scale_info::prelude::collections::VecDeque; use subtensor_runtime_common::NetUid; -use tle::curves::drand::TinyBLS381; -use tle::stream_ciphers::AESGCMStreamCipherProvider; -use tle::tlock::TLECiphertext; -use tle::tlock::tld; +use tle::{ + curves::drand::TinyBLS381, + stream_ciphers::AESGCMStreamCipherProvider, + tlock::{TLECiphertext, tld}, +}; use w3f_bls::EngineBLS; /// Contains all necessary information to set weights. @@ -16,8 +17,18 @@ use w3f_bls::EngineBLS; /// encrypted, compressed, serialized, and submitted to the `commit_crv3_weights` /// extrinsic. #[derive(Encode, Decode)] -#[freeze_struct("46e75a8326ba3665")] +#[freeze_struct("b6833b5029be4127")] pub struct WeightsTlockPayload { + pub hotkey: Vec, + pub uids: Vec, + pub values: Vec, + pub version_key: u64, +} + +/// For the old structure +#[derive(Encode, Decode)] +#[freeze_struct("304e55f41267caa")] +pub struct LegacyWeightsTlockPayload { pub uids: Vec, pub values: Vec, pub version_key: u64, @@ -26,12 +37,12 @@ pub struct WeightsTlockPayload { impl Pallet { /// The `reveal_crv3_commits` function is run at the very beginning of epoch `n`, pub fn reveal_crv3_commits(netuid: NetUid) -> dispatch::DispatchResult { + let reveal_period = Self::get_reveal_period(netuid); let cur_block = Self::get_current_block_as_u64(); let cur_epoch = Self::get_epoch_index(netuid, cur_block); // Weights revealed must have been committed during epoch `cur_epoch - reveal_period`. - let reveal_epoch = - cur_epoch.saturating_sub(Self::get_reveal_period(netuid).saturating_sub(1)); + let reveal_epoch = cur_epoch.saturating_sub(reveal_period); // Clean expired commits for (epoch, _) in CRV3WeightCommitsV2::::iter_prefix(netuid) { @@ -40,42 +51,43 @@ impl Pallet { } } - // No commits to reveal until at least epoch 2. - if cur_epoch < 2 { - log::warn!("Failed to reveal commit for subnet {} Too early", netuid); + // No commits to reveal until at least epoch reveal_period. + if cur_epoch < reveal_period { + log::trace!("Failed to reveal commit for subnet {netuid} Too early"); return Ok(()); } let mut entries = CRV3WeightCommitsV2::::take(netuid, reveal_epoch); + let mut unrevealed = VecDeque::new(); - // Keep popping item off the end of the queue until we sucessfully reveal a commit. - while let Some((who, _commit_block, serialized_compresssed_commit, round_number)) = + // Keep popping items off the front of the queue until we successfully reveal a commit. + while let Some((who, commit_block, serialized_compresssed_commit, round_number)) = entries.pop_front() { - let reader = &mut &serialized_compresssed_commit[..]; - let commit = match TLECiphertext::::deserialize_compressed(reader) { - Ok(c) => c, - Err(e) => { - log::warn!( - "Failed to reveal commit for subnet {} submitted by {:?} due to error deserializing the commit: {:?}", - netuid, - who, - e - ); - continue; - } - }; - // Try to get the round number from pallet_drand. let pulse = match pallet_drand::Pulses::::get(round_number) { Some(p) => p, None => { // Round number used was not found on the chain. Skip this commit. - log::warn!( - "Failed to reveal commit for subnet {} submitted by {:?} due to missing round number {} at time of reveal.", - netuid, + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} on block {commit_block} due to missing round number {round_number}; will retry every block in reveal epoch." + ); + unrevealed.push_back(( who, - round_number + commit_block, + serialized_compresssed_commit, + round_number, + )); + continue; + } + }; + + let reader = &mut &serialized_compresssed_commit[..]; + let commit = match TLECiphertext::::deserialize_compressed(reader) { + Ok(c) => c, + Err(e) => { + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to error deserializing the commit: {e:?}" ); continue; } @@ -92,11 +104,8 @@ impl Pallet { ) { Ok(s) => s, Err(e) => { - log::error!( - "Failed to reveal commit for subnet {} submitted by {:?} due to error deserializing signature from drand pallet: {:?}", - netuid, - who, - e + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to error deserializing signature from drand pallet: {e:?}" ); continue; } @@ -107,48 +116,80 @@ impl Pallet { ) { Ok(d) => d, Err(e) => { - log::warn!( - "Failed to reveal commit for subnet {} submitted by {:?} due to error decrypting the commit: {:?}", - netuid, - who, - e + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to error decrypting the commit: {e:?}" ); continue; } }; - // Decrypt the bytes into WeightsPayload - let mut reader = &decrypted_bytes[..]; - let payload: WeightsTlockPayload = match Decode::decode(&mut reader) { - Ok(w) => w, - Err(e) => { - log::warn!( - "Failed to reveal commit for subnet {} submitted by {:?} due to error deserializing WeightsPayload: {:?}", - netuid, - who, - e - ); - continue; + // ------------------------------------------------------------------ + // Try to decode payload with the new and legacy formats. + // ------------------------------------------------------------------ + let (uids, values, version_key) = { + let mut reader_new = &decrypted_bytes[..]; + if let Ok(payload) = WeightsTlockPayload::decode(&mut reader_new) { + // Verify hotkey matches committer + let mut hk_reader = &payload.hotkey[..]; + match T::AccountId::decode(&mut hk_reader) { + Ok(decoded_hotkey) if decoded_hotkey == who => { + (payload.uids, payload.values, payload.version_key) + } + Ok(_) => { + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to hotkey mismatch in payload" + ); + continue; + } + Err(e) => { + let mut reader_legacy = &decrypted_bytes[..]; + match LegacyWeightsTlockPayload::decode(&mut reader_legacy) { + Ok(legacy) => (legacy.uids, legacy.values, legacy.version_key), + Err(_) => { + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to error deserializing hotkey: {e:?}" + ); + continue; + } + } + } + } + } else { + // Fallback to legacy payload + let mut reader_legacy = &decrypted_bytes[..]; + match LegacyWeightsTlockPayload::decode(&mut reader_legacy) { + Ok(legacy) => (legacy.uids, legacy.values, legacy.version_key), + Err(e) => { + log::trace!( + "Failed to reveal commit for subnet {netuid} submitted by {who:?} due to error deserializing both payload formats: {e:?}" + ); + continue; + } + } } }; + // ------------------------------------------------------------------ + // Apply weights + // ------------------------------------------------------------------ if let Err(e) = Self::do_set_weights( T::RuntimeOrigin::signed(who.clone()), netuid, - payload.uids, - payload.values, - payload.version_key, + uids, + values, + version_key, ) { - log::warn!( - "Failed to `do_set_weights` for subnet {} submitted by {:?}: {:?}", - netuid, - who, - e + log::trace!( + "Failed to `do_set_weights` for subnet {netuid} submitted by {who:?}: {e:?}" ); continue; - } else { - Self::deposit_event(Event::CRV3WeightsRevealed(netuid, who)); - }; + } + + Self::deposit_event(Event::CRV3WeightsRevealed(netuid, who)); + } + + if !unrevealed.is_empty() { + CRV3WeightCommitsV2::::insert(netuid, reveal_epoch, unrevealed); } Ok(()) diff --git a/pallets/subtensor/src/coinbase/root.rs b/pallets/subtensor/src/coinbase/root.rs index 279132e938..fe1878f397 100644 --- a/pallets/subtensor/src/coinbase/root.rs +++ b/pallets/subtensor/src/coinbase/root.rs @@ -22,7 +22,7 @@ use frame_support::weights::Weight; use safe_math::*; use sp_core::Get; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; impl Pallet { /// Fetches the total count of root network validators @@ -60,10 +60,7 @@ impl Pallet { pub fn contains_invalid_root_uids(netuids: &[NetUid]) -> bool { for netuid in netuids { if !Self::if_subnet_exist(*netuid) { - log::debug!( - "contains_invalid_root_uids: netuid {:?} does not exist", - netuid - ); + log::debug!("contains_invalid_root_uids: netuid {netuid:?} does not exist"); return true; } } @@ -92,11 +89,7 @@ impl Pallet { // --- 1. Ensure that the call originates from a signed source and retrieve the caller's account ID (coldkey). let coldkey = ensure_signed(origin)?; - log::debug!( - "do_root_register( coldkey: {:?}, hotkey: {:?} )", - coldkey, - hotkey - ); + log::debug!("do_root_register( coldkey: {coldkey:?}, hotkey: {hotkey:?} )"); // --- 2. Ensure that the number of registrations in this block doesn't exceed the allowed limit. ensure!( @@ -135,7 +128,7 @@ impl Pallet { // --- 12.1.2 Add the new account and make them a member of the Senate. Self::append_neuron(NetUid::ROOT, &hotkey, current_block_number); - log::debug!("add new neuron: {:?} on uid {:?}", hotkey, subnetwork_uid); + log::debug!("add new neuron: {hotkey:?} on uid {subnetwork_uid:?}"); } else { // --- 13.1.1 The network is full. Perform replacement. // Find the neuron with the lowest stake value to replace. @@ -165,10 +158,7 @@ impl Pallet { Self::replace_neuron(NetUid::ROOT, lowest_uid, &hotkey, current_block_number); log::debug!( - "replace neuron: {:?} with {:?} on uid {:?}", - replaced_hotkey, - hotkey, - subnetwork_uid + "replace neuron: {replaced_hotkey:?} with {hotkey:?} on uid {subnetwork_uid:?}" ); } @@ -226,11 +216,7 @@ impl Pallet { // --- 1. Ensure that the call originates from a signed source and retrieve the caller's account ID (coldkey). let coldkey = ensure_signed(origin)?; - log::debug!( - "do_root_register( coldkey: {:?}, hotkey: {:?} )", - coldkey, - hotkey - ); + log::debug!("do_root_register( coldkey: {coldkey:?}, hotkey: {hotkey:?} )"); // --- 2. Check if the hotkey is already registered to the root network. If not, error out. ensure!( @@ -256,11 +242,7 @@ impl Pallet { } // --- 5. Log and announce the successful Senate adjustment. - log::debug!( - "SenateAdjusted(old_hotkey:{:?} hotkey:{:?})", - replaced, - hotkey - ); + log::debug!("SenateAdjusted(old_hotkey:{replaced:?} hotkey:{hotkey:?})"); Self::deposit_event(Event::SenateAdjusted { old_member: replaced.cloned(), new_member: hotkey, @@ -405,7 +387,7 @@ impl Pallet { Self::remove_network(netuid); // --- 6. Emit the NetworkRemoved event. - log::debug!("NetworkRemoved( netuid:{:?} )", netuid); + log::debug!("NetworkRemoved( netuid:{netuid:?} )"); Self::deposit_event(Event::NetworkRemoved(netuid)); // --- 7. Return success. @@ -427,7 +409,7 @@ impl Pallet { pub fn remove_network(netuid: NetUid) { // --- 1. Return balance to subnet owner. let owner_coldkey: T::AccountId = SubnetOwner::::get(netuid); - let reserved_amount: u64 = Self::get_subnet_locked_balance(netuid); + let reserved_amount = Self::get_subnet_locked_balance(netuid); // --- 2. Remove network count. SubnetworkN::::remove(netuid); @@ -502,8 +484,8 @@ impl Pallet { BurnRegistrationsThisInterval::::remove(netuid); // --- 12. Add the balance back to the owner. - Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount); - Self::set_subnet_locked_balance(netuid, 0); + Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount.into()); + Self::set_subnet_locked_balance(netuid, TaoCurrency::ZERO); SubnetOwner::::remove(netuid); // --- 13. Remove subnet identity if it exists. @@ -532,18 +514,20 @@ impl Pallet { /// * 'u64': /// - The lock cost for the network. /// - pub fn get_network_lock_cost() -> u64 { + pub fn get_network_lock_cost() -> TaoCurrency { let last_lock = Self::get_network_last_lock(); let min_lock = Self::get_network_min_lock(); let last_lock_block = Self::get_network_last_lock_block(); let current_block = Self::get_current_block_as_u64(); let lock_reduction_interval = Self::get_lock_reduction_interval(); - let mult = if last_lock_block == 0 { 1 } else { 2 }; + let mult: TaoCurrency = if last_lock_block == 0 { 1 } else { 2 }.into(); let mut lock_cost = last_lock.saturating_mul(mult).saturating_sub( last_lock + .to_u64() .safe_div(lock_reduction_interval) - .saturating_mul(current_block.saturating_sub(last_lock_block)), + .saturating_mul(current_block.saturating_sub(last_lock_block)) + .into(), ); if lock_cost < min_lock { @@ -551,14 +535,7 @@ impl Pallet { } log::debug!( - "last_lock: {:?}, min_lock: {:?}, last_lock_block: {:?}, lock_reduction_interval: {:?}, current_block: {:?}, mult: {:?} lock_cost: {:?}", - last_lock, - min_lock, - last_lock_block, - lock_reduction_interval, - current_block, - mult, - lock_cost + "last_lock: {last_lock:?}, min_lock: {min_lock:?}, last_lock_block: {last_lock_block:?}, lock_reduction_interval: {lock_reduction_interval:?}, current_block: {current_block:?}, mult: {mult:?} lock_cost: {lock_cost:?}" ); lock_cost @@ -574,17 +551,17 @@ impl Pallet { NetworkImmunityPeriod::::set(net_immunity_period); Self::deposit_event(Event::NetworkImmunityPeriodSet(net_immunity_period)); } - pub fn set_network_min_lock(net_min_lock: u64) { + pub fn set_network_min_lock(net_min_lock: TaoCurrency) { NetworkMinLockCost::::set(net_min_lock); Self::deposit_event(Event::NetworkMinLockCostSet(net_min_lock)); } - pub fn get_network_min_lock() -> u64 { + pub fn get_network_min_lock() -> TaoCurrency { NetworkMinLockCost::::get() } - pub fn set_network_last_lock(net_last_lock: u64) { + pub fn set_network_last_lock(net_last_lock: TaoCurrency) { NetworkLastLockCost::::set(net_last_lock); } - pub fn get_network_last_lock() -> u64 { + pub fn get_network_last_lock() -> TaoCurrency { NetworkLastLockCost::::get() } pub fn get_network_last_lock_block() -> u64 { @@ -600,8 +577,11 @@ impl Pallet { pub fn get_lock_reduction_interval() -> u64 { let interval: I64F64 = I64F64::saturating_from_num(NetworkLockReductionInterval::::get()); - let block_emission: I64F64 = - I64F64::saturating_from_num(Self::get_block_emission().unwrap_or(1_000_000_000)); + let block_emission: I64F64 = I64F64::saturating_from_num( + Self::get_block_emission() + .unwrap_or(1_000_000_000.into()) + .to_u64(), + ); let halving: I64F64 = block_emission .checked_div(I64F64::saturating_from_num(1_000_000_000)) .unwrap_or(I64F64::saturating_from_num(0.0)); diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index 4551365848..551883653b 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -2,7 +2,7 @@ use super::*; use alloc::collections::BTreeMap; use safe_math::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; use subtensor_swap_interface::SwapHandler; // Distribute dividends to each hotkey @@ -22,21 +22,21 @@ impl Pallet { pub fn run_coinbase(block_emission: U96F32) { // --- 0. Get current block. let current_block: u64 = Self::get_current_block_as_u64(); - log::debug!("Current block: {:?}", current_block); + log::debug!("Current block: {current_block:?}"); // --- 1. Get all netuids (filter out root) let subnets: Vec = Self::get_all_subnet_netuids() .into_iter() .filter(|netuid| *netuid != NetUid::ROOT) .collect(); - log::debug!("All subnet netuids: {:?}", subnets); + log::debug!("All subnet netuids: {subnets:?}"); // Filter out subnets with no first emission block number. let subnets_to_emit_to: Vec = subnets .clone() .into_iter() .filter(|netuid| FirstEmissionBlockNumber::::get(*netuid).is_some()) .collect(); - log::debug!("Subnets to emit to: {:?}", subnets_to_emit_to); + log::debug!("Subnets to emit to: {subnets_to_emit_to:?}"); // --- 2. Get sum of tao reserves ( in a later version we will switch to prices. ) let mut total_moving_prices = U96F32::saturating_from_num(0.0); @@ -46,7 +46,7 @@ impl Pallet { total_moving_prices = total_moving_prices.saturating_add(Self::get_moving_alpha_price(*netuid_i)); } - log::debug!("total_moving_prices: {:?}", total_moving_prices); + log::debug!("total_moving_prices: {total_moving_prices:?}"); // --- 3. Get subnet terms (tao_in, alpha_in, and alpha_out) // Computation is described in detail in the dtao whitepaper. @@ -58,25 +58,25 @@ impl Pallet { for netuid_i in subnets_to_emit_to.iter() { // Get subnet price. let price_i = T::SwapInterface::current_alpha_price((*netuid_i).into()); - log::debug!("price_i: {:?}", price_i); + log::debug!("price_i: {price_i:?}"); // Get subnet TAO. let moving_price_i: U96F32 = Self::get_moving_alpha_price(*netuid_i); - log::debug!("moving_price_i: {:?}", moving_price_i); + log::debug!("moving_price_i: {moving_price_i:?}"); // Emission is price over total. let default_tao_in_i: U96F32 = block_emission .saturating_mul(moving_price_i) .checked_div(total_moving_prices) .unwrap_or(asfloat!(0.0)); - log::debug!("default_tao_in_i: {:?}", default_tao_in_i); + log::debug!("default_tao_in_i: {default_tao_in_i:?}"); // Get alpha_emission total let alpha_emission_i: U96F32 = asfloat!( Self::get_block_emission_for_issuance(Self::get_alpha_issuance(*netuid_i).into()) .unwrap_or(0) ); - log::debug!("alpha_emission_i: {:?}", alpha_emission_i); + log::debug!("alpha_emission_i: {alpha_emission_i:?}"); // Get initial alpha_in - let alpha_in_i: U96F32; + let mut alpha_in_i: U96F32; let mut tao_in_i: U96F32; let tao_in_ratio: U96F32 = default_tao_in_i.safe_div_or( U96F32::saturating_from_num(block_emission), @@ -89,8 +89,8 @@ impl Pallet { // Difference becomes buy. let buy_swap_result = Self::swap_tao_for_alpha( *netuid_i, - tou64!(difference_tao), - T::SwapInterface::max_price(), + tou64!(difference_tao).into(), + T::SwapInterface::max_price().into(), true, ); if let Ok(buy_swap_result_ok) = buy_swap_result { @@ -105,24 +105,26 @@ impl Pallet { alpha_in_i = tao_in_i.safe_div_or(price_i, alpha_emission_i); is_subsidized.insert(*netuid_i, false); } - log::debug!("alpha_in_i: {:?}", alpha_in_i); + log::debug!("alpha_in_i: {alpha_in_i:?}"); // Get alpha_out. - let alpha_out_i = alpha_emission_i; + let mut alpha_out_i = alpha_emission_i; // Only emit TAO if the subnetwork allows registration. if !Self::get_network_registration_allowed(*netuid_i) && !Self::get_network_pow_registration_allowed(*netuid_i) { tao_in_i = asfloat!(0.0); + alpha_in_i = asfloat!(0.0); + alpha_out_i = asfloat!(0.0); } // Insert values into maps tao_in.insert(*netuid_i, tao_in_i); alpha_in.insert(*netuid_i, alpha_in_i); alpha_out.insert(*netuid_i, alpha_out_i); } - log::debug!("tao_in: {:?}", tao_in); - log::debug!("alpha_in: {:?}", alpha_in); - log::debug!("alpha_out: {:?}", alpha_out); + log::debug!("tao_in: {tao_in:?}"); + log::debug!("alpha_in: {alpha_in:?}"); + log::debug!("alpha_out: {alpha_out:?}"); // --- 4. Injection. // Actually perform the injection of alpha_in, alpha_out and tao_in into the subnet pool. @@ -143,16 +145,17 @@ impl Pallet { *total = total.saturating_add(alpha_out_i); }); // Inject TAO in. - let tao_in_i: u64 = tou64!(*tao_in.get(netuid_i).unwrap_or(&asfloat!(0))); - SubnetTaoInEmission::::insert(*netuid_i, tao_in_i); + let tao_in_i: TaoCurrency = + tou64!(*tao_in.get(netuid_i).unwrap_or(&asfloat!(0))).into(); + SubnetTaoInEmission::::insert(*netuid_i, TaoCurrency::from(tao_in_i)); SubnetTAO::::mutate(*netuid_i, |total| { - *total = total.saturating_add(tao_in_i); + *total = total.saturating_add(tao_in_i.into()); }); TotalStake::::mutate(|total| { - *total = total.saturating_add(tao_in_i); + *total = total.saturating_add(tao_in_i.into()); }); TotalIssuance::::mutate(|total| { - *total = total.saturating_add(tao_in_i); + *total = total.saturating_add(tao_in_i.into()); }); // Adjust protocol liquidity based on new reserves T::SwapInterface::adjust_protocol_liquidity(*netuid_i, tao_in_i, alpha_in_i); @@ -166,10 +169,10 @@ impl Pallet { for netuid_i in subnets_to_emit_to.iter() { // Get alpha out. let alpha_out_i: U96F32 = *alpha_out.get(netuid_i).unwrap_or(&asfloat!(0)); - log::debug!("alpha_out_i: {:?}", alpha_out_i); + log::debug!("alpha_out_i: {alpha_out_i:?}"); // Calculate the owner cut. let owner_cut_i: U96F32 = alpha_out_i.saturating_mul(cut_percent); - log::debug!("owner_cut_i: {:?}", owner_cut_i); + log::debug!("owner_cut_i: {owner_cut_i:?}"); // Save owner cut. *owner_cuts.entry(*netuid_i).or_insert(asfloat!(0)) = owner_cut_i; // Save new alpha_out. @@ -185,44 +188,44 @@ impl Pallet { for netuid_i in subnets_to_emit_to.iter() { // Get remaining alpha out. let alpha_out_i: U96F32 = *alpha_out.get(netuid_i).unwrap_or(&asfloat!(0.0)); - log::debug!("alpha_out_i: {:?}", alpha_out_i); + log::debug!("alpha_out_i: {alpha_out_i:?}"); // Get total TAO on root. let root_tao: U96F32 = asfloat!(SubnetTAO::::get(NetUid::ROOT)); - log::debug!("root_tao: {:?}", root_tao); + log::debug!("root_tao: {root_tao:?}"); // Get total ALPHA on subnet. let alpha_issuance: U96F32 = asfloat!(Self::get_alpha_issuance(*netuid_i)); - log::debug!("alpha_issuance: {:?}", alpha_issuance); + log::debug!("alpha_issuance: {alpha_issuance:?}"); // Get tao_weight let tao_weight: U96F32 = root_tao.saturating_mul(Self::get_tao_weight()); - log::debug!("tao_weight: {:?}", tao_weight); + log::debug!("tao_weight: {tao_weight:?}"); // Get root proportional dividends. let root_proportion: U96F32 = tao_weight .checked_div(tao_weight.saturating_add(alpha_issuance)) .unwrap_or(asfloat!(0.0)); - log::debug!("root_proportion: {:?}", root_proportion); + log::debug!("root_proportion: {root_proportion:?}"); // Get root proportion of alpha_out dividends. let root_alpha: U96F32 = root_proportion .saturating_mul(alpha_out_i) // Total alpha emission per block remaining. .saturating_mul(asfloat!(0.5)); // 50% to validators. // Remove root alpha from alpha_out. - log::debug!("root_alpha: {:?}", root_alpha); + log::debug!("root_alpha: {root_alpha:?}"); // Get pending alpha as original alpha_out - root_alpha. let pending_alpha: U96F32 = alpha_out_i.saturating_sub(root_alpha); - log::debug!("pending_alpha: {:?}", pending_alpha); + log::debug!("pending_alpha: {pending_alpha:?}"); // Sell root emission through the pool (do not pay fees) let subsidized: bool = *is_subsidized.get(netuid_i).unwrap_or(&false); if !subsidized { let swap_result = Self::swap_alpha_for_tao( *netuid_i, tou64!(root_alpha).into(), - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), true, ); if let Ok(ok_result) = swap_result { let root_tao: u64 = ok_result.amount_paid_out; // Accumulate root divs for subnet. PendingRootDivs::::mutate(*netuid_i, |total| { - *total = total.saturating_add(root_tao); + *total = total.saturating_add(root_tao.into()); }); } } @@ -246,16 +249,12 @@ impl Pallet { // --- 7. Drain pending emission through the subnet based on tempo. // Run the epoch for *all* subnets, even if we don't emit anything. for &netuid in subnets.iter() { + // Reveal matured weights. + if let Err(e) = Self::reveal_crv3_commits(netuid) { + log::warn!("Failed to reveal commits for subnet {netuid} due to error: {e:?}"); + }; // Pass on subnets that have not reached their tempo. if Self::should_run_epoch(netuid, current_block) { - if let Err(e) = Self::reveal_crv3_commits(netuid) { - log::warn!( - "Failed to reveal commits for subnet {} due to error: {:?}", - netuid, - e - ); - }; - // Restart counters. BlocksSinceLastStep::::insert(netuid, 0); LastMechansimStepBlock::::insert(netuid, current_block); @@ -266,7 +265,7 @@ impl Pallet { // Get and drain the subnet pending root divs. let pending_tao = PendingRootDivs::::get(netuid); - PendingRootDivs::::insert(netuid, 0); + PendingRootDivs::::insert(netuid, TaoCurrency::ZERO); // Get this amount as alpha that was swapped for pending root divs. let pending_swapped = PendingAlphaSwapped::::get(netuid); @@ -318,15 +317,15 @@ impl Pallet { .or_insert(asfloat!(parent_div)); } } - log::debug!("incentives: {:?}", incentives); - log::debug!("dividends: {:?}", dividends); + log::debug!("incentives: {incentives:?}"); + log::debug!("dividends: {dividends:?}"); (incentives, dividends) } pub fn calculate_dividend_distribution( pending_alpha: AlphaCurrency, - pending_tao: u64, + pending_tao: TaoCurrency, tao_weight: U96F32, stake_map: BTreeMap, dividends: BTreeMap, @@ -334,11 +333,11 @@ impl Pallet { BTreeMap, BTreeMap, ) { - log::debug!("dividends: {:?}", dividends); - log::debug!("stake_map: {:?}", stake_map); - log::debug!("pending_alpha: {:?}", pending_alpha); - log::debug!("pending_tao: {:?}", pending_tao); - log::debug!("tao_weight: {:?}", tao_weight); + log::debug!("dividends: {dividends:?}"); + log::debug!("stake_map: {stake_map:?}"); + log::debug!("pending_alpha: {pending_alpha:?}"); + log::debug!("pending_tao: {pending_tao:?}"); + log::debug!("tao_weight: {tao_weight:?}"); // Setup. let zero: U96F32 = asfloat!(0.0); @@ -384,45 +383,45 @@ impl Pallet { total_root_divs = total_root_divs.saturating_add(root_divs); } } - log::debug!("alpha_dividends: {:?}", alpha_dividends); - log::debug!("root_dividends: {:?}", root_dividends); - log::debug!("total_root_divs: {:?}", total_root_divs); - log::debug!("total_alpha_divs: {:?}", total_alpha_divs); + log::debug!("alpha_dividends: {alpha_dividends:?}"); + log::debug!("root_dividends: {root_dividends:?}"); + log::debug!("total_root_divs: {total_root_divs:?}"); + log::debug!("total_alpha_divs: {total_alpha_divs:?}"); // Compute root divs as TAO. Here we take let mut tao_dividends: BTreeMap = BTreeMap::new(); for (hotkey, root_divs) in root_dividends { // Root proportion. let root_share: U96F32 = root_divs.checked_div(total_root_divs).unwrap_or(zero); - log::debug!("hotkey: {:?}, root_share: {:?}", hotkey, root_share); + log::debug!("hotkey: {hotkey:?}, root_share: {root_share:?}"); // Root proportion in TAO let root_tao: U96F32 = asfloat!(pending_tao).saturating_mul(root_share); - log::debug!("hotkey: {:?}, root_tao: {:?}", hotkey, root_tao); + log::debug!("hotkey: {hotkey:?}, root_tao: {root_tao:?}"); // Record root dividends as TAO. tao_dividends .entry(hotkey) .and_modify(|e| *e = root_tao) .or_insert(root_tao); } - log::debug!("tao_dividends: {:?}", tao_dividends); + log::debug!("tao_dividends: {tao_dividends:?}"); // Compute proportional alpha divs using the pending alpha and total alpha divs from the epoch. let mut prop_alpha_dividends: BTreeMap = BTreeMap::new(); for (hotkey, alpha_divs) in alpha_dividends { // Alpha proportion. let alpha_share: U96F32 = alpha_divs.checked_div(total_alpha_divs).unwrap_or(zero); - log::debug!("hotkey: {:?}, alpha_share: {:?}", hotkey, alpha_share); + log::debug!("hotkey: {hotkey:?}, alpha_share: {alpha_share:?}"); // Compute the proportional pending_alpha to this hotkey. let prop_alpha = asfloat!(pending_alpha).saturating_mul(alpha_share); - log::debug!("hotkey: {:?}, prop_alpha: {:?}", hotkey, prop_alpha); + log::debug!("hotkey: {hotkey:?}, prop_alpha: {prop_alpha:?}"); // Record the proportional alpha dividends. prop_alpha_dividends .entry(hotkey.clone()) .and_modify(|e| *e = prop_alpha) .or_insert(prop_alpha); } - log::debug!("prop_alpha_dividends: {:?}", prop_alpha_dividends); + log::debug!("prop_alpha_dividends: {prop_alpha_dividends:?}"); (prop_alpha_dividends, tao_dividends) } @@ -439,10 +438,7 @@ impl Pallet { if let Ok(owner_hotkey) = SubnetOwnerHotkey::::try_get(netuid) { // Increase stake for owner hotkey and coldkey. log::debug!( - "owner_hotkey: {:?} owner_coldkey: {:?}, owner_cut: {:?}", - owner_hotkey, - owner_coldkey, - owner_cut + "owner_hotkey: {owner_hotkey:?} owner_coldkey: {owner_coldkey:?}, owner_cut: {owner_cut:?}" ); let real_owner_cut = Self::increase_stake_for_hotkey_and_coldkey_on_subnet( &owner_hotkey, @@ -459,14 +455,12 @@ impl Pallet { // Distribute mining incentives. for (hotkey, incentive) in incentives { - log::debug!("incentives: hotkey: {:?}", incentive); + log::debug!("incentives: hotkey: {incentive:?}"); if let Ok(owner_hotkey) = SubnetOwnerHotkey::::try_get(netuid) { if hotkey == owner_hotkey { log::debug!( - "incentives: hotkey: {:?} is SN owner hotkey, skipping {:?}", - hotkey, - incentive + "incentives: hotkey: {hotkey:?} is SN owner hotkey, skipping {incentive:?}" ); continue; // Skip/burn miner-emission for SN owner hotkey. } @@ -489,7 +483,7 @@ impl Pallet { // Remove take prop from alpha_divs alpha_divs = alpha_divs.saturating_sub(alpha_take); // Give the validator their take. - log::debug!("hotkey: {:?} alpha_take: {:?}", hotkey, alpha_take); + log::debug!("hotkey: {hotkey:?} alpha_take: {alpha_take:?}"); Self::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &Owner::::get(&hotkey), @@ -497,7 +491,7 @@ impl Pallet { tou64!(alpha_take).into(), ); // Give all other nominators. - log::debug!("hotkey: {:?} alpha_divs: {:?}", hotkey, alpha_divs); + log::debug!("hotkey: {hotkey:?} alpha_divs: {alpha_divs:?}"); Self::increase_stake_for_hotkey_on_subnet(&hotkey, netuid, tou64!(alpha_divs).into()); // Record dividends for this hotkey. AlphaDividendsPerSubnet::::mutate(netuid, &hotkey, |divs| { @@ -517,7 +511,7 @@ impl Pallet { // Remove take prop from root_tao root_tao = root_tao.saturating_sub(tao_take); // Give the validator their take. - log::debug!("hotkey: {:?} tao_take: {:?}", hotkey, tao_take); + log::debug!("hotkey: {hotkey:?} tao_take: {tao_take:?}"); let validator_stake = Self::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &Owner::::get(hotkey.clone()), @@ -525,7 +519,7 @@ impl Pallet { tou64!(tao_take).into(), ); // Give rest to nominators. - log::debug!("hotkey: {:?} root_tao: {:?}", hotkey, root_tao); + log::debug!("hotkey: {hotkey:?} root_tao: {root_tao:?}"); Self::increase_stake_for_hotkey_on_subnet( &hotkey, NetUid::ROOT, @@ -533,13 +527,13 @@ impl Pallet { ); // Record root dividends for this validator on this subnet. TaoDividendsPerSubnet::::mutate(netuid, hotkey.clone(), |divs| { - *divs = divs.saturating_add(tou64!(root_tao)); + *divs = divs.saturating_add(tou64!(root_tao).into()); }); // Update the total TAO on the subnet with root tao dividends. SubnetTAO::::mutate(NetUid::ROOT, |total| { *total = total - .saturating_add(validator_stake.to_u64()) - .saturating_add(tou64!(root_tao)); + .saturating_add(validator_stake.to_u64().into()) + .saturating_add(tou64!(root_tao).into()); }); } } @@ -561,7 +555,7 @@ impl Pallet { pub fn calculate_dividend_and_incentive_distribution( netuid: NetUid, - pending_tao: u64, + pending_tao: TaoCurrency, pending_validator_alpha: AlphaCurrency, hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)>, tao_weight: U96F32, @@ -591,17 +585,12 @@ impl Pallet { pub fn drain_pending_emission( netuid: NetUid, pending_alpha: AlphaCurrency, - pending_tao: u64, + pending_tao: TaoCurrency, pending_swapped: AlphaCurrency, owner_cut: AlphaCurrency, ) { log::debug!( - "Draining pending alpha emission for netuid {:?}, pending_alpha: {:?}, pending_tao: {:?}, pending_swapped: {:?}, owner_cut: {:?}", - netuid, - pending_alpha, - pending_tao, - pending_swapped, - owner_cut + "Draining pending alpha emission for netuid {netuid:?}, pending_alpha: {pending_alpha:?}, pending_tao: {pending_tao:?}, pending_swapped: {pending_swapped:?}, owner_cut: {owner_cut:?}" ); let tao_weight = Self::get_tao_weight(); @@ -609,7 +598,7 @@ impl Pallet { // Run the epoch. let hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> = Self::epoch(netuid, pending_alpha.saturating_add(pending_swapped)); - log::debug!("hotkey_emission: {:?}", hotkey_emission); + log::debug!("hotkey_emission: {hotkey_emission:?}"); // Compute the pending validator alpha. // This is the total alpha being injected, @@ -621,7 +610,7 @@ impl Pallet { .fold(AlphaCurrency::default(), |acc, (_, incentive, _)| { acc.saturating_add(*incentive) }); - log::debug!("incentive_sum: {:?}", incentive_sum); + log::debug!("incentive_sum: {incentive_sum:?}"); let pending_validator_alpha = if !incentive_sum.is_zero() { pending_alpha @@ -711,11 +700,7 @@ impl Pallet { let childkey_take_proportion: U96F32 = U96F32::saturating_from_num(Self::get_childkey_take(hotkey, netuid)) .safe_div(U96F32::saturating_from_num(u16::MAX)); - log::debug!( - "Childkey take proportion: {:?} for hotkey {:?}", - childkey_take_proportion, - hotkey - ); + log::debug!("Childkey take proportion: {childkey_take_proportion:?} for hotkey {hotkey:?}"); // NOTE: Only the validation emission should be split amongst parents. // Grab the owner of the childkey. @@ -735,10 +720,7 @@ impl Pallet { // Get self contribution, removing any childkey proportions. let self_contribution = Self::get_self_contribution(hotkey, netuid); log::debug!( - "Self contribution for hotkey {:?} on netuid {:?}: {:?}", - hotkey, - netuid, - self_contribution + "Self contribution for hotkey {hotkey:?} on netuid {netuid:?}: {self_contribution:?}" ); // Add self contribution to total contribution but not to the parent contributions. total_contribution = @@ -770,10 +752,7 @@ impl Pallet { // Store the parent's contributions for later use parent_contributions.push((parent.clone(), combined_contribution)); log::debug!( - "Parent contribution for hotkey {:?} from parent {:?}: {:?}", - hotkey, - parent, - combined_contribution + "Parent contribution for hotkey {hotkey:?} from parent {parent:?}: {combined_contribution:?}" ); } @@ -808,17 +787,9 @@ impl Pallet { total_child_emission_take = total_child_emission_take.saturating_add(child_emission_take); - log::debug!( - "Child emission take: {:?} for hotkey {:?}", - child_emission_take, - hotkey - ); - log::debug!( - "Parent emission: {:?} for hotkey {:?}", - parent_emission, - hotkey - ); - log::debug!("remaining emission: {:?}", remaining_emission); + log::debug!("Child emission take: {child_emission_take:?} for hotkey {hotkey:?}"); + log::debug!("Parent emission: {parent_emission:?} for hotkey {hotkey:?}"); + log::debug!("remaining emission: {remaining_emission:?}"); // Add the parent's emission to the distribution list dividend_tuples.push(( @@ -829,13 +800,7 @@ impl Pallet { // Keep track of total emission distributed to parents to_parents = to_parents.saturating_add(parent_emission.saturating_to_num::()); log::debug!( - "Parent contribution for parent {:?} with contribution: {:?}, of total: {:?} ({:?}), of emission: {:?} gets: {:?}", - parent, - contribution, - total_contribution, - emission_factor, - validating_emission, - parent_emission, + "Parent contribution for parent {parent:?} with contribution: {contribution:?}, of total: {total_contribution:?} ({emission_factor:?}), of emission: {validating_emission:?} gets: {parent_emission:?}", ); } // Calculate the final emission for the hotkey itself. diff --git a/pallets/subtensor/src/epoch/run_epoch.rs b/pallets/subtensor/src/epoch/run_epoch.rs index c536ffff82..ce3d3fd208 100644 --- a/pallets/subtensor/src/epoch/run_epoch.rs +++ b/pallets/subtensor/src/epoch/run_epoch.rs @@ -16,7 +16,7 @@ impl Pallet { ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { // Get subnetwork size. let n: u16 = Self::get_subnetwork_n(netuid); - log::trace!("n: {:?}", n); + log::trace!("n: {n:?}"); // ====================== // == Active & updated == @@ -24,15 +24,15 @@ impl Pallet { // Get current block. let current_block: u64 = Self::get_current_block_as_u64(); - log::trace!("current_block: {:?}", current_block); + log::trace!("current_block: {current_block:?}"); // Get tempo. let tempo: u64 = Self::get_tempo(netuid).into(); - log::trace!("tempo: {:?}", tempo); + log::trace!("tempo: {tempo:?}"); // Get activity cutoff. let activity_cutoff: u64 = Self::get_activity_cutoff(netuid) as u64; - log::trace!("activity_cutoff: {:?}", activity_cutoff); + log::trace!("activity_cutoff: {activity_cutoff:?}"); // Last update vector. let last_update: Vec = Self::get_last_update(netuid); @@ -112,19 +112,19 @@ impl Pallet { // Get validator permits. let validator_permits: Vec = Self::get_validator_permit(netuid); - log::trace!("validator_permits: {:?}", validator_permits); + log::trace!("validator_permits: {validator_permits:?}"); // Logical negation of validator_permits. let validator_forbids: Vec = validator_permits.iter().map(|&b| !b).collect(); // Get max allowed validators. let max_allowed_validators: u16 = Self::get_max_allowed_validators(netuid); - log::trace!("max_allowed_validators: {:?}", max_allowed_validators); + log::trace!("max_allowed_validators: {max_allowed_validators:?}"); // Get new validator permits. let new_validator_permits: Vec = is_topk_nonzero(&stake, max_allowed_validators as usize); - log::trace!("new_validator_permits: {:?}", new_validator_permits); + log::trace!("new_validator_permits: {new_validator_permits:?}"); // ================== // == Active Stake == @@ -448,7 +448,7 @@ impl Pallet { ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { // Get subnetwork size. let n = Self::get_subnetwork_n(netuid); - log::trace!("Number of Neurons in Network: {:?}", n); + log::trace!("Number of Neurons in Network: {n:?}"); // ====================== // == Active & updated == @@ -456,15 +456,15 @@ impl Pallet { // Get current block. let current_block: u64 = Self::get_current_block_as_u64(); - log::trace!("current_block: {:?}", current_block); + log::trace!("current_block: {current_block:?}"); // Get tempo. let tempo: u64 = Self::get_tempo(netuid).into(); - log::trace!("tempo:\n{:?}\n", tempo); + log::trace!("tempo:\n{tempo:?}\n"); // Get activity cutoff. let activity_cutoff: u64 = Self::get_activity_cutoff(netuid) as u64; - log::trace!("activity_cutoff: {:?}", activity_cutoff); + log::trace!("activity_cutoff: {activity_cutoff:?}"); // Last update vector. let last_update: Vec = Self::get_last_update(netuid); @@ -522,19 +522,19 @@ impl Pallet { // Get current validator permits. let validator_permits: Vec = Self::get_validator_permit(netuid); - log::trace!("validator_permits: {:?}", validator_permits); + log::trace!("validator_permits: {validator_permits:?}"); // Logical negation of validator_permits. let validator_forbids: Vec = validator_permits.iter().map(|&b| !b).collect(); // Get max allowed validators. let max_allowed_validators: u16 = Self::get_max_allowed_validators(netuid); - log::trace!("max_allowed_validators: {:?}", max_allowed_validators); + log::trace!("max_allowed_validators: {max_allowed_validators:?}"); // Get new validator permits. let new_validator_permits: Vec = is_topk_nonzero(&stake, max_allowed_validators as usize); - log::trace!("new_validator_permits: {:?}", new_validator_permits); + log::trace!("new_validator_permits: {new_validator_permits:?}"); // ================== // == Active Stake == @@ -1094,7 +1094,7 @@ impl Pallet { let ema_bonds = mat_ema_sparse(bonds_delta, bonds, alpha); // Log the computed EMA bonds for debugging purposes. - log::trace!("Exponential Moving Average Bonds Normal: {:?}", ema_bonds); + log::trace!("Exponential Moving Average Bonds Normal: {ema_bonds:?}"); // Return the computed EMA bonds. ema_bonds @@ -1128,7 +1128,7 @@ impl Pallet { let ema_bonds = mat_ema(bonds_delta, bonds, alpha); // Log the computed EMA bonds for debugging purposes. - log::trace!("Exponential Moving Average Bonds Normal: {:?}", ema_bonds); + log::trace!("Exponential Moving Average Bonds Normal: {ema_bonds:?}"); // Return the computed EMA bonds. ema_bonds @@ -1408,10 +1408,7 @@ impl Pallet { AlphaValues::::insert(netuid, (alpha_low, alpha_high)); log::debug!( - "AlphaValuesSet( netuid: {:?}, AlphaLow: {:?}, AlphaHigh: {:?} ) ", - netuid, - alpha_low, - alpha_high, + "AlphaValuesSet( netuid: {netuid:?}, AlphaLow: {alpha_low:?}, AlphaHigh: {alpha_high:?} ) ", ); Ok(()) } @@ -1435,12 +1432,10 @@ impl Pallet { .collect::>(), ); } - log::debug!("Reset bonds for {:?}, netuid {:?}", account_id, netuid); + log::debug!("Reset bonds for {account_id:?}, netuid {netuid:?}"); } else { log::warn!( - "Uid not found for {:?}, netuid {:?} - skipping bonds reset", - account_id, - netuid + "Uid not found for {account_id:?}, netuid {netuid:?} - skipping bonds reset" ); } diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index e61aae04e5..28e1248200 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -32,7 +32,7 @@ use sp_runtime::{ transaction_validity::{TransactionValidity, TransactionValidityError}, }; use sp_std::marker::PhantomData; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; // ============================ // ==== Benchmark Imports ===== @@ -92,7 +92,7 @@ pub mod pallet { use sp_std::vec::Vec; use substrate_fixed::types::{I96F32, U64F64}; use subtensor_macros::freeze_struct; - use subtensor_runtime_common::{AlphaCurrency, NetUid}; + use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; #[cfg(not(feature = "std"))] use alloc::boxed::Box; @@ -111,7 +111,7 @@ pub mod pallet { const STORAGE_VERSION: StorageVersion = StorageVersion::new(7); /// Minimum balance required to perform a coldkey swap - pub const MIN_BALANCE_TO_PERFORM_COLDKEY_SWAP: u64 = 100_000_000; // 0.1 TAO in RAO + pub const MIN_BALANCE_TO_PERFORM_COLDKEY_SWAP: TaoCurrency = TaoCurrency::new(100_000_000); // 0.1 TAO in RAO #[pallet::pallet] #[pallet::without_storage_info] @@ -281,8 +281,10 @@ pub mod pallet { /// Struct for SubnetIdentitiesV3. pub type SubnetIdentityOfV3 = SubnetIdentityV3; /// Data structure for Subnet Identities - #[crate::freeze_struct("3618af6beb882a23")] - #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] + #[crate::freeze_struct("6a441335f985a0b")] + #[derive( + Encode, Decode, DecodeWithMemTracking, Default, TypeInfo, Clone, PartialEq, Eq, Debug, + )] pub struct SubnetIdentityV3 { /// The name of the subnet pub subnet_name: Vec, @@ -311,10 +313,15 @@ pub mod pallet { pub fn DefaultZeroU64() -> u64 { 0 } - /// Default value for Alpha cyrrency. + /// Default value for Alpha currency. #[pallet::type_value] pub fn DefaultZeroAlpha() -> AlphaCurrency { - 0.into() + AlphaCurrency::ZERO + } + /// Default value for Tao currency. + #[pallet::type_value] + pub fn DefaultZeroTao() -> TaoCurrency { + TaoCurrency::ZERO } #[pallet::type_value] /// Default value for zero. @@ -392,8 +399,8 @@ pub mod pallet { } #[pallet::type_value] /// Default total issuance. - pub fn DefaultTotalIssuance() -> u64 { - T::InitialIssuance::get() + pub fn DefaultTotalIssuance() -> TaoCurrency { + T::InitialIssuance::get().into() } #[pallet::type_value] /// Default account, derived from zero trailing bytes. @@ -441,18 +448,18 @@ pub mod pallet { } #[pallet::type_value] /// Default registrations this block. - pub fn DefaultBurn() -> u64 { - T::InitialBurn::get() + pub fn DefaultBurn() -> TaoCurrency { + T::InitialBurn::get().into() } #[pallet::type_value] /// Default burn token. - pub fn DefaultMinBurn() -> u64 { - T::InitialMinBurn::get() + pub fn DefaultMinBurn() -> TaoCurrency { + T::InitialMinBurn::get().into() } #[pallet::type_value] /// Default min burn token. - pub fn DefaultMaxBurn() -> u64 { - T::InitialMaxBurn::get() + pub fn DefaultMaxBurn() -> TaoCurrency { + T::InitialMaxBurn::get().into() } #[pallet::type_value] /// Default max burn token. @@ -476,8 +483,8 @@ pub mod pallet { } #[pallet::type_value] /// Default max registrations per block. - pub fn DefaultRAORecycledForRegistration() -> u64 { - T::InitialRAORecycledForRegistration::get() + pub fn DefaultRAORecycledForRegistration() -> TaoCurrency { + T::InitialRAORecycledForRegistration::get().into() } #[pallet::type_value] /// Default number of networks. @@ -531,8 +538,8 @@ pub mod pallet { } #[pallet::type_value] /// Default value for network min lock cost. - pub fn DefaultNetworkMinLockCost() -> u64 { - T::InitialNetworkMinLockCost::get() + pub fn DefaultNetworkMinLockCost() -> TaoCurrency { + T::InitialNetworkMinLockCost::get().into() } #[pallet::type_value] /// Default value for network lock reduction interval. @@ -764,6 +771,11 @@ pub mod pallet { false } #[pallet::type_value] + /// Default value for weight commit/reveal version. + pub fn DefaultCommitRevealWeightsVersion() -> u16 { + 4 + } + #[pallet::type_value] /// Senate requirements pub fn DefaultSenateRequiredStakePercentage() -> u64 { T::InitialSenateRequiredStakePercentage::get() @@ -807,8 +819,8 @@ pub mod pallet { #[pallet::type_value] /// Default minimum stake. - pub fn DefaultMinStake() -> u64 { - 2_000_000 + pub fn DefaultMinStake() -> TaoCurrency { + 2_000_000.into() } #[pallet::type_value] @@ -998,9 +1010,9 @@ pub mod pallet { NetUid, Blake2_128Concat, T::AccountId, - u64, + TaoCurrency, ValueQuery, - DefaultZeroU64, + DefaultZeroTao, >; /// ================== @@ -1035,9 +1047,9 @@ pub mod pallet { /// Eventually, Bittensor should migrate to using Holds afterwhich time we will not require this /// separate accounting. #[pallet::storage] // --- ITEM ( total_issuance ) - pub type TotalIssuance = StorageValue<_, u64, ValueQuery, DefaultTotalIssuance>; + pub type TotalIssuance = StorageValue<_, TaoCurrency, ValueQuery, DefaultTotalIssuance>; #[pallet::storage] // --- ITEM ( total_stake ) - pub type TotalStake = StorageValue<_, u64, ValueQuery>; + pub type TotalStake = StorageValue<_, TaoCurrency, ValueQuery>; #[pallet::storage] // --- ITEM ( moving_alpha ) -- subnet moving alpha. pub type SubnetMovingAlpha = StorageValue<_, I96F32, ValueQuery, DefaultMovingAlpha>; #[pallet::storage] // --- MAP ( netuid ) --> moving_price | The subnet moving price. @@ -1048,10 +1060,10 @@ pub mod pallet { StorageMap<_, Identity, NetUid, u128, ValueQuery, DefaultZeroU128>; #[pallet::storage] // --- MAP ( netuid ) --> tao_in_subnet | Returns the amount of TAO in the subnet. pub type SubnetTAO = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultZeroTao>; #[pallet::storage] // --- MAP ( netuid ) --> tao_in_user_subnet | Returns the amount of TAO in the subnet reserve provided by users as liquidity. pub type SubnetTaoProvided = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultZeroTao>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_in_emission | Returns the amount of alph in emission into the pool per block. pub type SubnetAlphaInEmission = StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; @@ -1060,7 +1072,7 @@ pub mod pallet { StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] // --- MAP ( netuid ) --> tao_in_emission | Returns the amount of tao emitted into this subent on the last block. pub type SubnetTaoInEmission = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultZeroTao>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_supply_in_pool | Returns the amount of alpha in the pool. pub type SubnetAlphaIn = StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; @@ -1160,11 +1172,12 @@ pub mod pallet { StorageValue<_, u64, ValueQuery, DefaultNetworkLastRegistered>; #[pallet::storage] /// ITEM( min_network_lock_cost ) - pub type NetworkMinLockCost = StorageValue<_, u64, ValueQuery, DefaultNetworkMinLockCost>; + pub type NetworkMinLockCost = + StorageValue<_, TaoCurrency, ValueQuery, DefaultNetworkMinLockCost>; #[pallet::storage] /// ITEM( last_network_lock_cost ) pub type NetworkLastLockCost = - StorageValue<_, u64, ValueQuery, DefaultNetworkMinLockCost>; + StorageValue<_, TaoCurrency, ValueQuery, DefaultNetworkMinLockCost>; #[pallet::storage] /// ITEM( network_lock_reduction_interval ) pub type NetworkLockReductionInterval = @@ -1200,7 +1213,7 @@ pub mod pallet { StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultTrue>; #[pallet::storage] // --- MAP ( netuid ) --> total_subnet_locked pub type SubnetLocked = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultZeroTao>; #[pallet::storage] // --- MAP ( netuid ) --> largest_locked pub type LargestLocked = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; @@ -1264,7 +1277,7 @@ pub mod pallet { #[pallet::storage] /// --- MAP ( netuid ) --> pending_root_emission pub type PendingRootDivs = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultZeroTao>; #[pallet::storage] /// --- MAP ( netuid ) --> pending_alpha_swapped pub type PendingAlphaSwapped = @@ -1385,16 +1398,18 @@ pub mod pallet { StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultCommitRevealWeightsEnabled>; #[pallet::storage] /// --- MAP ( netuid ) --> Burn - pub type Burn = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultBurn>; + pub type Burn = StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultBurn>; #[pallet::storage] /// --- MAP ( netuid ) --> Difficulty pub type Difficulty = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultDifficulty>; #[pallet::storage] /// --- MAP ( netuid ) --> MinBurn - pub type MinBurn = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultMinBurn>; + pub type MinBurn = + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultMinBurn>; #[pallet::storage] /// --- MAP ( netuid ) --> MaxBurn - pub type MaxBurn = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultMaxBurn>; + pub type MaxBurn = + StorageMap<_, Identity, NetUid, TaoCurrency, ValueQuery, DefaultMaxBurn>; #[pallet::storage] /// --- MAP ( netuid ) --> MinDifficulty pub type MinDifficulty = @@ -1417,8 +1432,14 @@ pub mod pallet { StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultEMAPriceMovingBlocks>; #[pallet::storage] /// --- MAP ( netuid ) --> global_RAO_recycled_for_registration - pub type RAORecycledForRegistration = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultRAORecycledForRegistration>; + pub type RAORecycledForRegistration = StorageMap< + _, + Identity, + NetUid, + TaoCurrency, + ValueQuery, + DefaultRAORecycledForRegistration, + >; #[pallet::storage] /// --- ITEM ( tx_rate_limit ) pub type TxRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxRateLimit>; @@ -1631,6 +1652,7 @@ pub mod pallet { /// --- MAP ( key ) --> last_tx_block_delegate_take pub type LastTxBlockDelegateTake = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; + // FIXME: this storage is used interchangably for alpha/tao #[pallet::storage] /// ITEM( weights_min_stake ) pub type StakeThreshold = StorageValue<_, u64, ValueQuery, DefaultStakeThreshold>; @@ -1744,6 +1766,11 @@ pub mod pallet { pub type AccumulatedLeaseDividends = StorageMap<_, Twox64Concat, LeaseId, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; + #[pallet::storage] + /// --- ITEM ( CommitRevealWeightsVersion ) + pub type CommitRevealWeightsVersion = + StorageValue<_, u16, ValueQuery, DefaultCommitRevealWeightsVersion>; + /// ================== /// ==== Genesis ===== /// ================== @@ -1766,14 +1793,14 @@ pub mod pallet { /// Stakes record in genesis. pub stakes: Vec<(T::AccountId, Vec<(T::AccountId, (u64, u16))>)>, /// The total issued balance in genesis - pub balances_issuance: u64, + pub balances_issuance: TaoCurrency, } impl Default for GenesisConfig { fn default() -> Self { Self { stakes: Default::default(), - balances_issuance: 0, + balances_issuance: TaoCurrency::ZERO, } } } @@ -1793,6 +1820,8 @@ pub mod pallet { 0 } + // FIXME this function is used both to calculate for alpha stake amount as well as tao + // amount /// Returns the transaction priority for stake operations. pub fn get_priority_staking( coldkey: &T::AccountId, @@ -1888,6 +1917,7 @@ pub enum CustomTransactionError { InvalidPort, BadRequest, ZeroMaxAmount, + InvalidRevealRound, } impl From for u8 { @@ -1909,6 +1939,7 @@ impl From for u8 { CustomTransactionError::InvalidPort => 13, CustomTransactionError::BadRequest => 255, CustomTransactionError::ZeroMaxAmount => 14, + CustomTransactionError::InvalidRevealRound => 15, } } } @@ -1961,6 +1992,13 @@ where Pallet::::check_weights_min_stake(who, netuid) } + pub fn validity_ok(priority: u64) -> ValidTransaction { + ValidTransaction { + priority, + ..Default::default() + } + } + pub fn result_to_validity(result: Result<(), Error>, priority: u64) -> TransactionValidity { if let Err(err) = result { Err(match err { @@ -2037,11 +2075,7 @@ where Some(Call::commit_weights { netuid, .. }) => { if Self::check_weights_min_stake(who, *netuid) { let priority: u64 = Self::get_priority_set_weights(who, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) @@ -2050,11 +2084,7 @@ where Some(Call::reveal_weights { netuid, .. }) => { if Self::check_weights_min_stake(who, *netuid) { let priority: u64 = Self::get_priority_set_weights(who, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) @@ -2063,11 +2093,7 @@ where Some(Call::batch_reveal_weights { netuid, .. }) => { if Self::check_weights_min_stake(who, *netuid) { let priority: u64 = Self::get_priority_set_weights(who, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) @@ -2076,11 +2102,7 @@ where Some(Call::set_weights { netuid, .. }) => { if Self::check_weights_min_stake(who, *netuid) { let priority: u64 = Self::get_priority_set_weights(who, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) @@ -2089,24 +2111,39 @@ where Some(Call::set_tao_weights { netuid, hotkey, .. }) => { if Self::check_weights_min_stake(hotkey, *netuid) { let priority: u64 = Self::get_priority_set_weights(hotkey, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) } } - Some(Call::commit_crv3_weights { netuid, .. }) => { + Some(Call::commit_crv3_weights { + netuid, + reveal_round, + .. + }) => { + if Self::check_weights_min_stake(who, *netuid) { + if *reveal_round < pallet_drand::LastStoredRound::::get() { + return Err(CustomTransactionError::InvalidRevealRound.into()); + } + let priority: u64 = Pallet::::get_priority_set_weights(who, *netuid); + let validity = Self::validity_ok(priority); + Ok((validity, Some(who.clone()), origin)) + } else { + Err(CustomTransactionError::StakeAmountTooLow.into()) + } + } + Some(Call::commit_timelocked_weights { + netuid, + reveal_round, + .. + }) => { if Self::check_weights_min_stake(who, *netuid) { + if *reveal_round < pallet_drand::LastStoredRound::::get() { + return Err(CustomTransactionError::InvalidRevealRound.into()); + } let priority: u64 = Pallet::::get_priority_set_weights(who, *netuid); - let validity = ValidTransaction { - priority, - longevity: 1, - ..Default::default() - }; + let validity = Self::validity_ok(priority); Ok((validity, Some(who.clone()), origin)) } else { Err(CustomTransactionError::StakeAmountTooLow.into()) @@ -2114,243 +2151,128 @@ where } Some(Call::add_stake { hotkey, - netuid, + netuid: _, amount_staked, }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_add_stake( - who, - hotkey, - *netuid, - *amount_staked, - *amount_staked, - false, - ), - Self::get_priority_staking(who, hotkey, *amount_staked), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*amount_staked).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::add_stake_limit { hotkey, - netuid, + netuid: _, amount_staked, - limit_price, - allow_partial, + .. }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - // Calculate the maximum amount that can be executed with price limit - let Ok(max_amount) = Pallet::::get_max_amount_add(*netuid, *limit_price) else { - return Err(CustomTransactionError::ZeroMaxAmount.into()); - }; - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_add_stake( - who, - hotkey, - *netuid, - *amount_staked, - max_amount, - *allow_partial, - ), - Self::get_priority_staking(who, hotkey, *amount_staked), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*amount_staked).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::remove_stake { hotkey, - netuid, + netuid: _, amount_unstaked, }) => { - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_remove_stake( - who, - hotkey, - *netuid, - *amount_unstaked, - *amount_unstaked, - false, - ), - Self::get_priority_staking(who, hotkey, (*amount_unstaked).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*amount_unstaked).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::remove_stake_limit { hotkey, - netuid, + netuid: _, amount_unstaked, - limit_price, - allow_partial, + .. }) => { - // Calculate the maximum amount that can be executed with price limit - let Ok(max_amount) = Pallet::::get_max_amount_remove(*netuid, *limit_price) - else { - return Err(CustomTransactionError::ZeroMaxAmount.into()); - }; - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_remove_stake( - who, - hotkey, - *netuid, - *amount_unstaked, - max_amount, - *allow_partial, - ), - Self::get_priority_staking(who, hotkey, (*amount_unstaked).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) - } - Some(Call::unstake_all { hotkey }) => { - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_unstake_all(who, hotkey, false), - Self::get_priority_vanilla(), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) - } - Some(Call::unstake_all_alpha { hotkey }) => { - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_unstake_all(who, hotkey, true), - Self::get_priority_vanilla(), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*amount_unstaked).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::move_stake { origin_hotkey, - destination_hotkey, - origin_netuid, - destination_netuid, + destination_hotkey: _, + origin_netuid: _, + destination_netuid: _, alpha_amount, }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_stake_transition( - who, - who, - origin_hotkey, - destination_hotkey, - *origin_netuid, - *destination_netuid, - *alpha_amount, - *alpha_amount, - None, - false, - ), - Self::get_priority_staking(who, origin_hotkey, (*alpha_amount).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + origin_hotkey, + (*alpha_amount).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::transfer_stake { - destination_coldkey, + destination_coldkey: _, hotkey, - origin_netuid, - destination_netuid, + origin_netuid: _, + destination_netuid: _, alpha_amount, }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_stake_transition( - who, - destination_coldkey, - hotkey, - hotkey, - *origin_netuid, - *destination_netuid, - *alpha_amount, - *alpha_amount, - None, - true, - ), - Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*alpha_amount).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::swap_stake { hotkey, - origin_netuid, - destination_netuid, + origin_netuid: _, + destination_netuid: _, alpha_amount, }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_stake_transition( - who, - who, - hotkey, - hotkey, - *origin_netuid, - *destination_netuid, - *alpha_amount, - *alpha_amount, - None, - false, - ), - Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*alpha_amount).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::swap_stake_limit { hotkey, - origin_netuid, - destination_netuid, + origin_netuid: _, + destination_netuid: _, alpha_amount, - limit_price, - allow_partial, + .. }) => { if ColdkeySwapScheduled::::contains_key(who) { return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } - // Get the max amount possible to exchange - let Ok(max_amount) = Pallet::::get_max_amount_move( - *origin_netuid, - *destination_netuid, - *limit_price, - ) else { - return Err(CustomTransactionError::ZeroMaxAmount.into()); - }; - - // Fully validate the user input - Self::result_to_validity( - Pallet::::validate_stake_transition( - who, - who, - hotkey, - hotkey, - *origin_netuid, - *destination_netuid, - *alpha_amount, - max_amount, - Some(*allow_partial), - false, - ), - Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), - ) - .map(|validity| (validity, Some(who.clone()), origin.clone())) + let validity = Self::validity_ok(Self::get_priority_staking( + who, + hotkey, + (*alpha_amount).into(), + )); + Ok((validity, Some(who.clone()), origin)) } Some(Call::register { netuid, .. } | Call::burned_register { netuid, .. }) => { if ColdkeySwapScheduled::::contains_key(who) { @@ -2373,21 +2295,14 @@ where Ok((validity, Some(who.clone()), origin)) } Some(Call::register_network { .. }) => { - let validity = ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }; - + let validity = Self::validity_ok(Self::get_priority_vanilla()); Ok((validity, Some(who.clone()), origin)) } Some(Call::dissolve_network { .. }) => { if ColdkeySwapScheduled::::contains_key(who) { Err(CustomTransactionError::ColdkeyInSwapSchedule.into()) } else { - let validity = ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }; + let validity = Self::validity_ok(Self::get_priority_vanilla()); Ok((validity, Some(who.clone()), origin)) } } @@ -2429,10 +2344,7 @@ where return Err(CustomTransactionError::ColdkeyInSwapSchedule.into()); } } - let validity = ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }; + let validity = Self::validity_ok(Self::get_priority_vanilla()); Ok((validity, Some(who.clone()), origin)) } } @@ -2587,7 +2499,7 @@ impl CollectiveInterface for () { impl> subtensor_runtime_common::SubnetInfo for Pallet { - fn tao_reserve(netuid: NetUid) -> u64 { + fn tao_reserve(netuid: NetUid) -> TaoCurrency { SubnetTAO::::get(netuid).saturating_add(SubnetTaoProvided::::get(netuid)) } @@ -2611,8 +2523,8 @@ impl> impl> subtensor_runtime_common::BalanceOps for Pallet { - fn tao_balance(account_id: &T::AccountId) -> u64 { - pallet_balances::Pallet::::free_balance(account_id) + fn tao_balance(account_id: &T::AccountId) -> TaoCurrency { + pallet_balances::Pallet::::free_balance(account_id).into() } fn alpha_balance( @@ -2623,12 +2535,15 @@ impl> Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid) } - fn increase_balance(coldkey: &T::AccountId, tao: u64) { - Self::add_balance_to_coldkey_account(coldkey, tao) + fn increase_balance(coldkey: &T::AccountId, tao: TaoCurrency) { + Self::add_balance_to_coldkey_account(coldkey, tao.into()) } - fn decrease_balance(coldkey: &T::AccountId, tao: u64) -> Result { - Self::remove_balance_from_coldkey_account(coldkey, tao) + fn decrease_balance( + coldkey: &T::AccountId, + tao: TaoCurrency, + ) -> Result { + Self::remove_balance_from_coldkey_account(coldkey, tao.into()) } fn increase_stake( @@ -2673,11 +2588,11 @@ impl> )) } - fn increase_provided_tao_reserve(netuid: NetUid, tao: u64) { + fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) { Self::increase_provided_tao_reserve(netuid, tao); } - fn decrease_provided_tao_reserve(netuid: NetUid, tao: u64) { + fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) { Self::decrease_provided_tao_reserve(netuid, tao); } diff --git a/pallets/subtensor/src/macros/dispatches.rs b/pallets/subtensor/src/macros/dispatches.rs index 01ba58ef3b..1f9d85d08b 100644 --- a/pallets/subtensor/src/macros/dispatches.rs +++ b/pallets/subtensor/src/macros/dispatches.rs @@ -77,7 +77,7 @@ mod dispatches { /// * 'MaxWeightExceeded': /// - Attempting to set weights with max value exceeding limit. #[pallet::call_index(0)] - #[pallet::weight((Weight::from_parts(20_730_000_000, 0) + #[pallet::weight((Weight::from_parts(15_540_000_000, 0) .saturating_add(T::DbWeight::get().reads(4111)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn set_weights( @@ -120,7 +120,7 @@ mod dispatches { /// - On failure for each failed item in the batch. /// #[pallet::call_index(80)] - #[pallet::weight((Weight::from_parts(105_100_000, 0) + #[pallet::weight((Weight::from_parts(78_450_000, 0) .saturating_add(T::DbWeight::get().reads(14)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn batch_set_weights( @@ -152,7 +152,7 @@ mod dispatches { /// - Attempting to commit when the user has more than the allowed limit of unrevealed commits. /// #[pallet::call_index(96)] - #[pallet::weight((Weight::from_parts(72_300_000, 0) + #[pallet::weight((Weight::from_parts(55_130_000, 0) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn commit_weights( @@ -186,7 +186,7 @@ mod dispatches { /// - On failure for each failed item in the batch. /// #[pallet::call_index(100)] - #[pallet::weight((Weight::from_parts(89_380_000, 0) + #[pallet::weight((Weight::from_parts(64_320_000, 0) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn batch_commit_weights( @@ -279,8 +279,8 @@ mod dispatches { /// - Attempting to commit when the user has more than the allowed limit of unrevealed commits. /// #[pallet::call_index(99)] - #[pallet::weight((Weight::from_parts(73_750_000, 0) - .saturating_add(T::DbWeight::get().reads(6_u64)) + #[pallet::weight((Weight::from_parts(50_980_000, 0) + .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn commit_crv3_weights( origin: T::RuntimeOrigin, @@ -288,7 +288,7 @@ mod dispatches { commit: BoundedVec>, reveal_round: u64, ) -> DispatchResult { - Self::do_commit_crv3_weights(origin, netuid, commit, reveal_round) + Self::do_commit_timelocked_weights(origin, netuid, commit, reveal_round, 4) } /// ---- The implementation for batch revealing committed weights. @@ -331,7 +331,7 @@ mod dispatches { /// * `InvalidInputLengths`: /// - The input vectors are of mismatched lengths. #[pallet::call_index(98)] - #[pallet::weight((Weight::from_parts(420_500_000, 0) + #[pallet::weight((Weight::from_parts(330_600_000, 0) .saturating_add(T::DbWeight::get().reads(16)) .saturating_add(T::DbWeight::get().writes(2_u64)), DispatchClass::Normal, Pays::No))] pub fn batch_reveal_weights( @@ -413,7 +413,7 @@ mod dispatches { /// - Attempting to set weights with max value exceeding limit. /// #[pallet::call_index(8)] - #[pallet::weight((Weight::from_parts(3_757_000, 0) + #[pallet::weight((Weight::from_parts(2_033_000, 0) .saturating_add(T::DbWeight::get().reads(0_u64)) .saturating_add(T::DbWeight::get().writes(0_u64)), DispatchClass::Normal, Pays::No))] pub fn set_tao_weights( @@ -454,7 +454,7 @@ mod dispatches { /// - The hotkey we are delegating is not owned by the calling coldket. /// #[pallet::call_index(1)] - #[pallet::weight((Weight::from_parts(3_657_000, 0) + #[pallet::weight((Weight::from_parts(2_363_000, 0) .saturating_add(T::DbWeight::get().reads(0)) .saturating_add(T::DbWeight::get().writes(0)), DispatchClass::Normal, Pays::Yes))] pub fn become_delegate(_origin: OriginFor, _hotkey: T::AccountId) -> DispatchResult { @@ -498,7 +498,7 @@ mod dispatches { /// - The delegate is setting a take which is not lower than the previous. /// #[pallet::call_index(65)] - #[pallet::weight((Weight::from_parts(37_380_000, 0) + #[pallet::weight((Weight::from_parts(23_540_000, 0) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn decrease_take( @@ -540,7 +540,7 @@ mod dispatches { /// - The delegate is setting a take which is not greater than the previous. /// #[pallet::call_index(66)] - #[pallet::weight((Weight::from_parts(44_630_000, 0) + #[pallet::weight((Weight::from_parts(29_960_000, 0) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] pub fn increase_take( @@ -585,14 +585,14 @@ mod dispatches { /// - Errors stemming from transaction pallet. /// #[pallet::call_index(2)] - #[pallet::weight((Weight::from_parts(345_500_000, 0) + #[pallet::weight((Weight::from_parts(270_800_000, 0) .saturating_add(T::DbWeight::get().reads(26)) .saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))] pub fn add_stake( origin: OriginFor, hotkey: T::AccountId, netuid: NetUid, - amount_staked: u64, + amount_staked: TaoCurrency, ) -> DispatchResult { Self::do_add_stake(origin, hotkey, netuid, amount_staked) } @@ -693,7 +693,7 @@ mod dispatches { /// - Attempting to set prometheus information withing the rate limit min. /// #[pallet::call_index(4)] - #[pallet::weight((Weight::from_parts(35_670_000, 0) + #[pallet::weight((Weight::from_parts(28_150_000, 0) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))] pub fn serve_axon( @@ -777,7 +777,7 @@ mod dispatches { /// - Attempting to set prometheus information withing the rate limit min. /// #[pallet::call_index(40)] - #[pallet::weight((Weight::from_parts(33_890_000, 0) + #[pallet::weight((Weight::from_parts(26_600_000, 0) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))] pub fn serve_axon_tls( @@ -827,7 +827,7 @@ mod dispatches { /// - The ip type v4 or v6. /// #[pallet::call_index(5)] - #[pallet::weight((Weight::from_parts(31_170_000, 0) + #[pallet::weight((Weight::from_parts(30_170_000, 0) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))] pub fn serve_prometheus( @@ -889,7 +889,7 @@ mod dispatches { /// - The seal is incorrect. /// #[pallet::call_index(6)] - #[pallet::weight((Weight::from_parts(216_200_000, 0) + #[pallet::weight((Weight::from_parts(161_800_000, 0) .saturating_add(T::DbWeight::get().reads(26)) .saturating_add(T::DbWeight::get().writes(23)), DispatchClass::Normal, Pays::No))] pub fn register( @@ -906,7 +906,7 @@ mod dispatches { /// Register the hotkey to root network #[pallet::call_index(62)] - #[pallet::weight((Weight::from_parts(145_500_000, 0) + #[pallet::weight((Weight::from_parts(111_700_000, 0) .saturating_add(T::DbWeight::get().reads(23)) .saturating_add(T::DbWeight::get().writes(20)), DispatchClass::Normal, Pays::No))] pub fn root_register(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { @@ -915,7 +915,7 @@ mod dispatches { /// Attempt to adjust the senate membership to include a hotkey #[pallet::call_index(63)] - #[pallet::weight((Weight::from_parts(68_100_000, 0) + #[pallet::weight((Weight::from_parts(48_160_000, 0) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(4)), DispatchClass::Normal, Pays::Yes))] pub fn adjust_senate(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { @@ -924,7 +924,7 @@ mod dispatches { /// User register a new subnetwork via burning token #[pallet::call_index(7)] - #[pallet::weight((Weight::from_parts(354_400_000, 0) + #[pallet::weight((Weight::from_parts(278_400_000, 0) .saturating_add(T::DbWeight::get().reads(49)) .saturating_add(T::DbWeight::get().writes(43)), DispatchClass::Normal, Pays::No))] pub fn burned_register( @@ -937,7 +937,7 @@ mod dispatches { /// The extrinsic for user to change its hotkey in subnet or all subnets. #[pallet::call_index(70)] - #[pallet::weight((Weight::from_parts(285_900_000, 0) + #[pallet::weight((Weight::from_parts(211_900_000, 0) .saturating_add(T::DbWeight::get().reads(47)) .saturating_add(T::DbWeight::get().writes(37)), DispatchClass::Operational, Pays::No))] pub fn swap_hotkey( @@ -965,14 +965,14 @@ mod dispatches { /// /// Weight is calculated based on the number of database reads and writes. #[pallet::call_index(71)] - #[pallet::weight((Weight::from_parts(208600000, 0) + #[pallet::weight((Weight::from_parts(161_700_000, 0) .saturating_add(T::DbWeight::get().reads(14)) .saturating_add(T::DbWeight::get().writes(9)), DispatchClass::Operational, Pays::No))] pub fn swap_coldkey( origin: OriginFor, old_coldkey: T::AccountId, new_coldkey: T::AccountId, - swap_cost: u64, + swap_cost: TaoCurrency, ) -> DispatchResultWithPostInfo { // Ensure it's called with root privileges (scheduler has root privileges) ensure_root(origin)?; @@ -1012,12 +1012,12 @@ mod dispatches { /// #[pallet::call_index(75)] #[pallet::weight(( - Weight::from_parts(46_330_000, 0) + Weight::from_parts(36_590_000, 0) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)), - DispatchClass::Normal, - Pays::Yes -))] + DispatchClass::Normal, + Pays::Yes + ))] pub fn set_childkey_take( origin: OriginFor, hotkey: T::AccountId, @@ -1045,7 +1045,7 @@ mod dispatches { /// #[pallet::call_index(69)] #[pallet::weight(( - Weight::from_parts(5_760_000, 0) + Weight::from_parts(3_630_000, 0) .saturating_add(T::DbWeight::get().reads(0)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, @@ -1193,7 +1193,7 @@ mod dispatches { /// User register a new subnetwork #[pallet::call_index(59)] - #[pallet::weight((Weight::from_parts(260_500_000, 0) + #[pallet::weight((Weight::from_parts(191_600_000, 0) .saturating_add(T::DbWeight::get().reads(36)) .saturating_add(T::DbWeight::get().writes(52)), DispatchClass::Operational, Pays::No))] pub fn register_network(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { @@ -1327,7 +1327,7 @@ mod dispatches { /// - Consider adding checks to prevent scheduling too far into the future. /// TODO: Benchmark this call #[pallet::call_index(73)] - #[pallet::weight((Weight::from_parts(44_520_000, 0) + #[pallet::weight((Weight::from_parts(28_770_000, 0) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Operational, Pays::Yes))] pub fn schedule_swap_coldkey( @@ -1348,7 +1348,7 @@ mod dispatches { // Calculate the swap cost and ensure sufficient balance let swap_cost = Self::get_key_swap_cost(); ensure!( - Self::can_remove_balance_from_coldkey_account(&who, swap_cost), + Self::can_remove_balance_from_coldkey_account(&who, swap_cost.into()), Error::::NotEnoughBalanceToPaySwapColdKey ); @@ -1465,7 +1465,7 @@ mod dispatches { /// - The ip type v4 or v6. /// #[pallet::call_index(68)] - #[pallet::weight((Weight::from_parts(31_780_000, 0) + #[pallet::weight((Weight::from_parts(24_350_000, 0) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::Yes))] pub fn set_identity( @@ -1507,7 +1507,7 @@ mod dispatches { /// * `subnet_contact` (Vec): /// - The contact information for the subnet. #[pallet::call_index(78)] - #[pallet::weight((Weight::from_parts(23_080_000, 0) + #[pallet::weight((Weight::from_parts(15_000_000, 0) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::Yes))] pub fn set_subnet_identity( @@ -1538,7 +1538,7 @@ mod dispatches { /// User register a new subnetwork #[pallet::call_index(79)] - #[pallet::weight((Weight::from_parts(239_700_000, 0) + #[pallet::weight((Weight::from_parts(185_500_000, 0) .saturating_add(T::DbWeight::get().reads(35)) .saturating_add(T::DbWeight::get().writes(51)), DispatchClass::Operational, Pays::No))] pub fn register_network_with_identity( @@ -1575,7 +1575,7 @@ mod dispatches { /// * `TxRateLimitExceeded`: /// - Thrown if key has hit transaction rate limit #[pallet::call_index(83)] - #[pallet::weight((Weight::from_parts(30_190_000, 0) + #[pallet::weight((Weight::from_parts(21_160_000, 0) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(0)), DispatchClass::Operational, Pays::Yes))] pub fn unstake_all(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { @@ -1608,7 +1608,7 @@ mod dispatches { /// * `TxRateLimitExceeded`: /// - Thrown if key has hit transaction rate limit #[pallet::call_index(84)] - #[pallet::weight((Weight::from_parts(369_500_000, 0) + #[pallet::weight((Weight::from_parts(291_600_000, 0) .saturating_add(T::DbWeight::get().reads(33)) .saturating_add(T::DbWeight::get().writes(16)), DispatchClass::Operational, Pays::Yes))] pub fn unstake_all_alpha(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { @@ -1637,7 +1637,7 @@ mod dispatches { /// - The alpha stake amount to move. /// #[pallet::call_index(85)] - #[pallet::weight((Weight::from_parts(157_100_000, 0) + #[pallet::weight((Weight::from_parts(123_700_000, 0) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)), DispatchClass::Operational, Pays::Yes))] pub fn move_stake( @@ -1680,7 +1680,7 @@ mod dispatches { /// # Events /// May emit a `StakeTransferred` event on success. #[pallet::call_index(86)] - #[pallet::weight((Weight::from_parts(154_800_000, 0) + #[pallet::weight((Weight::from_parts(118_900_000, 0) .saturating_add(T::DbWeight::get().reads(13_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)), DispatchClass::Operational, Pays::Yes))] pub fn transfer_stake( @@ -1722,7 +1722,7 @@ mod dispatches { /// May emit a `StakeSwapped` event on success. #[pallet::call_index(87)] #[pallet::weight(( - Weight::from_parts(351_300_000, 0) + Weight::from_parts(274_400_000, 0) .saturating_add(T::DbWeight::get().reads(32)) .saturating_add(T::DbWeight::get().writes(17)), DispatchClass::Operational, @@ -1787,15 +1787,15 @@ mod dispatches { /// - Errors stemming from transaction pallet. /// #[pallet::call_index(88)] - #[pallet::weight((Weight::from_parts(402_800_000, 0) + #[pallet::weight((Weight::from_parts(316_400_000, 0) .saturating_add(T::DbWeight::get().reads(26)) .saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))] pub fn add_stake_limit( origin: OriginFor, hotkey: T::AccountId, netuid: NetUid, - amount_staked: u64, - limit_price: u64, + amount_staked: TaoCurrency, + limit_price: TaoCurrency, allow_partial: bool, ) -> DispatchResult { Self::do_add_stake_limit( @@ -1851,7 +1851,7 @@ mod dispatches { /// - Thrown if there is not enough stake on the hotkey to withdwraw this amount. /// #[pallet::call_index(89)] - #[pallet::weight((Weight::from_parts(403_800_000, 0) + #[pallet::weight((Weight::from_parts(311_800_000, 0) .saturating_add(T::DbWeight::get().reads(30)) .saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::Yes))] pub fn remove_stake_limit( @@ -1859,7 +1859,7 @@ mod dispatches { hotkey: T::AccountId, netuid: NetUid, amount_unstaked: AlphaCurrency, - limit_price: u64, + limit_price: TaoCurrency, allow_partial: bool, ) -> DispatchResult { Self::do_remove_stake_limit( @@ -1895,7 +1895,7 @@ mod dispatches { /// May emit a `StakeSwapped` event on success. #[pallet::call_index(90)] #[pallet::weight(( - Weight::from_parts(426_500_000, 0) + Weight::from_parts(330_400_000, 0) .saturating_add(T::DbWeight::get().reads(32)) .saturating_add(T::DbWeight::get().writes(17)), DispatchClass::Operational, @@ -1907,7 +1907,7 @@ mod dispatches { origin_netuid: NetUid, destination_netuid: NetUid, alpha_amount: AlphaCurrency, - limit_price: u64, + limit_price: TaoCurrency, allow_partial: bool, ) -> DispatchResult { Self::do_swap_stake_limit( @@ -1931,7 +1931,7 @@ mod dispatches { /// Will charge based on the weight even if the hotkey is already associated with a coldkey. #[pallet::call_index(91)] #[pallet::weight(( - Weight::from_parts(32_560_000, 0).saturating_add(T::DbWeight::get().reads_writes(3, 3)), + Weight::from_parts(19_930_000, 0).saturating_add(T::DbWeight::get().reads_writes(3, 3)), DispatchClass::Operational, Pays::Yes ))] @@ -1956,7 +1956,7 @@ mod dispatches { /// Emits a `FirstEmissionBlockNumberSet` event on success. #[pallet::call_index(92)] #[pallet::weight(( - Weight::from_parts(35_770_000, 0).saturating_add(T::DbWeight::get().reads_writes(4, 2)), + Weight::from_parts(24_370_000, 0).saturating_add(T::DbWeight::get().reads_writes(4, 2)), DispatchClass::Operational, Pays::Yes ))] @@ -2020,7 +2020,7 @@ mod dispatches { /// Emits a `TokensRecycled` event on success. #[pallet::call_index(101)] #[pallet::weight(( - Weight::from_parts(101_000_000, 0).saturating_add(T::DbWeight::get().reads_writes(7, 4)), + Weight::from_parts(76_470_000, 0).saturating_add(T::DbWeight::get().reads_writes(7, 4)), DispatchClass::Operational, Pays::Yes ))] @@ -2045,7 +2045,7 @@ mod dispatches { /// Emits a `TokensBurned` event on success. #[pallet::call_index(102)] #[pallet::weight(( - Weight::from_parts(98_010_000, 0).saturating_add(T::DbWeight::get().reads_writes(7, 3)), + Weight::from_parts(74_650_000, 0).saturating_add(T::DbWeight::get().reads_writes(7, 3)), DispatchClass::Operational, Pays::Yes ))] @@ -2075,14 +2075,14 @@ mod dispatches { /// at which or better (higher) the staking should execute. /// Without limit_price it remove all the stake similar to `remove_stake` extrinsic #[pallet::call_index(103)] - #[pallet::weight((Weight::from_parts(398_000_000, 10142) + #[pallet::weight((Weight::from_parts(317_700_000, 10142) .saturating_add(T::DbWeight::get().reads(30_u64)) .saturating_add(T::DbWeight::get().writes(14_u64)), DispatchClass::Normal, Pays::Yes))] pub fn remove_stake_full_limit( origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - limit_price: Option, + limit_price: Option, ) -> DispatchResult { Self::do_remove_stake_full_limit(origin, hotkey, netuid, limit_price) } @@ -2156,7 +2156,7 @@ mod dispatches { /// Emits a `SymbolUpdated` event on success. #[pallet::call_index(112)] #[pallet::weight(( - Weight::from_parts(28_840_000, 0).saturating_add(T::DbWeight::get().reads_writes(4, 1)), + Weight::from_parts(19_290_000, 0).saturating_add(T::DbWeight::get().reads_writes(4, 1)), DispatchClass::Operational, Pays::Yes ))] @@ -2175,5 +2175,49 @@ mod dispatches { Self::deposit_event(Event::SymbolUpdated { netuid, symbol }); Ok(()) } + + /// ---- Used to commit timelock encrypted commit-reveal weight values to later be revealed. + /// + /// # Args: + /// * `origin`: (`::RuntimeOrigin`): + /// - The committing hotkey. + /// + /// * `netuid` (`u16`): + /// - The u16 network identifier. + /// + /// * `commit` (`Vec`): + /// - The encrypted compressed commit. + /// The steps for this are: + /// 1. Instantiate [`WeightsTlockPayload`] + /// 2. Serialize it using the `parity_scale_codec::Encode` trait + /// 3. Encrypt it following the steps (here)[https://github.com/ideal-lab5/tle/blob/f8e6019f0fb02c380ebfa6b30efb61786dede07b/timelock/src/tlock.rs#L283-L336] + /// to produce a [`TLECiphertext`] type. + /// 4. Serialize and compress using the `ark-serialize` `CanonicalSerialize` trait. + /// + /// * reveal_round (`u64`): + /// - The drand reveal round which will be avaliable during epoch `n+1` from the current + /// epoch. + /// + /// * commit_reveal_version (`u16`): + /// - The client (bittensor-drand) version + #[pallet::call_index(113)] + #[pallet::weight((Weight::from_parts(52_290_000, 0) + .saturating_add(T::DbWeight::get().reads(7_u64)) + .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] + pub fn commit_timelocked_weights( + origin: T::RuntimeOrigin, + netuid: NetUid, + commit: BoundedVec>, + reveal_round: u64, + commit_reveal_version: u16, + ) -> DispatchResult { + Self::do_commit_timelocked_weights( + origin, + netuid, + commit, + reveal_round, + commit_reveal_version, + ) + } } } diff --git a/pallets/subtensor/src/macros/errors.rs b/pallets/subtensor/src/macros/errors.rs index 1151be75c4..71750e7534 100644 --- a/pallets/subtensor/src/macros/errors.rs +++ b/pallets/subtensor/src/macros/errors.rs @@ -242,5 +242,7 @@ mod errors { SymbolDoesNotExist, /// Symbol already in use. SymbolAlreadyInUse, + /// Incorrect commit-reveal version. + IncorrectCommitRevealVersion, } } diff --git a/pallets/subtensor/src/macros/events.rs b/pallets/subtensor/src/macros/events.rs index c0528d0600..d959ccd6e0 100644 --- a/pallets/subtensor/src/macros/events.rs +++ b/pallets/subtensor/src/macros/events.rs @@ -14,9 +14,23 @@ mod events { /// a network is removed. NetworkRemoved(NetUid), /// stake has been transferred from the a coldkey account onto the hotkey staking account. - StakeAdded(T::AccountId, T::AccountId, u64, AlphaCurrency, NetUid, u64), + StakeAdded( + T::AccountId, + T::AccountId, + TaoCurrency, + AlphaCurrency, + NetUid, + u64, + ), /// stake has been removed from the hotkey staking account onto the coldkey account. - StakeRemoved(T::AccountId, T::AccountId, u64, AlphaCurrency, NetUid, u64), + StakeRemoved( + T::AccountId, + T::AccountId, + TaoCurrency, + AlphaCurrency, + NetUid, + u64, + ), /// stake has been moved from origin (hotkey, subnet ID) to destination (hotkey, subnet ID) of this amount (in TAO). StakeMoved( T::AccountId, @@ -24,7 +38,7 @@ mod events { NetUid, T::AccountId, NetUid, - u64, + TaoCurrency, ), /// a caller successfully sets their weights on a subnetwork. WeightsSet(NetUid, u16), @@ -89,11 +103,11 @@ mod events { /// setting the prometheus serving rate limit. ServingRateLimitSet(NetUid, u64), /// setting burn on a network. - BurnSet(NetUid, u64), + BurnSet(NetUid, TaoCurrency), /// setting max burn on a network. - MaxBurnSet(NetUid, u64), + MaxBurnSet(NetUid, TaoCurrency), /// setting min burn on a network. - MinBurnSet(NetUid, u64), + MinBurnSet(NetUid, TaoCurrency), /// setting the transaction rate limit. TxRateLimitSet(u64), /// setting the delegate take transaction rate limit. @@ -115,7 +129,7 @@ mod events { /// setting tempo on a network TempoSet(NetUid, u16), /// setting the RAO recycled for registration. - RAORecycledForRegistrationSet(NetUid, u64), + RAORecycledForRegistrationSet(NetUid, TaoCurrency), /// min stake is set for validators to set weights. StakeThresholdSet(u64), /// setting the minimum required stake amount for senate registration. @@ -131,7 +145,7 @@ mod events { /// the network immunity period is set. NetworkImmunityPeriodSet(u64), /// the network minimum locking cost is set. - NetworkMinLockCostSet(u64), + NetworkMinLockCostSet(TaoCurrency), /// the maximum number of subnets is set // SubnetLimitSet(u16), /// the lock cost reduction is set @@ -167,7 +181,7 @@ mod events { /// the account ID of new coldkey new_coldkey: T::AccountId, /// the swap cost - swap_cost: u64, + swap_cost: TaoCurrency, }, /// All balance of a hotkey has been unstaked and transferred to a new coldkey AllBalanceUnstakedAndTransferredToNewColdkey { @@ -189,7 +203,7 @@ mod events { /// The arbitration block for the coldkey swap execution_block: BlockNumberFor, /// The swap cost - swap_cost: u64, + swap_cost: TaoCurrency, }, /// The arbitration period has been extended ArbitrationPeriodExtended { @@ -273,14 +287,14 @@ mod events { T::AccountId, NetUid, NetUid, - u64, + TaoCurrency, ), /// Stake has been swapped from one subnet to another for the same coldkey-hotkey pair. /// /// Parameters: /// (coldkey, hotkey, origin_netuid, destination_netuid, amount) - StakeSwapped(T::AccountId, T::AccountId, NetUid, NetUid, u64), + StakeSwapped(T::AccountId, T::AccountId, NetUid, NetUid, TaoCurrency), /// Event called when transfer is toggled on a subnet. /// @@ -380,5 +394,10 @@ mod events { /// The symbol that has been updated. symbol: Vec, }, + + /// Commit Reveal Weights version has been updated. + /// + /// - **version**: The required version. + CommitRevealVersionSet(u16), } } diff --git a/pallets/subtensor/src/macros/genesis.rs b/pallets/subtensor/src/macros/genesis.rs index db7c798fbc..e50bf01d7d 100644 --- a/pallets/subtensor/src/macros/genesis.rs +++ b/pallets/subtensor/src/macros/genesis.rs @@ -52,7 +52,7 @@ mod genesis { SubnetMechanism::::insert(netuid, 1); // Make dynamic. Owner::::insert(hotkey.clone(), hotkey.clone()); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(10_000_000_000)); - SubnetTAO::::insert(netuid, 10_000_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(10_000_000_000)); NetworksAdded::::insert(netuid, true); TotalNetworks::::mutate(|n| *n = n.saturating_add(1)); SubnetworkN::::insert(netuid, 0); @@ -63,7 +63,7 @@ mod genesis { Tempo::::insert(netuid, 100); NetworkRegistrationAllowed::::insert(netuid, true); SubnetOwner::::insert(netuid, hotkey.clone()); - SubnetLocked::::insert(netuid, 1); + SubnetLocked::::insert(netuid, TaoCurrency::from(1)); LargestLocked::::insert(netuid, 1); Alpha::::insert( // Lock the initial funds making this key the owner. diff --git a/pallets/subtensor/src/migrations/migrate_chain_identity.rs b/pallets/subtensor/src/migrations/migrate_chain_identity.rs index 142eb099de..735e63168c 100644 --- a/pallets/subtensor/src/migrations/migrate_chain_identity.rs +++ b/pallets/subtensor/src/migrations/migrate_chain_identity.rs @@ -73,11 +73,11 @@ pub fn migrate_set_hotkey_identities() -> Weight { let decoded_hotkey: T::AccountId = match T::AccountId::decode(&mut hotkey.as_ref()) { Ok(decoded) => decoded, Err(e) => { - log::warn!("Failed to decode hotkey: {:?}. Skipping this delegate.", e); + log::warn!("Failed to decode hotkey: {e:?}. Skipping this delegate."); continue; } }; - log::info!("Hotkey unwrapped: {:?}", decoded_hotkey); + log::info!("Hotkey unwrapped: {decoded_hotkey:?}"); // If we should continue with real values. let mut name: BoundedVec> = BoundedVec::default(); @@ -109,7 +109,7 @@ pub fn migrate_set_hotkey_identities() -> Weight { }; // Log the identity details - log::info!("Setting identity for hotkey: {:?}", hotkey); + log::info!("Setting identity for hotkey: {hotkey:?}"); log::info!("Name: {:?}", String::from_utf8_lossy(&identity.name)); log::info!("URL: {:?}", String::from_utf8_lossy(&identity.url)); log::info!("Image: {:?}", String::from_utf8_lossy(&identity.image)); @@ -146,7 +146,7 @@ pub fn migrate_set_hotkey_identities() -> Weight { // Get the owning coldkey. let coldkey = Owner::::get(decoded_hotkey.clone()); - log::info!("ColdKey: {:?}", decoded_hotkey); + log::info!("ColdKey: {decoded_hotkey:?}"); weight = weight.saturating_add(T::DbWeight::get().reads(1)); diff --git a/pallets/subtensor/src/migrations/migrate_commit_reveal_v2.rs b/pallets/subtensor/src/migrations/migrate_commit_reveal_v2.rs index 344d72cb46..bedc43d724 100644 --- a/pallets/subtensor/src/migrations/migrate_commit_reveal_v2.rs +++ b/pallets/subtensor/src/migrations/migrate_commit_reveal_v2.rs @@ -42,10 +42,7 @@ pub fn migrate_commit_reveal_2() -> Weight { weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count)); - log::info!( - "Removed {:?} entries from WeightCommitRevealInterval.", - removed_entries_count - ); + log::info!("Removed {removed_entries_count:?} entries from WeightCommitRevealInterval."); // ------------------------------ // Step 2: Remove WeightCommits entries @@ -67,10 +64,7 @@ pub fn migrate_commit_reveal_2() -> Weight { weight = weight.saturating_add(T::DbWeight::get().writes(removed_commits_entries)); - log::info!( - "Removed {} entries from WeightCommits.", - removed_commits_entries - ); + log::info!("Removed {removed_commits_entries} entries from WeightCommits."); // ------------------------------ // Step 3: Mark Migration as Completed diff --git a/pallets/subtensor/src/migrations/migrate_delete_subnet_21.rs b/pallets/subtensor/src/migrations/migrate_delete_subnet_21.rs index eae5eedc87..e6a8c72eae 100644 --- a/pallets/subtensor/src/migrations/migrate_delete_subnet_21.rs +++ b/pallets/subtensor/src/migrations/migrate_delete_subnet_21.rs @@ -51,7 +51,7 @@ pub fn migrate_delete_subnet_21() -> Weight { // Only runs if we haven't already updated version past above new_storage_version and subnet 21 exists. if onchain_version < new_storage_version && Pallet::::if_subnet_exist(NetUid::from(21)) { - info!(target: LOG_TARGET, ">>> Removing subnet 21 {:?}", onchain_version); + info!(target: LOG_TARGET, ">>> Removing subnet 21 {onchain_version:?}"); let netuid = NetUid::from(21); diff --git a/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs b/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs index a30f0a84ea..c479bd613a 100644 --- a/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs +++ b/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs @@ -53,8 +53,7 @@ pub fn migrate_delete_subnet_3() -> Weight { if onchain_version < new_storage_version && Pallet::::if_subnet_exist(3.into()) { info!( target: LOG_TARGET, - "Removing subnet 3. Current version: {:?}", - onchain_version + "Removing subnet 3. Current version: {onchain_version:?}" ); let netuid = NetUid::from(3); diff --git a/pallets/subtensor/src/migrations/migrate_disable_commit_reveal.rs b/pallets/subtensor/src/migrations/migrate_disable_commit_reveal.rs new file mode 100644 index 0000000000..5465adbdd1 --- /dev/null +++ b/pallets/subtensor/src/migrations/migrate_disable_commit_reveal.rs @@ -0,0 +1,37 @@ +use super::*; +use crate::HasMigrationRun; +use frame_support::{traits::Get, weights::Weight}; +use scale_info::prelude::string::String; + +pub fn migrate_disable_commit_reveal() -> Weight { + const MIG_NAME: &[u8] = b"disable_commit_reveal_v1"; + + // 1 ─ check if we already ran + if HasMigrationRun::::get(MIG_NAME) { + log::info!( + "Migration '{}' already executed - skipping", + String::from_utf8_lossy(MIG_NAME) + ); + return T::DbWeight::get().reads(1); + } + + log::info!("Running migration '{}'", String::from_utf8_lossy(MIG_NAME)); + + let mut total_weight = T::DbWeight::get().reads(1); + + // 2 ─ iterate over every stored key and set value -> false + for (netuid, _) in CommitRevealWeightsEnabled::::drain() { + CommitRevealWeightsEnabled::::insert(netuid, false); + total_weight = total_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); + } + + // 3 ─ mark migration as done + HasMigrationRun::::insert(MIG_NAME, true); + total_weight = total_weight.saturating_add(T::DbWeight::get().writes(1)); + + log::info!( + "Migration '{}' completed: commit-reveal disabled on all subnets", + String::from_utf8_lossy(MIG_NAME) + ); + total_weight +} diff --git a/pallets/subtensor/src/migrations/migrate_fix_root_subnet_tao.rs b/pallets/subtensor/src/migrations/migrate_fix_root_subnet_tao.rs index 96593b9e5c..60d300f29d 100644 --- a/pallets/subtensor/src/migrations/migrate_fix_root_subnet_tao.rs +++ b/pallets/subtensor/src/migrations/migrate_fix_root_subnet_tao.rs @@ -19,20 +19,16 @@ pub fn migrate_fix_root_subnet_tao() -> Weight { String::from_utf8_lossy(&migration_name) ); - let mut total_stake: u64 = 0; + let mut total_stake = TaoCurrency::ZERO; let mut hotkey_count: u64 = 0; // We accumulate the total stake for all hotkeys on the root subnet. for hotkey in Owner::::iter_keys() { let hotkey_stake = TotalHotkeyAlpha::::get(&hotkey, NetUid::ROOT); - total_stake = total_stake.saturating_add(hotkey_stake.to_u64()); + total_stake = total_stake.saturating_add(hotkey_stake.to_u64().into()); hotkey_count = hotkey_count.saturating_add(1); } - log::info!( - "Total stake: {}, hotkey count: {}", - total_stake, - hotkey_count - ); + log::info!("Total stake: {total_stake}, hotkey count: {hotkey_count}"); weight = weight.saturating_add(T::DbWeight::get().reads(hotkey_count).saturating_mul(2)); diff --git a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs index 5bccfff9a0..042ad0fe77 100644 --- a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs +++ b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs @@ -26,31 +26,29 @@ pub(crate) fn migrate_init_total_issuance() -> Weight { let prev_total_stake = crate::TotalStake::::get(); // Calculate new total stake using the sum of all subnet TAO - let total_subnet_tao: u64 = - crate::SubnetTAO::::iter().fold(0, |acc, (_, v)| acc.saturating_add(v)); + let total_subnet_tao = + crate::SubnetTAO::::iter().fold(TaoCurrency::ZERO, |acc, (_, v)| acc.saturating_add(v)); let total_stake = total_subnet_tao; // Update the total stake in storage crate::TotalStake::::put(total_stake); log::info!( - "Subtensor Pallet Total Stake Updated: previous: {:?}, new: {:?}", - prev_total_stake, - total_stake + "Subtensor Pallet Total Stake Updated: previous: {prev_total_stake:?}, new: {total_stake:?}" ); // Retrieve the previous total issuance for logging purposes let prev_total_issuance = crate::TotalIssuance::::get(); // Calculate the new total issuance - let new_total_issuance = total_account_balances.saturating_add(total_stake); + let new_total_issuance: TaoCurrency = total_account_balances + .saturating_add(total_stake.to_u64()) + .into(); // Update the total issuance in storage crate::TotalIssuance::::put(new_total_issuance); // Log the change in total issuance log::info!( - "Subtensor Pallet Total Issuance Updated: previous: {:?}, new: {:?}", - prev_total_issuance, - new_total_issuance + "Subtensor Pallet Total Issuance Updated: previous: {prev_total_issuance:?}, new: {new_total_issuance:?}" ); // Return the weight of the operation diff --git a/pallets/subtensor/src/migrations/migrate_populate_owned_hotkeys.rs b/pallets/subtensor/src/migrations/migrate_populate_owned_hotkeys.rs index e8fd212ec3..26d35dbd09 100644 --- a/pallets/subtensor/src/migrations/migrate_populate_owned_hotkeys.rs +++ b/pallets/subtensor/src/migrations/migrate_populate_owned_hotkeys.rs @@ -30,7 +30,7 @@ pub fn migrate_populate_owned() -> Weight { // Only runs if the migration is needed if migrate { - info!(target: LOG_TARGET_1, ">>> Starting Migration: {}", migration_name); + info!(target: LOG_TARGET_1, ">>> Starting Migration: {migration_name}"); let mut longest_hotkey_vector: usize = 0; let mut longest_coldkey: Option = None; @@ -67,16 +67,15 @@ pub fn migrate_populate_owned() -> Weight { // Log migration results info!( target: LOG_TARGET_1, - "Migration {} finished. Keys touched: {}, Longest hotkey vector: {}, Storage reads: {}, Storage writes: {}", - migration_name, keys_touched, longest_hotkey_vector, storage_reads, storage_writes + "Migration {migration_name} finished. Keys touched: {keys_touched}, Longest hotkey vector: {longest_hotkey_vector}, Storage reads: {storage_reads}, Storage writes: {storage_writes}" ); if let Some(c) = longest_coldkey { - info!(target: LOG_TARGET_1, "Longest hotkey vector is controlled by: {:?}", c); + info!(target: LOG_TARGET_1, "Longest hotkey vector is controlled by: {c:?}"); } weight } else { - info!(target: LOG_TARGET_1, "Migration {} already done!", migration_name); + info!(target: LOG_TARGET_1, "Migration {migration_name} already done!"); Weight::zero() } } diff --git a/pallets/subtensor/src/migrations/migrate_rao.rs b/pallets/subtensor/src/migrations/migrate_rao.rs index d529e77098..e614827e90 100644 --- a/pallets/subtensor/src/migrations/migrate_rao.rs +++ b/pallets/subtensor/src/migrations/migrate_rao.rs @@ -59,7 +59,7 @@ pub fn migrate_rao() -> Weight { // Convert subnets and give them lock. // Set global weight to 18% from the start // Set min lock - NetworkMinLockCost::::set(1_000_000_000); + NetworkMinLockCost::::set(TaoCurrency::from(1_000_000_000)); // Set tao weight. TaoWeight::::set(3_320_413_933_267_719_290); for netuid in netuids.iter() { @@ -77,7 +77,7 @@ pub fn migrate_rao() -> Weight { // The initial TAO is the locked amount, with a minimum of 1 RAO and a cap of 100 TAO. let pool_initial_tao = Pallet::::get_network_min_lock(); if lock < pool_initial_tao { - let difference: u64 = pool_initial_tao.saturating_sub(lock); + let difference = pool_initial_tao.saturating_sub(lock); TotalIssuance::::mutate(|total| { *total = total.saturating_add(difference); }); @@ -91,13 +91,13 @@ pub fn migrate_rao() -> Weight { // .checked_div(I96F32::from_num(1_000_000_000)) // .unwrap_or(I96F32::from_num(0.0)), // ); - Pallet::::add_balance_to_coldkey_account(&owner, remaining_lock); - SubnetLocked::::insert(netuid, 0); // Clear lock amount. + Pallet::::add_balance_to_coldkey_account(&owner, remaining_lock.into()); + SubnetLocked::::insert(netuid, TaoCurrency::ZERO); // Clear lock amount. SubnetTAO::::insert(netuid, pool_initial_tao); TotalStake::::mutate(|total| { *total = total.saturating_add(pool_initial_tao); }); // Increase total stake. - SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(pool_initial_tao)); // Set initial alpha to pool initial tao. + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(pool_initial_tao.to_u64())); // Set initial alpha to pool initial tao. SubnetAlphaOut::::insert(netuid, AlphaCurrency::ZERO); // Set zero subnet alpha out. SubnetMechanism::::insert(netuid, 1); // Convert to dynamic immediately with initialization. @@ -119,7 +119,7 @@ pub fn migrate_rao() -> Weight { if !IdentitiesV2::::contains_key(owner_coldkey.clone()) { // Set the identitiy for the Owner coldkey if non existent. let identity = ChainIdentityOfV2 { - name: format!("Owner{}", netuid).as_bytes().to_vec(), + name: format!("Owner{netuid}").as_bytes().to_vec(), url: Vec::new(), image: Vec::new(), github_repo: Vec::new(), diff --git a/pallets/subtensor/src/migrations/migrate_remove_commitments_rate_limit.rs b/pallets/subtensor/src/migrations/migrate_remove_commitments_rate_limit.rs index 5544467a13..06fcad0a10 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_commitments_rate_limit.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_commitments_rate_limit.rs @@ -37,7 +37,7 @@ pub fn migrate_remove_commitments_rate_limit() -> Weight { }; weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries)); - log::info!("Removed {} entries from `RateLimit`.", removed_entries); + log::info!("Removed {removed_entries} entries from `RateLimit`."); // ------------------------------------------------------------- // Step 2: Mark this migration as completed diff --git a/pallets/subtensor/src/migrations/migrate_remove_stake_map.rs b/pallets/subtensor/src/migrations/migrate_remove_stake_map.rs index cef2dad873..bffe7f8fe5 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_stake_map.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_stake_map.rs @@ -34,17 +34,14 @@ pub fn migrate_remove_stake_map() -> Weight { let removed_entries_count = match removal_results { KillStorageResult::AllRemoved(removed) => removed as u64, KillStorageResult::SomeRemaining(removed) => { - log::info!("Failed To Remove Some Items During {:?}", migration_name); + log::info!("Failed To Remove Some Items During {migration_name:?}"); removed as u64 } }; weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count)); - log::info!( - "Removed {:?} entries from Stake map.", - removed_entries_count - ); + log::info!("Removed {removed_entries_count:?} entries from Stake map."); // ------------------------------ // Step 2: Mark Migration as Completed diff --git a/pallets/subtensor/src/migrations/migrate_remove_total_hotkey_coldkey_stakes_this_interval.rs b/pallets/subtensor/src/migrations/migrate_remove_total_hotkey_coldkey_stakes_this_interval.rs index 16782a5d8c..9d6b2d681f 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_total_hotkey_coldkey_stakes_this_interval.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_total_hotkey_coldkey_stakes_this_interval.rs @@ -9,14 +9,11 @@ pub fn migrate_remove_total_hotkey_coldkey_stakes_this_interval() -> let mut weight = T::DbWeight::get().reads(1); if HasMigrationRun::::get(&migration_name_bytes) { - log::info!( - "Migration '{:?}' has already run. Skipping.", - migration_name - ); + log::info!("Migration '{migration_name:?}' has already run. Skipping."); return weight; } - log::info!("Running migration '{}'", migration_name); + log::info!("Running migration '{migration_name}'"); let pallet_name = twox_128(b"SubtensorModule"); let storage_name = twox_128(b"TotalHotkeyColdkeyStakesThisInterval"); @@ -25,7 +22,7 @@ pub fn migrate_remove_total_hotkey_coldkey_stakes_this_interval() -> // Remove all entries. let removed_entries_count = match clear_prefix(&prefix, Some(u32::MAX)) { KillStorageResult::AllRemoved(removed) => { - log::info!("Removed all entries from {:?}.", storage_name); + log::info!("Removed all entries from {storage_name:?}."); // Mark migration as completed HasMigrationRun::::insert(&migration_name_bytes, true); @@ -34,7 +31,7 @@ pub fn migrate_remove_total_hotkey_coldkey_stakes_this_interval() -> removed as u64 } KillStorageResult::SomeRemaining(removed) => { - log::info!("Failed to remove all entries from {:?}", storage_name); + log::info!("Failed to remove all entries from {storage_name:?}"); removed as u64 } }; @@ -42,9 +39,7 @@ pub fn migrate_remove_total_hotkey_coldkey_stakes_this_interval() -> weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count as u64)); log::info!( - "Migration '{:?}' completed successfully. {:?} entries removed.", - migration_name, - removed_entries_count + "Migration '{migration_name:?}' completed successfully. {removed_entries_count:?} entries removed." ); weight diff --git a/pallets/subtensor/src/migrations/migrate_remove_unused_maps_and_values.rs b/pallets/subtensor/src/migrations/migrate_remove_unused_maps_and_values.rs index 6ad34baf24..701ab14893 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_unused_maps_and_values.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_unused_maps_and_values.rs @@ -23,11 +23,7 @@ fn remove_prefix(old_map: &str, weight: &mut Weight) { } }; - log::info!( - "Removed {:?} entries from {:?} map.", - removed_entries_count, - old_map - ); + log::info!("Removed {removed_entries_count:?} entries from {old_map:?} map."); *weight = (*weight).saturating_add(T::DbWeight::get().writes(removed_entries_count)); } diff --git a/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs b/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs index b85ee78af6..94458a88b3 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs @@ -40,10 +40,7 @@ pub fn migrate_remove_zero_total_hotkey_alpha() -> Weight { weight = weight.saturating_add(T::DbWeight::get().reads(removed_entries_count)); weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count)); - log::info!( - "Removed {} zero entries from TotalHotkeyAlpha.", - removed_entries_count - ); + log::info!("Removed {removed_entries_count} zero entries from TotalHotkeyAlpha."); // ------------------------------ // Step 2: Mark Migration as Completed diff --git a/pallets/subtensor/src/migrations/migrate_reset_bonds_moving_average.rs b/pallets/subtensor/src/migrations/migrate_reset_bonds_moving_average.rs index 5505e49e84..9825aed391 100644 --- a/pallets/subtensor/src/migrations/migrate_reset_bonds_moving_average.rs +++ b/pallets/subtensor/src/migrations/migrate_reset_bonds_moving_average.rs @@ -39,10 +39,7 @@ pub fn migrate_reset_bonds_moving_average() -> Weight { weight = weight .saturating_add(T::DbWeight::get().reads_writes(reset_entries_count, reset_entries_count)); - log::info!( - "Reset {} subnets from BondsMovingAverage.", - reset_entries_count - ); + log::info!("Reset {reset_entries_count} subnets from BondsMovingAverage."); // ------------------------------ // Step 2: Mark Migration as Completed diff --git a/pallets/subtensor/src/migrations/migrate_reset_max_burn.rs b/pallets/subtensor/src/migrations/migrate_reset_max_burn.rs index 4de473b2fb..e52d15fb07 100644 --- a/pallets/subtensor/src/migrations/migrate_reset_max_burn.rs +++ b/pallets/subtensor/src/migrations/migrate_reset_max_burn.rs @@ -31,7 +31,7 @@ pub fn migrate_reset_max_burn() -> Weight { for netuid in MaxBurn::::iter_keys() { MaxBurn::::mutate(netuid, |max| { - *max = 100_000_000_000; + *max = 100_000_000_000.into(); }); reset_entries_count = reset_entries_count.saturating_add(1); } @@ -39,7 +39,7 @@ pub fn migrate_reset_max_burn() -> Weight { weight = weight .saturating_add(T::DbWeight::get().reads_writes(reset_entries_count, reset_entries_count)); - log::info!("Reset {} subnets from MaxBurn.", reset_entries_count); + log::info!("Reset {reset_entries_count} subnets from MaxBurn."); // ------------------------------ // Step 2: Mark Migration as Completed diff --git a/pallets/subtensor/src/migrations/migrate_set_min_burn.rs b/pallets/subtensor/src/migrations/migrate_set_min_burn.rs index 505ea94a74..80518eb188 100644 --- a/pallets/subtensor/src/migrations/migrate_set_min_burn.rs +++ b/pallets/subtensor/src/migrations/migrate_set_min_burn.rs @@ -35,7 +35,7 @@ pub fn migrate_set_min_burn() -> Weight { continue; } // Set min burn to the newest initial min burn - Pallet::::set_min_burn(*netuid, T::InitialMinBurn::get()); + Pallet::::set_min_burn(*netuid, T::InitialMinBurn::get().into()); weight = weight.saturating_add(T::DbWeight::get().writes(1)); } diff --git a/pallets/subtensor/src/migrations/migrate_subnet_volume.rs b/pallets/subtensor/src/migrations/migrate_subnet_volume.rs index 5d9a8583d4..eb763e68e0 100644 --- a/pallets/subtensor/src/migrations/migrate_subnet_volume.rs +++ b/pallets/subtensor/src/migrations/migrate_subnet_volume.rs @@ -28,7 +28,7 @@ pub fn migrate_subnet_volume() -> Weight { Some(old_value as u128) // Convert and store as u128 }); - log::info!("Migrated {} entries in SubnetVolume", migrated); + log::info!("Migrated {migrated} entries in SubnetVolume"); weight = weight.saturating_add(T::DbWeight::get().reads_writes(migrated, migrated)); // Mark the migration as completed diff --git a/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs b/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs index 84d8a681da..f6816b291d 100644 --- a/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs +++ b/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs @@ -51,7 +51,7 @@ pub fn migrate_to_v1_separate_emission() -> Weight { if onchain_version < 1 { info!( target: LOG_TARGET, - ">>> Updating the LoadedEmission to a new format {:?}", onchain_version + ">>> Updating the LoadedEmission to a new format {onchain_version:?}" ); // Collect all network IDs (netuids) from old LoadedEmission storage @@ -63,10 +63,7 @@ pub fn migrate_to_v1_separate_emission() -> Weight { if old::LoadedEmission::::try_get(netuid).is_err() { weight.saturating_accrue(T::DbWeight::get().writes(1)); old::LoadedEmission::::remove(netuid); - warn!( - "Was unable to decode old loaded_emission for netuid {}", - netuid - ); + warn!("Was unable to decode old loaded_emission for netuid {netuid}"); } } @@ -75,7 +72,7 @@ pub fn migrate_to_v1_separate_emission() -> Weight { |netuid: NetUid, netuid_emissions: Vec<(AccountIdOf, u64)>| -> Option, u64, u64)>> { - info!(target: LOG_TARGET, " Do migration of netuid: {:?}...", netuid); + info!(target: LOG_TARGET, " Do migration of netuid: {netuid:?}..."); // Convert old format (server, validator_emission) to new format (server, server_emission, validator_emission) // Assume all loaded emission is validator emissions diff --git a/pallets/subtensor/src/migrations/migrate_to_v2_fixed_total_stake.rs b/pallets/subtensor/src/migrations/migrate_to_v2_fixed_total_stake.rs index 6410f79321..c8ea6a33af 100644 --- a/pallets/subtensor/src/migrations/migrate_to_v2_fixed_total_stake.rs +++ b/pallets/subtensor/src/migrations/migrate_to_v2_fixed_total_stake.rs @@ -52,8 +52,7 @@ pub fn migrate_to_v2_fixed_total_stake() -> Weight { if onchain_version < new_storage_version { info!( target: LOG_TARGET, - "Fixing the TotalStake and TotalColdkeyStake storage. Current version: {:?}", - onchain_version + "Fixing the TotalStake and TotalColdkeyStake storage. Current version: {onchain_version:?}" ); // TODO: Fix or remove migration diff --git a/pallets/subtensor/src/migrations/migrate_total_issuance.rs b/pallets/subtensor/src/migrations/migrate_total_issuance.rs index a7adfe8ffb..bd69c60436 100644 --- a/pallets/subtensor/src/migrations/migrate_total_issuance.rs +++ b/pallets/subtensor/src/migrations/migrate_total_issuance.rs @@ -43,17 +43,18 @@ pub fn migrate_total_issuance(test: bool) -> Weight { // Execute migration if the current storage version is 5 or if in test mode if Pallet::::on_chain_storage_version() == StorageVersion::new(5) || test { // Calculate the sum of all stake values - let stake_sum: u64 = Owner::::iter() + let stake_sum = Owner::::iter() .map(|(hotkey, _coldkey)| Pallet::::get_total_stake_for_hotkey(&hotkey)) - .fold(0, |acc, stake| acc.saturating_add(stake)); + .fold(TaoCurrency::ZERO, |acc, stake| acc.saturating_add(stake)); // Add weight for reading all Owner and TotalHotkeyStake entries weight = weight.saturating_add( T::DbWeight::get().reads((Owner::::iter().count() as u64).saturating_mul(2)), ); // Calculate the sum of all locked subnet values - let locked_sum: u64 = - SubnetLocked::::iter().fold(0, |acc, (_, locked)| acc.saturating_add(locked)); + let locked_sum = SubnetLocked::::iter().fold(TaoCurrency::ZERO, |acc, (_, locked)| { + acc.saturating_add(locked) + }); // Add weight for reading all subnet locked entries weight = weight .saturating_add(T::DbWeight::get().reads(SubnetLocked::::iter().count() as u64)); @@ -67,9 +68,9 @@ pub fn migrate_total_issuance(test: bool) -> Weight { match TryInto::::try_into(total_balance) { Ok(total_balance_sum) => { // Compute the total issuance value - let total_issuance_value: u64 = stake_sum - .saturating_add(total_balance_sum) - .saturating_add(locked_sum); + let total_issuance_value = stake_sum + .saturating_add(total_balance_sum.into()) + .saturating_add(locked_sum.into()); // Update the total issuance in storage TotalIssuance::::put(total_issuance_value); diff --git a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs index 25a11958f0..cf9b1fdf07 100644 --- a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs +++ b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs @@ -51,15 +51,14 @@ pub fn migrate_transfer_ownership_to_foundation(coldkey: [u8; 32]) -> if onchain_version < new_storage_version { info!( target: LOG_TARGET, - "Migrating subnet 1 and 11 to foundation control. Current version: {:?}", - onchain_version + "Migrating subnet 1 and 11 to foundation control. Current version: {onchain_version:?}" ); // Decode the foundation's coldkey into an AccountId // TODO: Consider error handling for decoding failure let coldkey_account: T::AccountId = T::AccountId::decode(&mut &coldkey[..]) .expect("coldkey should be a valid 32-byte array"); - info!(target: LOG_TARGET, "Foundation coldkey: {:?}", coldkey_account); + info!(target: LOG_TARGET, "Foundation coldkey: {coldkey_account:?}"); // Get the current block number let current_block = Pallet::::get_current_block_as_u64(); diff --git a/pallets/subtensor/src/migrations/migrate_upgrade_revealed_commitments.rs b/pallets/subtensor/src/migrations/migrate_upgrade_revealed_commitments.rs index eb15bfe0af..6c10bf24e3 100644 --- a/pallets/subtensor/src/migrations/migrate_upgrade_revealed_commitments.rs +++ b/pallets/subtensor/src/migrations/migrate_upgrade_revealed_commitments.rs @@ -38,10 +38,7 @@ pub fn migrate_upgrade_revealed_commitments() -> Weight { }; weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count)); - log::info!( - "Removed {} entries from `RevealedCommitments`.", - removed_entries_count - ); + log::info!("Removed {removed_entries_count} entries from `RevealedCommitments`."); // ------------------------------------------------------------- // 2) Mark this migration as completed diff --git a/pallets/subtensor/src/migrations/mod.rs b/pallets/subtensor/src/migrations/mod.rs index 3acf7fafc9..cdf142357b 100644 --- a/pallets/subtensor/src/migrations/mod.rs +++ b/pallets/subtensor/src/migrations/mod.rs @@ -11,6 +11,7 @@ pub mod migrate_create_root_network; pub mod migrate_crv3_commits_add_block; pub mod migrate_delete_subnet_21; pub mod migrate_delete_subnet_3; +pub mod migrate_disable_commit_reveal; pub mod migrate_fix_is_network_member; pub mod migrate_fix_root_subnet_tao; pub mod migrate_identities_v2; @@ -57,7 +58,7 @@ pub(crate) fn migrate_storage( return weight; } - log::info!("Running migration '{}'", migration_name); + log::info!("Running migration '{migration_name}'"); let pallet_name = twox_128(pallet_name.as_bytes()); let storage_name = twox_128(storage_name.as_bytes()); @@ -66,7 +67,7 @@ pub(crate) fn migrate_storage( // Remove all entries. let removed_entries_count = match clear_prefix(&prefix, Some(u32::MAX)) { KillStorageResult::AllRemoved(removed) => { - log::info!("Removed all entries from {:?}.", storage_name); + log::info!("Removed all entries from {storage_name:?}."); // Mark migration as completed HasMigrationRun::::insert(&migration_name_bytes, true); @@ -75,7 +76,7 @@ pub(crate) fn migrate_storage( removed as u64 } KillStorageResult::SomeRemaining(removed) => { - log::info!("Failed to remove all entries from {:?}", storage_name); + log::info!("Failed to remove all entries from {storage_name:?}"); removed as u64 } }; @@ -83,9 +84,7 @@ pub(crate) fn migrate_storage( weight = weight.saturating_add(T::DbWeight::get().writes(removed_entries_count as u64)); log::info!( - "Migration '{:?}' completed successfully. {:?} entries removed.", - migration_name, - removed_entries_count + "Migration '{migration_name:?}' completed successfully. {removed_entries_count:?} entries removed." ); weight diff --git a/pallets/subtensor/src/rpc_info/dynamic_info.rs b/pallets/subtensor/src/rpc_info/dynamic_info.rs index b4394bc68c..28b3990082 100644 --- a/pallets/subtensor/src/rpc_info/dynamic_info.rs +++ b/pallets/subtensor/src/rpc_info/dynamic_info.rs @@ -4,9 +4,9 @@ use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; -#[freeze_struct("944ecd330621c61e")] +#[freeze_struct("e526a1c6d2303d32")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct DynamicInfo { netuid: Compact, @@ -20,12 +20,12 @@ pub struct DynamicInfo { emission: Compact, alpha_in: Compact, alpha_out: Compact, - tao_in: Compact, + tao_in: Compact, alpha_out_emission: Compact, alpha_in_emission: Compact, - tao_in_emission: Compact, + tao_in_emission: Compact, pending_alpha_emission: Compact, - pending_root_emission: Compact, + pending_root_emission: Compact, subnet_volume: Compact, network_registered_at: Compact, subnet_identity: Option, diff --git a/pallets/subtensor/src/rpc_info/metagraph.rs b/pallets/subtensor/src/rpc_info/metagraph.rs index 3f48c9ad45..7f9dc46bee 100644 --- a/pallets/subtensor/src/rpc_info/metagraph.rs +++ b/pallets/subtensor/src/rpc_info/metagraph.rs @@ -7,9 +7,9 @@ use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; -#[freeze_struct("c25c5560ffd47ccb")] +#[freeze_struct("6fc49d5a7dc0e339")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct Metagraph { // Subnet index @@ -35,12 +35,12 @@ pub struct Metagraph { subnet_emission: Compact, // subnet emission via stao alpha_in: Compact, // amount of alpha in reserve alpha_out: Compact, // amount of alpha outstanding - tao_in: Compact, // amount of tao injected per block + tao_in: Compact, // amount of tao injected per block alpha_out_emission: Compact, // amount injected in alpha reserves per block alpha_in_emission: Compact, // amount injected outstanding per block - tao_in_emission: Compact, // amount of tao injected per block + tao_in_emission: Compact, // amount of tao injected per block pending_alpha_emission: Compact, // pending alpha to be distributed - pending_root_emission: Compact, // panding tao for root divs to be distributed + pending_root_emission: Compact, // pending tao for root divs to be distributed subnet_volume: Compact, // volume of the subnet in TAO moving_price: I96F32, // subnet moving price. @@ -52,34 +52,34 @@ pub struct Metagraph { min_allowed_weights: Compact, // min allowed weights per val max_weights_limit: Compact, // max allowed weights per val weights_version: Compact, // allowed weights version - weights_rate_limit: Compact, // rate limit on weights. + weights_rate_limit: Compact, // rate limit on weights activity_cutoff: Compact, // validator weights cut off period in blocks - max_validators: Compact, // max allowed validators. + max_validators: Compact, // max allowed validators // Registration num_uids: Compact, max_uids: Compact, - burn: Compact, // current burn cost.. - difficulty: Compact, // current difficulty. - registration_allowed: bool, // allows registrations. - pow_registration_allowed: bool, // pow registration enabled. + burn: Compact, // current burn cost + difficulty: Compact, // current difficulty + registration_allowed: bool, // allows registrations + pow_registration_allowed: bool, // pow registration enabled immunity_period: Compact, // subnet miner immunity period min_difficulty: Compact, // min pow difficulty max_difficulty: Compact, // max pow difficulty - min_burn: Compact, // min tao burn - max_burn: Compact, // max tao burn - adjustment_alpha: Compact, // adjustment speed for registration params. + min_burn: Compact, // min tao burn + max_burn: Compact, // max tao burn + adjustment_alpha: Compact, // adjustment speed for registration params adjustment_interval: Compact, // pow and burn adjustment interval target_regs_per_interval: Compact, // target registrations per interval - max_regs_per_block: Compact, // max registrations per block. + max_regs_per_block: Compact, // max registrations per block serving_rate_limit: Compact, // axon serving rate limit // CR - commit_reveal_weights_enabled: bool, // Is CR enabled. + commit_reveal_weights_enabled: bool, // Is CR enabled commit_reveal_period: Compact, // Commit reveal interval // Bonds - liquid_alpha_enabled: bool, // Bonds liquid enabled. + liquid_alpha_enabled: bool, // Bonds liquid enabled alpha_high: Compact, // Alpha param high alpha_low: Compact, // Alpha param low bonds_moving_avg: Compact, // Bonds moving avg @@ -88,7 +88,7 @@ pub struct Metagraph { hotkeys: Vec, // hotkey per UID coldkeys: Vec, // coldkey per UID identities: Vec>, // coldkeys identities - axons: Vec, // UID axons. + axons: Vec, // UID axons active: Vec, // Avtive per UID validator_permit: Vec, // Val permit per UID pruning_score: Vec>, // Pruning per UID @@ -100,16 +100,16 @@ pub struct Metagraph { trust: Vec>, // Trust per UID rank: Vec>, // Rank per UID block_at_registration: Vec>, // Reg block per UID - alpha_stake: Vec>, // Alpha staked per UID - tao_stake: Vec>, // TAO staked per UID - total_stake: Vec>, // Total stake per UID + alpha_stake: Vec>, // Alpha staked per UID + tao_stake: Vec>, // TAO staked per UID + total_stake: Vec>, // Total stake per UID // Dividend break down. - tao_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payouts in tao via root. + tao_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payouts in tao via root. alpha_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payout in alpha via subnet. } -#[freeze_struct("2fa92e896b40a104")] +#[freeze_struct("7604bd3817c55848")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SelectiveMetagraph { // Subnet index @@ -118,31 +118,31 @@ pub struct SelectiveMetagraph { // Name and symbol name: Option>>, // name symbol: Option>>, // token symbol - identity: Option>, // identity information. + identity: Option>, // identity information network_registered_at: Option>, // block at registration // Keys for owner. owner_hotkey: Option, // hotkey - owner_coldkey: Option, // coldkey. + owner_coldkey: Option, // coldkey - // Tempo terms. - block: Option>, // block at call. + // Tempo terms + block: Option>, // block at call tempo: Option>, // epoch tempo last_step: Option>, // last epoch - blocks_since_last_step: Option>, // blocks since last epoch. + blocks_since_last_step: Option>, // blocks since last epoch // Subnet emission terms subnet_emission: Option>, // subnet emission via stao alpha_in: Option>, // amount of alpha in reserve alpha_out: Option>, // amount of alpha outstanding - tao_in: Option>, // amount of tao injected per block + tao_in: Option>, // amount of tao injected per block alpha_out_emission: Option>, // amount injected in alpha reserves per block alpha_in_emission: Option>, // amount injected outstanding per block - tao_in_emission: Option>, // amount of tao injected per block + tao_in_emission: Option>, // amount of tao injected per block pending_alpha_emission: Option>, // pending alpha to be distributed - pending_root_emission: Option>, // panding tao for root divs to be distributed - subnet_volume: Option>, // volume of the subnet in TAO - moving_price: Option, // subnet moving price. + pending_root_emission: Option>, // panding tao for root divs to be distributed + subnet_volume: Option>, // volume of the subnet in TAO + moving_price: Option, // subnet moving price. // Hparams for epoch rho: Option>, // subnet rho param @@ -152,36 +152,36 @@ pub struct SelectiveMetagraph { min_allowed_weights: Option>, // min allowed weights per val max_weights_limit: Option>, // max allowed weights per val weights_version: Option>, // allowed weights version - weights_rate_limit: Option>, // rate limit on weights. + weights_rate_limit: Option>, // rate limit on weights activity_cutoff: Option>, // validator weights cut off period in blocks - max_validators: Option>, // max allowed validators. + max_validators: Option>, // max allowed validators // Registration num_uids: Option>, max_uids: Option>, - burn: Option>, // current burn cost.. - difficulty: Option>, // current difficulty. - registration_allowed: Option, // allows registrations. - pow_registration_allowed: Option, // pow registration enabled. - immunity_period: Option>, // subnet miner immunity period - min_difficulty: Option>, // min pow difficulty - max_difficulty: Option>, // max pow difficulty - min_burn: Option>, // min tao burn - max_burn: Option>, // max tao burn - adjustment_alpha: Option>, // adjustment speed for registration params. - adjustment_interval: Option>, // pow and burn adjustment interval + burn: Option>, // current burn cost + difficulty: Option>, // current difficulty + registration_allowed: Option, // allows registrations + pow_registration_allowed: Option, // pow registration enabled + immunity_period: Option>, // subnet miner immunity period + min_difficulty: Option>, // min pow difficulty + max_difficulty: Option>, // max pow difficulty + min_burn: Option>, // min tao burn + max_burn: Option>, // max tao burn + adjustment_alpha: Option>, // adjustment speed for registration params + adjustment_interval: Option>, // pow and burn adjustment interval target_regs_per_interval: Option>, // target registrations per interval - max_regs_per_block: Option>, // max registrations per block. - serving_rate_limit: Option>, // axon serving rate limit + max_regs_per_block: Option>, // max registrations per block + serving_rate_limit: Option>, // axon serving rate limit // CR - commit_reveal_weights_enabled: Option, // Is CR enabled. + commit_reveal_weights_enabled: Option, // Is CR enabled commit_reveal_period: Option>, // Commit reveal interval // Bonds - liquid_alpha_enabled: Option, // Bonds liquid enabled. - alpha_high: Option>, // Alpha param high - alpha_low: Option>, // Alpha param low + liquid_alpha_enabled: Option, // Bonds liquid enabled + alpha_high: Option>, // Alpha param high + alpha_low: Option>, // Alpha param low bonds_moving_avg: Option>, // Bonds moving avg // Metagraph info. @@ -200,13 +200,13 @@ pub struct SelectiveMetagraph { trust: Option>>, // Trust per UID rank: Option>>, // Rank per UID block_at_registration: Option>>, // Reg block per UID - alpha_stake: Option>>, // Alpha staked per UID - tao_stake: Option>>, // TAO staked per UID - total_stake: Option>>, // Total stake per UID + alpha_stake: Option>>, // Alpha staked per UID + tao_stake: Option>>, // TAO staked per UID + total_stake: Option>>, // Total stake per UID // Dividend break down. - tao_dividends_per_hotkey: Option)>>, // List of dividend payouts in tao via root. - alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet. + tao_dividends_per_hotkey: Option)>>, // List of dividend payouts in tao via root + alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet // validators validators: Option>>, // List of validators @@ -632,7 +632,7 @@ impl Pallet { identities.push(IdentitiesV2::::get(coldkey.clone())); axons.push(Self::get_axon_info(netuid, &hotkey)); } - let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; for hotkey in hotkeys.clone() { let tao_divs = TaoDividendsPerSubnet::::get(netuid, hotkey.clone()); @@ -707,12 +707,12 @@ impl Pallet { registration_allowed: Self::get_network_registration_allowed(netuid), // allows registrations. pow_registration_allowed: Self::get_network_pow_registration_allowed(netuid), // allows pow registrations. difficulty: Self::get_difficulty_as_u64(netuid).into(), // current difficulty. - burn: Self::get_burn_as_u64(netuid).into(), + burn: Self::get_burn(netuid).into(), immunity_period: Self::get_immunity_period(netuid).into(), // subnet miner immunity period min_difficulty: Self::get_min_difficulty(netuid).into(), // min pow difficulty max_difficulty: Self::get_max_difficulty(netuid).into(), // max pow difficulty - min_burn: Self::get_min_burn_as_u64(netuid).into(), // min tao burn - max_burn: Self::get_max_burn_as_u64(netuid).into(), // max tao burn + min_burn: Self::get_min_burn(netuid).into(), // min tao burn + max_burn: Self::get_max_burn(netuid).into(), // max tao burn adjustment_alpha: Self::get_adjustment_alpha(netuid).into(), // adjustment speed for registration params. adjustment_interval: Self::get_adjustment_interval(netuid).into(), // pow and burn adjustment interval target_regs_per_interval: Self::get_target_registrations_per_interval(netuid).into(), // target registrations per interval @@ -771,16 +771,16 @@ impl Pallet { block_at_registration, // Reg block per UID alpha_stake: alpha_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), // Alpha staked per UID + .map(|xi| Compact::from(AlphaCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), // Alpha staked per UID tao_stake: tao_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), // TAO staked per UID + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), // TAO staked per UID total_stake: total_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), // Total stake per UID + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), // Total stake per UID // Dividend break down. tao_dividends_per_hotkey, @@ -1024,7 +1024,7 @@ impl Pallet { Some(SelectiveMetagraphIndex::Burn) => SelectiveMetagraph { netuid: netuid.into(), - burn: Some(Self::get_burn_as_u64(netuid).into()), + burn: Some(Self::get_burn(netuid).into()), ..Default::default() }, @@ -1045,12 +1045,12 @@ impl Pallet { }, Some(SelectiveMetagraphIndex::MinBurn) => SelectiveMetagraph { netuid: netuid.into(), - min_burn: Some(Self::get_min_burn_as_u64(netuid).into()), + min_burn: Some(Self::get_min_burn(netuid).into()), ..Default::default() }, Some(SelectiveMetagraphIndex::MaxBurn) => SelectiveMetagraph { netuid: netuid.into(), - max_burn: Some(Self::get_max_burn_as_u64(netuid).into()), + max_burn: Some(Self::get_max_burn(netuid).into()), ..Default::default() }, Some(SelectiveMetagraphIndex::AdjustmentAlpha) => SelectiveMetagraph { @@ -1290,8 +1290,8 @@ impl Pallet { alpha_stake: Some( alpha_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), + .map(|xi| Compact::from(AlphaCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), ), ..Default::default() } @@ -1304,8 +1304,8 @@ impl Pallet { tao_stake: Some( tao_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), ), ..Default::default() } @@ -1318,8 +1318,8 @@ impl Pallet { total_stake: Some( total_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(), + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect::>>(), ), ..Default::default() } @@ -1333,7 +1333,8 @@ impl Pallet { let hotkey = Keys::::get(netuid, uid); hotkeys.push(hotkey.clone()); } - let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = + vec![]; for hotkey in hotkeys.clone() { let tao_divs = TaoDividendsPerSubnet::::get(netuid, hotkey.clone()); tao_dividends_per_hotkey.push((hotkey.clone(), tao_divs.into())); diff --git a/pallets/subtensor/src/rpc_info/show_subnet.rs b/pallets/subtensor/src/rpc_info/show_subnet.rs index 4c39542ace..2123345a4e 100644 --- a/pallets/subtensor/src/rpc_info/show_subnet.rs +++ b/pallets/subtensor/src/rpc_info/show_subnet.rs @@ -4,9 +4,9 @@ use crate::epoch::math::*; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; -#[freeze_struct("c990700ae235dee9")] +#[freeze_struct("9354762261420485")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetState { netuid: Compact, @@ -23,9 +23,9 @@ pub struct SubnetState { trust: Vec>, rank: Vec>, block_at_registration: Vec>, - alpha_stake: Vec>, - tao_stake: Vec>, - total_stake: Vec>, + alpha_stake: Vec>, + tao_stake: Vec>, + total_stake: Vec>, emission_history: Vec>>, // identities: Vec, // tao_stake: Compact, @@ -136,18 +136,18 @@ impl Pallet { Vec, Vec, ) = Self::get_stake_weights_for_network(netuid); - let alpha_stake: Vec> = alpha_stake_fl + let alpha_stake: Vec> = alpha_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(); - let tao_stake: Vec> = tao_stake_fl + .map(|xi| Compact::from(AlphaCurrency::from(fixed64_to_u64(*xi)))) + .collect(); + let tao_stake: Vec> = tao_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(); - let total_stake: Vec> = total_stake_fl + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect(); + let total_stake: Vec> = total_stake_fl .iter() - .map(|xi| Compact::from(fixed64_to_u64(*xi))) - .collect::>>(); + .map(|xi| Compact::from(TaoCurrency::from(fixed64_to_u64(*xi)))) + .collect(); let emission_history = Self::get_emissions_history(hotkeys.clone()); Some(SubnetState { netuid: netuid.into(), diff --git a/pallets/subtensor/src/rpc_info/stake_info.rs b/pallets/subtensor/src/rpc_info/stake_info.rs index 23c2a7df0e..84e9e6d6b7 100644 --- a/pallets/subtensor/src/rpc_info/stake_info.rs +++ b/pallets/subtensor/src/rpc_info/stake_info.rs @@ -2,12 +2,12 @@ extern crate alloc; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; use subtensor_swap_interface::SwapHandler; use super::*; -#[freeze_struct("cff08b08c64eb867")] +#[freeze_struct("28269be895d7b5ba")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct StakeInfo { hotkey: AccountId, @@ -16,7 +16,7 @@ pub struct StakeInfo { stake: Compact, locked: Compact, emission: Compact, - tao_emission: Compact, + tao_emission: Compact, drain: Compact, is_registered: bool, } @@ -43,7 +43,7 @@ impl Pallet { continue; } let emission = AlphaDividendsPerSubnet::::get(*netuid_i, &hotkey_i); - let tao_emission: u64 = TaoDividendsPerSubnet::::get(*netuid_i, &hotkey_i); + let tao_emission = TaoDividendsPerSubnet::::get(*netuid_i, &hotkey_i); let is_registered: bool = Self::is_hotkey_registered_on_network(*netuid_i, hotkey_i); stake_info_for_coldkey.push(StakeInfo { @@ -101,7 +101,7 @@ impl Pallet { netuid, ); let emission = AlphaDividendsPerSubnet::::get(netuid, &hotkey_account); - let tao_emission: u64 = TaoDividendsPerSubnet::::get(netuid, &hotkey_account); + let tao_emission = TaoDividendsPerSubnet::::get(netuid, &hotkey_account); let is_registered: bool = Self::is_hotkey_registered_on_network(netuid, &hotkey_account); Some(StakeInfo { diff --git a/pallets/subtensor/src/rpc_info/subnet_info.rs b/pallets/subtensor/src/rpc_info/subnet_info.rs index cab1f8800b..d1e0a05419 100644 --- a/pallets/subtensor/src/rpc_info/subnet_info.rs +++ b/pallets/subtensor/src/rpc_info/subnet_info.rs @@ -4,9 +4,9 @@ use frame_support::storage::IterableStorageMap; extern crate alloc; use codec::Compact; use substrate_fixed::types::I32F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; -#[freeze_struct("dd2293544ffd8f2e")] +#[freeze_struct("edd6bd3273dfea76")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetInfo { netuid: Compact, @@ -25,11 +25,11 @@ pub struct SubnetInfo { network_modality: Compact, network_connect: Vec<[u16; 2]>, emission_values: Compact, - burn: Compact, + burn: Compact, owner: AccountId, } -#[freeze_struct("4e60a45245fc2ad1")] +#[freeze_struct("e5f66b14b33331c3")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetInfov2 { netuid: Compact, @@ -48,12 +48,12 @@ pub struct SubnetInfov2 { network_modality: Compact, network_connect: Vec<[u16; 2]>, emission_value: Compact, - burn: Compact, + burn: Compact, owner: AccountId, identity: Option, } -#[freeze_struct("7b506df55bd44646")] +#[freeze_struct("24f0815487879ed3")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetHyperparams { rho: Compact, @@ -70,8 +70,8 @@ pub struct SubnetHyperparams { activity_cutoff: Compact, pub registration_allowed: bool, target_regs_per_interval: Compact, - min_burn: Compact, - max_burn: Compact, + min_burn: Compact, + max_burn: Compact, bonds_moving_avg: Compact, max_regs_per_block: Compact, serving_rate_limit: Compact, @@ -85,7 +85,7 @@ pub struct SubnetHyperparams { liquid_alpha_enabled: bool, } -#[freeze_struct("a13c536303dec16f")] +#[freeze_struct("2153c3f3bb01ef66")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetHyperparamsV2 { rho: Compact, @@ -102,8 +102,8 @@ pub struct SubnetHyperparamsV2 { activity_cutoff: Compact, pub registration_allowed: bool, target_regs_per_interval: Compact, - min_burn: Compact, - max_burn: Compact, + min_burn: Compact, + max_burn: Compact, bonds_moving_avg: Compact, max_regs_per_block: Compact, serving_rate_limit: Compact, @@ -142,7 +142,7 @@ impl Pallet { let blocks_since_last_step = Self::get_blocks_since_last_step(netuid); let tempo = Self::get_tempo(netuid); let network_modality = >::get(netuid); - let burn: Compact = Self::get_burn_as_u64(netuid).into(); + let burn = Compact::from(Self::get_burn(netuid)); // DEPRECATED let network_connect: Vec<[u16; 2]> = Vec::<[u16; 2]>::new(); // DEPRECATED for ( _netuid_, con_req) in < NetworkConnect as IterableStorageDoubleMap >::iter_prefix(netuid) { @@ -211,7 +211,7 @@ impl Pallet { let blocks_since_last_step = Self::get_blocks_since_last_step(netuid); let tempo = Self::get_tempo(netuid); let network_modality = >::get(netuid); - let burn: Compact = Self::get_burn_as_u64(netuid).into(); + let burn = Compact::from(Self::get_burn(netuid)); let identity: Option = SubnetIdentitiesV3::::get(netuid); // DEPRECATED @@ -284,8 +284,8 @@ impl Pallet { let activity_cutoff = Self::get_activity_cutoff(netuid); let registration_allowed = Self::get_network_registration_allowed(netuid); let target_regs_per_interval = Self::get_target_registrations_per_interval(netuid); - let min_burn = Self::get_min_burn_as_u64(netuid); - let max_burn = Self::get_max_burn_as_u64(netuid); + let min_burn = Self::get_min_burn(netuid); + let max_burn = Self::get_max_burn(netuid); let bonds_moving_avg = Self::get_bonds_moving_average(netuid); let max_regs_per_block = Self::get_max_registrations_per_block(netuid); let serving_rate_limit = Self::get_serving_rate_limit(netuid); @@ -347,8 +347,8 @@ impl Pallet { let activity_cutoff = Self::get_activity_cutoff(netuid); let registration_allowed = Self::get_network_registration_allowed(netuid); let target_regs_per_interval = Self::get_target_registrations_per_interval(netuid); - let min_burn = Self::get_min_burn_as_u64(netuid); - let max_burn = Self::get_max_burn_as_u64(netuid); + let min_burn = Self::get_min_burn(netuid); + let max_burn = Self::get_max_burn(netuid); let bonds_moving_avg = Self::get_bonds_moving_average(netuid); let max_regs_per_block = Self::get_max_registrations_per_block(netuid); let serving_rate_limit = Self::get_serving_rate_limit(netuid); diff --git a/pallets/subtensor/src/staking/add_stake.rs b/pallets/subtensor/src/staking/add_stake.rs index 7388c9484a..fe90de270a 100644 --- a/pallets/subtensor/src/staking/add_stake.rs +++ b/pallets/subtensor/src/staking/add_stake.rs @@ -1,5 +1,5 @@ use substrate_fixed::types::I96F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::*; @@ -41,16 +41,12 @@ impl Pallet { origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - stake_to_be_added: u64, + stake_to_be_added: TaoCurrency, ) -> dispatch::DispatchResult { // 1. We check that the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::debug!( - "do_add_stake( origin:{:?} hotkey:{:?}, netuid:{:?}, stake_to_be_added:{:?} )", - coldkey, - hotkey, - netuid, - stake_to_be_added + "do_add_stake( origin:{coldkey:?} hotkey:{hotkey:?}, netuid:{netuid:?}, stake_to_be_added:{stake_to_be_added:?} )" ); Self::ensure_subtoken_enabled(netuid)?; @@ -67,7 +63,9 @@ impl Pallet { // 3. Ensure the remove operation from the coldkey is a success. let tao_staked: I96F32 = - Self::remove_balance_from_coldkey_account(&coldkey, stake_to_be_added)?.into(); + Self::remove_balance_from_coldkey_account(&coldkey, stake_to_be_added.into())? + .to_u64() + .into(); // 4. Swap the stake into alpha on the subnet and increase counters. // Emit the staking event. @@ -75,8 +73,8 @@ impl Pallet { &hotkey, &coldkey, netuid, - tao_staked.saturating_to_num::(), - T::SwapInterface::max_price(), + tao_staked.saturating_to_num::().into(), + T::SwapInterface::max_price().into(), true, )?; @@ -128,22 +126,18 @@ impl Pallet { origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - stake_to_be_added: u64, - limit_price: u64, + stake_to_be_added: TaoCurrency, + limit_price: TaoCurrency, allow_partial: bool, ) -> dispatch::DispatchResult { // 1. We check that the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::debug!( - "do_add_stake( origin:{:?} hotkey:{:?}, netuid:{:?}, stake_to_be_added:{:?} )", - coldkey, - hotkey, - netuid, - stake_to_be_added + "do_add_stake( origin:{coldkey:?} hotkey:{hotkey:?}, netuid:{netuid:?}, stake_to_be_added:{stake_to_be_added:?} )" ); // 2. Calculate the maximum amount that can be executed with price limit - let max_amount = Self::get_max_amount_add(netuid, limit_price)?; + let max_amount: TaoCurrency = Self::get_max_amount_add(netuid, limit_price)?.into(); let mut possible_stake = stake_to_be_added; if possible_stake > max_amount { possible_stake = max_amount; @@ -155,7 +149,7 @@ impl Pallet { &hotkey, netuid, stake_to_be_added, - max_amount, + max_amount.into(), allow_partial, )?; @@ -165,7 +159,8 @@ impl Pallet { } // 5. Ensure the remove operation from the coldkey is a success. - let tao_staked: u64 = Self::remove_balance_from_coldkey_account(&coldkey, possible_stake)?; + let tao_staked = + Self::remove_balance_from_coldkey_account(&coldkey, possible_stake.into())?; // 6. Swap the stake into alpha on the subnet and increase counters. // Emit the staking event. @@ -176,12 +171,12 @@ impl Pallet { } // Returns the maximum amount of RAO that can be executed with price limit - pub fn get_max_amount_add(netuid: NetUid, limit_price: u64) -> Result> { + pub fn get_max_amount_add(netuid: NetUid, limit_price: TaoCurrency) -> Result> { // Corner case: root and stao // There's no slippage for root or stable subnets, so if limit price is 1e9 rao or // higher, then max_amount equals u64::MAX, otherwise it is 0. if netuid.is_root() || SubnetMechanism::::get(netuid) == 0 { - if limit_price >= 1_000_000_000 { + if limit_price >= 1_000_000_000.into() { return Ok(u64::MAX); } else { return Err(Error::ZeroMaxStakeAmount); @@ -193,7 +188,7 @@ impl Pallet { netuid.into(), OrderType::Buy, u64::MAX, - limit_price, + limit_price.into(), false, true, ) diff --git a/pallets/subtensor/src/staking/decrease_take.rs b/pallets/subtensor/src/staking/decrease_take.rs index c227aad8a3..43bc633431 100644 --- a/pallets/subtensor/src/staking/decrease_take.rs +++ b/pallets/subtensor/src/staking/decrease_take.rs @@ -34,12 +34,7 @@ impl Pallet { ) -> dispatch::DispatchResult { // --- 1. We check the coldkey signature. let coldkey = ensure_signed(origin)?; - log::debug!( - "do_decrease_take( origin:{:?} hotkey:{:?}, take:{:?} )", - coldkey, - hotkey, - take - ); + log::debug!("do_decrease_take( origin:{coldkey:?} hotkey:{hotkey:?}, take:{take:?} )"); // --- 2. Ensure we are delegating a known key. // Ensure that the coldkey is the owner. @@ -62,12 +57,7 @@ impl Pallet { Self::set_last_tx_block_delegate_take(&hotkey, block); // --- 6. Emit the take value. - log::debug!( - "TakeDecreased( coldkey:{:?}, hotkey:{:?}, take:{:?} )", - coldkey, - hotkey, - take - ); + log::debug!("TakeDecreased( coldkey:{coldkey:?}, hotkey:{hotkey:?}, take:{take:?} )"); Self::deposit_event(Event::TakeDecreased(coldkey, hotkey, take)); // --- 6. Ok and return. diff --git a/pallets/subtensor/src/staking/helpers.rs b/pallets/subtensor/src/staking/helpers.rs index 4b897fef96..7b8d0ba1de 100644 --- a/pallets/subtensor/src/staking/helpers.rs +++ b/pallets/subtensor/src/staking/helpers.rs @@ -7,7 +7,7 @@ use frame_support::traits::{ }; use safe_math::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::*; @@ -27,24 +27,24 @@ impl Pallet { // Returns the total amount of stake in the staking table. // - pub fn get_total_stake() -> u64 { + pub fn get_total_stake() -> TaoCurrency { TotalStake::::get() } // Increases the total amount of stake by the passed amount. // - pub fn increase_total_stake(increment: u64) { + pub fn increase_total_stake(increment: TaoCurrency) { TotalStake::::put(Self::get_total_stake().saturating_add(increment)); } // Decreases the total amount of stake by the passed amount. // - pub fn decrease_total_stake(decrement: u64) { + pub fn decrease_total_stake(decrement: TaoCurrency) { TotalStake::::put(Self::get_total_stake().saturating_sub(decrement)); } /// Returns the total amount of stake (in TAO) under a hotkey (delegative or otherwise) - pub fn get_total_stake_for_hotkey(hotkey: &T::AccountId) -> u64 { + pub fn get_total_stake_for_hotkey(hotkey: &T::AccountId) -> TaoCurrency { Self::get_all_subnet_netuids() .into_iter() .map(|netuid| { @@ -58,11 +58,12 @@ impl Pallet { }) .sum::() .saturating_to_num::() + .into() } // Returns the total amount of stake under a coldkey // - pub fn get_total_stake_for_coldkey(coldkey: &T::AccountId) -> u64 { + pub fn get_total_stake_for_coldkey(coldkey: &T::AccountId) -> TaoCurrency { let hotkeys = StakingHotkeys::::get(coldkey); hotkeys .iter() @@ -90,6 +91,7 @@ impl Pallet { .sum::() }) .sum::() + .into() } // Creates a cold - hot pairing account if the hotkey is not already an active account. @@ -200,13 +202,13 @@ impl Pallet { coldkey, netuid, alpha_stake, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), false, ); if let Ok(cleared_stake) = maybe_cleared_stake { // Add the stake to the coldkey account. - Self::add_balance_to_coldkey_account(coldkey, cleared_stake); + Self::add_balance_to_coldkey_account(coldkey, cleared_stake.into()); } else { // Just clear small alpha let alpha = @@ -269,9 +271,9 @@ impl Pallet { pub fn remove_balance_from_coldkey_account( coldkey: &T::AccountId, amount: <::Currency as fungible::Inspect<::AccountId>>::Balance, - ) -> Result { + ) -> Result { if amount == 0 { - return Ok(0); + return Ok(TaoCurrency::ZERO); } let credit = ::Currency::withdraw( @@ -288,7 +290,7 @@ impl Pallet { return Err(Error::::ZeroBalanceAfterWithdrawn.into()); } - Ok(credit) + Ok(credit.into()) } pub fn kill_coldkey_account( diff --git a/pallets/subtensor/src/staking/increase_take.rs b/pallets/subtensor/src/staking/increase_take.rs index 349f86e7cf..3a101c7e0f 100644 --- a/pallets/subtensor/src/staking/increase_take.rs +++ b/pallets/subtensor/src/staking/increase_take.rs @@ -37,12 +37,7 @@ impl Pallet { ) -> dispatch::DispatchResult { // --- 1. We check the coldkey signature. let coldkey = ensure_signed(origin)?; - log::debug!( - "do_increase_take( origin:{:?} hotkey:{:?}, take:{:?} )", - coldkey, - hotkey, - take - ); + log::debug!("do_increase_take( origin:{coldkey:?} hotkey:{hotkey:?}, take:{take:?} )"); // --- 2. Ensure we are delegating a known key. // Ensure that the coldkey is the owner. @@ -74,12 +69,7 @@ impl Pallet { Delegates::::insert(hotkey.clone(), take); // --- 7. Emit the take value. - log::debug!( - "TakeIncreased( coldkey:{:?}, hotkey:{:?}, take:{:?} )", - coldkey, - hotkey, - take - ); + log::debug!("TakeIncreased( coldkey:{coldkey:?}, hotkey:{hotkey:?}, take:{take:?} )"); Self::deposit_event(Event::TakeIncreased(coldkey, hotkey, take)); // --- 8. Ok and return. diff --git a/pallets/subtensor/src/staking/move_stake.rs b/pallets/subtensor/src/staking/move_stake.rs index 15f2dd511a..c81569e49d 100644 --- a/pallets/subtensor/src/staking/move_stake.rs +++ b/pallets/subtensor/src/staking/move_stake.rs @@ -2,7 +2,7 @@ use super::*; use safe_math::*; use sp_core::Get; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; use subtensor_swap_interface::SwapHandler; impl Pallet { @@ -88,11 +88,7 @@ impl Pallet { /// Emits a `TransferToggle` event upon successful completion. pub fn toggle_transfer(netuid: NetUid, toggle: bool) -> dispatch::DispatchResult { TransferToggle::::insert(netuid, toggle); - log::debug!( - "TransferToggle( netuid: {:?}, toggle: {:?} ) ", - netuid, - toggle - ); + log::debug!("TransferToggle( netuid: {netuid:?}, toggle: {toggle:?} ) "); Self::deposit_event(Event::TransferToggle(netuid, toggle)); Ok(()) } @@ -150,13 +146,7 @@ impl Pallet { // 9. Emit an event for logging/monitoring. log::debug!( - "StakeTransferred(origin_coldkey: {:?}, destination_coldkey: {:?}, hotkey: {:?}, origin_netuid: {:?}, destination_netuid: {:?}, amount: {:?})", - coldkey, - destination_coldkey, - hotkey, - origin_netuid, - destination_netuid, - tao_moved + "StakeTransferred(origin_coldkey: {coldkey:?}, destination_coldkey: {destination_coldkey:?}, hotkey: {hotkey:?}, origin_netuid: {origin_netuid:?}, destination_netuid: {destination_netuid:?}, amount: {tao_moved:?})" ); Self::deposit_event(Event::StakeTransferred( coldkey, @@ -221,12 +211,7 @@ impl Pallet { // Emit an event for logging. log::debug!( - "StakeSwapped(coldkey: {:?}, hotkey: {:?}, origin_netuid: {:?}, destination_netuid: {:?}, amount: {:?})", - coldkey, - hotkey, - origin_netuid, - destination_netuid, - tao_moved + "StakeSwapped(coldkey: {coldkey:?}, hotkey: {hotkey:?}, origin_netuid: {origin_netuid:?}, destination_netuid: {destination_netuid:?}, amount: {tao_moved:?})" ); Self::deposit_event(Event::StakeSwapped( coldkey, @@ -271,7 +256,7 @@ impl Pallet { origin_netuid: NetUid, destination_netuid: NetUid, alpha_amount: AlphaCurrency, - limit_price: u64, + limit_price: TaoCurrency, allow_partial: bool, ) -> dispatch::DispatchResult { // Ensure the extrinsic is signed by the coldkey. @@ -294,12 +279,7 @@ impl Pallet { // Emit an event for logging. log::debug!( - "StakeSwapped(coldkey: {:?}, hotkey: {:?}, origin_netuid: {:?}, destination_netuid: {:?}, amount: {:?})", - coldkey, - hotkey, - origin_netuid, - destination_netuid, - tao_moved + "StakeSwapped(coldkey: {coldkey:?}, hotkey: {hotkey:?}, origin_netuid: {origin_netuid:?}, destination_netuid: {destination_netuid:?}, amount: {tao_moved:?})" ); Self::deposit_event(Event::StakeSwapped( coldkey, @@ -323,11 +303,20 @@ impl Pallet { origin_netuid: NetUid, destination_netuid: NetUid, alpha_amount: AlphaCurrency, - maybe_limit_price: Option, + maybe_limit_price: Option, maybe_allow_partial: Option, check_transfer_toggle: bool, set_limit: bool, - ) -> Result { + ) -> Result { + // Cap the alpha_amount at available Alpha because user might be paying transaxtion fees + // in Alpha and their total is already reduced by now. + let alpha_available = Self::get_stake_for_hotkey_and_coldkey_on_subnet( + origin_hotkey, + origin_coldkey, + origin_netuid, + ); + let alpha_amount = alpha_amount.min(alpha_available); + // Calculate the maximum amount that can be executed let max_amount = if origin_netuid != destination_netuid { if let Some(limit_price) = maybe_limit_price { @@ -367,7 +356,7 @@ impl Pallet { origin_coldkey, origin_netuid, move_amount, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), true, )?; @@ -385,7 +374,7 @@ impl Pallet { destination_coldkey, destination_netuid, tao_unstaked, - T::SwapInterface::max_price(), + T::SwapInterface::max_price().into(), set_limit, )?; } @@ -429,7 +418,7 @@ impl Pallet { pub fn get_max_amount_move( origin_netuid: NetUid, destination_netuid: NetUid, - limit_price: u64, + limit_price: TaoCurrency, ) -> Result> { let tao: U64F64 = U64F64::saturating_from_num(1_000_000_000); @@ -439,7 +428,7 @@ impl Pallet { if (origin_netuid.is_root() || SubnetMechanism::::get(origin_netuid) == 0) && (destination_netuid.is_root() || SubnetMechanism::::get(destination_netuid) == 0) { - if limit_price > tao.saturating_to_num::() { + if limit_price > tao.saturating_to_num::().into() { return Err(Error::ZeroMaxStakeAmount); } else { return Ok(AlphaCurrency::MAX); @@ -451,7 +440,7 @@ impl Pallet { if (origin_netuid.is_root() || SubnetMechanism::::get(origin_netuid) == 0) && (SubnetMechanism::::get(destination_netuid) == 1) { - if limit_price == 0 { + if limit_price.is_zero() { return Ok(AlphaCurrency::MAX); } else { // The destination price is reverted because the limit_price is origin_price / destination_price @@ -459,8 +448,12 @@ impl Pallet { .safe_div(U64F64::saturating_from_num(limit_price)) .saturating_mul(tao) .saturating_to_num::(); - return Self::get_max_amount_add(destination_netuid, destination_subnet_price) - .map(Into::into); + // FIXME: mixed types alpha/tao + return Self::get_max_amount_add( + destination_netuid, + destination_subnet_price.into(), + ) + .map(Into::into); } } @@ -469,7 +462,7 @@ impl Pallet { if (destination_netuid.is_root() || SubnetMechanism::::get(destination_netuid) == 0) && (SubnetMechanism::::get(origin_netuid) == 1) { - return Self::get_max_amount_remove(origin_netuid, limit_price); + return Self::get_max_amount_remove(origin_netuid, limit_price).into(); } // Corner case: SubnetTAO for any of two subnets is zero @@ -477,7 +470,7 @@ impl Pallet { .saturating_add(SubnetTaoProvided::::get(origin_netuid)); let subnet_tao_2 = SubnetTAO::::get(destination_netuid) .saturating_add(SubnetTaoProvided::::get(destination_netuid)); - if (subnet_tao_1 == 0) || (subnet_tao_2 == 0) { + if subnet_tao_1.is_zero() || subnet_tao_2.is_zero() { return Err(Error::ZeroMaxStakeAmount); } let subnet_tao_1_float: U64F64 = U64F64::saturating_from_num(subnet_tao_1); @@ -509,7 +502,7 @@ impl Pallet { } // Corner case: limit_price is zero - if limit_price == 0 { + if limit_price.is_zero() { return Ok(AlphaCurrency::MAX); } diff --git a/pallets/subtensor/src/staking/recycle_alpha.rs b/pallets/subtensor/src/staking/recycle_alpha.rs index 2fbbfb3b06..cbd5161a4c 100644 --- a/pallets/subtensor/src/staking/recycle_alpha.rs +++ b/pallets/subtensor/src/staking/recycle_alpha.rs @@ -42,7 +42,11 @@ impl Pallet { ); // Ensure that the hotkey has enough stake to withdraw. - Self::calculate_reduced_stake_on_subnet(&hotkey, &coldkey, netuid, amount)?; + // Cap the amount at available Alpha because user might be paying transaxtion fees + // in Alpha and their total is already reduced by now. + let alpha_available = + Self::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); + let amount = amount.min(alpha_available); ensure!( SubnetAlphaOut::::get(netuid) >= amount, @@ -108,7 +112,11 @@ impl Pallet { ); // Ensure that the hotkey has enough stake to withdraw. - Self::calculate_reduced_stake_on_subnet(&hotkey, &coldkey, netuid, amount)?; + // Cap the amount at available Alpha because user might be paying transaxtion fees + // in Alpha and their total is already reduced by now. + let alpha_available = + Self::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); + let amount = amount.min(alpha_available); ensure!( SubnetAlphaOut::::get(netuid) >= amount, diff --git a/pallets/subtensor/src/staking/remove_stake.rs b/pallets/subtensor/src/staking/remove_stake.rs index afe9d19308..c0311f7f33 100644 --- a/pallets/subtensor/src/staking/remove_stake.rs +++ b/pallets/subtensor/src/staking/remove_stake.rs @@ -1,7 +1,7 @@ use subtensor_swap_interface::{OrderType, SwapHandler}; use super::*; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; impl Pallet { /// ---- The implementation for the extrinsic remove_stake: Removes stake from a hotkey account and adds it onto a coldkey. @@ -45,15 +45,17 @@ impl Pallet { // 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::debug!( - "do_remove_stake( origin:{:?} hotkey:{:?}, netuid: {:?}, alpha_unstaked:{:?} )", - coldkey, - hotkey, - netuid, - alpha_unstaked + "do_remove_stake( origin:{coldkey:?} hotkey:{hotkey:?}, netuid: {netuid:?}, alpha_unstaked:{alpha_unstaked:?} )" ); Self::ensure_subtoken_enabled(netuid)?; + // 1.1. Cap the alpha_unstaked at available Alpha because user might be paying transaxtion fees + // in Alpha and their total is already reduced by now. + let alpha_available = + Self::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); + let alpha_unstaked = alpha_unstaked.min(alpha_available); + // 2. Validate the user input Self::validate_remove_stake( &coldkey, @@ -70,18 +72,18 @@ impl Pallet { &coldkey, netuid, alpha_unstaked, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), false, )?; // 4. We add the balance to the coldkey. If the above fails we will not credit this coldkey. - Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked); + Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked.into()); // 5. If the stake is below the minimum, we clear the nomination from storage. Self::clear_small_nomination_if_required(&hotkey, &coldkey, netuid); // 6. Check if stake lowered below MinStake and remove Pending children if it did - if Self::get_total_stake_for_hotkey(&hotkey) < StakeThreshold::::get() { + if Self::get_total_stake_for_hotkey(&hotkey) < StakeThreshold::::get().into() { Self::get_all_subnet_netuids().iter().for_each(|netuid| { PendingChildKeys::::remove(netuid, &hotkey); }) @@ -123,7 +125,7 @@ impl Pallet { ) -> dispatch::DispatchResult { // 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; - log::debug!("do_unstake_all( origin:{:?} hotkey:{:?} )", coldkey, hotkey); + log::debug!("do_unstake_all( origin:{coldkey:?} hotkey:{hotkey:?} )"); // 2. Ensure that the hotkey account exists this is only possible through registration. ensure!( @@ -133,7 +135,7 @@ impl Pallet { // 3. Get all netuids. let netuids = Self::get_all_subnet_netuids(); - log::debug!("All subnet netuids: {:?}", netuids); + log::debug!("All subnet netuids: {netuids:?}"); // 4. Iterate through all subnets and remove stake. for netuid in netuids.into_iter() { @@ -160,17 +162,17 @@ impl Pallet { if !alpha_unstaked.is_zero() { // Swap the alpha to tao and update counters for this subnet. - let tao_unstaked: u64 = Self::unstake_from_subnet( + let tao_unstaked = Self::unstake_from_subnet( &hotkey, &coldkey, netuid, alpha_unstaked, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), false, )?; // Add the balance to the coldkey. If the above fails we will not credit this coldkey. - Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked); + Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked.into()); // If the stake is below the minimum, we clear the nomination from storage. Self::clear_small_nomination_if_required(&hotkey, &coldkey, netuid); @@ -213,7 +215,7 @@ impl Pallet { ) -> dispatch::DispatchResult { // 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; - log::debug!("do_unstake_all( origin:{:?} hotkey:{:?} )", coldkey, hotkey); + log::debug!("do_unstake_all( origin:{coldkey:?} hotkey:{hotkey:?} )"); // 2. Ensure that the hotkey account exists this is only possible through registration. ensure!( @@ -223,10 +225,10 @@ impl Pallet { // 3. Get all netuids. let netuids = Self::get_all_subnet_netuids(); - log::debug!("All subnet netuids: {:?}", netuids); + log::debug!("All subnet netuids: {netuids:?}"); // 4. Iterate through all subnets and remove stake. - let mut total_tao_unstaked: u64 = 0; + let mut total_tao_unstaked = TaoCurrency::ZERO; for netuid in netuids.into_iter() { if !SubtokenEnabled::::get(netuid) { continue; @@ -258,7 +260,7 @@ impl Pallet { &coldkey, netuid, alpha_unstaked, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), false, )?; @@ -277,7 +279,7 @@ impl Pallet { &coldkey, NetUid::ROOT, total_tao_unstaked, - T::SwapInterface::max_price(), + T::SwapInterface::max_price().into(), false, // no limit for Root subnet )?; @@ -331,17 +333,13 @@ impl Pallet { hotkey: T::AccountId, netuid: NetUid, alpha_unstaked: AlphaCurrency, - limit_price: u64, + limit_price: TaoCurrency, allow_partial: bool, ) -> dispatch::DispatchResult { // 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::debug!( - "do_remove_stake( origin:{:?} hotkey:{:?}, netuid: {:?}, alpha_unstaked:{:?} )", - coldkey, - hotkey, - netuid, - alpha_unstaked + "do_remove_stake( origin:{coldkey:?} hotkey:{hotkey:?}, netuid: {netuid:?}, alpha_unstaked:{alpha_unstaked:?} )" ); // 2. Calculate the maximum amount that can be executed with price limit @@ -372,13 +370,13 @@ impl Pallet { )?; // 5. We add the balance to the coldkey. If the above fails we will not credit this coldkey. - Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked); + Self::add_balance_to_coldkey_account(&coldkey, tao_unstaked.into()); // 6. If the stake is below the minimum, we clear the nomination from storage. Self::clear_small_nomination_if_required(&hotkey, &coldkey, netuid); // 7. Check if stake lowered below MinStake and remove Pending children if it did - if Self::get_total_stake_for_hotkey(&hotkey) < StakeThreshold::::get() { + if Self::get_total_stake_for_hotkey(&hotkey) < StakeThreshold::::get().into() { Self::get_all_subnet_netuids().iter().for_each(|netuid| { PendingChildKeys::::remove(netuid, &hotkey); }) @@ -391,13 +389,13 @@ impl Pallet { // Returns the maximum amount of RAO that can be executed with price limit pub fn get_max_amount_remove( netuid: NetUid, - limit_price: u64, + limit_price: TaoCurrency, ) -> Result> { // Corner case: root and stao // There's no slippage for root or stable subnets, so if limit price is 1e9 rao or // lower, then max_amount equals u64::MAX, otherwise it is 0. if netuid.is_root() || SubnetMechanism::::get(netuid) == 0 { - if limit_price <= 1_000_000_000 { + if limit_price <= 1_000_000_000.into() { return Ok(AlphaCurrency::MAX); } else { return Err(Error::ZeroMaxStakeAmount); @@ -409,7 +407,7 @@ impl Pallet { netuid.into(), OrderType::Sell, u64::MAX, - limit_price, + limit_price.into(), false, true, ) @@ -427,7 +425,7 @@ impl Pallet { origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - limit_price: Option, + limit_price: Option, ) -> DispatchResult { let coldkey = ensure_signed(origin.clone())?; diff --git a/pallets/subtensor/src/staking/set_children.rs b/pallets/subtensor/src/staking/set_children.rs index 35867f82ca..139ea82c5d 100644 --- a/pallets/subtensor/src/staking/set_children.rs +++ b/pallets/subtensor/src/staking/set_children.rs @@ -43,11 +43,7 @@ impl Pallet { // Check that the caller has signed the transaction. (the coldkey of the pairing) let coldkey = ensure_signed(origin)?; log::trace!( - "do_set_children( coldkey:{:?} hotkey:{:?} netuid:{:?} children:{:?} )", - coldkey, - netuid, - hotkey, - children + "do_set_children( coldkey:{coldkey:?} hotkey:{netuid:?} netuid:{hotkey:?} children:{children:?} )" ); // Ensure the hotkey passes the rate limit. @@ -107,7 +103,7 @@ impl Pallet { // grandparent stake in this case) ensure!( children.is_empty() - || Self::get_total_stake_for_hotkey(&hotkey) >= StakeThreshold::::get() + || Self::get_total_stake_for_hotkey(&hotkey) >= StakeThreshold::::get().into() || SubnetOwnerHotkey::::try_get(netuid) .is_ok_and(|owner_hotkey| owner_hotkey.eq(&hotkey)), Error::::NotEnoughStakeToSetChildkeys @@ -354,11 +350,7 @@ impl Pallet { // Emit the event Self::deposit_event(Event::ChildKeyTakeSet(hotkey.clone(), take)); - log::debug!( - "Childkey take set for hotkey: {:?} and take: {:?}", - hotkey, - take - ); + log::debug!("Childkey take set for hotkey: {hotkey:?} and take: {take:?}"); Ok(()) } diff --git a/pallets/subtensor/src/staking/stake_utils.rs b/pallets/subtensor/src/staking/stake_utils.rs index a244f9f5a7..d3e6d69bd2 100644 --- a/pallets/subtensor/src/staking/stake_utils.rs +++ b/pallets/subtensor/src/staking/stake_utils.rs @@ -3,7 +3,7 @@ use safe_math::*; use share_pool::{SharePool, SharePoolDataOperations}; use sp_std::ops::Neg; use substrate_fixed::types::{I64F64, I96F32, U64F64, U96F32}; -use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler, SwapResult}; impl Pallet { @@ -126,22 +126,22 @@ impl Pallet { ) -> (I64F64, I64F64, I64F64) { // Retrieve the global tao weight. let tao_weight = I64F64::saturating_from_num(Self::get_tao_weight()); - log::debug!("tao_weight: {:?}", tao_weight); + log::debug!("tao_weight: {tao_weight:?}"); // Step 1: Get stake of hotkey (neuron) let alpha_stake = I64F64::saturating_from_num(Self::get_inherited_for_hotkey_on_subnet(hotkey, netuid)); - log::debug!("alpha_stake: {:?}", alpha_stake); + log::debug!("alpha_stake: {alpha_stake:?}"); // Step 2: Get the global tao stake for the hotkey let tao_stake = I64F64::saturating_from_num(Self::get_tao_inherited_for_hotkey_on_subnet( hotkey, netuid, )); - log::debug!("tao_stake: {:?}", tao_stake); + log::debug!("tao_stake: {tao_stake:?}"); // Step 3: Combine alpha and tao stakes let total_stake = alpha_stake.saturating_add(tao_stake.saturating_mul(tao_weight)); - log::debug!("total_stake: {:?}", total_stake); + log::debug!("total_stake: {total_stake:?}"); (total_stake, alpha_stake, tao_stake) } @@ -153,7 +153,7 @@ impl Pallet { ) -> (Vec, Vec, Vec) { // Retrieve the global tao weight. let tao_weight: I64F64 = I64F64::saturating_from_num(Self::get_tao_weight()); - log::debug!("tao_weight: {:?}", tao_weight); + log::debug!("tao_weight: {tao_weight:?}"); // Step 1: Get subnetwork size let n: u16 = Self::get_subnetwork_n(netuid); @@ -171,7 +171,7 @@ impl Pallet { } }) .collect(); - log::debug!("alpha_stake: {:?}", alpha_stake); + log::debug!("alpha_stake: {alpha_stake:?}"); // Step 3: Calculate the global tao stake vector. // Initialize a vector to store global tao stakes for each neuron. @@ -187,7 +187,7 @@ impl Pallet { } }) .collect(); - log::trace!("tao_stake: {:?}", tao_stake); + log::trace!("tao_stake: {tao_stake:?}"); // Step 4: Combine alpha and root tao stakes. // Calculate the weighted average of alpha and global tao stakes for each neuron. @@ -196,7 +196,7 @@ impl Pallet { .zip(tao_stake.iter()) .map(|(alpha_i, tao_i)| alpha_i.saturating_add(tao_i.saturating_mul(tao_weight))) .collect(); - log::trace!("total_stake: {:?}", total_stake); + log::trace!("total_stake: {total_stake:?}"); (total_stake, alpha_stake, tao_stake) } @@ -228,7 +228,10 @@ impl Pallet { /// /// # Note /// This function uses saturating arithmetic to prevent overflows. - pub fn get_tao_inherited_for_hotkey_on_subnet(hotkey: &T::AccountId, netuid: NetUid) -> u64 { + pub fn get_tao_inherited_for_hotkey_on_subnet( + hotkey: &T::AccountId, + netuid: NetUid, + ) -> TaoCurrency { let initial_tao: U96F32 = U96F32::saturating_from_num(Self::get_stake_for_hotkey_on_subnet(hotkey, NetUid::ROOT)); @@ -239,38 +242,25 @@ impl Pallet { // Step 2: Retrieve the lists of parents and children for the hotkey on the subnet. let parents: Vec<(u64, T::AccountId)> = Self::get_parents(hotkey, netuid); let children: Vec<(u64, T::AccountId)> = Self::get_children(hotkey, netuid); - log::trace!( - "Parents for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - parents - ); - log::trace!( - "Children for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - children - ); + log::trace!("Parents for hotkey {hotkey:?} on subnet {netuid}: {parents:?}"); + log::trace!("Children for hotkey {hotkey:?} on subnet {netuid}: {children:?}"); // Step 3: Calculate the total tao allocated to children. for (proportion, _) in children { // Convert the proportion to a normalized value between 0 and 1. let normalized_proportion: U96F32 = U96F32::saturating_from_num(proportion) .safe_div(U96F32::saturating_from_num(u64::MAX)); - log::trace!( - "Normalized proportion for child: {:?}", - normalized_proportion - ); + log::trace!("Normalized proportion for child: {normalized_proportion:?}"); // Calculate the amount of tao to be allocated to this child. let tao_proportion_to_child: U96F32 = U96F32::saturating_from_num(initial_tao).saturating_mul(normalized_proportion); - log::trace!("Tao proportion to child: {:?}", tao_proportion_to_child); + log::trace!("Tao proportion to child: {tao_proportion_to_child:?}"); // Add this child's allocation to the total tao allocated to children. tao_to_children = tao_to_children.saturating_add(tao_proportion_to_child); } - log::trace!("Total tao allocated to children: {:?}", tao_to_children); + log::trace!("Total tao allocated to children: {tao_to_children:?}"); // Step 4: Calculate the total tao inherited from parents. for (proportion, parent) in parents { @@ -279,47 +269,31 @@ impl Pallet { &parent, NetUid::ROOT, )); - log::trace!( - "Parent tao for parent {:?} on subnet {}: {:?}", - parent, - netuid, - parent_tao - ); + log::trace!("Parent tao for parent {parent:?} on subnet {netuid}: {parent_tao:?}"); // Convert the proportion to a normalized value between 0 and 1. let normalized_proportion = U96F32::saturating_from_num(proportion) .safe_div(U96F32::saturating_from_num(u64::MAX)); - log::trace!( - "Normalized proportion from parent: {:?}", - normalized_proportion - ); + log::trace!("Normalized proportion from parent: {normalized_proportion:?}"); // Calculate the amount of tao to be inherited from this parent. let tao_proportion_from_parent: U96F32 = U96F32::saturating_from_num(parent_tao).saturating_mul(normalized_proportion); - log::trace!( - "Tao proportion from parent: {:?}", - tao_proportion_from_parent - ); + log::trace!("Tao proportion from parent: {tao_proportion_from_parent:?}"); // Add this parent's contribution to the total tao inherited from parents. tao_from_parents = tao_from_parents.saturating_add(tao_proportion_from_parent); } - log::trace!("Total tao inherited from parents: {:?}", tao_from_parents); + log::trace!("Total tao inherited from parents: {tao_from_parents:?}"); // Step 5: Calculate the final inherited tao for the hotkey. let finalized_tao: U96F32 = initial_tao .saturating_sub(tao_to_children) // Subtract tao allocated to children .saturating_add(tao_from_parents); // Add tao inherited from parents - log::trace!( - "Finalized tao for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - finalized_tao - ); + log::trace!("Finalized tao for hotkey {hotkey:?} on subnet {netuid}: {finalized_tao:?}"); // Step 6: Return the final inherited tao value. - finalized_tao.saturating_to_num::() + finalized_tao.saturating_to_num::().into() } pub fn get_inherited_for_hotkey_on_subnet( @@ -329,12 +303,7 @@ impl Pallet { // Step 1: Retrieve the initial total stake (alpha) for the hotkey on the specified subnet. let initial_alpha: U96F32 = U96F32::saturating_from_num(Self::get_stake_for_hotkey_on_subnet(hotkey, netuid)); - log::debug!( - "Initial alpha for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - initial_alpha - ); + log::debug!("Initial alpha for hotkey {hotkey:?} on subnet {netuid}: {initial_alpha:?}"); if netuid.is_root() { return initial_alpha.saturating_to_num::().into(); } @@ -346,84 +315,54 @@ impl Pallet { // Step 2: Retrieve the lists of parents and children for the hotkey on the subnet. let parents: Vec<(u64, T::AccountId)> = Self::get_parents(hotkey, netuid); let children: Vec<(u64, T::AccountId)> = Self::get_children(hotkey, netuid); - log::debug!( - "Parents for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - parents - ); - log::debug!( - "Children for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - children - ); + log::debug!("Parents for hotkey {hotkey:?} on subnet {netuid}: {parents:?}"); + log::debug!("Children for hotkey {hotkey:?} on subnet {netuid}: {children:?}"); // Step 3: Calculate the total alpha allocated to children. for (proportion, _) in children { // Convert the proportion to a normalized value between 0 and 1. let normalized_proportion: U96F32 = U96F32::saturating_from_num(proportion) .safe_div(U96F32::saturating_from_num(u64::MAX)); - log::trace!( - "Normalized proportion for child: {:?}", - normalized_proportion - ); + log::trace!("Normalized proportion for child: {normalized_proportion:?}"); // Calculate the amount of alpha to be allocated to this child. let alpha_proportion_to_child: U96F32 = U96F32::saturating_from_num(initial_alpha).saturating_mul(normalized_proportion); - log::trace!("Alpha proportion to child: {:?}", alpha_proportion_to_child); + log::trace!("Alpha proportion to child: {alpha_proportion_to_child:?}"); // Add this child's allocation to the total alpha allocated to children. alpha_to_children = alpha_to_children.saturating_add(alpha_proportion_to_child); } - log::debug!("Total alpha allocated to children: {:?}", alpha_to_children); + log::debug!("Total alpha allocated to children: {alpha_to_children:?}"); // Step 4: Calculate the total alpha inherited from parents. for (proportion, parent) in parents { // Retrieve the parent's total stake on this subnet. let parent_alpha: U96F32 = U96F32::saturating_from_num(Self::get_stake_for_hotkey_on_subnet(&parent, netuid)); - log::trace!( - "Parent alpha for parent {:?} on subnet {}: {:?}", - parent, - netuid, - parent_alpha - ); + log::trace!("Parent alpha for parent {parent:?} on subnet {netuid}: {parent_alpha:?}"); // Convert the proportion to a normalized value between 0 and 1. let normalized_proportion: U96F32 = U96F32::saturating_from_num(proportion) .safe_div(U96F32::saturating_from_num(u64::MAX)); - log::trace!( - "Normalized proportion from parent: {:?}", - normalized_proportion - ); + log::trace!("Normalized proportion from parent: {normalized_proportion:?}"); // Calculate the amount of alpha to be inherited from this parent. let alpha_proportion_from_parent: U96F32 = U96F32::saturating_from_num(parent_alpha).saturating_mul(normalized_proportion); - log::trace!( - "Alpha proportion from parent: {:?}", - alpha_proportion_from_parent - ); + log::trace!("Alpha proportion from parent: {alpha_proportion_from_parent:?}"); // Add this parent's contribution to the total alpha inherited from parents. alpha_from_parents = alpha_from_parents.saturating_add(alpha_proportion_from_parent); } - log::debug!( - "Total alpha inherited from parents: {:?}", - alpha_from_parents - ); + log::debug!("Total alpha inherited from parents: {alpha_from_parents:?}"); // Step 5: Calculate the final inherited alpha for the hotkey. let finalized_alpha: U96F32 = initial_alpha .saturating_sub(alpha_to_children) // Subtract alpha allocated to children .saturating_add(alpha_from_parents); // Add alpha inherited from parents log::trace!( - "Finalized alpha for hotkey {:?} on subnet {}: {:?}", - hotkey, - netuid, - finalized_alpha + "Finalized alpha for hotkey {hotkey:?} on subnet {netuid}: {finalized_alpha:?}" ); // Step 6: Return the final inherited alpha value. @@ -627,8 +566,8 @@ impl Pallet { /// Updates TaoIn, AlphaIn, and AlphaOut pub fn swap_tao_for_alpha( netuid: NetUid, - tao: u64, - price_limit: u64, + tao: TaoCurrency, + price_limit: TaoCurrency, drop_fees: bool, ) -> Result { // Step 1: Get the mechanism type for the subnet (0 for Stable, 1 for Dynamic) @@ -637,8 +576,8 @@ impl Pallet { let swap_result = T::SwapInterface::swap( netuid.into(), OrderType::Buy, - tao, - price_limit, + tao.into(), + price_limit.into(), drop_fees, false, )?; @@ -657,7 +596,7 @@ impl Pallet { // (SubnetTAO + SubnetTaoProvided) in tao_reserve(), so it is irrelevant // which one to increase. SubnetTAO::::mutate(netuid, |total| { - *total = total.saturating_add(swap_result.tao_reserve_delta as u64); + *total = total.saturating_add((swap_result.tao_reserve_delta as u64).into()); }); // Increase Total Tao reserves. @@ -665,7 +604,7 @@ impl Pallet { // Increase total subnet TAO volume. SubnetVolume::::mutate(netuid, |total| { - *total = total.saturating_add(tao.into()); + *total = total.saturating_add(tao.to_u64() as u128); }); // Return the alpha received. @@ -673,8 +612,8 @@ impl Pallet { } else { // Step 3.b.1: Stable mechanism, just return the value 1:1 Ok(SwapResult { - amount_paid_in: tao, - amount_paid_out: tao, + amount_paid_in: tao.into(), + amount_paid_out: tao.into(), fee_paid: 0, tao_reserve_delta: 0, alpha_reserve_delta: 0, @@ -688,7 +627,7 @@ impl Pallet { pub fn swap_alpha_for_tao( netuid: NetUid, alpha: AlphaCurrency, - price_limit: u64, + price_limit: TaoCurrency, drop_fees: bool, ) -> Result { // Step 1: Get the mechanism type for the subnet (0 for Stable, 1 for Dynamic) @@ -699,7 +638,7 @@ impl Pallet { netuid.into(), OrderType::Sell, alpha.into(), - price_limit, + price_limit.into(), drop_fees, false, )?; @@ -720,12 +659,17 @@ impl Pallet { // Decrease tao reserves. Self::decrease_provided_tao_reserve( netuid.into(), - swap_result.tao_reserve_delta.abs().try_into().unwrap_or(0), + swap_result + .tao_reserve_delta + .abs() + .try_into() + .unwrap_or(0) + .into(), ); // Reduce total TAO reserves. TotalStake::::mutate(|total| { - *total = total.saturating_sub(swap_result.amount_paid_out) + *total = total.saturating_sub(swap_result.amount_paid_out.into()) }); // Increase total subnet TAO volume. @@ -755,9 +699,9 @@ impl Pallet { coldkey: &T::AccountId, netuid: NetUid, alpha: AlphaCurrency, - price_limit: u64, + price_limit: TaoCurrency, drop_fees: bool, - ) -> Result { + ) -> Result { // Decrease alpha on subnet let actual_alpha_decrease = Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid, alpha); @@ -791,7 +735,7 @@ impl Pallet { Self::deposit_event(Event::StakeRemoved( coldkey.clone(), hotkey.clone(), - swap_result.amount_paid_out, + swap_result.amount_paid_out.into(), actual_alpha_decrease, netuid, swap_result.fee_paid, @@ -807,7 +751,7 @@ impl Pallet { swap_result.fee_paid ); - Ok(swap_result.amount_paid_out) + Ok(swap_result.amount_paid_out.into()) } /// Stakes TAO into a subnet for a given hotkey and coldkey pair. @@ -817,8 +761,8 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - tao: u64, - price_limit: u64, + tao: TaoCurrency, + price_limit: TaoCurrency, set_limit: bool, ) -> Result { // Swap the tao to alpha. @@ -895,7 +839,7 @@ impl Pallet { destination_hotkey: &T::AccountId, netuid: NetUid, alpha: AlphaCurrency, - ) -> Result { + ) -> Result { // Decrease alpha on origin keys let actual_alpha_decrease = Self::decrease_stake_for_hotkey_and_coldkey_on_subnet( origin_hotkey, @@ -916,9 +860,10 @@ impl Pallet { // there's no slippage in this move) let current_price = ::SwapInterface::current_alpha_price(netuid.into()); - let tao_equivalent = current_price + let tao_equivalent: TaoCurrency = current_price .saturating_mul(U96F32::saturating_from_num(actual_alpha_moved)) - .saturating_to_num::(); + .saturating_to_num::() + .into(); // Ensure tao_equivalent is above DefaultMinStake ensure!( @@ -974,8 +919,8 @@ impl Pallet { coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, - mut stake_to_be_added: u64, - max_amount: u64, + mut stake_to_be_added: TaoCurrency, + max_amount: TaoCurrency, allow_partial: bool, ) -> Result<(), Error> { // Ensure that the subnet exists. @@ -987,13 +932,13 @@ impl Pallet { // Get the minimum balance (and amount) that satisfies the transaction let min_stake = DefaultMinStake::::get(); let min_amount = { - let fee = T::SwapInterface::sim_swap(netuid.into(), OrderType::Buy, min_stake) + let fee = T::SwapInterface::sim_swap(netuid.into(), OrderType::Buy, min_stake.into()) .map(|res| res.fee_paid) .unwrap_or(T::SwapInterface::approx_fee_amount( netuid.into(), - min_stake, + min_stake.into(), )); - min_stake.saturating_add(fee) + min_stake.saturating_add(fee.into()) }; // Ensure that the stake_to_be_added is at least the min_amount @@ -1009,7 +954,7 @@ impl Pallet { // Ensure the callers coldkey has enough stake to perform the transaction. ensure!( - Self::can_remove_balance_from_coldkey_account(coldkey, stake_to_be_added), + Self::can_remove_balance_from_coldkey_account(coldkey, stake_to_be_added.into()), Error::::NotEnoughBalanceToStake ); @@ -1020,12 +965,12 @@ impl Pallet { ); let swap_result = - T::SwapInterface::sim_swap(netuid.into(), OrderType::Buy, stake_to_be_added) + T::SwapInterface::sim_swap(netuid.into(), OrderType::Buy, stake_to_be_added.into()) .map_err(|_| Error::::InsufficientLiquidity)?; // Check that actual withdrawn TAO amount is not lower than the minimum stake ensure!( - swap_result.amount_paid_in >= min_stake, + TaoCurrency::from(swap_result.amount_paid_in) >= min_stake, Error::::AmountTooLow ); @@ -1074,7 +1019,7 @@ impl Pallet { Ok(res) => { if !remaining_alpha_stake.is_zero() { ensure!( - res.amount_paid_out >= DefaultMinStake::::get(), + TaoCurrency::from(res.amount_paid_out) >= DefaultMinStake::::get(), Error::::AmountTooLow ); } @@ -1215,7 +1160,7 @@ impl Pallet { .map(|res| res.amount_paid_out) .map_err(|_| Error::::InsufficientLiquidity)?; ensure!( - tao_equivalent > DefaultMinStake::::get(), + TaoCurrency::from(tao_equivalent) > DefaultMinStake::::get(), Error::::AmountTooLow ); @@ -1245,22 +1190,22 @@ impl Pallet { Ok(()) } - pub fn increase_provided_tao_reserve(netuid: NetUid, tao: u64) { + pub fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) { SubnetTaoProvided::::mutate(netuid, |total| { *total = total.saturating_add(tao); }); } - pub fn decrease_provided_tao_reserve(netuid: NetUid, tao: u64) { + pub fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) { // First, decrease SubnetTaoProvided, then deduct the rest from SubnetTAO let subnet_tao = SubnetTAO::::get(netuid); let subnet_tao_provided = SubnetTaoProvided::::get(netuid); let remainder = subnet_tao_provided.saturating_sub(tao); let carry_over = tao.saturating_sub(subnet_tao_provided); - if carry_over == 0 { + if carry_over.is_zero() { SubnetTaoProvided::::set(netuid, remainder); } else { - SubnetTaoProvided::::set(netuid, 0_u64); + SubnetTaoProvided::::set(netuid, TaoCurrency::ZERO); SubnetTAO::::set(netuid, subnet_tao.saturating_sub(carry_over)); } } diff --git a/pallets/subtensor/src/subnets/leasing.rs b/pallets/subtensor/src/subnets/leasing.rs index de4cbf3e5b..244b9af2e9 100644 --- a/pallets/subtensor/src/subnets/leasing.rs +++ b/pallets/subtensor/src/subnets/leasing.rs @@ -1,3 +1,20 @@ +//! This file defines abstraction for subnet leasing. +//! +//! It is used to register a new leased network through a crowdloan using the `register_leased_network` extrinsic +//! as a call parameter to the crowdloan pallet `create` extrinsic. A new subnet will be registered +//! paying the lock cost using the crowdloan funds and a proxy will be created for the beneficiary +//! to operate the subnet. +//! +//! The crowdloan's contributions are used to compute the share of the emissions that the contributors +//! will receive as dividends. The leftover cap is refunded to the contributors and the beneficiary. +//! +//! The lease can have a defined end block, after which the lease will be terminated and the subnet +//! will be transferred to the beneficiary. In case the lease is perpetual, the lease will never be +//! terminated and emissions will continue to be distributed to the contributors. +//! +//! The lease can be terminated by the beneficiary after the end block has passed (if any) and the subnet +//! ownership will be transferred to the beneficiary. + use super::*; use frame_support::{ dispatch::RawOrigin, @@ -7,7 +24,7 @@ use frame_system::pallet_prelude::*; use sp_core::blake2_256; use sp_runtime::{Percent, traits::TrailingZeroInput}; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; use subtensor_swap_interface::SwapHandler; pub type LeaseId = u32; @@ -293,7 +310,7 @@ impl Pallet { &lease.coldkey, lease.netuid, total_contributors_cut_alpha, - T::SwapInterface::min_price(), + T::SwapInterface::min_price().into(), false, ) { Ok(tao_unstaked) => tao_unstaked, @@ -306,19 +323,19 @@ impl Pallet { // Distribute the contributors cut to the contributors and accumulate the tao // distributed so far to obtain how much tao is left to distribute to the beneficiary - let mut tao_distributed = 0u64; + let mut tao_distributed = TaoCurrency::ZERO; for (contributor, share) in SubnetLeaseShares::::iter_prefix(lease_id) { let tao_for_contributor = share - .saturating_mul(U64F64::from(tao_unstaked)) + .saturating_mul(U64F64::from(tao_unstaked.to_u64())) .floor() .saturating_to_num::(); Self::add_balance_to_coldkey_account(&contributor, tao_for_contributor); - tao_distributed = tao_distributed.saturating_add(tao_for_contributor); + tao_distributed = tao_distributed.saturating_add(tao_for_contributor.into()); } // Distribute the leftover tao to the beneficiary let beneficiary_cut_tao = tao_unstaked.saturating_sub(tao_distributed); - Self::add_balance_to_coldkey_account(&lease.beneficiary, beneficiary_cut_tao); + Self::add_balance_to_coldkey_account(&lease.beneficiary, beneficiary_cut_tao.into()); // Reset the accumulated dividends AccumulatedLeaseDividends::::insert(lease_id, AlphaCurrency::ZERO); diff --git a/pallets/subtensor/src/subnets/registration.rs b/pallets/subtensor/src/subnets/registration.rs index 67631d3fc1..bfde68601d 100644 --- a/pallets/subtensor/src/subnets/registration.rs +++ b/pallets/subtensor/src/subnets/registration.rs @@ -71,12 +71,7 @@ impl Pallet { ) -> DispatchResult { // --- 1. Check that the caller has signed the transaction. (the coldkey of the pairing) let coldkey = ensure_signed(origin)?; - log::debug!( - "do_registration( coldkey:{:?} netuid:{:?} hotkey:{:?} )", - coldkey, - netuid, - hotkey - ); + log::debug!("do_registration( coldkey:{coldkey:?} netuid:{netuid:?} hotkey:{hotkey:?} )"); // --- 2. Ensure the passed network is valid. ensure!( @@ -115,9 +110,9 @@ impl Pallet { ); // --- 7. Ensure the callers coldkey has enough stake to perform the transaction. - let registration_cost = Self::get_burn_as_u64(netuid); + let registration_cost = Self::get_burn(netuid); ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, registration_cost), + Self::can_remove_balance_from_coldkey_account(&coldkey, registration_cost.into()), Error::::NotEnoughBalanceToStake ); @@ -138,13 +133,13 @@ impl Pallet { // --- 10. Ensure the remove operation from the coldkey is a success. let actual_burn_amount = - Self::remove_balance_from_coldkey_account(&coldkey, registration_cost)?; + Self::remove_balance_from_coldkey_account(&coldkey, registration_cost.into())?; // Tokens are swapped and then burned. let burned_alpha = Self::swap_tao_for_alpha( netuid, actual_burn_amount, - T::SwapInterface::max_price(), + T::SwapInterface::max_price().into(), false, )? .amount_paid_out; @@ -159,15 +154,10 @@ impl Pallet { BurnRegistrationsThisInterval::::mutate(netuid, |val| val.saturating_inc()); RegistrationsThisInterval::::mutate(netuid, |val| val.saturating_inc()); RegistrationsThisBlock::::mutate(netuid, |val| val.saturating_inc()); - Self::increase_rao_recycled(netuid, Self::get_burn_as_u64(netuid)); + Self::increase_rao_recycled(netuid, Self::get_burn(netuid).into()); // --- 15. Deposit successful event. - log::debug!( - "NeuronRegistered( netuid:{:?} uid:{:?} hotkey:{:?} ) ", - netuid, - neuron_uid, - hotkey - ); + log::debug!("NeuronRegistered( netuid:{netuid:?} uid:{neuron_uid:?} hotkey:{hotkey:?} ) "); Self::deposit_event(Event::NeuronRegistered(netuid, neuron_uid, hotkey)); // --- 16. Ok and done. @@ -233,11 +223,7 @@ impl Pallet { // --- 1. Check that the caller has signed the transaction. let signing_origin = ensure_signed(origin)?; log::debug!( - "do_registration( origin:{:?} netuid:{:?} hotkey:{:?}, coldkey:{:?} )", - signing_origin, - netuid, - hotkey, - coldkey + "do_registration( origin:{signing_origin:?} netuid:{netuid:?} hotkey:{hotkey:?}, coldkey:{coldkey:?} )" ); ensure!( @@ -336,12 +322,7 @@ impl Pallet { RegistrationsThisBlock::::mutate(netuid, |val| val.saturating_inc()); // --- 13. Deposit successful event. - log::debug!( - "NeuronRegistered( netuid:{:?} uid:{:?} hotkey:{:?} ) ", - netuid, - neuron_uid, - hotkey - ); + log::debug!("NeuronRegistered( netuid:{netuid:?} uid:{neuron_uid:?} hotkey:{hotkey:?} ) "); Self::deposit_event(Event::NeuronRegistered(netuid, neuron_uid, hotkey)); // --- 14. Ok and done. @@ -359,7 +340,7 @@ impl Pallet { // --- 1. Check that the caller has signed the transaction. let coldkey = ensure_signed(origin)?; - log::debug!("do_faucet( coldkey:{:?} )", coldkey); + log::debug!("do_faucet( coldkey:{coldkey:?} )"); // --- 2. Ensure the passed block number is valid, not in the future or too old. // Work must have been done within 3 blocks (stops long range attacks). @@ -388,16 +369,12 @@ impl Pallet { // --- 5. Add Balance via faucet. let balance_to_add: u64 = 1_000_000_000_000; - Self::coinbase(100_000_000_000); // We are creating tokens here from the coinbase. + Self::coinbase(100_000_000_000.into()); // We are creating tokens here from the coinbase. Self::add_balance_to_coldkey_account(&coldkey, balance_to_add); // --- 6. Deposit successful event. - log::debug!( - "Faucet( coldkey:{:?} amount:{:?} ) ", - coldkey, - balance_to_add - ); + log::debug!("Faucet( coldkey:{coldkey:?} amount:{balance_to_add:?} ) "); Self::deposit_event(Event::Faucet(coldkey, balance_to_add)); // --- 7. Ok and done. @@ -496,13 +473,7 @@ impl Pallet { log::trace!( target: LOG_TARGET, - "Difficulty: hash: {:?}, hash_bytes: {:?}, hash_as_num: {:?}, difficulty: {:?}, value: {:?} overflowed: {:?}", - hash, - bytes, - num_hash, - difficulty, - value, - overflowed + "Difficulty: hash: {hash:?}, hash_bytes: {bytes:?}, hash_as_num: {num_hash:?}, difficulty: {difficulty:?}, value: {value:?} overflowed: {overflowed:?}" ); !overflowed } @@ -519,10 +490,7 @@ impl Pallet { log::trace!( target: LOG_TARGET, - "block_number: {:?}, vec_hash: {:?}, real_hash: {:?}", - block_number, - vec_hash, - real_hash + "block_number: {block_number:?}, vec_hash: {vec_hash:?}, real_hash: {real_hash:?}" ); real_hash @@ -578,15 +546,7 @@ impl Pallet { let seal_hash: H256 = H256::from_slice(&keccak_256_seal_hash_vec); log::trace!( - "\n hotkey:{:?} \nblock_number: {:?}, \nnonce_u64: {:?}, \nblock_hash: {:?}, \nfull_bytes: {:?}, \nsha256_seal_hash_vec: {:?}, \nkeccak_256_seal_hash_vec: {:?}, \nseal_hash: {:?}", - hotkey, - block_number_u64, - nonce_u64, - block_hash_at_number, - full_bytes, - sha256_seal_hash_vec, - keccak_256_seal_hash_vec, - seal_hash + "\n hotkey:{hotkey:?} \nblock_number: {block_number_u64:?}, \nnonce_u64: {nonce_u64:?}, \nblock_hash: {block_hash_at_number:?}, \nfull_bytes: {full_bytes:?}, \nsha256_seal_hash_vec: {sha256_seal_hash_vec:?}, \nkeccak_256_seal_hash_vec: {keccak_256_seal_hash_vec:?}, \nseal_hash: {seal_hash:?}" ); seal_hash diff --git a/pallets/subtensor/src/subnets/subnet.rs b/pallets/subtensor/src/subnets/subnet.rs index 1e9aaca229..17e349c995 100644 --- a/pallets/subtensor/src/subnets/subnet.rs +++ b/pallets/subtensor/src/subnets/subnet.rs @@ -1,6 +1,6 @@ use super::*; use sp_core::Get; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; impl Pallet { /// Fetches the total count of subnets. @@ -141,10 +141,10 @@ impl Pallet { ); // --- 5. Calculate and lock the required tokens. - let lock_amount: u64 = Self::get_network_lock_cost(); - log::debug!("network lock_amount: {:?}", lock_amount); + let lock_amount = Self::get_network_lock_cost(); + log::debug!("network lock_amount: {lock_amount:?}"); ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, lock_amount), + Self::can_remove_balance_from_coldkey_account(&coldkey, lock_amount.into()), Error::::NotEnoughBalanceToStake ); @@ -152,9 +152,9 @@ impl Pallet { let netuid_to_register = Self::get_next_netuid(); // --- 7. Perform the lock operation. - let actual_tao_lock_amount: u64 = - Self::remove_balance_from_coldkey_account(&coldkey, lock_amount)?; - log::debug!("actual_tao_lock_amount: {:?}", actual_tao_lock_amount); + let actual_tao_lock_amount = + Self::remove_balance_from_coldkey_account(&coldkey, lock_amount.into())?; + log::debug!("actual_tao_lock_amount: {actual_tao_lock_amount:?}"); // --- 8. Set the lock amount for use to determine pricing. Self::set_network_last_lock(actual_tao_lock_amount); @@ -162,24 +162,16 @@ impl Pallet { // --- 9. Set initial and custom parameters for the network. let default_tempo = DefaultTempo::::get(); Self::init_new_network(netuid_to_register, default_tempo); - log::debug!("init_new_network: {:?}", netuid_to_register); + log::debug!("init_new_network: {netuid_to_register:?}"); // --- 10. Add the caller to the neuron set. Self::create_account_if_non_existent(&coldkey, hotkey); Self::append_neuron(netuid_to_register, hotkey, current_block); - log::debug!( - "Appended neuron for netuid {:?}, hotkey: {:?}", - netuid_to_register, - hotkey - ); + log::debug!("Appended neuron for netuid {netuid_to_register:?}, hotkey: {hotkey:?}"); // --- 11. Set the mechanism. SubnetMechanism::::insert(netuid_to_register, mechid); - log::debug!( - "SubnetMechanism for netuid {:?} set to: {:?}", - netuid_to_register, - mechid - ); + log::debug!("SubnetMechanism for netuid {netuid_to_register:?} set to: {mechid:?}"); // --- 12. Set the creation terms. NetworkLastRegistered::::set(current_block); @@ -193,7 +185,8 @@ impl Pallet { // Put initial TAO from lock into subnet TAO and produce numerically equal amount of Alpha // The initial TAO is the locked amount, with a minimum of 1 RAO and a cap of 100 TAO. let pool_initial_tao = Self::get_network_min_lock(); - let pool_initial_alpha = AlphaCurrency::from(Self::get_network_min_lock()); + // FIXME: the result from function is used as a mixed type alpha/tao + let pool_initial_alpha = AlphaCurrency::from(Self::get_network_min_lock().to_u64()); let actual_tao_lock_amount_less_pool_tao = actual_tao_lock_amount.saturating_sub(pool_initial_tao); SubnetTAO::::insert(netuid_to_register, pool_initial_tao); @@ -201,11 +194,11 @@ impl Pallet { SubnetOwner::::insert(netuid_to_register, coldkey.clone()); SubnetOwnerHotkey::::insert(netuid_to_register, hotkey.clone()); - if actual_tao_lock_amount_less_pool_tao > 0 { + if actual_tao_lock_amount_less_pool_tao > TaoCurrency::ZERO { Self::burn_tokens(actual_tao_lock_amount_less_pool_tao); } - if actual_tao_lock_amount > 0 && pool_initial_tao > 0 { + if actual_tao_lock_amount > TaoCurrency::ZERO && pool_initial_tao > TaoCurrency::ZERO { // Record in TotalStake the initial TAO in the pool. Self::increase_total_stake(pool_initial_tao); } @@ -226,11 +219,7 @@ impl Pallet { NetworkPowRegistrationAllowed::::set(netuid_to_register, true); // --- 17. Emit the NetworkAdded event. - log::info!( - "NetworkAdded( netuid:{:?}, mechanism:{:?} )", - netuid_to_register, - mechid - ); + log::info!("NetworkAdded( netuid:{netuid_to_register:?}, mechanism:{mechid:?} )"); Self::deposit_event(Event::NetworkAdded(netuid_to_register, mechid)); // --- 18. Return success. diff --git a/pallets/subtensor/src/subnets/symbols.rs b/pallets/subtensor/src/subnets/symbols.rs index a601865010..4b37e9b6b0 100644 --- a/pallets/subtensor/src/subnets/symbols.rs +++ b/pallets/subtensor/src/subnets/symbols.rs @@ -949,8 +949,7 @@ impl Pallet { if available_symbol.is_none() { log::warn!( - "All available symbols have been exhausted for netuid: {:?}. Using default symbol.", - netuid + "All available symbols have been exhausted for netuid: {netuid:?}. Using default symbol." ); } diff --git a/pallets/subtensor/src/subnets/uids.rs b/pallets/subtensor/src/subnets/uids.rs index 67c0a24c29..f5a14c490b 100644 --- a/pallets/subtensor/src/subnets/uids.rs +++ b/pallets/subtensor/src/subnets/uids.rs @@ -35,10 +35,7 @@ impl Pallet { block_number: u64, ) { log::debug!( - "replace_neuron( netuid: {:?} | uid_to_replace: {:?} | new_hotkey: {:?} ) ", - netuid, - uid_to_replace, - new_hotkey + "replace_neuron( netuid: {netuid:?} | uid_to_replace: {uid_to_replace:?} | new_hotkey: {new_hotkey:?} ) " ); // 1. Get the old hotkey under this position. @@ -49,11 +46,7 @@ impl Pallet { if sn_owner_hotkey == old_hotkey.clone() { log::warn!( "replace_neuron: Skipped replacement because neuron is the subnet owner hotkey. \ - netuid: {:?}, uid_to_replace: {:?}, new_hotkey: {:?}, owner_hotkey: {:?}", - netuid, - uid_to_replace, - new_hotkey, - sn_owner_hotkey + netuid: {netuid:?}, uid_to_replace: {uid_to_replace:?}, new_hotkey: {new_hotkey:?}, owner_hotkey: {sn_owner_hotkey:?}" ); return; } @@ -88,10 +81,7 @@ impl Pallet { // 1. Get the next uid. This is always equal to subnetwork_n. let next_uid: u16 = Self::get_subnetwork_n(netuid); log::debug!( - "append_neuron( netuid: {:?} | next_uid: {:?} | new_hotkey: {:?} ) ", - netuid, - new_hotkey, - next_uid + "append_neuron( netuid: {netuid:?} | next_uid: {new_hotkey:?} | new_hotkey: {next_uid:?} ) " ); // 2. Get and increase the uid count. diff --git a/pallets/subtensor/src/subnets/weights.rs b/pallets/subtensor/src/subnets/weights.rs index e234d62be4..2e7162ab36 100644 --- a/pallets/subtensor/src/subnets/weights.rs +++ b/pallets/subtensor/src/subnets/weights.rs @@ -47,7 +47,7 @@ impl Pallet { // 1. Verify the caller's signature (hotkey). let who = ensure_signed(origin)?; - log::debug!("do_commit_weights(hotkey: {:?}, netuid: {:?})", who, netuid); + log::debug!("do_commit_weights(hotkey: {who:?}, netuid: {netuid:?})"); // 2. Ensure commit-reveal is enabled. ensure!( @@ -145,10 +145,7 @@ impl Pallet { // --- 1. Check the caller's signature. This is the hotkey of a registered account. let hotkey = ensure_signed(origin.clone())?; log::debug!( - "do_batch_commit_weights( origin:{:?}, netuids:{:?}, hashes:{:?} )", - hotkey, - netuids, - commit_hashes + "do_batch_commit_weights( origin:{hotkey:?}, netuids:{netuids:?}, hashes:{commit_hashes:?} )" ); ensure!( @@ -178,69 +175,68 @@ impl Pallet { } // --- 19. Emit the tracking event. - log::debug!( - "BatchWeightsCompleted( netuids:{:?}, hotkey:{:?} )", - netuids, - hotkey - ); + log::debug!("BatchWeightsCompleted( netuids:{netuids:?}, hotkey:{hotkey:?} )"); Self::deposit_event(Event::BatchWeightsCompleted(netuids, hotkey)); // --- 20. Return ok. Ok(()) } - /// ---- The implementation for committing commit-reveal v3 weights. - /// - /// # Args: - /// * `origin`: (`::RuntimeOrigin`): - /// - The signature of the committing hotkey. - /// - /// * `netuid` (`u16`): - /// - The u16 network identifier. - /// - /// * `commit` (`Vec`): - /// - The encrypted compressed commit. - /// The steps for this are: - /// 1. Instantiate [`WeightsPayload`] - /// 2. Serialize it using the `parity_scale_codec::Encode` trait - /// 3. Encrypt it following the steps (here)[https://github.com/ideal-lab5/tle/blob/f8e6019f0fb02c380ebfa6b30efb61786dede07b/timelock/src/tlock.rs#L283-L336] - /// to produce a [`TLECiphertext`] type. - /// 4. Serialize and compress using the `ark-serialize` `CanonicalSerialize` trait. - /// - /// * reveal_round (`u64`): - /// - The drand reveal round which will be avaliable during epoch `n+1` from the current - /// epoch. - /// - /// # Raises: - /// * `CommitRevealDisabled`: - /// - Raised if commit-reveal v3 is disabled for the specified network. - /// - /// * `HotKeyNotRegisteredInSubNet`: - /// - Raised if the hotkey is not registered on the specified network. - /// - /// * `CommittingWeightsTooFast`: - /// - Raised if the hotkey's commit rate exceeds the permitted limit. - /// - /// * `TooManyUnrevealedCommits`: - /// - Raised if the hotkey has reached the maximum number of unrevealed commits. - /// - /// # Events: - /// * `WeightsCommitted`: - /// - Emitted upon successfully storing the weight hash. - pub fn do_commit_crv3_weights( + /// ---- Commits a timelocked, encrypted weight payload (Commit-Reveal v3). + /// + /// # Args + /// * `origin` (`::RuntimeOrigin`): + /// The signed origin of the committing hotkey. + /// * `netuid` (`NetUid` = `u16`): + /// Unique identifier for the subnet on which the commit is made. + /// * `commit` (`BoundedVec>`): + /// The encrypted weight payload, produced as follows: + /// 1. Build a [`WeightsPayload`] structure. + /// 2. SCALE-encode it (`parity_scale_codec::Encode`). + /// 3. Encrypt it following the steps + /// [here](https://github.com/ideal-lab5/tle/blob/f8e6019f0fb02c380ebfa6b30efb61786dede07b/timelock/src/tlock.rs#L283-L336) to + /// produce a [`TLECiphertext`]. + /// 4. Compress & serialise. + /// * `reveal_round` (`u64`): + /// DRAND round whose output becomes known during epoch `n + 1`; the payload + /// must be revealed in that epoch. + /// * `commit_reveal_version` (`u16`): + /// Version tag that **must** match [`get_commit_reveal_weights_version`] for + /// the call to succeed. Used to gate runtime upgrades. + /// + /// # Behaviour + /// 1. Verifies the caller’s signature and registration on `netuid`. + /// 2. Ensures commit-reveal is enabled **and** the supplied + /// `commit_reveal_version` is current. + /// 3. Enforces per-neuron rate-limiting via [`Pallet::check_rate_limit`]. + /// 4. Rejects the call when the hotkey already has ≥ 10 unrevealed commits in + /// the current epoch. + /// 5. Appends `(hotkey, commit_block, commit, reveal_round)` to + /// `CRV3WeightCommitsV2[netuid][epoch]`. + /// 6. Emits `CRV3WeightsCommitted` with the Blake2 hash of `commit`. + /// 7. Updates `LastUpdateForUid` so subsequent rate-limit checks include this + /// commit. + /// + /// # Raises + /// * `CommitRevealDisabled` – Commit-reveal is disabled on `netuid`. + /// * `IncorrectCommitRevealVersion` – Provided version ≠ runtime version. + /// * `HotKeyNotRegisteredInSubNet` – Caller’s hotkey is not registered. + /// * `CommittingWeightsTooFast` – Caller exceeds commit-rate limit. + /// * `TooManyUnrevealedCommits` – Caller already has 10 unrevealed commits. + /// + /// # Events + /// * `CRV3WeightsCommitted(hotkey, netuid, commit_hash)` – Fired after the commit is successfully stored. + pub fn do_commit_timelocked_weights( origin: T::RuntimeOrigin, netuid: NetUid, commit: BoundedVec>, reveal_round: u64, + commit_reveal_version: u16, ) -> DispatchResult { // 1. Verify the caller's signature (hotkey). let who = ensure_signed(origin)?; - log::debug!( - "do_commit_v3_weights(hotkey: {:?}, netuid: {:?})", - who, - netuid - ); + log::debug!("do_commit_v3_weights(hotkey: {who:?}, netuid: {netuid:?})"); // 2. Ensure commit-reveal is enabled. ensure!( @@ -248,13 +244,19 @@ impl Pallet { Error::::CommitRevealDisabled ); - // 3. Ensure the hotkey is registered on the network. + // 3. Ensure correct client version + ensure!( + commit_reveal_version == Self::get_commit_reveal_weights_version(), + Error::::IncorrectCommitRevealVersion + ); + + // 4. Ensure the hotkey is registered on the network. ensure!( Self::is_hotkey_registered_on_network(netuid, &who), Error::::HotKeyNotRegisteredInSubNet ); - // 4. Check that the commit rate does not exceed the allowed frequency. + // 5. Check that the commit rate does not exceed the allowed frequency. let commit_block = Self::get_current_block_as_u64(); let neuron_uid = Self::get_uid_for_net_and_hotkey(netuid, &who)?; ensure!( @@ -262,7 +264,7 @@ impl Pallet { Error::::CommittingWeightsTooFast ); - // 5. Retrieve or initialize the VecDeque of commits for the hotkey. + // 6. Retrieve or initialize the VecDeque of commits for the hotkey. let cur_block = Self::get_current_block_as_u64(); let cur_epoch = match Self::should_run_epoch(netuid, commit_block) { true => Self::get_epoch_index(netuid, cur_block).saturating_add(1), @@ -270,7 +272,7 @@ impl Pallet { }; CRV3WeightCommitsV2::::try_mutate(netuid, cur_epoch, |commits| -> DispatchResult { - // 6. Verify that the number of unrevealed commits is within the allowed limit. + // 7. Verify that the number of unrevealed commits is within the allowed limit. let unrevealed_commits_for_who = commits .iter() @@ -281,22 +283,22 @@ impl Pallet { Error::::TooManyUnrevealedCommits ); - // 7. Append the new commit with calculated reveal blocks. + // 8. Append the new commit with calculated reveal blocks. // Hash the commit before it is moved, for the event let commit_hash = BlakeTwo256::hash(&commit); commits.push_back((who.clone(), cur_block, commit, reveal_round)); - // 8. Emit the WeightsCommitted event + // 9. Emit the WeightsCommitted event Self::deposit_event(Event::CRV3WeightsCommitted( who.clone(), netuid, commit_hash, )); - // 9. Update the last commit block for the hotkey's UID. + // 10. Update the last commit block for the hotkey's UID. Self::set_last_update_for_uid(netuid, neuron_uid, commit_block); - // 10. Return success. + // 11. Return success. Ok(()) }) } @@ -348,7 +350,7 @@ impl Pallet { // --- 1. Check the caller's signature (hotkey). let who = ensure_signed(origin.clone())?; - log::debug!("do_reveal_weights( hotkey:{:?} netuid:{:?})", who, netuid); + log::debug!("do_reveal_weights( hotkey:{who:?} netuid:{netuid:?})"); // --- 2. Ensure commit-reveal is enabled for the network. ensure!( @@ -498,11 +500,7 @@ impl Pallet { // --- 2. Check the caller's signature (hotkey). let who = ensure_signed(origin.clone())?; - log::debug!( - "do_batch_reveal_weights( hotkey:{:?} netuid:{:?})", - who, - netuid - ); + log::debug!("do_batch_reveal_weights( hotkey:{who:?} netuid:{netuid:?})"); // --- 3. Ensure commit-reveal is enabled for the network. ensure!( @@ -684,11 +682,7 @@ impl Pallet { // --- 1. Check the caller's signature. This is the hotkey of a registered account. let hotkey = ensure_signed(origin)?; log::debug!( - "do_set_weights( origin:{:?} netuid:{:?}, uids:{:?}, values:{:?})", - hotkey, - netuid, - uids, - values + "do_set_weights( origin:{hotkey:?} netuid:{netuid:?}, uids:{uids:?}, values:{values:?})" ); // --- Check that the netuid is not the root network. @@ -784,11 +778,7 @@ impl Pallet { } // --- 19. Emit the tracking event. - log::debug!( - "WeightsSet( netuid:{:?}, neuron_uid:{:?} )", - netuid, - neuron_uid - ); + log::debug!("WeightsSet( netuid:{netuid:?}, neuron_uid:{neuron_uid:?} )"); Self::deposit_event(Event::WeightsSet(netuid, neuron_uid)); // --- 20. Return ok. @@ -834,10 +824,7 @@ impl Pallet { // --- 1. Check the caller's signature. This is the hotkey of a registered account. let hotkey = ensure_signed(origin.clone())?; log::debug!( - "do_batch_set_weights( origin:{:?} netuids:{:?}, weights:{:?}", - hotkey, - netuids, - weights + "do_batch_set_weights( origin:{hotkey:?} netuids:{netuids:?}, weights:{weights:?}" ); ensure!( @@ -882,11 +869,7 @@ impl Pallet { } // --- 19. Emit the tracking event. - log::debug!( - "BatchWeightsSet( netuids:{:?}, hotkey:{:?} )", - netuids, - hotkey - ); + log::debug!("BatchWeightsSet( netuids:{netuids:?}, hotkey:{hotkey:?} )"); Self::deposit_event(Event::BatchWeightsCompleted(netuids, hotkey)); // --- 20. Return ok. @@ -902,9 +885,7 @@ impl Pallet { pub fn check_version_key(netuid: NetUid, version_key: u64) -> bool { let network_version_key: u64 = WeightsVersionKey::::get(netuid); log::debug!( - "check_version_key( network_version_key:{:?}, version_key:{:?} )", - network_version_key, - version_key + "check_version_key( network_version_key:{network_version_key:?}, version_key:{version_key:?} )" ); network_version_key == 0 || version_key >= network_version_key } @@ -930,9 +911,7 @@ impl Pallet { for uid in uids { if !Self::is_uid_exist_on_network(netuid, *uid) { log::debug!( - "contains_invalid_uids( netuid:{:?}, uid:{:?} does not exist on network. )", - netuid, - uids + "contains_invalid_uids( netuid:{netuid:?}, uid:{uids:?} does not exist on network. )" ); return true; } diff --git a/pallets/subtensor/src/swap/swap_coldkey.rs b/pallets/subtensor/src/swap/swap_coldkey.rs index 7047a204e1..91da83e4e7 100644 --- a/pallets/subtensor/src/swap/swap_coldkey.rs +++ b/pallets/subtensor/src/swap/swap_coldkey.rs @@ -33,7 +33,7 @@ impl Pallet { pub fn do_swap_coldkey( old_coldkey: &T::AccountId, new_coldkey: &T::AccountId, - swap_cost: u64, + swap_cost: TaoCurrency, ) -> DispatchResultWithPostInfo { // 2. Initialize the weight for this operation let mut weight: Weight = T::DbWeight::get().reads(2); @@ -58,12 +58,13 @@ impl Pallet { // 6. Ensure sufficient balance for the swap cost ensure!( - Self::can_remove_balance_from_coldkey_account(old_coldkey, swap_cost), + Self::can_remove_balance_from_coldkey_account(old_coldkey, swap_cost.into()), Error::::NotEnoughBalanceToPaySwapColdKey ); // 7. Remove and burn the swap cost from the old coldkey's account - let actual_burn_amount = Self::remove_balance_from_coldkey_account(old_coldkey, swap_cost)?; + let actual_burn_amount = + Self::remove_balance_from_coldkey_account(old_coldkey, swap_cost.into())?; Self::burn_tokens(actual_burn_amount); // 8. Update the weight for the balance operations diff --git a/pallets/subtensor/src/swap/swap_hotkey.rs b/pallets/subtensor/src/swap/swap_hotkey.rs index 1b6274db54..e233460e39 100644 --- a/pallets/subtensor/src/swap/swap_hotkey.rs +++ b/pallets/subtensor/src/swap/swap_hotkey.rs @@ -89,18 +89,19 @@ impl Pallet { // Start to do everything for swap hotkey on all subnets case // 12. Get the cost for swapping the key let swap_cost = Self::get_key_swap_cost(); - log::debug!("Swap cost: {:?}", swap_cost); + log::debug!("Swap cost: {swap_cost:?}"); // 13. Ensure the coldkey has enough balance to pay for the swap ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost), + Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost.into()), Error::::NotEnoughBalanceToPaySwapHotKey ); weight.saturating_accrue(T::DbWeight::get().reads_writes(3, 0)); // 14. Remove the swap cost from the coldkey's account - let actual_burn_amount = Self::remove_balance_from_coldkey_account(&coldkey, swap_cost)?; + let actual_burn_amount = + Self::remove_balance_from_coldkey_account(&coldkey, swap_cost.into())?; // 18. Burn the tokens Self::burn_tokens(actual_burn_amount); @@ -288,7 +289,7 @@ impl Pallet { // 3. Get the cost for swapping the key on the subnet let swap_cost = T::KeySwapOnSubnetCost::get(); - log::debug!("Swap cost in subnet {:?}: {:?}", netuid, swap_cost); + log::debug!("Swap cost in subnet {netuid:?}: {swap_cost:?}"); weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 0)); // 4. Ensure the coldkey has enough balance to pay for the swap diff --git a/pallets/subtensor/src/tests/children.rs b/pallets/subtensor/src/tests/children.rs index 24b858628a..64769389bb 100644 --- a/pallets/subtensor/src/tests/children.rs +++ b/pallets/subtensor/src/tests/children.rs @@ -6,7 +6,7 @@ use super::mock::*; use approx::assert_abs_diff_eq; use frame_support::{assert_err, assert_noop, assert_ok}; use substrate_fixed::types::{I64F64, I96F32, U96F32}; -use subtensor_runtime_common::AlphaCurrency; +use subtensor_runtime_common::{AlphaCurrency, TaoCurrency}; use subtensor_swap_interface::SwapHandler; use crate::{utils::rate_limiting::TransactionType, *}; @@ -15,11 +15,7 @@ use sp_core::U256; fn close(value: u64, target: u64, eps: u64, msg: &str) { assert!( (value as i64 - target as i64).abs() <= eps as i64, - "{}: value = {}, target = {}, eps = {}", - msg, - value, - target, - eps + "{msg}: value = {value}, target = {target}, eps = {eps}" ) } @@ -874,7 +870,7 @@ fn test_childkey_take_functionality() { // Test default and max childkey take let default_take = SubtensorModule::get_default_childkey_take(); let min_take = SubtensorModule::get_min_childkey_take(); - log::info!("Default take: {}, Max take: {}", default_take, min_take); + log::info!("Default take: {default_take}, Max take: {min_take}"); // Check if default take and max take are the same assert_eq!( @@ -899,7 +895,7 @@ fn test_childkey_take_functionality() { // Verify childkey take was set correctly let stored_take = SubtensorModule::get_childkey_take(&hotkey, netuid); - log::info!("Stored take: {}", stored_take); + log::info!("Stored take: {stored_take}"); assert_eq!(stored_take, new_take); // Test setting childkey take outside of allowed range @@ -1065,12 +1061,11 @@ fn test_multiple_networks_childkey_take() { let stored_take = SubtensorModule::get_childkey_take(&hotkey, netuid); assert_eq!( stored_take, take_value, - "Childkey take not set correctly for network {}", - netuid + "Childkey take not set correctly for network {netuid}" ); // Log the set value - log::info!("Network {}: Childkey take set to {}", netuid, take_value); + log::info!("Network {netuid}: Childkey take set to {take_value}"); } // Verify all networks have different childkey take values @@ -1080,8 +1075,7 @@ fn test_multiple_networks_childkey_take() { let take_j = SubtensorModule::get_childkey_take(&hotkey, j.into()); assert_ne!( take_i, take_j, - "Childkey take values should be different for networks {} and {}", - i, j + "Childkey take values should be different for networks {i} and {j}" ); } } @@ -1533,31 +1527,24 @@ fn test_get_parents_chain() { let proportion = u64::MAX / 2; // 50% stake allocation log::info!( - "Test setup: netuid={}, coldkey={}, num_keys={}, proportion={}", - netuid, - coldkey, - num_keys, - proportion + "Test setup: netuid={netuid}, coldkey={coldkey}, num_keys={num_keys}, proportion={proportion}" ); // Create a vector of hotkeys let hotkeys: Vec = (0..num_keys).map(|i| U256::from(i as u64 + 2)).collect(); - log::info!("Created hotkeys: {:?}", hotkeys); + log::info!("Created hotkeys: {hotkeys:?}"); // Add network add_network(netuid, 13, 0); SubtensorModule::set_max_registrations_per_block(netuid, 1000); SubtensorModule::set_target_registrations_per_interval(netuid, 1000); - log::info!("Network added and parameters set: netuid={}", netuid); + log::info!("Network added and parameters set: netuid={netuid}"); // Register all neurons for hotkey in &hotkeys { register_ok_neuron(netuid, *hotkey, coldkey, 0); log::info!( - "Registered neuron: hotkey={}, coldkey={}, netuid={}", - hotkey, - coldkey, - netuid + "Registered neuron: hotkey={hotkey}, coldkey={coldkey}, netuid={netuid}" ); } @@ -1590,14 +1577,12 @@ fn test_get_parents_chain() { assert_eq!( parents.len(), 1, - "Hotkey {} should have exactly one parent", - i + "Hotkey {i} should have exactly one parent" ); assert_eq!( parents[0], (proportion, hotkeys[i - 1]), - "Incorrect parent for hotkey {}", - i + "Incorrect parent for hotkey {i}" ); } @@ -1620,10 +1605,7 @@ fn test_get_parents_chain() { SubtensorModule::set_difficulty(netuid, 1); register_ok_neuron(netuid, new_parent, coldkey, 99 * 2); log::info!( - "Registered new parent neuron: new_parent={}, coldkey={}, netuid={}", - new_parent, - coldkey, - netuid + "Registered new parent neuron: new_parent={new_parent}, coldkey={coldkey}, netuid={netuid}" ); mock_set_children( @@ -1642,9 +1624,7 @@ fn test_get_parents_chain() { let last_hotkey_parents = SubtensorModule::get_parents(&last_hotkey, netuid); log::info!( - "Testing get_parents for last hotkey {} with multiple parents: {:?}", - last_hotkey, - last_hotkey_parents + "Testing get_parents for last hotkey {last_hotkey} with multiple parents: {last_hotkey_parents:?}" ); assert_eq!( last_hotkey_parents.len(), @@ -1886,9 +1866,9 @@ fn test_get_stake_for_hotkey_on_subnet_single_parent_multiple_children() { close(child2_stake.into(), 1000, 10, "Child2 stake incorrect"); // Log the actual stake values - log::info!("Parent stake: {}", parent_stake); - log::info!("Child1 stake: {}", child1_stake); - log::info!("Child2 stake: {}", child2_stake); + log::info!("Parent stake: {parent_stake}"); + log::info!("Child1 stake: {child1_stake}"); + log::info!("Child2 stake: {child2_stake}"); }); } @@ -1934,9 +1914,9 @@ fn test_get_stake_for_hotkey_on_subnet_edge_cases() { let child1_stake = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid); let child2_stake = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid); - log::info!("Parent stake: {}", parent_stake); - log::info!("Child1 stake: {}", child1_stake); - log::info!("Child2 stake: {}", child2_stake); + log::info!("Parent stake: {parent_stake}"); + log::info!("Child1 stake: {child1_stake}"); + log::info!("Child2 stake: {child2_stake}"); assert_eq!(parent_stake, 0.into(), "Parent should have 0 stake"); assert_eq!(child1_stake, 0.into(), "Child1 should have 0 stake"); @@ -2038,9 +2018,9 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { let child1_stake_1 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid); let child2_stake_1 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid); - log::info!("Parent stake: {}", parent_stake_1); - log::info!("Child1 stake: {}", child1_stake_1); - log::info!("Child2 stake: {}", child2_stake_1); + log::info!("Parent stake: {parent_stake_1}"); + log::info!("Child1 stake: {child1_stake_1}"); + log::info!("Child2 stake: {child2_stake_1}"); assert_eq!( parent_stake_1, @@ -2079,10 +2059,10 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { let grandchild_stake = SubtensorModule::get_inherited_for_hotkey_on_subnet(&grandchild, netuid); - log::info!("Parent stake: {}", parent_stake_2); - log::info!("Child1 stake: {}", child1_stake_2); - log::info!("Child2 stake: {}", child2_stake_2); - log::info!("Grandchild stake: {}", grandchild_stake); + log::info!("Parent stake: {parent_stake_2}"); + log::info!("Child1 stake: {child1_stake_2}"); + log::info!("Child2 stake: {child2_stake_2}"); + log::info!("Grandchild stake: {grandchild_stake}"); close(parent_stake_2.into(), 0, 10, "Parent stake should remain 2"); close( @@ -2258,7 +2238,7 @@ fn test_do_remove_stake_clears_pending_childkeys() { SubtensorModule::add_balance_to_coldkey_account(&coldkey, 10_000_000_000_000); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Set non-default value for childkey stake threshold StakeThreshold::::set(1_000_000_000_000); @@ -2277,7 +2257,7 @@ fn test_do_remove_stake_clears_pending_childkeys() { "StakeThreshold::::get() = {:?}", StakeThreshold::::get() ); - println!("alpha = {:?}", alpha); + println!("alpha = {alpha:?}"); // Attempt to set child assert_ok!(SubtensorModule::do_schedule_children( @@ -2470,13 +2450,13 @@ fn test_revoke_child_no_min_stake_check() { register_ok_neuron(netuid, parent, coldkey, 0); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); - mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); + mock::setup_reserves(NetUid::ROOT, reserve.into(), reserve.into()); // Set minimum stake for setting children StakeThreshold::::put(1_000_000_000_000); - let (_, fee) = mock::swap_tao_to_alpha(NetUid::ROOT, StakeThreshold::::get()); + let (_, fee) = mock::swap_tao_to_alpha(NetUid::ROOT, StakeThreshold::::get().into()); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &parent, &coldkey, @@ -2548,11 +2528,11 @@ fn test_do_set_child_registration_disabled() { register_ok_neuron(netuid, parent, coldkey, 0); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Set minimum stake for setting children StakeThreshold::::put(1_000_000_000_000); - let (_, fee) = mock::swap_tao_to_alpha(netuid, StakeThreshold::::get()); + let (_, fee) = mock::swap_tao_to_alpha(netuid, StakeThreshold::::get().into()); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &parent, &coldkey, @@ -2813,9 +2793,7 @@ fn test_set_weights_no_parent() { let curr_stake_threshold = SubtensorModule::get_stake_threshold(); assert!( curr_stake_weight < curr_stake_threshold, - "{:?} is not less than {:?} ", - curr_stake_weight, - curr_stake_threshold + "{curr_stake_weight:?} is not less than {curr_stake_threshold:?} " ); // Check the hotkey cannot set weights @@ -2843,9 +2821,7 @@ fn test_set_weights_no_parent() { let new_stake_threshold = SubtensorModule::get_stake_threshold(); assert!( new_stake_weight >= new_stake_threshold, - "{:?} is not greater than or equal to {:?} ", - new_stake_weight, - new_stake_threshold + "{new_stake_weight:?} is not greater than or equal to {new_stake_threshold:?} " ); // Check the hotkey can set weights @@ -2883,7 +2859,7 @@ fn test_childkey_take_drain() { // Add network, register hotkeys, and setup network parameters add_network(netuid, subnet_tempo, 0); - mock::setup_reserves(netuid, stake * 10_000, (stake * 10_000).into()); + mock::setup_reserves(netuid, (stake * 10_000).into(), (stake * 10_000).into()); register_ok_neuron(netuid, child_hotkey, child_coldkey, 0); register_ok_neuron(netuid, parent_hotkey, parent_coldkey, 1); register_ok_neuron(netuid, miner_hotkey, miner_coldkey, 1); @@ -2928,13 +2904,13 @@ fn test_childkey_take_drain() { RuntimeOrigin::signed(parent_coldkey), parent_hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(nominator), child_hotkey, netuid, - stake + stake.into() )); // Setup YUMA so that it creates emissions @@ -2972,9 +2948,17 @@ fn test_childkey_take_drain() { SubtensorModule::get_total_stake_for_coldkey(&nominator) - nominator_stake_before; let total_emission = child_emission + parent_emission + nominator_emission; - assert_abs_diff_eq!(child_emission, 0, epsilon = 10); - assert_abs_diff_eq!(parent_emission, total_emission * 9 / 20, epsilon = 10); - assert_abs_diff_eq!(nominator_emission, total_emission * 11 / 20, epsilon = 10); + assert_abs_diff_eq!(child_emission, TaoCurrency::ZERO, epsilon = 10.into()); + assert_abs_diff_eq!( + parent_emission, + total_emission * 9.into() / 20.into(), + epsilon = 10.into() + ); + assert_abs_diff_eq!( + nominator_emission, + total_emission * 11.into() / 20.into(), + epsilon = 10.into() + ); }); }); } @@ -2997,7 +2981,7 @@ fn test_parent_child_chain_emission() { Tempo::::insert(netuid, 1); // Setup large LPs to prevent slippage - SubnetTAO::::insert(netuid, 1_000_000_000_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(1_000_000_000_000_000)); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000_000_000_000)); // Set owner cut to 0 @@ -3029,8 +3013,8 @@ fn test_parent_child_chain_emission() { let total_alpha: I96F32 = I96F32::from_num( SubtensorModule::swap_tao_for_alpha( netuid, - total_tao.to_num::(), - ::SwapInterface::max_price(), + total_tao.to_num::().into(), + ::SwapInterface::max_price().into(), false, ) .unwrap() @@ -3065,9 +3049,9 @@ fn test_parent_child_chain_emission() { ); // Get old stakes - let stake_a: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); - let stake_b: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); - let stake_c: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); + let stake_a = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); + let stake_b = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); + let stake_c = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); let _total_stake: I96F32 = I96F32::from_num(stake_a + stake_b + stake_c); @@ -3076,9 +3060,9 @@ fn test_parent_child_chain_emission() { let rel_stake_b = I96F32::from_num(stake_b) / total_tao; let rel_stake_c = I96F32::from_num(stake_c) / total_tao; - log::info!("rel_stake_a: {:?}", rel_stake_a); // 0.6666 -> 2/3 - log::info!("rel_stake_b: {:?}", rel_stake_b); // 0.2222 -> 2/9 - log::info!("rel_stake_c: {:?}", rel_stake_c); // 0.1111 -> 1/9 + log::info!("rel_stake_a: {rel_stake_a:?}"); // 0.6666 -> 2/3 + log::info!("rel_stake_b: {rel_stake_b:?}"); // 0.2222 -> 2/9 + log::info!("rel_stake_c: {rel_stake_c:?}"); // 0.1111 -> 1/9 assert!((rel_stake_a - I96F32::from_num(stake_a) / total_tao).abs() < 0.001); assert!((rel_stake_b - I96F32::from_num(stake_b) / total_tao).abs() < 0.001); assert!((rel_stake_c - I96F32::from_num(stake_c) / total_tao).abs() < 0.001); @@ -3091,15 +3075,16 @@ fn test_parent_child_chain_emission() { mock_set_children_no_epochs(netuid, &hotkey_b, &[(u64::MAX / 2, hotkey_c)]); // Get old stakes after children are scheduled - let stake_a_old: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); - let stake_b_old: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); - let stake_c_old: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); + let stake_a_old = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); + let stake_b_old = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); + let stake_c_old = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); - let total_stake_old: I96F32 = I96F32::from_num(stake_a_old + stake_b_old + stake_c_old); - log::info!("Old stake for hotkey A: {:?}", stake_a_old); - log::info!("Old stake for hotkey B: {:?}", stake_b_old); - log::info!("Old stake for hotkey C: {:?}", stake_c_old); - log::info!("Total old stake: {:?}", total_stake_old); + let total_stake_old: I96F32 = + I96F32::from_num((stake_a_old + stake_b_old + stake_c_old).to_u64()); + log::info!("Old stake for hotkey A: {stake_a_old:?}"); + log::info!("Old stake for hotkey B: {stake_b_old:?}"); + log::info!("Old stake for hotkey C: {stake_c_old:?}"); + log::info!("Total old stake: {total_stake_old:?}"); // Set CHK take rate to 1/9 let chk_take: I96F32 = I96F32::from_num(1_f64 / 9_f64); @@ -3110,7 +3095,11 @@ fn test_parent_child_chain_emission() { // Set the weight of root TAO to be 0%, so only alpha is effective. SubtensorModule::set_tao_weight(0); - let emission: U96F32 = U96F32::from_num(SubtensorModule::get_block_emission().unwrap_or(0)); + let emission = U96F32::from_num( + SubtensorModule::get_block_emission() + .unwrap_or(TaoCurrency::ZERO) + .to_u64(), + ); // Set pending emission to 0 PendingEmission::::insert(netuid, AlphaCurrency::ZERO); @@ -3119,31 +3108,31 @@ fn test_parent_child_chain_emission() { SubtensorModule::run_coinbase(emission); // Log new stake - let stake_a_new: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); - let stake_b_new: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); - let stake_c_new: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); - let total_stake_new: I96F32 = I96F32::from_num(stake_a_new + stake_b_new + stake_c_new); - log::info!("Stake for hotkey A: {:?}", stake_a_new); - log::info!("Stake for hotkey B: {:?}", stake_b_new); - log::info!("Stake for hotkey C: {:?}", stake_c_new); - - let stake_inc_a: u64 = stake_a_new - stake_a_old; - let stake_inc_b: u64 = stake_b_new - stake_b_old; - let stake_inc_c: u64 = stake_c_new - stake_c_old; + let stake_a_new = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); + let stake_b_new = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); + let stake_c_new = SubtensorModule::get_total_stake_for_hotkey(&hotkey_c); + let total_stake_new = I96F32::from_num((stake_a_new + stake_b_new + stake_c_new).to_u64()); + log::info!("Stake for hotkey A: {stake_a_new:?}"); + log::info!("Stake for hotkey B: {stake_b_new:?}"); + log::info!("Stake for hotkey C: {stake_c_new:?}"); + + let stake_inc_a = stake_a_new - stake_a_old; + let stake_inc_b = stake_b_new - stake_b_old; + let stake_inc_c = stake_c_new - stake_c_old; let total_stake_inc: I96F32 = total_stake_new - total_stake_old; - log::info!("Stake increase for hotkey A: {:?}", stake_inc_a); - log::info!("Stake increase for hotkey B: {:?}", stake_inc_b); - log::info!("Stake increase for hotkey C: {:?}", stake_inc_c); - log::info!("Total stake increase: {:?}", total_stake_inc); + log::info!("Stake increase for hotkey A: {stake_inc_a:?}"); + log::info!("Stake increase for hotkey B: {stake_inc_b:?}"); + log::info!("Stake increase for hotkey C: {stake_inc_c:?}"); + log::info!("Total stake increase: {total_stake_inc:?}"); let rel_stake_inc_a = I96F32::from_num(stake_inc_a) / total_stake_inc; let rel_stake_inc_b = I96F32::from_num(stake_inc_b) / total_stake_inc; let rel_stake_inc_c = I96F32::from_num(stake_inc_c) / total_stake_inc; - log::info!("rel_stake_inc_a: {:?}", rel_stake_inc_a); - log::info!("rel_stake_inc_b: {:?}", rel_stake_inc_b); - log::info!("rel_stake_inc_c: {:?}", rel_stake_inc_c); + log::info!("rel_stake_inc_a: {rel_stake_inc_a:?}"); + log::info!("rel_stake_inc_b: {rel_stake_inc_b:?}"); + log::info!("rel_stake_inc_c: {rel_stake_inc_c:?}"); // Verify the final stake distribution - let stake_inc_eps: I96F32 = I96F32::from_num(1e-4); // 4 decimal places + let stake_inc_eps = I96F32::from_num(1e-4); // 4 decimal places // Each child has chk_take take let expected_a = I96F32::from_num(2_f64 / 3_f64) @@ -3151,9 +3140,7 @@ fn test_parent_child_chain_emission() { assert!( (rel_stake_inc_a - expected_a).abs() // B's take on 50% CHK <= stake_inc_eps, - "A should have {:?} of total stake increase; {:?}", - expected_a, - rel_stake_inc_a + "A should have {expected_a:?} of total stake increase; {rel_stake_inc_a:?}" ); let expected_b = I96F32::from_num(2_f64 / 9_f64) * (I96F32::from_num(1_f64) - (I96F32::from_num(1_f64 / 2_f64) * chk_take)) @@ -3161,18 +3148,14 @@ fn test_parent_child_chain_emission() { assert!( (rel_stake_inc_b - expected_b).abs() // C's take on 50% CHK + take from A <= stake_inc_eps, - "B should have {:?} of total stake increase; {:?}", - expected_b, - rel_stake_inc_b + "B should have {expected_b:?} of total stake increase; {rel_stake_inc_b:?}" ); let expected_c = I96F32::from_num(1_f64 / 9_f64) + (I96F32::from_num(2_f64 / 9_f64) * I96F32::from_num(1_f64 / 2_f64) * chk_take); assert!( (rel_stake_inc_c - expected_c).abs() // B's take on 50% CHK <= stake_inc_eps, - "C should have {:?} of total stake increase; {:?}", - expected_c, - rel_stake_inc_c + "C should have {expected_c:?} of total stake increase; {rel_stake_inc_c:?}" ); let hotkeys = [hotkey_a, hotkey_b, hotkey_c]; @@ -3181,19 +3164,10 @@ fn test_parent_child_chain_emission() { if hotkeys.contains(&hotkey) { total_stake_now += stake; } else { - log::info!( - "hotkey: {:?}, netuid: {:?}, stake: {:?}", - hotkey, - netuid, - stake - ); + log::info!("hotkey: {hotkey:?}, netuid: {netuid:?}, stake: {stake:?}"); } } - log::info!( - "total_stake_now: {:?}, total_stake_new: {:?}", - total_stake_now, - total_stake_new - ); + log::info!("total_stake_now: {total_stake_now:?}, total_stake_new: {total_stake_new:?}"); assert_abs_diff_eq!( total_stake_inc.to_num::(), @@ -3237,11 +3211,11 @@ fn test_parent_child_chain_epoch() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_b, 1_000); SubtensorModule::add_balance_to_coldkey_account(&coldkey_c, 1_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); // Swap to alpha let total_tao = I96F32::from_num(300_000 + 100_000 + 50_000); - let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num()); + let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num::().into()); let total_alpha = I96F32::from_num(total_alpha); // Set the stakes directly @@ -3281,9 +3255,9 @@ fn test_parent_child_chain_epoch() { let rel_stake_b = I96F32::from_num(stake_b) / total_alpha; let rel_stake_c = I96F32::from_num(stake_c) / total_alpha; - log::info!("rel_stake_a: {:?}", rel_stake_a); // 0.6666 -> 2/3 - log::info!("rel_stake_b: {:?}", rel_stake_b); // 0.2222 -> 2/9 - log::info!("rel_stake_c: {:?}", rel_stake_c); // 0.1111 -> 1/9 + log::info!("rel_stake_a: {rel_stake_a:?}"); // 0.6666 -> 2/3 + log::info!("rel_stake_b: {rel_stake_b:?}"); // 0.2222 -> 2/9 + log::info!("rel_stake_c: {rel_stake_c:?}"); // 0.1111 -> 1/9 assert!(rel_stake_a > I96F32::from_num(0)); assert!(rel_stake_b > I96F32::from_num(0)); @@ -3315,7 +3289,7 @@ fn test_parent_child_chain_epoch() { let hotkey_emission = SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); - log::info!("hotkey_emission: {:?}", hotkey_emission); + log::info!("hotkey_emission: {hotkey_emission:?}"); let total_emission: I96F32 = hotkey_emission .iter() .map(|(_, _, emission)| I96F32::from_num(*emission)) @@ -3360,7 +3334,11 @@ fn test_dividend_distribution_with_children() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000_000, 1_000_000_000_000_000.into()); + mock::setup_reserves( + netuid, + 1_000_000_000_000_000.into(), + 1_000_000_000_000_000.into(), + ); // Set owner cut to 0 SubtensorModule::set_subnet_owner_cut(0_u16); @@ -3384,7 +3362,7 @@ fn test_dividend_distribution_with_children() { // Swap to alpha let total_tao = I96F32::from_num(300_000 + 100_000 + 50_000); - let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num()); + let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num::().into()); let total_alpha = I96F32::from_num(total_alpha); // Set the stakes directly @@ -3424,9 +3402,9 @@ fn test_dividend_distribution_with_children() { let rel_stake_b = I96F32::from_num(stake_b) / total_alpha; let rel_stake_c = I96F32::from_num(stake_c) / total_alpha; - log::info!("rel_stake_a: {:?}", rel_stake_a); // 0.6666 -> 2/3 - log::info!("rel_stake_b: {:?}", rel_stake_b); // 0.2222 -> 2/9 - log::info!("rel_stake_c: {:?}", rel_stake_c); // 0.1111 -> 1/9 + log::info!("rel_stake_a: {rel_stake_a:?}"); // 0.6666 -> 2/3 + log::info!("rel_stake_b: {rel_stake_b:?}"); // 0.2222 -> 2/9 + log::info!("rel_stake_c: {rel_stake_c:?}"); // 0.1111 -> 1/9 let epsilon = I96F32::from_num(0.00001); assert!((rel_stake_a - I96F32::from_num(300_000) / total_tao).abs() <= epsilon); assert!((rel_stake_b - I96F32::from_num(100_000) / total_tao).abs() <= epsilon); @@ -3452,7 +3430,7 @@ fn test_dividend_distribution_with_children() { let hotkey_emission = SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); - log::info!("hotkey_emission: {:?}", hotkey_emission); + log::info!("hotkey_emission: {hotkey_emission:?}"); let total_emission: I96F32 = hotkey_emission .iter() .map(|(_, _, emission)| I96F32::from_num(*emission)) @@ -3497,9 +3475,9 @@ fn test_dividend_distribution_with_children() { netuid, hardcoded_emission.saturating_to_num::().into(), ); - log::info!("dividends_a: {:?}", dividends_a); - log::info!("dividends_b: {:?}", dividends_b); - log::info!("dividends_c: {:?}", dividends_c); + log::info!("dividends_a: {dividends_a:?}"); + log::info!("dividends_b: {dividends_b:?}"); + log::info!("dividends_c: {dividends_c:?}"); // We expect A to get all of its own emission, as it has no parents. assert_eq!(dividends_a.len(), 1); @@ -3607,8 +3585,8 @@ fn test_dynamic_parent_child_relationships() { let chk_take_1 = SubtensorModule::get_childkey_take(&child1, netuid); let chk_take_2 = SubtensorModule::get_childkey_take(&child2, netuid); - log::info!("child take 1: {:?}", chk_take_1); - log::info!("child take 2: {:?}", chk_take_2); + log::info!("child take 1: {chk_take_1:?}"); + log::info!("child take 2: {chk_take_2:?}"); // Add initial stakes SubtensorModule::add_balance_to_coldkey_account(&coldkey_parent, 500_000 + 1_000); @@ -3616,13 +3594,13 @@ fn test_dynamic_parent_child_relationships() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_child2, 30_000 + 1_000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Swap to alpha let total_tao = I96F32::from_num(500_000 + 50_000 + 30_000); - let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num()); + let (total_alpha, _) = mock::swap_tao_to_alpha(netuid, total_tao.to_num::().into()); let total_alpha = I96F32::from_num(total_alpha); - log::info!("total_alpha: {:?}", total_alpha); + log::info!("total_alpha: {total_alpha:?}"); // Set the stakes directly // This avoids needing to swap tao to alpha, impacting the initial stake distribution. @@ -3655,9 +3633,9 @@ fn test_dynamic_parent_child_relationships() { let stake_parent_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); let stake_child1_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid); let stake_child2_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); - log::info!("stake_parent_0: {:?}", stake_parent_0); - log::info!("stake_child1_0: {:?}", stake_child1_0); - log::info!("stake_child2_0: {:?}", stake_child2_0); + log::info!("stake_parent_0: {stake_parent_0:?}"); + log::info!("stake_child1_0: {stake_child1_0:?}"); + log::info!("stake_child2_0: {stake_child2_0:?}"); let total_stake_0 = stake_parent_0 + stake_child1_0 + stake_child2_0; @@ -3666,9 +3644,9 @@ fn test_dynamic_parent_child_relationships() { let rel_stake_child1_0 = I96F32::from_num(stake_child1_0) / total_alpha; let rel_stake_child2_0 = I96F32::from_num(stake_child2_0) / total_alpha; - log::info!("rel_stake_parent_0: {:?}", rel_stake_parent_0); - log::info!("rel_stake_child1_0: {:?}", rel_stake_child1_0); - log::info!("rel_stake_child2_0: {:?}", rel_stake_child2_0); + log::info!("rel_stake_parent_0: {rel_stake_parent_0:?}"); + log::info!("rel_stake_child1_0: {rel_stake_child1_0:?}"); + log::info!("rel_stake_child2_0: {rel_stake_child2_0:?}"); let epsilon = I96F32::from_num(0.00001); assert!((rel_stake_parent_0 - I96F32::from_num(500_000) / total_tao).abs() <= epsilon); assert!((rel_stake_child1_0 - I96F32::from_num(50_000) / total_tao).abs() <= epsilon); @@ -3703,7 +3681,7 @@ fn test_dynamic_parent_child_relationships() { let total_stake_1 = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid) + SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid) + SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); - log::info!("total_stake_1: {:?}", total_stake_1); + log::info!("total_stake_1: {total_stake_1:?}"); // Change parent-child relationships mock_set_children( @@ -3720,7 +3698,7 @@ fn test_dynamic_parent_child_relationships() { let total_stake_2 = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid) + SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid) + SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); - log::info!("total_stake_2: {:?}", total_stake_2); + log::info!("total_stake_2: {total_stake_2:?}"); // Check final emission distribution let stake_parent_2 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent, netuid); @@ -3731,17 +3709,17 @@ fn test_dynamic_parent_child_relationships() { let _total_child2_stake = SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); log::info!("Final stakes:"); - log::info!("Parent stake: {}", stake_parent_2); - log::info!("Child1 stake: {}", stake_child1_2); - log::info!("Child2 stake: {}", stake_child2_2); + log::info!("Parent stake: {stake_parent_2}"); + log::info!("Child1 stake: {stake_child1_2}"); + log::info!("Child2 stake: {stake_child2_2}"); // Payout 1 let payout_1 = total_stake_1 - total_stake_0; - log::info!("payout_1: {:?}", payout_1); + log::info!("payout_1: {payout_1:?}"); // Payout 2 let payout_2 = total_stake_2 - total_stake_1; - log::info!("payout_2: {:?}", payout_2); + log::info!("payout_2: {payout_2:?}"); let total_emission = I96F32::from_num(payout_1 + payout_2); @@ -3749,7 +3727,7 @@ fn test_dynamic_parent_child_relationships() { let TOLERANCE = I96F32::from_num(0.001); // Allow for a small discrepancy due to potential rounding // Precise assertions with tolerance - log::info!("total_emission: {:?}", total_emission); + log::info!("total_emission: {total_emission:?}"); let expected_parent_stake = ((I96F32::from_num(u64::from(stake_parent_0)) + total_emission * rel_stake_parent_0) * I96F32::from_num(5)) @@ -3758,9 +3736,7 @@ fn test_dynamic_parent_child_relationships() { (I96F32::from_num(stake_parent_2) - expected_parent_stake).abs() / expected_parent_stake <= TOLERANCE, - "Parent stake should be close to {:?}, but was {}", - expected_parent_stake, - stake_parent_2 + "Parent stake should be close to {expected_parent_stake:?}, but was {stake_parent_2}" ); // Parent stake calculation: // Initial stake: 500,000 @@ -3773,9 +3749,7 @@ fn test_dynamic_parent_child_relationships() { (I96F32::from_num(stake_child1_2) - expected_child1_stake).abs() / expected_child1_stake <= TOLERANCE, - "Child1 stake should be close to {:?}, but was {}", - expected_child1_stake, - stake_child1_2 + "Child1 stake should be close to {expected_child1_stake:?}, but was {stake_child1_2}" ); // Child1 stake calculation: // Initial stake: 50,000 @@ -3788,9 +3762,7 @@ fn test_dynamic_parent_child_relationships() { (I96F32::from_num(stake_child2_2) - expected_child2_stake).abs() / expected_child2_stake <= TOLERANCE, - "Child2 stake should be close to {:?}, but was {}", - expected_child2_stake, - stake_child2_2 + "Child2 stake should be close to {expected_child2_stake:?}, but was {stake_child2_2}" ); // Child2 stake calculation: // Initial stake: 30,000 @@ -3855,7 +3827,7 @@ fn test_do_set_child_as_sn_owner_not_enough_stake() { // Verify stake of sn_owner_hotkey is NOT enough assert!( SubtensorModule::get_total_stake_for_hotkey(&sn_owner_hotkey) - < StakeThreshold::::get() + < StakeThreshold::::get().into() ); // Verify that we can set child as sn owner, even though sn_owner_hotkey has insufficient stake @@ -3873,7 +3845,7 @@ fn test_do_set_child_as_sn_owner_not_enough_stake() { // Verify stake of other_sn_owner_hotkey is NOT enough assert!( SubtensorModule::get_total_stake_for_hotkey(&other_sn_owner_hotkey) - < StakeThreshold::::get() + < StakeThreshold::::get().into() ); // Can't set child as sn owner, because it is not in SubnetOwnerHotkey map @@ -3898,7 +3870,7 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { add_network(netuid, 1, 0); // Set SN owner cut to 0 SubtensorModule::set_subnet_owner_cut(0_u16); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); // Define hotkeys and coldkeys let hotkey_a: U256 = U256::from(1); @@ -3915,7 +3887,7 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { // Swap to alpha let total_tao = 300_000 + 100_000; - let total_alpha = I96F32::from_num(mock::swap_tao_to_alpha(netuid, total_tao).0); + let total_alpha = I96F32::from_num(mock::swap_tao_to_alpha(netuid, total_tao.into()).0); let total_tao = I96F32::from_num(total_tao); // Set the stakes directly @@ -3945,8 +3917,8 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { let rel_stake_a = I96F32::from_num(stake_a) / total_alpha; let rel_stake_b = I96F32::from_num(stake_b) / total_alpha; - log::info!("rel_stake_a: {:?}", rel_stake_a); // 0.75 -> 3/4 - log::info!("rel_stake_b: {:?}", rel_stake_b); // 0.25 -> 1/4 + log::info!("rel_stake_a: {rel_stake_a:?}"); // 0.75 -> 3/4 + log::info!("rel_stake_b: {rel_stake_b:?}"); // 0.25 -> 1/4 let epsilon = I96F32::from_num(0.0001); assert!((rel_stake_a - I96F32::from_num(300_000) / total_tao).abs() <= epsilon); assert!((rel_stake_b - I96F32::from_num(100_000) / total_tao).abs() <= epsilon); @@ -3967,7 +3939,7 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { let hotkey_emission = SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); - log::info!("hotkey_emission: {:?}", hotkey_emission); + log::info!("hotkey_emission: {hotkey_emission:?}"); let total_emission: I96F32 = hotkey_emission .iter() .map(|(_, _, emission)| I96F32::from_num(*emission)) @@ -4002,8 +3974,8 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { netuid, hardcoded_emission.saturating_to_num::().into(), ); - log::info!("dividends_a: {:?}", dividends_a); - log::info!("dividends_b: {:?}", dividends_b); + log::info!("dividends_a: {dividends_a:?}"); + log::info!("dividends_b: {dividends_b:?}"); // We expect A should have no impact from B, as they have the same owner. assert_eq!(dividends_a.len(), 1); diff --git a/pallets/subtensor/src/tests/coinbase.rs b/pallets/subtensor/src/tests/coinbase.rs index 2ed25b4c10..f74565c44e 100644 --- a/pallets/subtensor/src/tests/coinbase.rs +++ b/pallets/subtensor/src/tests/coinbase.rs @@ -16,10 +16,7 @@ use subtensor_swap_interface::SwapHandler; fn close(value: u64, target: u64, eps: u64) { assert!( (value as i64 - target as i64).abs() < eps as i64, - "Assertion failed: value = {}, target = {}, eps = {}", - value, - target, - eps + "Assertion failed: value = {value}, target = {target}, eps = {eps}" ) } @@ -53,7 +50,7 @@ fn test_dynamic_function_various_values() { for &alpha_emission in alpha_emission_values.iter() { // Set the price. SubnetMechanism::::insert(NetUid::from(1), 1); - SubnetTAO::::insert(NetUid::from(1), (price * 1_000_000_000.0) as u64); + SubnetTAO::::insert(NetUid::from(1), TaoCurrency::from((price * 1_000_000_000.0) as u64)); SubnetAlphaIn::::insert(NetUid::from(1), AlphaCurrency::from(1_000_000_000)); let (tao_in_emission, alpha_in_emission, alpha_out_emission) = SubtensorModule::get_dynamic_tao_emission(1.into(), tao_in, alpha_emission); assert!(tao_in_emission <= tao_in, "tao_in_emission is greater than tao_in"); @@ -91,9 +88,9 @@ fn test_coinbase_basecase() { fn test_coinbase_tao_issuance_base() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); - let emission: u64 = 1_234_567; + let emission = TaoCurrency::from(1_234_567); add_network(netuid, 1, 0); - assert_eq!(SubnetTAO::::get(netuid), 0); + assert_eq!(SubnetTAO::::get(netuid), TaoCurrency::ZERO); SubtensorModule::run_coinbase(U96F32::from_num(emission)); assert_eq!(SubnetTAO::::get(netuid), emission); assert_eq!(TotalIssuance::::get(), emission); @@ -106,9 +103,9 @@ fn test_coinbase_tao_issuance_base() { fn test_coinbase_tao_issuance_base_low() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); - let emission: u64 = 1; + let emission = TaoCurrency::from(1); add_network(netuid, 1, 0); - assert_eq!(SubnetTAO::::get(netuid), 0); + assert_eq!(SubnetTAO::::get(netuid), TaoCurrency::ZERO); SubtensorModule::run_coinbase(U96F32::from_num(emission)); assert_eq!(SubnetTAO::::get(netuid), emission); assert_eq!(TotalIssuance::::get(), emission); @@ -129,17 +126,17 @@ fn test_coinbase_tao_issuance_multiple() { let netuid1 = NetUid::from(1); let netuid2 = NetUid::from(2); let netuid3 = NetUid::from(3); - let emission: u64 = 3_333_333; + let emission = TaoCurrency::from(3_333_333); add_network(netuid1, 1, 0); add_network(netuid2, 1, 0); add_network(netuid3, 1, 0); - assert_eq!(SubnetTAO::::get(netuid1), 0); - assert_eq!(SubnetTAO::::get(netuid2), 0); - assert_eq!(SubnetTAO::::get(netuid3), 0); + assert_eq!(SubnetTAO::::get(netuid1), TaoCurrency::ZERO); + assert_eq!(SubnetTAO::::get(netuid2), TaoCurrency::ZERO); + assert_eq!(SubnetTAO::::get(netuid3), TaoCurrency::ZERO); SubtensorModule::run_coinbase(U96F32::from_num(emission)); - assert_eq!(SubnetTAO::::get(netuid1), emission / 3); - assert_eq!(SubnetTAO::::get(netuid2), emission / 3); - assert_eq!(SubnetTAO::::get(netuid3), emission / 3); + assert_eq!(SubnetTAO::::get(netuid1), emission / 3.into()); + assert_eq!(SubnetTAO::::get(netuid2), emission / 3.into()); + assert_eq!(SubnetTAO::::get(netuid3), emission / 3.into()); assert_eq!(TotalIssuance::::get(), emission); assert_eq!(TotalStake::::get(), emission); }); @@ -156,7 +153,7 @@ fn test_coinbase_tao_issuance_different_prices() { new_test_ext(1).execute_with(|| { let netuid1 = NetUid::from(1); let netuid2 = NetUid::from(2); - let emission: u64 = 100_000_000; + let emission = 100_000_000; add_network(netuid1, 1, 0); add_network(netuid2, 1, 0); @@ -164,12 +161,24 @@ fn test_coinbase_tao_issuance_different_prices() { let initial_tao: u64 = 100_000_u64; let initial_alpha1: u64 = initial_tao * 10; let initial_alpha2: u64 = initial_tao * 5; - mock::setup_reserves(netuid1, initial_tao, initial_alpha1.into()); - mock::setup_reserves(netuid2, initial_tao, initial_alpha2.into()); + mock::setup_reserves(netuid1, initial_tao.into(), initial_alpha1.into()); + mock::setup_reserves(netuid2, initial_tao.into(), initial_alpha2.into()); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid1, 0, 1_000_000_000_000, false).unwrap(); - SubtensorModule::swap_tao_for_alpha(netuid2, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid1, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid2, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); // Make subnets dynamic. SubnetMechanism::::insert(netuid1, 1); @@ -180,8 +189,8 @@ fn test_coinbase_tao_issuance_different_prices() { SubnetMovingPrice::::insert(netuid2, I96F32::from_num(2)); // Assert initial TAO reserves. - assert_eq!(SubnetTAO::::get(netuid1), initial_tao); - assert_eq!(SubnetTAO::::get(netuid2), initial_tao); + assert_eq!(SubnetTAO::::get(netuid1), initial_tao.into()); + assert_eq!(SubnetTAO::::get(netuid2), initial_tao.into()); // Run the coinbase with the emission amount. SubtensorModule::run_coinbase(U96F32::from_num(emission)); @@ -189,19 +198,27 @@ fn test_coinbase_tao_issuance_different_prices() { // Assert tao emission is split evenly. assert_abs_diff_eq!( SubnetTAO::::get(netuid1), - initial_tao + emission / 3, - epsilon = 1, + TaoCurrency::from(initial_tao + emission / 3), + epsilon = 1.into(), ); assert_abs_diff_eq!( SubnetTAO::::get(netuid2), - initial_tao + 2 * emission / 3, - epsilon = 1, + TaoCurrency::from(initial_tao + 2 * emission / 3), + epsilon = 1.into(), ); // Prices are low => we limit tao issued (buy alpha with it) - let tao_issued = ((0.1 + 0.2) * emission as f64) as u64; - assert_abs_diff_eq!(TotalIssuance::::get(), tao_issued, epsilon = 10); - assert_abs_diff_eq!(TotalStake::::get(), emission, epsilon = 10); + let tao_issued = TaoCurrency::from(((0.1 + 0.2) * emission as f64) as u64); + assert_abs_diff_eq!( + TotalIssuance::::get(), + tao_issued, + epsilon = 10.into() + ); + assert_abs_diff_eq!( + TotalStake::::get(), + emission.into(), + epsilon = 10.into() + ); }); } @@ -217,7 +234,7 @@ fn test_coinbase_moving_prices() { let netuid = NetUid::from(1); add_network(netuid, 1, 0); // Set price to 1.0 - SubnetTAO::::insert(netuid, 1_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(1_000_000)); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingPrice::::insert(netuid, I96F32::from_num(1)); @@ -273,7 +290,7 @@ fn test_update_moving_price_initial() { let netuid = NetUid::from(1); add_network(netuid, 1, 0); // Set current price to 1.0 - SubnetTAO::::insert(netuid, 1_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(1_000_000)); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingAlpha::::set(I96F32::from_num(0.5)); @@ -298,7 +315,7 @@ fn test_update_moving_price_after_time() { let netuid = NetUid::from(1); add_network(netuid, 1, 0); // Set current price to 1.0 - SubnetTAO::::insert(netuid, 1_000_000); + SubnetTAO::::insert(netuid, TaoCurrency::from(1_000_000)); SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingAlpha::::set(I96F32::from_num(0.5)); @@ -331,9 +348,9 @@ fn test_coinbase_alpha_issuance_base() { add_network(netuid2, 1, 0); // Set up prices 1 and 1 let initial: u64 = 1_000_000; - SubnetTAO::::insert(netuid1, initial); + SubnetTAO::::insert(netuid1, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial)); - SubnetTAO::::insert(netuid2, initial); + SubnetTAO::::insert(netuid2, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial)); // Check initial SubtensorModule::run_coinbase(U96F32::from_num(emission)); @@ -369,9 +386,9 @@ fn test_coinbase_alpha_issuance_different() { SubnetMechanism::::insert(netuid2, 1); // Setup prices 1 and 1 let initial: u64 = 1_000_000; - SubnetTAO::::insert(netuid1, initial); + SubnetTAO::::insert(netuid1, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial)); - SubnetTAO::::insert(netuid2, initial); + SubnetTAO::::insert(netuid2, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial)); // Set subnet prices. SubnetMovingPrice::::insert(netuid1, I96F32::from_num(1)); @@ -408,9 +425,9 @@ fn test_coinbase_alpha_issuance_with_cap_trigger() { // Setup prices 1000000 let initial: u64 = 1_000; let initial_alpha: u64 = initial * 1000000; - SubnetTAO::::insert(netuid1, initial); + SubnetTAO::::insert(netuid1, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial_alpha)); // Make price extremely low. - SubnetTAO::::insert(netuid2, initial); + SubnetTAO::::insert(netuid2, TaoCurrency::from(initial)); SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial_alpha)); // Make price extremely low. // Set subnet prices. SubnetMovingPrice::::insert(netuid1, I96F32::from_num(1)); @@ -445,8 +462,8 @@ fn test_coinbase_alpha_issuance_with_cap_trigger_and_block_emission() { // Setup prices 0.000001 let initial_tao: u64 = 10_000_u64; let initial_alpha: u64 = initial_tao * 100_000_u64; - mock::setup_reserves(netuid1, initial_tao, initial_alpha.into()); - mock::setup_reserves(netuid2, initial_tao, initial_alpha.into()); + mock::setup_reserves(netuid1, initial_tao.into(), initial_alpha.into()); + mock::setup_reserves(netuid2, initial_tao.into(), initial_alpha.into()); // Enable emission FirstEmissionBlockNumber::::insert(netuid1, 0); @@ -455,8 +472,20 @@ fn test_coinbase_alpha_issuance_with_cap_trigger_and_block_emission() { SubnetMovingPrice::::insert(netuid2, I96F32::from_num(2)); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid1, 0, 1_000_000_000_000, false).unwrap(); - SubtensorModule::swap_tao_for_alpha(netuid2, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid1, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid2, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); // Get the prices before the run_coinbase let price_1_before = ::SwapInterface::current_alpha_price(netuid1); @@ -496,7 +525,7 @@ fn test_owner_cut_base() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); SubtensorModule::set_tempo(netuid, 10000); // Large number (dont drain) SubtensorModule::set_subnet_owner_cut(0); SubtensorModule::run_coinbase(U96F32::from_num(0)); @@ -514,10 +543,10 @@ fn test_pending_swapped() { let netuid = NetUid::from(1); let emission: u64 = 1_000_000; add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000, 1.into()); + mock::setup_reserves(netuid, 1_000_000.into(), 1.into()); SubtensorModule::run_coinbase(U96F32::from_num(0)); assert_eq!(PendingAlphaSwapped::::get(netuid), 0.into()); // Zero tao weight and no root. - SubnetTAO::::insert(NetUid::ROOT, 1_000_000_000); // Add root weight. + SubnetTAO::::insert(NetUid::ROOT, TaoCurrency::from(1_000_000_000)); // Add root weight. SubtensorModule::run_coinbase(U96F32::from_num(0)); assert_eq!(PendingAlphaSwapped::::get(netuid), 0.into()); // Zero tao weight with 1 root. SubtensorModule::set_tempo(netuid, 10000); // Large number (dont drain) @@ -546,7 +575,13 @@ fn test_pending_swapped() { #[test] fn test_drain_base() { new_test_ext(1).execute_with(|| { - SubtensorModule::drain_pending_emission(0.into(), 0.into(), 0, 0.into(), 0.into()) + SubtensorModule::drain_pending_emission( + 0.into(), + AlphaCurrency::ZERO, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ) }); } @@ -556,7 +591,13 @@ fn test_drain_base_with_subnet() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - SubtensorModule::drain_pending_emission(netuid, 0.into(), 0, 0.into(), 0.into()) + SubtensorModule::drain_pending_emission( + netuid, + AlphaCurrency::ZERO, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ) }); } @@ -579,9 +620,9 @@ fn test_drain_base_with_subnet_with_single_staker_not_registered() { SubtensorModule::drain_pending_emission( netuid, pending_alpha.into(), - 0, - 0.into(), - 0.into(), + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, ); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); @@ -606,7 +647,13 @@ fn test_drain_base_with_subnet_with_single_staker_registered() { stake_before, ); let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); close( @@ -642,15 +689,15 @@ fn test_drain_base_with_subnet_with_single_staker_registered_root_weight() { netuid, stake_before, ); - let pending_tao = 1_000_000_000; + let pending_tao = TaoCurrency::from(1_000_000_000); let pending_alpha = AlphaCurrency::from(1_000_000_000); - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); SubtensorModule::drain_pending_emission( netuid, pending_alpha, pending_tao, - 0.into(), - 0.into(), + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, ); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); @@ -664,7 +711,11 @@ fn test_drain_base_with_subnet_with_single_staker_registered_root_weight() { stake_after.into(), 10, ); // Registered gets all alpha emission. - close(u64::from(stake_before) + pending_tao, root_after.into(), 10); // Registered gets all tao emission + close( + stake_before.to_u64() + pending_tao.to_u64(), + root_after.into(), + 10, + ); // Registered gets all tao emission assert_eq!(SubnetTAO::::get(NetUid::ROOT), pending_tao); }); } @@ -694,7 +745,13 @@ fn test_drain_base_with_subnet_with_two_stakers_registered() { stake_before, ); let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); let stake_after2 = @@ -751,15 +808,15 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root() { NetUid::ROOT, stake_before, ); - let pending_tao: u64 = 1_000_000_000; + let pending_tao = TaoCurrency::from(1_000_000_000); let pending_alpha = AlphaCurrency::from(1_000_000_000); - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); SubtensorModule::drain_pending_emission( netuid, pending_alpha, pending_tao, - 0.into(), - 0.into(), + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); @@ -786,12 +843,12 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root() { 10, ); // Registered gets 1/2 emission. close( - u64::from(stake_before) + pending_tao / 2, + stake_before.to_u64() + pending_tao.to_u64() / 2, root_after1.into(), 10, ); // Registered gets 1/2 tao emission close( - u64::from(stake_before) + pending_tao / 2, + stake_before.to_u64() + pending_tao.to_u64() / 2, root_after2.into(), 10, ); // Registered gets 1/2 tao emission @@ -838,9 +895,9 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am NetUid::ROOT, stake_before, ); - let pending_tao: u64 = 1_000_000_000; + let pending_tao = TaoCurrency::from(1_000_000_000); let pending_alpha = AlphaCurrency::from(1_000_000_000); - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); SubtensorModule::drain_pending_emission( netuid, pending_alpha, @@ -877,14 +934,14 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am epsilon = 10 ); // Registered gets 50% emission let expected_root1 = I96F32::from_num(2 * u64::from(stake_before)) - + I96F32::from_num(pending_tao) * I96F32::from_num(2.0 / 3.0); + + I96F32::from_num(pending_tao.to_u64()) * I96F32::from_num(2.0 / 3.0); assert_abs_diff_eq!( expected_root1.to_num::(), root_after1.into(), epsilon = 10 ); // Registered gets 2/3 tao emission let expected_root2 = I96F32::from_num(u64::from(stake_before)) - + I96F32::from_num(pending_tao) * I96F32::from_num(1.0 / 3.0); + + I96F32::from_num(pending_tao.to_u64()) * I96F32::from_num(1.0 / 3.0); assert_abs_diff_eq!( expected_root2.to_num::(), root_after2.into(), @@ -893,7 +950,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am assert_abs_diff_eq!( SubnetTAO::::get(NetUid::ROOT), pending_tao, - epsilon = 10 + epsilon = 10.into() ); }); } @@ -938,15 +995,15 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am NetUid::ROOT, stake_before, ); - let pending_tao: u64 = 1_000_000_000; + let pending_tao = TaoCurrency::from(1_000_000_000); let pending_alpha = AlphaCurrency::from(1_000_000_000); - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); SubtensorModule::drain_pending_emission( netuid, pending_alpha, pending_tao, - 0.into(), - 0.into(), + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); @@ -995,7 +1052,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am assert_abs_diff_eq!( SubnetTAO::::get(NetUid::ROOT), pending_tao, - epsilon = 10 + epsilon = 10.into() ); }); } @@ -1023,7 +1080,13 @@ fn test_drain_alpha_childkey_parentkey() { ChildkeyTake::::insert(child, netuid, u16::MAX / 10); let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); let parent_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); let child_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&child, netuid); @@ -1145,11 +1208,11 @@ fn test_get_root_children() { // Assert Alice and Bob TAO inherited stakes assert_eq!( SubtensorModule::get_tao_inherited_for_hotkey_on_subnet(&alice, alpha), - 0 + TaoCurrency::ZERO ); assert_eq!( SubtensorModule::get_tao_inherited_for_hotkey_on_subnet(&bob, alpha), - u64::from(bob_root_stake + alice_root_stake) + u64::from(bob_root_stake + alice_root_stake).into() ); // Get Alice stake amounts on subnet alpha. @@ -1245,7 +1308,7 @@ fn test_get_root_children_drain() { SubtensorModule::drain_pending_emission( alpha, pending_alpha, - 0, + TaoCurrency::ZERO, AlphaCurrency::ZERO, AlphaCurrency::ZERO, ); @@ -1261,11 +1324,11 @@ fn test_get_root_children_drain() { ); // There should be no TAO on the root subnet. - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); // Lets drain let pending_alpha = AlphaCurrency::from(1_000_000_000); - let pending_root1: u64 = 1_000_000_000; + let pending_root1 = TaoCurrency::from(1_000_000_000); SubtensorModule::drain_pending_emission( alpha, pending_alpha, @@ -1277,11 +1340,11 @@ fn test_get_root_children_drain() { // Alice and Bob both made half of the dividends. assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&alice, NetUid::ROOT), - AlphaCurrency::from(alice_root_stake + pending_root1 / 2) + AlphaCurrency::from(alice_root_stake + pending_root1.to_u64() / 2) ); assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&bob, NetUid::ROOT), - AlphaCurrency::from(bob_root_stake + pending_root1 / 2) + AlphaCurrency::from(bob_root_stake + pending_root1.to_u64() / 2) ); // The pending root dividends should be present in root subnet. @@ -1292,7 +1355,7 @@ fn test_get_root_children_drain() { // Lets drain let pending_alpha = AlphaCurrency::from(1_000_000_000); - let pending_root2: u64 = 1_000_000_000; + let pending_root2 = TaoCurrency::from(1_000_000_000); SubtensorModule::drain_pending_emission( alpha, pending_alpha, @@ -1306,7 +1369,10 @@ fn test_get_root_children_drain() { AlphaDividendsPerSubnet::::get(alpha, alice), AlphaCurrency::ZERO ); - assert_eq!(TaoDividendsPerSubnet::::get(alpha, alice), 0); + assert_eq!( + TaoDividendsPerSubnet::::get(alpha, alice), + TaoCurrency::ZERO + ); // Bob makes it all. assert_abs_diff_eq!( AlphaDividendsPerSubnet::::get(alpha, bob), @@ -1391,7 +1457,13 @@ fn test_get_root_children_drain_half_proportion() { // Lets drain! let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + alpha, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); // Alice and Bob make the same amount. close( @@ -1472,7 +1544,13 @@ fn test_get_root_children_drain_with_take() { // Lets drain! let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + alpha, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); // Bob makes it all. close( @@ -1553,7 +1631,13 @@ fn test_get_root_children_drain_with_half_take() { // Lets drain! let pending_alpha = AlphaCurrency::from(1_000_000_000); - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + alpha, + pending_alpha, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); // Alice and Bob make the same amount. close( @@ -1721,7 +1805,7 @@ fn test_calculate_dividend_distribution_totals() { let mut dividends: BTreeMap = BTreeMap::new(); let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); - let pending_tao: u64 = 837_120_949_872; + let pending_tao = TaoCurrency::from(837_120_949_872); let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; @@ -1751,7 +1835,7 @@ fn test_calculate_dividend_distribution_totals() { ); assert_abs_diff_eq!( total_tao_dividends.saturating_to_num::(), - pending_tao, + pending_tao.to_u64(), epsilon = 1_000 ); }); @@ -1764,7 +1848,7 @@ fn test_calculate_dividend_distribution_total_only_tao() { let mut dividends: BTreeMap = BTreeMap::new(); let pending_validator_alpha = AlphaCurrency::ZERO; - let pending_tao: u64 = 837_120_949_872; + let pending_tao = TaoCurrency::from(837_120_949_872); let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; @@ -1794,7 +1878,7 @@ fn test_calculate_dividend_distribution_total_only_tao() { ); assert_abs_diff_eq!( total_tao_dividends.saturating_to_num::(), - pending_tao, + pending_tao.to_u64(), epsilon = 1_000 ); }); @@ -1807,7 +1891,7 @@ fn test_calculate_dividend_distribution_total_no_tao_weight() { let mut dividends: BTreeMap = BTreeMap::new(); let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); - let pending_tao: u64 = 0; // If tao weight is 0, then only alpha dividends should be input. + let pending_tao = TaoCurrency::ZERO; // If tao weight is 0, then only alpha dividends should be input. let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% let hotkeys = [U256::from(0), U256::from(1)]; @@ -1837,7 +1921,7 @@ fn test_calculate_dividend_distribution_total_no_tao_weight() { ); assert_abs_diff_eq!( total_tao_dividends.saturating_to_num::(), - pending_tao, + pending_tao.to_u64(), epsilon = 1_000 ); }); @@ -1850,7 +1934,7 @@ fn test_calculate_dividend_distribution_total_only_alpha() { let mut dividends: BTreeMap = BTreeMap::new(); let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); - let pending_tao: u64 = 0; + let pending_tao = TaoCurrency::ZERO; let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; @@ -1880,7 +1964,7 @@ fn test_calculate_dividend_distribution_total_only_alpha() { ); assert_abs_diff_eq!( total_tao_dividends.saturating_to_num::(), - pending_tao, + pending_tao.to_u64(), epsilon = 1_000 ); }); @@ -1907,7 +1991,7 @@ fn test_calculate_dividend_and_incentive_distribution() { let pending_alpha = AlphaCurrency::from(123_456_789); let pending_validator_alpha = pending_alpha / 2.into(); // Pay half to validators. - let pending_tao: u64 = 0; + let pending_tao = TaoCurrency::ZERO; let pending_swapped = 0; // Only alpha output. let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% @@ -1958,7 +2042,7 @@ fn test_calculate_dividend_and_incentive_distribution_all_to_validators() { let pending_alpha = AlphaCurrency::from(123_456_789); let pending_validator_alpha = pending_alpha; // Pay all to validators. - let pending_tao: u64 = 0; + let pending_tao = TaoCurrency::ZERO; let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% // Hotkey, Incentive, Dividend @@ -2138,7 +2222,7 @@ fn test_drain_pending_emission_no_miners_all_drained() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), - init_stake + init_stake.into() ); // Set the weight of root TAO to be 0%, so only alpha is effective. @@ -2147,7 +2231,13 @@ fn test_drain_pending_emission_no_miners_all_drained() { // Set the emission to be 1 million. let emission = AlphaCurrency::from(1_000_000); // Run drain pending without any miners. - SubtensorModule::drain_pending_emission(netuid, emission, 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + netuid, + emission, + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); // Get the new stake of the hotkey. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); @@ -2155,8 +2245,8 @@ fn test_drain_pending_emission_no_miners_all_drained() { // Slight epsilon due to rounding (hotkey_take). assert_abs_diff_eq!( new_stake, - u64::from(emission.saturating_add(init_stake.into())), - epsilon = 1 + u64::from(emission.saturating_add(init_stake.into())).into(), + epsilon = 1.into() ); }); } @@ -2186,7 +2276,7 @@ fn test_drain_pending_emission_zero_emission() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), - init_stake + init_stake.into() ); // Set the weight of root TAO to be 0%, so only alpha is effective. @@ -2213,12 +2303,18 @@ fn test_drain_pending_emission_zero_emission() { Dividends::::remove(netuid); // Set the emission to be ZERO. - SubtensorModule::drain_pending_emission(netuid, 0.into(), 0, 0.into(), 0.into()); + SubtensorModule::drain_pending_emission( + netuid, + 0.into(), + TaoCurrency::ZERO, + AlphaCurrency::ZERO, + AlphaCurrency::ZERO, + ); // Get the new stake of the hotkey. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // We expect the stake to remain unchanged. - assert_eq!(new_stake, init_stake); + assert_eq!(new_stake, init_stake.into()); // Check that the incentive and dividends are set by epoch. assert!(Incentive::::get(netuid).iter().sum::() > 0); @@ -2252,7 +2348,7 @@ fn test_run_coinbase_not_started() { SubtensorModule::set_weights_set_rate_limit(netuid, 0); let reserve = init_stake * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); register_ok_neuron(netuid, hotkey, coldkey, 0); register_ok_neuron(netuid, miner_hk, miner_ck, 0); @@ -2266,7 +2362,7 @@ fn test_run_coinbase_not_started() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), - init_stake + init_stake.into() ); // Set the weight of root TAO to be 0%, so only alpha is effective. @@ -2306,7 +2402,7 @@ fn test_run_coinbase_not_started() { // Get the new stake of the hotkey. We expect no emissions. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // We expect the stake to remain unchanged. - assert_eq!(new_stake, init_stake); + assert_eq!(new_stake, init_stake.into()); // Check that the incentive and dividends are set. assert!(Incentive::::get(netuid).iter().sum::() > 0); @@ -2351,7 +2447,7 @@ fn test_run_coinbase_not_started_start_after() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), - init_stake + init_stake.into() ); // Set the weight of root TAO to be 0%, so only alpha is effective. @@ -2410,8 +2506,8 @@ fn test_run_coinbase_not_started_start_after() { // Get the new stake of the hotkey. We expect no emissions. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // We expect the stake to remain unchanged. - assert!(new_stake > init_stake); - log::info!("new_stake: {}", new_stake); + assert!(new_stake > init_stake.into()); + log::info!("new_stake: {new_stake}"); }); } @@ -2427,7 +2523,13 @@ fn test_coinbase_v3_liquidity_update() { let netuid = add_dynamic_network(&owner_hotkey, &owner_coldkey); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); let protocol_account_id = pallet_subtensor_swap::Pallet::::protocol_account_id(); let position = pallet_subtensor_swap::Positions::::get(( diff --git a/pallets/subtensor/src/tests/consensus.rs b/pallets/subtensor/src/tests/consensus.rs index 0afca99445..6a7aa7d467 100644 --- a/pallets/subtensor/src/tests/consensus.rs +++ b/pallets/subtensor/src/tests/consensus.rs @@ -257,10 +257,7 @@ fn init_run_epochs( } } let duration = start.elapsed(); - log::info!( - "Time elapsed in (sparse={sparse}) epoch() is: {:?}", - duration - ); + log::info!("Time elapsed in (sparse={sparse}) epoch() is: {duration:?}"); // let bonds = SubtensorModule::get_bonds( netuid ); // for (uid, node) in [ (validators[0], "validator"), (servers[0], "server") ] { diff --git a/pallets/subtensor/src/tests/delegate_info.rs b/pallets/subtensor/src/tests/delegate_info.rs index 22b2aab2bf..c7aabb899e 100644 --- a/pallets/subtensor/src/tests/delegate_info.rs +++ b/pallets/subtensor/src/tests/delegate_info.rs @@ -29,9 +29,7 @@ fn test_return_per_1000_tao() { let eps: f64 = 0.0005e9; // Precision within 0.0005 TAO assert!( diff_from_expected.abs() <= eps, - "Difference from expected: {} is greater than precision: {}", - diff_from_expected, - eps + "Difference from expected: {diff_from_expected} is greater than precision: {eps}" ); } @@ -125,7 +123,7 @@ fn test_get_delegated() { RuntimeOrigin::signed(*delegatee), *delegate, *netuid, - *amount + (*amount).into() )); let expected_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( delegate, delegatee, *netuid, @@ -160,7 +158,7 @@ fn test_get_delegated() { ); }; } else { - panic!("Coldkey {} not found in expected stake map", coldkey); + panic!("Coldkey {coldkey} not found in expected stake map"); } } } diff --git a/pallets/subtensor/src/tests/epoch.rs b/pallets/subtensor/src/tests/epoch.rs index c682417bab..bdf675648b 100644 --- a/pallets/subtensor/src/tests/epoch.rs +++ b/pallets/subtensor/src/tests/epoch.rs @@ -11,7 +11,7 @@ use frame_support::{assert_err, assert_ok}; use rand::{Rng, SeedableRng, distributions::Uniform, rngs::StdRng, seq::SliceRandom, thread_rng}; use sp_core::{Get, U256}; use substrate_fixed::types::I32F32; -use subtensor_runtime_common::AlphaCurrency; +use subtensor_runtime_common::{AlphaCurrency, TaoCurrency}; use subtensor_swap_interface::SwapHandler; use super::mock::*; @@ -251,10 +251,7 @@ fn init_run_epochs( } } let duration = start.elapsed(); - log::info!( - "Time elapsed in (sparse={sparse}) epoch() is: {:?}", - duration - ); + log::info!("Time elapsed in (sparse={sparse}) epoch() is: {duration:?}"); // let bonds = SubtensorModule::get_bonds( netuid ); // for (uid, node) in vec![ (validators[0], "validator"), (servers[0], "server") ] { @@ -576,7 +573,7 @@ fn test_1_graph() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - stake_amount + stake_amount.into() )); assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 1); @@ -593,7 +590,7 @@ fn test_1_graph() { SubtensorModule::epoch(netuid, 1_000_000_000.into()); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), - stake_amount + stake_amount.into() ); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 0); assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 0); @@ -655,7 +652,7 @@ fn test_10_graph() { for i in 0..n { assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&(U256::from(i))), - 1 + TaoCurrency::from(1) ); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, i as u16), 0); assert_eq!(SubtensorModule::get_trust_for_uid(netuid, i as u16), 0); @@ -712,7 +709,7 @@ fn test_512_graph() { for uid in validators { assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))), - max_stake_per_validator + max_stake_per_validator.into() ); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 0); assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 0); @@ -730,7 +727,7 @@ fn test_512_graph() { for uid in servers { assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))), - 0 + TaoCurrency::ZERO ); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 146); // Note R = floor(1 / (512 - 64) * 65_535) = 146 assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 65535); @@ -1315,13 +1312,13 @@ fn test_set_alpha_disabled() { assert_ok!(SubtensorModule::root_register(signer.clone(), hotkey,)); let fee = ::SwapInterface::approx_fee_amount( netuid.into(), - DefaultMinStake::::get(), + DefaultMinStake::::get().into(), ); assert_ok!(SubtensorModule::add_stake( signer.clone(), hotkey, netuid, - 5 * DefaultMinStake::::get() + fee + (5 * DefaultMinStake::::get().to_u64() + fee).into() )); // Only owner can set alpha values assert_ok!(SubtensorModule::register_network(signer.clone(), hotkey)); @@ -2097,9 +2094,7 @@ fn test_deregistered_miner_bonds() { let block_number = System::block_number(); assert!( block_at_registration >= block_number - 2, - "block at registration: {}, block number: {}", - block_at_registration, - block_number + "block at registration: {block_at_registration}, block number: {block_number}" ); // set tempo to 2 blocks @@ -2120,15 +2115,11 @@ fn test_deregistered_miner_bonds() { // For server1, (uid2), the bond should be higher than before. assert!( bond_0_2_new >= bond_0_2, - "bond_0_2_new: {}, bond_0_2: {}", - bond_0_2_new, - bond_0_2 + "bond_0_2_new: {bond_0_2_new}, bond_0_2: {bond_0_2}" ); assert!( bond_0_3_new <= bond_0_3, - "bond_0_3_new: {}, bond_0_3: {}", - bond_0_3_new, - bond_0_3 + "bond_0_3_new: {bond_0_3_new}, bond_0_3: {bond_0_3}" ); }); } @@ -2290,14 +2281,14 @@ fn test_get_set_alpha() { let fee = ::SwapInterface::approx_fee_amount( netuid.into(), - DefaultMinStake::::get(), + DefaultMinStake::::get().into(), ); assert_ok!(SubtensorModule::add_stake( signer.clone(), hotkey, netuid, - DefaultMinStake::::get() + fee * 2 + (DefaultMinStake::::get().to_u64() + fee * 2).into() )); assert_ok!(SubtensorModule::do_set_alpha_values( @@ -2309,11 +2300,7 @@ fn test_get_set_alpha() { let (grabbed_alpha_low, grabbed_alpha_high): (u16, u16) = SubtensorModule::get_alpha_values(netuid); - log::info!( - "alpha_low: {:?} alpha_high: {:?}", - grabbed_alpha_low, - grabbed_alpha_high - ); + log::info!("alpha_low: {grabbed_alpha_low:?} alpha_high: {grabbed_alpha_high:?}"); assert_eq!(grabbed_alpha_low, alpha_low); assert_eq!(grabbed_alpha_high, alpha_high); @@ -2510,7 +2497,7 @@ fn test_can_set_self_weight_as_subnet_owner() { assert_eq!(hotkey_emission[0].0, subnet_owner_hotkey); assert_eq!(hotkey_emission[1].0, other_hotkey); - log::debug!("hotkey_emission: {:?}", hotkey_emission); + log::debug!("hotkey_emission: {hotkey_emission:?}"); // Both should have received incentive emission assert!(hotkey_emission[0].1 > 0.into()); assert!(hotkey_emission[1].1 > 0.into()); @@ -2673,8 +2660,7 @@ fn test_epoch_outputs_single_staker_registered_no_weights() { pub fn assert_approx_eq(left: I32F32, right: I32F32, epsilon: I32F32) { if (left - right).abs() > epsilon { panic!( - "assertion failed: `(left ≈ right)`\n left: `{:?}`,\n right: `{:?}`,\n epsilon: `{:?}`", - left, right, epsilon + "assertion failed: `(left ≈ right)`\n left: `{left:?}`,\n right: `{right:?}`,\n epsilon: `{epsilon:?}`" ); } } diff --git a/pallets/subtensor/src/tests/leasing.rs b/pallets/subtensor/src/tests/leasing.rs index ac27347055..4ffc18230a 100644 --- a/pallets/subtensor/src/tests/leasing.rs +++ b/pallets/subtensor/src/tests/leasing.rs @@ -528,26 +528,27 @@ fn test_distribute_lease_network_dividends_multiple_contributors_works() { assert_eq!( distributed_tao, - beneficiary_balance_delta + contributor1_balance_delta + contributor2_balance_delta + (beneficiary_balance_delta + contributor1_balance_delta + contributor2_balance_delta) + .into() ); let expected_contributor1_balance = SubnetLeaseShares::::get(lease_id, contributions[0].0) - .saturating_mul(U64F64::from(distributed_tao)) + .saturating_mul(U64F64::from(distributed_tao.to_u64())) .floor() .to_num::(); assert_eq!(contributor1_balance_delta, expected_contributor1_balance); let expected_contributor2_balance = SubnetLeaseShares::::get(lease_id, contributions[1].0) - .saturating_mul(U64F64::from(distributed_tao)) + .saturating_mul(U64F64::from(distributed_tao.to_u64())) .floor() .to_num::(); assert_eq!(contributor2_balance_delta, expected_contributor2_balance); // The beneficiary should have received the remaining dividends - let expected_beneficiary_balance = - distributed_tao - (expected_contributor1_balance + expected_contributor2_balance); + let expected_beneficiary_balance = distributed_tao.to_u64() + - (expected_contributor1_balance + expected_contributor2_balance); assert_eq!(beneficiary_balance_delta, expected_beneficiary_balance); // Ensure nothing was accumulated for later distribution @@ -599,7 +600,7 @@ fn test_distribute_lease_network_dividends_only_beneficiary_works() { let distributed_tao = subnet_tao_before - SubnetTAO::::get(lease.netuid); let beneficiary_balance_delta = SubtensorModule::get_coldkey_balance(&beneficiary) .saturating_sub(beneficiary_balance_before); - assert_eq!(distributed_tao, beneficiary_balance_delta); + assert_eq!(distributed_tao, beneficiary_balance_delta.into()); // Ensure nothing was accumulated for later distribution assert_eq!( @@ -916,7 +917,7 @@ fn setup_leased_network( RuntimeOrigin::signed(lease.coldkey), lease.hotkey, netuid, - tao_to_stake + tao_to_stake.into() )); } diff --git a/pallets/subtensor/src/tests/math.rs b/pallets/subtensor/src/tests/math.rs index 1db3622373..a200fa8b25 100644 --- a/pallets/subtensor/src/tests/math.rs +++ b/pallets/subtensor/src/tests/math.rs @@ -13,11 +13,11 @@ use substrate_fixed::{ }; fn assert_float_compare(a: I32F32, b: I32F32, epsilon: I32F32) { - assert!(I32F32::abs(a - b) <= epsilon, "a({:?}) != b({:?})", a, b); + assert!(I32F32::abs(a - b) <= epsilon, "a({a:?}) != b({b:?})"); } fn assert_float_compare_64(a: I64F64, b: I64F64, epsilon: I64F64) { - assert!(I64F64::abs(a - b) <= epsilon, "a({:?}) != b({:?})", a, b); + assert!(I64F64::abs(a - b) <= epsilon, "a({a:?}) != b({b:?})"); } fn assert_vec_compare(va: &[I32F32], vb: &[I32F32], epsilon: I32F32) { @@ -87,9 +87,7 @@ fn assert_mat_approx_eq(left: &[Vec], right: &[Vec], epsilon: I3 for (left_val, right_val) in left_row.iter().zip(right_row.iter()) { assert!( (left_val - right_val).abs() <= epsilon, - "left: {:?}, right: {:?}", - left_val, - right_val + "left: {left_val:?}, right: {right_val:?}" ); } } @@ -2505,9 +2503,9 @@ fn test_fixed_proportion_to_u16() { fn test_fixed_proportion_to_u16_saturates() { let expected = u16::MAX; let input = I32F32::from_num(expected); - log::trace!("Testing with input: {:?}", input); // Debug output + log::trace!("Testing with input: {input:?}"); // Debug output let result = fixed_proportion_to_u16(input); - log::trace!("Testing with result: {:?}", result); // Debug output + log::trace!("Testing with result: {result:?}"); // Debug output assert_eq!(result, expected); } diff --git a/pallets/subtensor/src/tests/migration.rs b/pallets/subtensor/src/tests/migration.rs index 895d48b2eb..e62dacf89e 100644 --- a/pallets/subtensor/src/tests/migration.rs +++ b/pallets/subtensor/src/tests/migration.rs @@ -22,15 +22,13 @@ use sp_io::hashing::twox_128; use sp_runtime::traits::Zero; use substrate_fixed::types::I96F32; use substrate_fixed::types::extra::U2; +use subtensor_runtime_common::TaoCurrency; #[allow(clippy::arithmetic_side_effects)] fn close(value: u64, target: u64, eps: u64) { assert!( (value as i64 - target as i64).abs() < eps as i64, - "Assertion failed: value = {}, target = {}, eps = {}", - value, - target, - eps + "Assertion failed: value = {value}, target = {target}, eps = {eps}" ) } @@ -40,20 +38,19 @@ fn test_initialise_ti() { new_test_ext(1).execute_with(|| { pallet_balances::TotalIssuance::::put(1000); - crate::SubnetTAO::::insert(NetUid::from(1), 100); - crate::SubnetTAO::::insert(NetUid::from(2), 5); + crate::SubnetTAO::::insert(NetUid::from(1), TaoCurrency::from(100)); + crate::SubnetTAO::::insert(NetUid::from(2), TaoCurrency::from(5)); // Ensure values are NOT initialized prior to running migration - assert!(crate::TotalIssuance::::get() == 0); - assert!(crate::TotalStake::::get() == 0); + assert!(crate::TotalIssuance::::get().is_zero()); + assert!(crate::TotalStake::::get().is_zero()); crate::migrations::migrate_init_total_issuance::initialise_total_issuance::Migration::::on_runtime_upgrade(); // Ensure values were initialized correctly - assert!(crate::TotalStake::::get() == 105); - assert!( - crate::TotalIssuance::::get() - == 105u64.saturating_add(1000) + assert_eq!(crate::TotalStake::::get(), TaoCurrency::from(105)); + assert_eq!( + crate::TotalIssuance::::get(), TaoCurrency::from(105 + 1000) ); }); } @@ -842,7 +839,7 @@ fn test_migrate_fix_root_subnet_tao() { expected_total_stake += stake; } - assert_eq!(SubnetTAO::::get(NetUid::ROOT), 0); + assert_eq!(SubnetTAO::::get(NetUid::ROOT), TaoCurrency::ZERO); assert!( !HasMigrationRun::::get(MIGRATION_NAME.as_bytes().to_vec()), "Migration should not have run yet" @@ -858,7 +855,10 @@ fn test_migrate_fix_root_subnet_tao() { "Migration should be marked as run" ); assert!(!weight.is_zero(), "Migration weight should be non-zero"); - assert_eq!(SubnetTAO::::get(NetUid::ROOT), expected_total_stake); + assert_eq!( + SubnetTAO::::get(NetUid::ROOT), + expected_total_stake.into() + ); }); } @@ -1071,3 +1071,64 @@ fn test_migrate_crv3_commits_add_block() { ); }); } + +#[test] +fn test_migrate_disable_commit_reveal() { + const MIG_NAME: &[u8] = b"disable_commit_reveal_v1"; + let netuids = [NetUid::from(1), NetUid::from(2), NetUid::from(42)]; + + // --------------------------------------------------------------------- + // 1. build initial state ─ all nets enabled + // --------------------------------------------------------------------- + new_test_ext(1).execute_with(|| { + for (i, netuid) in netuids.iter().enumerate() { + add_network(*netuid, 5u16 + i as u16, 0); + CommitRevealWeightsEnabled::::insert(*netuid, true); + } + assert!( + !HasMigrationRun::::get(MIG_NAME), + "migration flag should be unset before run" + ); + + // ----------------------------------------------------------------- + // 2. run migration + // ----------------------------------------------------------------- + let w = crate::migrations::migrate_disable_commit_reveal::migrate_disable_commit_reveal::< + Test, + >(); + + assert!( + HasMigrationRun::::get(MIG_NAME), + "migration flag not set" + ); + + // ----------------------------------------------------------------- + // 3. verify every netuid is now disabled and only one value exists + // ----------------------------------------------------------------- + for netuid in netuids { + assert!( + !CommitRevealWeightsEnabled::::get(netuid), + "commit-reveal should be disabled for netuid {netuid}" + ); + } + + // There should be no stray keys + let collected: Vec<_> = CommitRevealWeightsEnabled::::iter().collect(); + assert_eq!(collected.len(), netuids.len(), "unexpected key count"); + for (k, v) in collected { + assert!(!v, "found an enabled flag after migration for netuid {k}"); + } + + // ----------------------------------------------------------------- + // 4. running again should be a no-op + // ----------------------------------------------------------------- + let w2 = crate::migrations::migrate_disable_commit_reveal::migrate_disable_commit_reveal::< + Test, + >(); + assert_eq!( + w2, + ::DbWeight::get().reads(1), + "second run should read the flag and do nothing else" + ); + }); +} diff --git a/pallets/subtensor/src/tests/mock.rs b/pallets/subtensor/src/tests/mock.rs index 7f0ff7e597..fd7dcbab45 100644 --- a/pallets/subtensor/src/tests/mock.rs +++ b/pallets/subtensor/src/tests/mock.rs @@ -23,7 +23,7 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, }; use sp_std::{cell::RefCell, cmp::Ordering}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler}; type Block = frame_system::mocking::MockBlock; @@ -503,6 +503,7 @@ impl pallet_scheduler::Config for Test { type WeightInfo = pallet_scheduler::weights::SubstrateWeight; type OriginPrivilegeCmp = OriginPrivilegeCmp; type Preimages = Preimage; + type BlockNumberProvider = System; } impl pallet_utility::Config for Test { @@ -682,6 +683,7 @@ pub fn test_ext_with_balances(balances: Vec<(U256, u128)>) -> sp_io::TestExterna .iter() .map(|(a, b)| (*a, *b as u64)) .collect::>(), + dev_accounts: None, } .assimilate_storage(&mut t) .unwrap(); @@ -758,7 +760,7 @@ pub(crate) fn step_epochs(count: u16, netuid: NetUid) { SubtensorModule::get_tempo(netuid), SubtensorModule::get_current_block_as_u64(), ); - log::info!("Blocks to next epoch: {:?}", blocks_to_next_epoch); + log::info!("Blocks to next epoch: {blocks_to_next_epoch:?}"); step_block(blocks_to_next_epoch as u16); assert!(SubtensorModule::should_run_epoch( @@ -808,10 +810,7 @@ pub fn register_ok_neuron( ); assert_ok!(result); log::info!( - "Register ok neuron: netuid: {:?}, coldkey: {:?}, hotkey: {:?}", - netuid, - hotkey_account_id, - coldkey_account_id + "Register ok neuron: netuid: {netuid:?}, coldkey: {hotkey_account_id:?}, hotkey: {coldkey_account_id:?}" ); } @@ -843,7 +842,7 @@ pub fn add_network_disable_subtoken(netuid: NetUid, tempo: u16, _modality: u16) pub fn add_dynamic_network(hotkey: &U256, coldkey: &U256) -> NetUid { let netuid = SubtensorModule::get_next_netuid(); let lock_cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(coldkey, lock_cost); + SubtensorModule::add_balance_to_coldkey_account(coldkey, lock_cost.into()); assert_ok!(SubtensorModule::register_network( RawOrigin::Signed(*coldkey).into(), @@ -860,7 +859,7 @@ pub fn add_dynamic_network(hotkey: &U256, coldkey: &U256) -> NetUid { pub fn add_dynamic_network_without_emission_block(hotkey: &U256, coldkey: &U256) -> NetUid { let netuid = SubtensorModule::get_next_netuid(); let lock_cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(coldkey, lock_cost); + SubtensorModule::add_balance_to_coldkey_account(coldkey, lock_cost.into()); assert_ok!(SubtensorModule::register_network( RawOrigin::Signed(*coldkey).into(), @@ -873,8 +872,8 @@ pub fn add_dynamic_network_without_emission_block(hotkey: &U256, coldkey: &U256) // Helper function to set up a neuron with stake #[allow(dead_code)] -pub fn setup_neuron_with_stake(netuid: NetUid, hotkey: U256, coldkey: U256, stake: u64) { - register_ok_neuron(netuid, hotkey, coldkey, stake); +pub fn setup_neuron_with_stake(netuid: NetUid, hotkey: U256, coldkey: U256, stake: TaoCurrency) { + register_ok_neuron(netuid, hotkey, coldkey, stake.into()); increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); } @@ -943,7 +942,7 @@ pub fn step_rate_limit(transaction_type: &TransactionType, netuid: NetUid) { pub fn increase_stake_on_coldkey_hotkey_account( coldkey: &U256, hotkey: &U256, - tao_staked: u64, + tao_staked: TaoCurrency, netuid: NetUid, ) { SubtensorModule::stake_into_subnet( @@ -951,7 +950,7 @@ pub fn increase_stake_on_coldkey_hotkey_account( coldkey, netuid, tao_staked, - ::SwapInterface::max_price(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -963,7 +962,7 @@ pub fn increase_stake_on_coldkey_hotkey_account( /// * `hotkey` - The hotkey account ID. /// * `increment` - The amount to be incremented. #[allow(dead_code)] -pub fn increase_stake_on_hotkey_account(hotkey: &U256, increment: u64, netuid: NetUid) { +pub fn increase_stake_on_hotkey_account(hotkey: &U256, increment: TaoCurrency, netuid: NetUid) { increase_stake_on_coldkey_hotkey_account( &SubtensorModule::get_owning_coldkey_for_hotkey(hotkey), hotkey, @@ -976,20 +975,20 @@ pub(crate) fn remove_stake_rate_limit_for_tests(hotkey: &U256, coldkey: &U256, n StakingOperationRateLimiter::::remove((hotkey, coldkey, netuid)); } -pub(crate) fn setup_reserves(netuid: NetUid, tao: u64, alpha: AlphaCurrency) { +pub(crate) fn setup_reserves(netuid: NetUid, tao: TaoCurrency, alpha: AlphaCurrency) { SubnetTAO::::set(netuid, tao); SubnetAlphaIn::::set(netuid, alpha); } -pub(crate) fn swap_tao_to_alpha(netuid: NetUid, tao: u64) -> (AlphaCurrency, u64) { +pub(crate) fn swap_tao_to_alpha(netuid: NetUid, tao: TaoCurrency) -> (AlphaCurrency, u64) { if netuid.is_root() { - return (tao.into(), 0); + return (tao.to_u64().into(), 0); } let result = ::SwapInterface::swap( netuid.into(), OrderType::Buy, - tao, + tao.into(), ::SwapInterface::max_price(), false, true, @@ -1009,9 +1008,9 @@ pub(crate) fn swap_alpha_to_tao_ext( netuid: NetUid, alpha: AlphaCurrency, drop_fees: bool, -) -> (u64, u64) { +) -> (TaoCurrency, u64) { if netuid.is_root() { - return (alpha.into(), 0); + return (alpha.to_u64().into(), 0); } println!( @@ -1035,10 +1034,10 @@ pub(crate) fn swap_alpha_to_tao_ext( // we don't want to have silent 0 comparissons in tests assert!(result.amount_paid_out > 0); - (result.amount_paid_out, result.fee_paid) + (result.amount_paid_out.into(), result.fee_paid) } -pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: AlphaCurrency) -> (u64, u64) { +pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: AlphaCurrency) -> (TaoCurrency, u64) { swap_alpha_to_tao_ext(netuid, alpha, false) } diff --git a/pallets/subtensor/src/tests/move_stake.rs b/pallets/subtensor/src/tests/move_stake.rs index d80571c594..46f2a77e27 100644 --- a/pallets/subtensor/src/tests/move_stake.rs +++ b/pallets/subtensor/src/tests/move_stake.rs @@ -2,10 +2,9 @@ use approx::assert_abs_diff_eq; use frame_support::{assert_err, assert_noop, assert_ok}; -use frame_system::RawOrigin; use sp_core::{Get, U256}; -use sp_runtime::traits::TxBaseImplication; use substrate_fixed::types::{U64F64, U96F32}; +use subtensor_runtime_common::TaoCurrency; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -24,7 +23,7 @@ fn test_do_move_success() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get() * 10.into(); // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); @@ -34,7 +33,7 @@ fn test_do_move_success() { &coldkey, netuid.into(), stake_amount, - ::SwapInterface::max_price(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -89,16 +88,16 @@ fn test_do_move_different_subnets() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; mock::setup_reserves( origin_netuid, - stake_amount * 100, + (stake_amount * 100).into(), (stake_amount * 100).into(), ); mock::setup_reserves( destination_netuid, - stake_amount * 100, + (stake_amount * 100).into(), (stake_amount * 100).into(), ); @@ -109,8 +108,8 @@ fn test_do_move_different_subnets() { &origin_hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -171,15 +170,15 @@ fn test_do_move_nonexistent_subnet() { let stake_amount = 1_000_000; let reserve = stake_amount * 1000; - mock::setup_reserves(origin_netuid, reserve, reserve.into()); + mock::setup_reserves(origin_netuid, reserve.into(), reserve.into()); // Set up initial stake SubtensorModule::stake_into_subnet( &origin_hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -273,7 +272,7 @@ fn test_do_move_nonexistent_destination_hotkey() { let stake_amount = 1_000_000; let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); @@ -281,8 +280,8 @@ fn test_do_move_nonexistent_destination_hotkey() { &origin_hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -338,15 +337,15 @@ fn test_do_move_partial_stake() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let total_stake = DefaultMinStake::::get() * 20; + let total_stake = DefaultMinStake::::get().to_u64() * 20; // Set up initial stake SubtensorModule::stake_into_subnet( &origin_hotkey, &coldkey, netuid, - total_stake, - ::SwapInterface::max_price(), + total_stake.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -404,7 +403,7 @@ fn test_do_move_multiple_times() { let coldkey = U256::from(1); let hotkey1 = U256::from(2); let hotkey2 = U256::from(3); - let initial_stake = DefaultMinStake::::get() * 10; + let initial_stake = DefaultMinStake::::get().to_u64() * 10; // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey1); @@ -413,8 +412,8 @@ fn test_do_move_multiple_times() { &hotkey1, &coldkey, netuid, - initial_stake, - ::SwapInterface::max_price(), + initial_stake.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -474,18 +473,18 @@ fn test_do_move_wrong_origin() { let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); let netuid = NetUid::from(1); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Set up initial stake SubtensorModule::stake_into_subnet( &origin_hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -508,7 +507,7 @@ fn test_do_move_wrong_origin() { netuid, alpha, ), - Error::::NotEnoughStakeToWithdraw + Error::::AmountTooLow ); // Check that no stake was moved @@ -542,7 +541,7 @@ fn test_do_move_same_hotkey_fails() { let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -550,8 +549,8 @@ fn test_do_move_same_hotkey_fails() { &hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -591,7 +590,7 @@ fn test_do_move_event_emission() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); @@ -600,8 +599,8 @@ fn test_do_move_event_emission() { &origin_hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -633,7 +632,7 @@ fn test_do_move_event_emission() { netuid, destination_hotkey, netuid, - tao_equivalent, // Should be TAO equivalent + tao_equivalent.into(), // Should be TAO equivalent ) .into(), ); @@ -653,15 +652,15 @@ fn test_do_move_storage_updates() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; // Set up initial stake SubtensorModule::stake_into_subnet( &origin_hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -717,7 +716,7 @@ fn test_move_full_amount_same_netuid() { let coldkey = U256::from(1); let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); SubtensorModule::create_account_if_non_existent(&coldkey, &destination_hotkey); @@ -726,8 +725,8 @@ fn test_move_full_amount_same_netuid() { &origin_hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -787,14 +786,14 @@ fn test_do_move_max_values() { // Add lots of liquidity to bypass low liquidity check let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); SubtensorModule::stake_into_subnet( &origin_hotkey, &coldkey, netuid, - max_stake, - ::SwapInterface::max_price(), + max_stake.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -850,13 +849,16 @@ fn test_moving_too_little_unstakes() { let (_, fee) = mock::swap_tao_to_alpha(netuid, amount); - SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount + fee * 2); + SubtensorModule::add_balance_to_coldkey_account( + &coldkey_account_id, + amount.to_u64() + fee * 2, + ); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + fee * 2 + (amount.to_u64() + fee * 2).into() )); remove_stake_rate_limit_for_tests(&hotkey_account_id, &coldkey_account_id, netuid); @@ -886,7 +888,7 @@ fn test_do_transfer_success() { let origin_coldkey = U256::from(1); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; // 3. Set up initial stake: (origin_coldkey, hotkey) on netuid. SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); @@ -895,8 +897,8 @@ fn test_do_transfer_success() { &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -945,7 +947,7 @@ fn test_do_transfer_nonexistent_subnet() { let destination_coldkey = U256::from(2); let hotkey = U256::from(3); let nonexistent_netuid = NetUid::from(9999); - let stake_amount = DefaultMinStake::::get() * 5; + let stake_amount = DefaultMinStake::::get().to_u64() * 5; assert_noop!( SubtensorModule::do_transfer_stake( @@ -996,31 +998,30 @@ fn test_do_transfer_insufficient_stake() { let origin_coldkey = U256::from(1); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); + // Amount over available stake succeeds (because fees can be paid in Alpha, + // this limitation is removed) let alpha = stake_amount * 2; - assert_noop!( - SubtensorModule::do_transfer_stake( - RuntimeOrigin::signed(origin_coldkey), - destination_coldkey, - hotkey, - netuid, - netuid, - alpha.into() - ), - Error::::NotEnoughStakeToWithdraw - ); + assert_ok!(SubtensorModule::do_transfer_stake( + RuntimeOrigin::signed(origin_coldkey), + destination_coldkey, + hotkey, + netuid, + netuid, + alpha.into() + )); }); } @@ -1035,7 +1036,7 @@ fn test_do_transfer_wrong_origin() { let wrong_coldkey = U256::from(9999); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; let fee: u64 = 0; // FIXME: DefaultStakingFee is deprecated SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); @@ -1044,8 +1045,8 @@ fn test_do_transfer_wrong_origin() { &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1059,7 +1060,7 @@ fn test_do_transfer_wrong_origin() { netuid, stake_amount.into() ), - Error::::NotEnoughStakeToWithdraw + Error::::AmountTooLow ); }); } @@ -1082,7 +1083,7 @@ fn test_do_transfer_minimum_stake_check() { &origin_coldkey, netuid, stake_amount, - ::SwapInterface::max_price(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1114,7 +1115,7 @@ fn test_do_transfer_different_subnets() { let origin_coldkey = U256::from(1); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; // 3. Create accounts if needed. SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); @@ -1128,8 +1129,8 @@ fn test_do_transfer_different_subnets() { &hotkey, &origin_coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1186,15 +1187,15 @@ fn test_do_swap_success() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1292,7 +1293,7 @@ fn test_do_swap_insufficient_stake() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = DefaultMinStake::::get() * 5; + let stake_amount = DefaultMinStake::::get().to_u64() * 5; let attempted_swap = stake_amount * 2; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -1300,22 +1301,19 @@ fn test_do_swap_insufficient_stake() { &hotkey, &coldkey, netuid1, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); - assert_noop!( - SubtensorModule::do_swap_stake( - RuntimeOrigin::signed(coldkey), - hotkey, - netuid1, - netuid2, - attempted_swap.into() - ), - Error::::NotEnoughStakeToWithdraw - ); + assert_ok!(SubtensorModule::do_swap_stake( + RuntimeOrigin::signed(coldkey), + hotkey, + netuid1, + netuid2, + attempted_swap.into() + )); }); } @@ -1337,8 +1335,8 @@ fn test_do_swap_wrong_origin() { &hotkey, &real_coldkey, netuid1, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1351,7 +1349,7 @@ fn test_do_swap_wrong_origin() { netuid2, stake_amount.into() ), - Error::::NotEnoughStakeToWithdraw + Error::::AmountTooLow ); }); } @@ -1375,7 +1373,7 @@ fn test_do_swap_minimum_stake_check() { &coldkey, netuid1, total_stake, - ::SwapInterface::max_price(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1402,15 +1400,15 @@ fn test_do_swap_same_subnet() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1446,15 +1444,15 @@ fn test_do_swap_partial_stake() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let total_stake_tao = DefaultMinStake::::get() * 10; + let total_stake_tao = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, origin_netuid, - total_stake_tao, - ::SwapInterface::max_price(), + total_stake_tao.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1497,15 +1495,15 @@ fn test_do_swap_storage_updates() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1556,15 +1554,15 @@ fn test_do_swap_multiple_times() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let initial_stake = DefaultMinStake::::get() * 10; + let initial_stake = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, netuid1, - initial_stake, - ::SwapInterface::max_price(), + initial_stake.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1626,15 +1624,15 @@ fn test_do_swap_allows_non_owned_hotkey() { let coldkey = U256::from(1); let hotkey = U256::from(2); let foreign_coldkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&foreign_coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, origin_netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -1654,177 +1652,6 @@ fn test_do_swap_allows_non_owned_hotkey() { }); } -// cargo test --package pallet-subtensor --lib -- tests::move_stake::test_swap_stake_limit_validate --exact --show-output -#[test] -fn test_swap_stake_limit_validate() { - // Testing the signed extension validate function - // correctly filters the `add_stake` transaction. - - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let origin_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let destination_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - - let coldkey = U256::from(1); - let hotkey = U256::from(2); - let stake_amount = 100_000_000_000; - - let reserve = 1_000_000_000_000; - mock::setup_reserves(origin_netuid, reserve, reserve.into()); - mock::setup_reserves(destination_netuid, reserve, reserve.into()); - - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - let unstake_amount = SubtensorModule::stake_into_subnet( - &hotkey, - &coldkey, - origin_netuid, - stake_amount, - ::SwapInterface::max_price(), - false, - ) - .unwrap(); - - // Setup limit price so that it doesn't allow much slippage at all - let limit_price = - ((::SwapInterface::current_alpha_price(origin_netuid.into()) - / ::SwapInterface::current_alpha_price( - destination_netuid.into(), - )) - * U96F32::from_num(1_000_000_000)) - .to_num::() - - 1_u64; - - // Swap stake limit call - let call = RuntimeCall::SubtensorModule(SubtensorCall::swap_stake_limit { - hotkey, - origin_netuid, - destination_netuid, - alpha_amount: unstake_amount, - limit_price, - allow_partial: false, - }); - - let info: crate::DispatchInfo = - crate::DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = crate::SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to slippage - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::SlippageTooHigh.into() - ); - }); -} - -#[test] -fn test_stake_transfers_disabled_validate() { - // Testing the signed extension validate function - // correctly filters the `transfer_stake` transaction. - - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let origin_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let destination_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - - let coldkey = U256::from(1); - let hotkey = U256::from(2); - let destination_coldkey = U256::from(3); - let stake_amount = 100_000_000_000; - - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - let unstake_amount = SubtensorModule::stake_into_subnet( - &hotkey, - &coldkey, - origin_netuid, - stake_amount, - ::SwapInterface::max_price(), - false, - ) - .unwrap(); - - // Swap stake limit call - let call = RuntimeCall::SubtensorModule(SubtensorCall::transfer_stake { - destination_coldkey, - hotkey, - origin_netuid, - destination_netuid, - alpha_amount: unstake_amount, - }); - - let info: crate::DispatchInfo = - crate::DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = crate::SubtensorTransactionExtension::::new(); - - // Disable transfers in origin subnet - TransferToggle::::insert(origin_netuid, false); - TransferToggle::::insert(destination_netuid, true); - - // Submit to the signed extension validate function - let result1 = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - assert_eq!( - result1.unwrap_err(), - CustomTransactionError::TransferDisallowed.into() - ); - - // Disable transfers in destination subnet - TransferToggle::::insert(origin_netuid, true); - TransferToggle::::insert(destination_netuid, false); - - // Submit to the signed extension validate function - let result2 = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - assert_eq!( - result2.unwrap_err(), - CustomTransactionError::TransferDisallowed.into() - ); - - // Enable transfers - TransferToggle::::insert(origin_netuid, true); - TransferToggle::::insert(destination_netuid, true); - - // Submit to the signed extension validate function - let result3 = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - assert_ok!(result3); - }); -} - #[test] // RUST_LOG=info cargo test --package pallet-subtensor --lib -- tests::move_stake::test_move_stake_specific_stake_into_subnet_fail --exact --show-output fn test_move_stake_specific_stake_into_subnet_fail() { @@ -1839,7 +1666,7 @@ fn test_move_stake_specific_stake_into_subnet_fail() { U64F64::from_num(161_986_254).saturating_div(U64F64::from_num(u64::MAX)); let existing_stake = AlphaCurrency::from(36_711_495_953); - let tao_in = 2_409_892_148_947; + let tao_in = TaoCurrency::from(2_409_892_148_947); let alpha_in = AlphaCurrency::from(15_358_708_513_716); let tao_staked = 200_000_000; @@ -1857,7 +1684,7 @@ fn test_move_stake_specific_stake_into_subnet_fail() { // Check we have zero staked assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); // Set a hotkey pool for the hotkey on destination subnet @@ -1883,14 +1710,14 @@ fn test_move_stake_specific_stake_into_subnet_fail() { // Setup Subnet pool for origin netuid SubnetAlphaIn::::insert(origin_netuid, alpha_in + 10_000_000.into()); - SubnetTAO::::insert(origin_netuid, tao_in + 10_000_000); + SubnetTAO::::insert(origin_netuid, tao_in + 10_000_000.into()); // Add stake as new hotkey assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, origin_netuid, - tao_staked, + tao_staked.into(), ),); let alpha_to_move = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_account_id, @@ -1943,7 +1770,7 @@ fn test_transfer_stake_rate_limited() { let origin_coldkey = U256::from(1); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); SubtensorModule::create_account_if_non_existent(&destination_coldkey, &hotkey); @@ -1951,8 +1778,8 @@ fn test_transfer_stake_rate_limited() { &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), true, ) .unwrap(); @@ -1987,7 +1814,7 @@ fn test_transfer_stake_doesnt_limit_destination_coldkey() { let origin_coldkey = U256::from(1); let destination_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); SubtensorModule::create_account_if_non_existent(&destination_coldkey, &hotkey); @@ -1995,8 +1822,8 @@ fn test_transfer_stake_doesnt_limit_destination_coldkey() { &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); @@ -2033,15 +1860,15 @@ fn test_swap_stake_limits_destination_netuid() { let origin_coldkey = U256::from(1); let hotkey = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::create_account_if_non_existent(&origin_coldkey, &hotkey); SubtensorModule::stake_into_subnet( &hotkey, &origin_coldkey, netuid, - stake_amount, - ::SwapInterface::max_price(), + stake_amount.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); diff --git a/pallets/subtensor/src/tests/networks.rs b/pallets/subtensor/src/tests/networks.rs index aa6a65918c..4f0634c64c 100644 --- a/pallets/subtensor/src/tests/networks.rs +++ b/pallets/subtensor/src/tests/networks.rs @@ -3,6 +3,7 @@ use crate::*; use frame_support::assert_ok; use frame_system::Config; use sp_core::U256; +use subtensor_runtime_common::TaoCurrency; #[test] fn test_registration_ok() { @@ -285,12 +286,12 @@ fn test_registration_ok() { #[test] fn test_register_subnet_low_lock_cost() { new_test_ext(1).execute_with(|| { - NetworkMinLockCost::::set(1_000); - NetworkLastLockCost::::set(1_000); + NetworkMinLockCost::::set(TaoCurrency::from(1_000)); + NetworkLastLockCost::::set(TaoCurrency::from(1_000)); // Make sure lock cost is lower than 100 TAO let lock_cost = SubtensorModule::get_network_lock_cost(); - assert!(lock_cost < 100_000_000_000); + assert!(lock_cost < 100_000_000_000.into()); let subnet_owner_coldkey = U256::from(1); let subnet_owner_hotkey = U256::from(2); @@ -299,7 +300,10 @@ fn test_register_subnet_low_lock_cost() { // Ensure that both Subnet TAO and Subnet Alpha In equal to (actual) lock_cost assert_eq!(SubnetTAO::::get(netuid), lock_cost); - assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost.into()); + assert_eq!( + SubnetAlphaIn::::get(netuid), + lock_cost.to_u64().into() + ); }) } @@ -307,13 +311,13 @@ fn test_register_subnet_low_lock_cost() { #[test] fn test_register_subnet_high_lock_cost() { new_test_ext(1).execute_with(|| { - let lock_cost: u64 = 1_000_000_000_000; + let lock_cost = TaoCurrency::from(1_000_000_000_000); NetworkMinLockCost::::set(lock_cost); NetworkLastLockCost::::set(lock_cost); // Make sure lock cost is higher than 100 TAO let lock_cost = SubtensorModule::get_network_lock_cost(); - assert!(lock_cost >= 1_000_000_000_000); + assert!(lock_cost >= 1_000_000_000_000.into()); let subnet_owner_coldkey = U256::from(1); let subnet_owner_hotkey = U256::from(2); @@ -322,7 +326,10 @@ fn test_register_subnet_high_lock_cost() { // Ensure that both Subnet TAO and Subnet Alpha In equal to 100 TAO assert_eq!(SubnetTAO::::get(netuid), lock_cost); - assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost.into()); + assert_eq!( + SubnetAlphaIn::::get(netuid), + lock_cost.to_u64().into() + ); }) } diff --git a/pallets/subtensor/src/tests/recycle_alpha.rs b/pallets/subtensor/src/tests/recycle_alpha.rs index e2dd644fa7..e61a7aee26 100644 --- a/pallets/subtensor/src/tests/recycle_alpha.rs +++ b/pallets/subtensor/src/tests/recycle_alpha.rs @@ -28,7 +28,7 @@ fn test_recycle_success() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // get initial total issuance and alpha out let initial_alpha = TotalHotkeyAlpha::::get(hotkey, netuid); @@ -84,11 +84,11 @@ fn test_recycle_two_stakers() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake); - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake.into()); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // add some stake to other coldkey on same hotkey. - increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake.into(), netuid); // get initial total issuance and alpha out let initial_alpha = TotalHotkeyAlpha::::get(hotkey, netuid); @@ -154,12 +154,12 @@ fn test_recycle_staker_is_nominator() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake); - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake.into()); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // add some stake to other coldkey on same hotkey. // Note: this coldkey DOES NOT own the hotkey, so it is a nominator. - increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake.into(), netuid); // Verify the ownership assert_ne!( SubtensorModule::get_owning_coldkey_for_hotkey(&hotkey), @@ -227,7 +227,7 @@ fn test_burn_success() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // get initial total issuance and alpha out let initial_alpha = TotalHotkeyAlpha::::get(hotkey, netuid); @@ -283,12 +283,12 @@ fn test_burn_staker_is_nominator() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake); - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake.into()); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // add some stake to other coldkey on same hotkey. // Note: this coldkey DOES NOT own the hotkey, so it is a nominator. - increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake.into(), netuid); // get initial total issuance and alpha out let initial_alpha = TotalHotkeyAlpha::::get(hotkey, netuid); @@ -353,11 +353,11 @@ fn test_burn_two_stakers() { // add stake to coldkey-hotkey pair so we can recycle it let stake = 200_000; - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake); - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake, netuid); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, stake.into()); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake.into(), netuid); // add some stake to other coldkey on same hotkey. - increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake, netuid); + increase_stake_on_coldkey_hotkey_account(&other_coldkey, &hotkey, stake.into(), netuid); // get initial total issuance and alpha out let initial_alpha = TotalHotkeyAlpha::::get(hotkey, netuid); @@ -421,7 +421,7 @@ fn test_recycle_errors() { register_ok_neuron(netuid, hotkey, coldkey, 0); let stake_amount = 200_000; - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_amount, netuid); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_amount.into(), netuid); assert_noop!( SubtensorModule::recycle_alpha( @@ -453,16 +453,6 @@ fn test_recycle_errors() { Error::::HotKeyAccountNotExists ); - assert_noop!( - SubtensorModule::recycle_alpha( - RuntimeOrigin::signed(coldkey), - hotkey, - 10_000_000_000.into(), // too much - netuid - ), - Error::::NotEnoughStakeToWithdraw - ); - // make it pass the stake check TotalHotkeyAlpha::::set( hotkey, @@ -503,7 +493,7 @@ fn test_burn_errors() { register_ok_neuron(netuid, hotkey, coldkey, 0); let stake_amount = 200_000; - increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_amount, netuid); + increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_amount.into(), netuid); assert_noop!( SubtensorModule::burn_alpha( @@ -535,16 +525,6 @@ fn test_burn_errors() { Error::::HotKeyAccountNotExists ); - assert_noop!( - SubtensorModule::burn_alpha( - RuntimeOrigin::signed(coldkey), - hotkey, - 10_000_000_000.into(), // too much - netuid - ), - Error::::NotEnoughStakeToWithdraw - ); - // make it pass the hotkey alpha check TotalHotkeyAlpha::::set( hotkey, diff --git a/pallets/subtensor/src/tests/registration.rs b/pallets/subtensor/src/tests/registration.rs index 997a71268e..09b129dc67 100644 --- a/pallets/subtensor/src/tests/registration.rs +++ b/pallets/subtensor/src/tests/registration.rs @@ -39,7 +39,7 @@ fn test_registration_subscribe_ok_dispatch_info_ok() { assert_eq!( call.get_dispatch_info(), DispatchInfo { - call_weight: frame_support::weights::Weight::from_parts(3_166_200_000, 0), + call_weight: frame_support::weights::Weight::from_parts(3_111_800_000, 0), extension_weight: frame_support::weights::Weight::zero(), class: DispatchClass::Normal, pays_fee: Pays::No @@ -317,10 +317,10 @@ fn test_burned_registration_under_limit() { let who: ::AccountId = coldkey_account_id; let burn_cost = 1000; // Set the burn cost - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); add_network(netuid, 13, 0); // Add the network // Give it some TAO to the coldkey balance; more than the burn cost @@ -417,10 +417,10 @@ fn test_burned_registration_rate_allows_burn_adjustment() { let burn_cost = 1000; // Set the burn cost - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); add_network(netuid, 13, 0); // Add the network // Give it some TAO to the coldkey balance; more than the burn cost @@ -473,11 +473,11 @@ fn test_burned_registration_ok() { let burn_cost = 1000; let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -524,7 +524,7 @@ fn test_burn_registration_without_neuron_slot() { let burn_cost = 1000; let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -553,7 +553,7 @@ fn test_burn_registration_doesnt_write_on_failure() { // Add network and set burn cost add_network(netuid, tempo, 0); - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); // Give coldkey balance to pay for registration SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, initial_balance); // Set max allowed uids to 0 so registration will fail, but only on last check. @@ -590,7 +590,7 @@ fn test_burn_adjustment() { let adjustment_interval = 1; let target_registrations_per_interval = 1; add_network(netuid, tempo, 0); - SubtensorModule::set_burn(netuid, init_burn_cost); + SubtensorModule::set_burn(netuid, init_burn_cost.into()); SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); SubtensorModule::set_adjustment_alpha(netuid, 58000); // Set to old value. SubtensorModule::set_target_registrations_per_interval( @@ -599,7 +599,7 @@ fn test_burn_adjustment() { ); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Register key 1. let hotkey_account_id_1 = U256::from(1); @@ -626,11 +626,11 @@ fn test_burn_adjustment() { step_block(1); // Check the adjusted burn is above the initial min burn. - assert!(SubtensorModule::get_burn_as_u64(netuid) > init_burn_cost); + assert!(SubtensorModule::get_burn(netuid) > init_burn_cost.into()); assert_abs_diff_eq!( - SubtensorModule::get_burn_as_u64(netuid), - init_burn_cost.saturating_mul(3).saturating_div(2), // 1.5x - epsilon = 1000 + SubtensorModule::get_burn(netuid), + (init_burn_cost.saturating_mul(3).saturating_div(2)).into(), // 1.5x + epsilon = 1000.into() ); }); } @@ -649,17 +649,17 @@ fn test_burn_registration_pruning_scenarios() { const NOT_IMMUNE: bool = false; // Initial setup - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); SubtensorModule::set_max_allowed_uids(netuid, max_allowed_uids); SubtensorModule::set_target_registrations_per_interval(netuid, max_allowed_uids); SubtensorModule::set_immunity_period(netuid, immunity_period); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); add_network(netuid, tempo, 0); - let mint_balance = burn_cost * u64::from(max_allowed_uids) + 1_000_000_000; + let mint_balance = burn_cost * max_allowed_uids as u64 + 1_000_000_000; SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, mint_balance); // Register first half of neurons @@ -1560,8 +1560,8 @@ fn test_burn_registration_increase_recycled_rao() { Balances::deposit_creating(&coldkey_account_id, Balance::from(1_000_000_000_000_u64)); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); - mock::setup_reserves(netuid2, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); + mock::setup_reserves(netuid2, reserve.into(), reserve.into()); add_network(netuid, 13, 0); assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 0); @@ -1571,7 +1571,7 @@ fn test_burn_registration_increase_recycled_rao() { run_to_block(1); - let burn_amount = SubtensorModule::get_burn_as_u64(netuid); + let burn_amount = SubtensorModule::get_burn(netuid); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(hotkey_account_id), netuid, @@ -1581,7 +1581,7 @@ fn test_burn_registration_increase_recycled_rao() { run_to_block(2); - let burn_amount2 = SubtensorModule::get_burn_as_u64(netuid2); + let burn_amount2 = SubtensorModule::get_burn(netuid2); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(hotkey_account_id), netuid2, @@ -1592,7 +1592,10 @@ fn test_burn_registration_increase_recycled_rao() { netuid2, U256::from(2) )); - assert_eq!(SubtensorModule::get_rao_recycled(netuid2), burn_amount2 * 2); + assert_eq!( + SubtensorModule::get_rao_recycled(netuid2), + burn_amount2 * 2.into() + ); // Validate netuid is not affected. assert_eq!(SubtensorModule::get_rao_recycled(netuid), burn_amount); }); diff --git a/pallets/subtensor/src/tests/senate.rs b/pallets/subtensor/src/tests/senate.rs index be1a90ded4..1b1f85e5ab 100644 --- a/pallets/subtensor/src/tests/senate.rs +++ b/pallets/subtensor/src/tests/senate.rs @@ -12,6 +12,7 @@ use sp_runtime::{ BuildStorage, traits::{BlakeTwo256, Hash}, }; +use subtensor_runtime_common::TaoCurrency; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -67,16 +68,16 @@ fn test_senate_join_works() { let hotkey_account_id = U256::from(6); let burn_cost = 1000; let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har - let stake = DefaultMinStake::::get() * 100; + let stake = DefaultMinStake::::get() * 100.into(); //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -101,7 +102,7 @@ fn test_senate_join_works() { Delegates::::insert(hotkey_account_id, u16::MAX / 10); let staker_coldkey = U256::from(7); - SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake); + SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(staker_coldkey), @@ -116,12 +117,12 @@ fn test_senate_join_works() { &staker_coldkey, netuid ), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); @@ -146,13 +147,13 @@ fn test_senate_vote_works() { let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -177,8 +178,8 @@ fn test_senate_vote_works() { Delegates::::insert(hotkey_account_id, u16::MAX / 10); let staker_coldkey = U256::from(7); - let stake = DefaultMinStake::::get() * 10; - SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake); + let stake = DefaultMinStake::::get() * 10.into(); + SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(staker_coldkey), @@ -193,12 +194,12 @@ fn test_senate_vote_works() { &staker_coldkey, netuid ), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); @@ -262,13 +263,13 @@ fn test_senate_vote_not_member() { let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -323,16 +324,16 @@ fn test_senate_leave_works() { let hotkey_account_id = U256::from(6); let burn_cost = 1000; let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get() * 10.into(); //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); - let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + let reserve = stake.to_u64() * 1000; + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -357,7 +358,7 @@ fn test_senate_leave_works() { Delegates::::insert(hotkey_account_id, u16::MAX / 10); let staker_coldkey = U256::from(7); - SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake); + SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(staker_coldkey), @@ -372,12 +373,12 @@ fn test_senate_leave_works() { &staker_coldkey, netuid ), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); @@ -401,17 +402,17 @@ fn test_senate_leave_vote_removal() { let burn_cost = 1000; let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har let coldkey_origin = <::RuntimeOrigin>::signed(coldkey_account_id); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get() * 10.into(); //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance - SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, stake); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, stake.into()); SubtokenEnabled::::insert(netuid, true); - let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + let reserve = stake.to_u64() * 1000; + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -422,7 +423,7 @@ fn test_senate_leave_vote_removal() { // Check if balance has decreased to pay for the burn. assert_eq!( SubtensorModule::get_coldkey_balance(&coldkey_account_id), - (stake - burn_cost) + (stake.to_u64() - burn_cost) ); // funds drained on reg. // Check if neuron has added to the specified network(netuid) assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 1); @@ -436,7 +437,7 @@ fn test_senate_leave_vote_removal() { Delegates::::insert(hotkey_account_id, u16::MAX / 10); let staker_coldkey = U256::from(7); - SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake); + SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(staker_coldkey), @@ -451,12 +452,12 @@ fn test_senate_leave_vote_removal() { &staker_coldkey, netuid ), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - AlphaCurrency::from(stake), + AlphaCurrency::from(stake.to_u64()), epsilon = 1.into() ); @@ -489,15 +490,15 @@ fn test_senate_leave_vote_removal() { // Add two networks. let other_netuid = NetUid::from(5); add_network(other_netuid, 1, 0); - SubtensorModule::set_burn(other_netuid, 0); + SubtensorModule::set_burn(other_netuid, TaoCurrency::ZERO); SubtensorModule::set_max_registrations_per_block(other_netuid, 1000); SubtensorModule::set_target_registrations_per_interval(other_netuid, 1000); SubtensorModule::set_max_registrations_per_block(NetUid::ROOT, 1000); SubtensorModule::set_target_registrations_per_interval(NetUid::ROOT, 1000); let reserve = 1_000_000_000_000; - mock::setup_reserves(other_netuid, reserve, reserve.into()); - mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); + mock::setup_reserves(other_netuid, reserve.into(), reserve.into()); + mock::setup_reserves(NetUid::ROOT, reserve.into(), reserve.into()); SubtokenEnabled::::insert(NetUid::ROOT, true); SubtokenEnabled::::insert(other_netuid, true); @@ -517,7 +518,7 @@ fn test_senate_leave_vote_removal() { <::RuntimeOrigin>::signed(cold), hot, NetUid::ROOT, - 100_000_000 + (i as u64) + (100_000_000 + (i as u64)).into() )); // Register them on the root network. assert_ok!(SubtensorModule::root_register( @@ -556,13 +557,13 @@ fn test_senate_not_leave_when_stake_removed() { let coldkey_account_id = U256::from(667); // Neighbour of the beast, har har //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -587,8 +588,8 @@ fn test_senate_not_leave_when_stake_removed() { Delegates::::insert(hotkey_account_id, u16::MAX / 10); let staker_coldkey = U256::from(7); - let stake_amount: u64 = DefaultMinStake::::get() * 10; - SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake_amount); + let stake_amount = DefaultMinStake::::get() * 10.into(); + SubtensorModule::add_balance_to_coldkey_account(&staker_coldkey, stake_amount.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(staker_coldkey), @@ -603,12 +604,12 @@ fn test_senate_not_leave_when_stake_removed() { &staker_coldkey, netuid ), - AlphaCurrency::from(stake_amount), + AlphaCurrency::from(stake_amount.to_u64()), epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - AlphaCurrency::from(stake_amount), + AlphaCurrency::from(stake_amount.to_u64()), epsilon = 1.into() ); @@ -624,7 +625,7 @@ fn test_senate_not_leave_when_stake_removed() { <::RuntimeOrigin>::signed(staker_coldkey), hotkey_account_id, netuid, - (stake_amount - 1).into() + (stake_amount - 1.into()).to_u64().into() )); assert!(Senate::is_member(&hotkey_account_id)); }); @@ -643,13 +644,13 @@ fn test_senate_join_current_delegate() { let coldkey_account_id = U256::from(667); //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give some coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -721,23 +722,23 @@ fn test_adjust_senate_events() { let max_senate_size: u16 = SenateMaxMembers::get() as u16; let stake_threshold = { - let default_stake = DefaultMinStake::::get(); + let default_stake = DefaultMinStake::::get().to_u64(); let fee = ::SwapInterface::approx_fee_amount( - netuid.into(), - default_stake, + netuid, + default_stake.into(), ); default_stake + fee }; // We will be registering MaxMembers hotkeys and two more to try a replace - let balance_to_add = DefaultMinStake::::get() * 10 + let balance_to_add = DefaultMinStake::::get().to_u64() * 10 + 50_000 + (stake_threshold + burn_cost) * (max_senate_size + 2) as u64; let replacement_hotkey_account_id = U256::from(7); // Will be added to the senate to replace hotkey_account_id //add network - SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_burn(netuid, burn_cost.into()); add_network(netuid, tempo, 0); // Give some coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, balance_to_add); @@ -751,7 +752,7 @@ fn test_adjust_senate_events() { SubtokenEnabled::::insert(NetUid::ROOT, true); let reserve = 100_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -804,7 +805,7 @@ fn test_adjust_senate_events() { <::RuntimeOrigin>::signed(coldkey_account_id), new_hotkey_account_id, netuid, - stake_threshold + 1 + i as u64 // Increasing with i to make them ordered + (stake_threshold + 1 + i as u64).into() // Increasing with i to make them ordered )); // Join senate assert_ok!(SubtensorModule::root_register( @@ -838,10 +839,10 @@ fn test_adjust_senate_events() { // as they have no stake assert!(!Senate::is_member(&replacement_hotkey_account_id)); // Add/delegate enough stake to join the senate - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get() * 10.into(); let reserve = 100_000_000_000_000; - mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); + mock::setup_reserves(NetUid::ROOT, reserve.into(), reserve.into()); let (_, fee) = mock::swap_tao_to_alpha(NetUid::ROOT, stake); @@ -857,16 +858,16 @@ fn test_adjust_senate_events() { &coldkey_account_id, NetUid::ROOT ), - AlphaCurrency::from(stake - fee), - epsilon = (stake / 1000).into() + AlphaCurrency::from(stake.to_u64() - fee), + epsilon = (stake.to_u64() / 1000).into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet( &replacement_hotkey_account_id, NetUid::ROOT ), - AlphaCurrency::from(stake - fee), - epsilon = (stake / 1000).into() + AlphaCurrency::from(stake.to_u64() - fee), + epsilon = (stake.to_u64() / 1000).into() ); System::reset_events(); diff --git a/pallets/subtensor/src/tests/serving.rs b/pallets/subtensor/src/tests/serving.rs index e0471fd89b..c874831fcb 100644 --- a/pallets/subtensor/src/tests/serving.rs +++ b/pallets/subtensor/src/tests/serving.rs @@ -52,15 +52,10 @@ fn test_serving_subscribe_ok_dispatch_info_ok() { placeholder1, placeholder2, }); - assert_eq!( - call.get_dispatch_info(), - DispatchInfo { - call_weight: frame_support::weights::Weight::from_parts(235_670_000, 0), - extension_weight: frame_support::weights::Weight::zero(), - class: DispatchClass::Normal, - pays_fee: Pays::No - } - ); + let di = call.get_dispatch_info(); + assert!(di.total_weight().ref_time() > 0); + assert_eq!(di.class, DispatchClass::Normal); + assert_eq!(di.pays_fee, Pays::No); }); } @@ -355,15 +350,10 @@ fn test_prometheus_serving_subscribe_ok_dispatch_info_ok() { port, ip_type, }); - assert_eq!( - call.get_dispatch_info(), - DispatchInfo { - call_weight: frame_support::weights::Weight::from_parts(231_170_000, 0), - extension_weight: frame_support::weights::Weight::zero(), - class: DispatchClass::Normal, - pays_fee: Pays::No - } - ); + let di = call.get_dispatch_info(); + assert!(di.total_weight().ref_time() > 0); + assert_eq!(di.class, DispatchClass::Normal); + assert_eq!(di.pays_fee, Pays::No); }); } diff --git a/pallets/subtensor/src/tests/staking.rs b/pallets/subtensor/src/tests/staking.rs index 08dade7ef3..c04b83f1fb 100644 --- a/pallets/subtensor/src/tests/staking.rs +++ b/pallets/subtensor/src/tests/staking.rs @@ -3,9 +3,7 @@ use approx::assert_abs_diff_eq; use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}; -use frame_support::sp_runtime::{ - DispatchError, traits::TxBaseImplication, transaction_validity::TransactionSource, -}; +use frame_support::sp_runtime::DispatchError; use frame_support::{assert_err, assert_noop, assert_ok, traits::Currency}; use frame_system::RawOrigin; use pallet_subtensor_swap::Call as SwapCall; @@ -14,7 +12,7 @@ use safe_math::FixedExt; use sp_core::{Get, H256, U256}; use substrate_fixed::traits::FromFixed; use substrate_fixed::types::{I96F32, I110F18, U64F64, U96F32}; -use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyT, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyT, NetUid, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; @@ -29,22 +27,17 @@ use crate::*; fn test_add_stake_dispatch_info_ok() { new_test_ext(1).execute_with(|| { let hotkey = U256::from(0); - let amount_staked = 5000; + let amount_staked = TaoCurrency::from(5000); let netuid = NetUid::from(1); let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { hotkey, netuid, amount_staked, }); - assert_eq!( - call.get_dispatch_info(), - DispatchInfo { - call_weight: frame_support::weights::Weight::from_parts(2_495_500_000, 0), - extension_weight: frame_support::weights::Weight::zero(), - class: DispatchClass::Normal, - pays_fee: Pays::Yes - } - ); + let di = call.get_dispatch_info(); + assert_eq!(di.extension_weight, frame_support::weights::Weight::zero(),); + assert_eq!(di.class, DispatchClass::Normal,); + assert_eq!(di.pays_fee, Pays::Yes,); }); } #[test] @@ -52,12 +45,16 @@ fn test_add_stake_ok_no_emission() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(533453); let coldkey_account_id = U256::from(55453); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; //add network let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); - mock::setup_reserves(netuid, amount * 1_000_000, (amount * 10_000_000).into()); + mock::setup_reserves( + netuid, + (amount * 1_000_000).into(), + (amount * 10_000_000).into(), + ); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); @@ -65,7 +62,7 @@ fn test_add_stake_ok_no_emission() { // Check we have zero staked before transfer assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); // Also total stake should be equal to the network initial lock @@ -75,12 +72,12 @@ fn test_add_stake_ok_no_emission() { ); // Transfer to hotkey account, and check if the result is ok - let (alpha_staked, fee) = mock::swap_tao_to_alpha(netuid, amount); + let (alpha_staked, fee) = mock::swap_tao_to_alpha(netuid, amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); let (tao_expected, _) = mock::swap_alpha_to_tao(netuid, alpha_staked); @@ -89,15 +86,15 @@ fn test_add_stake_ok_no_emission() { assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - tao_expected + approx_fee, // swap returns value after fee, so we need to compensate it - epsilon = 10000, + tao_expected + approx_fee.into(), // swap returns value after fee, so we need to compensate it + epsilon = 10000.into(), ); // Check if stake has increased assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - amount - fee, - epsilon = 10000 + (amount - fee).into(), + epsilon = 10000.into() ); // Check if balance has decreased @@ -106,7 +103,7 @@ fn test_add_stake_ok_no_emission() { // Check if total stake has increased accordingly. assert_eq!( SubtensorModule::get_total_stake(), - amount + SubtensorModule::get_network_min_lock() + SubtensorModule::get_network_min_lock() + amount.into() ); }); } @@ -142,8 +139,8 @@ fn test_dividends_with_run_to_block() { // Check if the initial stake has arrived assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&neuron_src_hotkey_id), - initial_stake, - epsilon = 2 + initial_stake.into(), + epsilon = 2.into() ); // Check if all three neurons are registered @@ -155,14 +152,14 @@ fn test_dividends_with_run_to_block() { // Check if the stake is equal to the inital stake + transfer assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&neuron_src_hotkey_id), - initial_stake, - epsilon = 2 + initial_stake.into(), + epsilon = 2.into() ); // Check if the stake is equal to the inital stake + transfer assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&neuron_dest_hotkey_id), - 0 + TaoCurrency::ZERO ); }); } @@ -175,7 +172,12 @@ fn test_add_stake_err_signature() { let netuid = NetUid::from(1); assert_err!( - SubtensorModule::add_stake(RawOrigin::None.into(), hotkey_account_id, netuid, amount), + SubtensorModule::add_stake( + RawOrigin::None.into(), + hotkey_account_id, + netuid, + amount.into() + ), DispatchError::BadOrigin ); }); @@ -189,15 +191,14 @@ fn test_add_stake_not_registered_key_pair() { let coldkey_account_id = U256::from(435445); let hotkey_account_id = U256::from(54544); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let amount = DefaultMinStake::::get() * 10; - let fee: u64 = 0; // FIXME: DefaultStakingFee is deprecated - SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount + fee); + let amount = DefaultMinStake::::get().to_u64() * 10; + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); assert_err!( SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() ), Error::::HotKeyAccountNotExists ); @@ -211,10 +212,10 @@ fn test_add_stake_ok_neuron_does_not_belong_to_coldkey() { let hotkey_id = U256::from(54544); let other_cold_key = U256::from(99498); let netuid = add_dynamic_network(&hotkey_id, &coldkey_id); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get() * 10.into(); // Give it some $$$ in his coldkey balance - SubtensorModule::add_balance_to_coldkey_account(&other_cold_key, stake); + SubtensorModule::add_balance_to_coldkey_account(&other_cold_key, stake.into()); // Perform the request which is signed by a different cold key assert_ok!(SubtensorModule::add_stake( @@ -231,11 +232,11 @@ fn test_add_stake_err_not_enough_belance() { new_test_ext(1).execute_with(|| { let coldkey_id = U256::from(544); let hotkey_id = U256::from(54544); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get() * 10.into(); let netuid = add_dynamic_network(&hotkey_id, &coldkey_id); // Lets try to stake with 0 balance in cold key account - assert!(SubtensorModule::get_coldkey_balance(&coldkey_id) < stake); + assert!(SubtensorModule::get_coldkey_balance(&coldkey_id) < stake.to_u64()); assert_err!( SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_id), @@ -264,33 +265,33 @@ fn test_add_stake_total_balance_no_change() { // Check we have zero staked before transfer let initial_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id); - assert_eq!(initial_stake, 0); + assert_eq!(initial_stake, TaoCurrency::ZERO); // Check total balance is equal to initial balance let initial_total_balance = Balances::total_balance(&coldkey_account_id); assert_eq!(initial_total_balance, initial_balance); // Also total stake should be zero - assert_eq!(SubtensorModule::get_total_stake(), 0); + assert_eq!(SubtensorModule::get_total_stake(), TaoCurrency::ZERO); // Stake to hotkey account, and check if the result is ok assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - 10000 + 10000.into() )); // Check if stake has increased let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id); - assert_eq!(new_stake, 10000); + assert_eq!(new_stake, 10000.into()); // Check if free balance has decreased let new_free_balance = SubtensorModule::get_coldkey_balance(&coldkey_account_id); assert_eq!(new_free_balance, 0); // Check if total stake has increased accordingly. - assert_eq!(SubtensorModule::get_total_stake(), 10000); + assert_eq!(SubtensorModule::get_total_stake(), 10000.into()); // Check if total balance has remained the same. (no fee, includes reserved/locked balance) let total_balance = Balances::total_balance(&coldkey_account_id); @@ -314,7 +315,7 @@ fn test_add_stake_total_issuance_no_change() { // Check we have zero staked before transfer let initial_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id); - assert_eq!(initial_stake, 0); + assert_eq!(initial_stake, TaoCurrency::ZERO); // Check total balance is equal to initial balance let initial_total_balance = Balances::total_balance(&coldkey_account_id); @@ -325,26 +326,26 @@ fn test_add_stake_total_issuance_no_change() { assert_eq!(initial_total_issuance, initial_balance); // Also total stake should be zero - assert_eq!(SubtensorModule::get_total_stake(), 0); + assert_eq!(SubtensorModule::get_total_stake(), TaoCurrency::ZERO); // Stake to hotkey account, and check if the result is ok assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - 10000 + 10000.into() )); // Check if stake has increased let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id); - assert_eq!(new_stake, 10000); + assert_eq!(new_stake, 10000.into()); // Check if free balance has decreased let new_free_balance = SubtensorModule::get_coldkey_balance(&coldkey_account_id); assert_eq!(new_free_balance, 0); // Check if total stake has increased accordingly. - assert_eq!(SubtensorModule::get_total_stake(), 10000); + assert_eq!(SubtensorModule::get_total_stake(), 10000.into()); // Check if total issuance has remained the same. (no fee, includes reserved/locked balance) let total_issuance = Balances::total_issuance(); @@ -383,7 +384,7 @@ fn test_remove_stake_ok_no_emission() { let subnet_owner_hotkey = U256::from(2); let coldkey_account_id = U256::from(4343); let hotkey_account_id = U256::from(4968585); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get() * 10.into(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 192213123); @@ -394,7 +395,7 @@ fn test_remove_stake_ok_no_emission() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_eq!(SubtensorModule::get_coldkey_balance(&coldkey_account_id), 0); @@ -403,38 +404,41 @@ fn test_remove_stake_ok_no_emission() { &hotkey_account_id, &coldkey_account_id, netuid, - amount.into(), + amount.to_u64().into(), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), amount, - epsilon = amount / 1000 + epsilon = amount / 1000.into() ); // Add subnet TAO for the equivalent amount added at price - let (amount_tao, fee) = mock::swap_alpha_to_tao(netuid, amount.into()); - SubnetTAO::::mutate(netuid, |v| *v += amount_tao + fee); - TotalStake::::mutate(|v| *v += amount_tao + fee); + let (amount_tao, fee) = mock::swap_alpha_to_tao(netuid, amount.to_u64().into()); + SubnetTAO::::mutate(netuid, |v| *v += amount_tao + fee.into()); + TotalStake::::mutate(|v| *v += amount_tao + fee.into()); // Do the magic assert_ok!(SubtensorModule::remove_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount.into() + amount.to_u64().into() )); // we do not expect the exact amount due to slippage - assert!(SubtensorModule::get_coldkey_balance(&coldkey_account_id) > amount / 10 * 9 - fee); + assert!( + SubtensorModule::get_coldkey_balance(&coldkey_account_id) + > amount.to_u64() / 10 * 9 - fee + ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0, - epsilon = 20000 + TaoCurrency::ZERO, + epsilon = 20000.into() ); assert_abs_diff_eq!( SubtensorModule::get_total_stake(), - SubtensorModule::get_network_min_lock() + fee, - epsilon = SubtensorModule::get_total_stake() / 100_000 + SubtensorModule::get_network_min_lock() + fee.into(), + epsilon = SubtensorModule::get_total_stake() / 100_000.into() ); }); } @@ -457,7 +461,7 @@ fn test_remove_stake_amount_too_low() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_eq!(SubtensorModule::get_coldkey_balance(&coldkey_account_id), 0); @@ -493,7 +497,7 @@ fn test_remove_stake_below_min_stake() { register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 192213123); let min_stake = DefaultMinStake::::get(); - let amount = AlphaCurrency::from(min_stake / 2); + let amount = AlphaCurrency::from(min_stake.to_u64() / 2); // Some basic assertions assert_eq!( @@ -502,7 +506,7 @@ fn test_remove_stake_below_min_stake() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_eq!(SubtensorModule::get_coldkey_balance(&coldkey_account_id), 0); @@ -555,17 +559,23 @@ fn test_add_stake_partial_below_min_stake_fails() { // Stake TAO amount is above min stake let min_stake = DefaultMinStake::::get(); - let amount = min_stake * 2; + let amount = min_stake.to_u64() * 2; SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id, amount + ExistentialDeposit::get(), ); // Setup reserves so that price is 1.0 and init swap - mock::setup_reserves(netuid, amount * 10, (amount * 10).into()); + mock::setup_reserves(netuid, (amount * 10).into(), (amount * 10).into()); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); // Get the current price (should be 1.0) let current_price = @@ -581,8 +591,8 @@ fn test_add_stake_partial_below_min_stake_fails() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, - limit_price, + amount.into(), + limit_price.into(), true ), Error::::AmountTooLow @@ -619,7 +629,7 @@ fn test_remove_stake_ok_hotkey_does_not_belong_to_coldkey() { let coldkey_id = U256::from(544); let hotkey_id = U256::from(54544); let other_cold_key = U256::from(99498); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&hotkey_id, &coldkey_id); // Give the neuron some stake to remove @@ -644,10 +654,13 @@ fn test_remove_stake_no_enough_stake() { new_test_ext(1).execute_with(|| { let coldkey_id = U256::from(544); let hotkey_id = U256::from(54544); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&hotkey_id, &coldkey_id); - assert_eq!(SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), + TaoCurrency::ZERO + ); assert_err!( SubtensorModule::remove_stake( @@ -656,7 +669,7 @@ fn test_remove_stake_no_enough_stake() { netuid, amount.into(), ), - Error::::NotEnoughStakeToWithdraw + Error::::AmountTooLow ); }); } @@ -672,7 +685,7 @@ fn test_remove_stake_total_balance_no_change() { let subnet_owner_hotkey = U256::from(2); let hotkey_account_id = U256::from(571337); let coldkey_account_id = U256::from(71337); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 192213123); @@ -683,7 +696,7 @@ fn test_remove_stake_total_balance_no_change() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_eq!(SubtensorModule::get_coldkey_balance(&coldkey_account_id), 0); let initial_total_balance = Balances::total_balance(&coldkey_account_id); @@ -700,8 +713,10 @@ fn test_remove_stake_total_balance_no_change() { // Add subnet TAO for the equivalent amount added at price let amount_tao = U96F32::saturating_from_num(amount) * ::SwapInterface::current_alpha_price(netuid.into()); - SubnetTAO::::mutate(netuid, |v| *v += amount_tao.saturating_to_num::()); - TotalStake::::mutate(|v| *v += amount_tao.saturating_to_num::()); + SubnetTAO::::mutate(netuid, |v| { + *v += amount_tao.saturating_to_num::().into() + }); + TotalStake::::mutate(|v| *v += amount_tao.saturating_to_num::().into()); // Do the magic assert_ok!(SubtensorModule::remove_stake( @@ -719,12 +734,12 @@ fn test_remove_stake_total_balance_no_change() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_total_stake(), - SubtensorModule::get_network_min_lock() + fee, - epsilon = SubtensorModule::get_total_stake() / 10_000_000 + SubtensorModule::get_network_min_lock() + fee.into(), + epsilon = SubtensorModule::get_total_stake() / 10_000_000.into() ); // Check total balance is equal to the added stake. Even after remove stake (no fee, includes reserved/locked balance) @@ -740,7 +755,7 @@ fn test_add_stake_insufficient_liquidity() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; + let amount_staked = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -748,7 +763,7 @@ fn test_add_stake_insufficient_liquidity() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Check the error assert_noop!( @@ -756,7 +771,7 @@ fn test_add_stake_insufficient_liquidity() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - amount_staked + amount_staked.into() ), Error::::InsufficientLiquidity ); @@ -771,7 +786,7 @@ fn test_add_stake_insufficient_liquidity_one_side_ok() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; + let amount_staked = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -780,14 +795,14 @@ fn test_add_stake_insufficient_liquidity_one_side_ok() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve_alpha = u64::from(mock::SwapMinimumReserve::get()); let reserve_tao = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve_tao, reserve_alpha.into()); + mock::setup_reserves(netuid, reserve_tao.into(), reserve_alpha.into()); // Check the error assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), hotkey, netuid, - amount_staked + amount_staked.into() )); }); } @@ -800,7 +815,7 @@ fn test_add_stake_insufficient_liquidity_one_side_fail() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; + let amount_staked = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -809,7 +824,7 @@ fn test_add_stake_insufficient_liquidity_one_side_fail() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve_alpha = u64::from(mock::SwapMinimumReserve::get()) - 1; let reserve_tao = u64::from(mock::SwapMinimumReserve::get()); - mock::setup_reserves(netuid, reserve_tao, reserve_alpha.into()); + mock::setup_reserves(netuid, reserve_tao.into(), reserve_alpha.into()); // Check the error assert_noop!( @@ -817,7 +832,7 @@ fn test_add_stake_insufficient_liquidity_one_side_fail() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - amount_staked + amount_staked.into() ), Error::::InsufficientLiquidity ); @@ -831,7 +846,7 @@ fn test_remove_stake_insufficient_liquidity() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; + let amount_staked = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -839,21 +854,21 @@ fn test_remove_stake_insufficient_liquidity() { // Simulate stake for hotkey let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); let alpha = SubtensorModule::stake_into_subnet( &hotkey, &coldkey, netuid, - amount_staked, - ::SwapInterface::max_price(), + amount_staked.into(), + ::SwapInterface::max_price().into(), false, ) .unwrap(); // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Check the error assert_noop!( @@ -862,7 +877,7 @@ fn test_remove_stake_insufficient_liquidity() { ); // Mock provided liquidity - remove becomes successful - SubnetTaoProvided::::insert(netuid, amount_staked + 1); + SubnetTaoProvided::::insert(netuid, TaoCurrency::from(amount_staked + 1)); SubnetAlphaInProvided::::insert(netuid, AlphaCurrency::from(1)); assert_ok!(SubtensorModule::remove_stake( RuntimeOrigin::signed(coldkey), @@ -883,14 +898,14 @@ fn test_remove_stake_total_issuance_no_change() { let subnet_owner_hotkey = U256::from(2); let hotkey_account_id = U256::from(581337); let coldkey_account_id = U256::from(81337); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 192213123); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); - mock::setup_reserves(netuid, amount * 100, (amount * 100).into()); + mock::setup_reserves(netuid, (amount * 100).into(), (amount * 100).into()); // Some basic assertions assert_eq!( @@ -899,7 +914,7 @@ fn test_remove_stake_total_issuance_no_change() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_eq!( SubtensorModule::get_coldkey_balance(&coldkey_account_id), @@ -910,12 +925,12 @@ fn test_remove_stake_total_issuance_no_change() { let inital_total_issuance = Balances::total_issuance(); // Stake to hotkey account, and check if the result is ok - let (_, fee) = mock::swap_tao_to_alpha(netuid, amount); + let (_, fee) = mock::swap_tao_to_alpha(netuid, amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); let total_issuance_after_stake = Balances::total_issuance(); @@ -947,12 +962,12 @@ fn test_remove_stake_total_issuance_no_change() { ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_total_stake(), - total_fee + SubtensorModule::get_network_min_lock(), - epsilon = fee / 1000 + SubtensorModule::get_network_min_lock() + total_fee.into(), + epsilon = TaoCurrency::from(fee) / 1000.into() ); // Check if total issuance is equal to the added stake, even after remove stake (no fee, @@ -980,7 +995,11 @@ fn test_remove_prev_epoch_stake() { // Test case: (amount_to_stake, AlphaDividendsPerSubnet, TotalHotkeyAlphaLastEpoch, expected_fee) [ // No previous epoch stake and low hotkey stake - (DefaultMinStake::::get() * 10, 0_u64, 1000_u64), + ( + DefaultMinStake::::get().to_u64() * 10, + 0_u64, + 1000_u64, + ), // Same, but larger amount to stake - we get 0.005% for unstake (1_000_000_000, 0_u64, 1000_u64), (100_000_000_000, 0_u64, 1000_u64), @@ -1009,15 +1028,19 @@ fn test_remove_prev_epoch_stake() { AlphaDividendsPerSubnet::::insert(netuid, hotkey_account_id, alpha_divs); TotalHotkeyAlphaLastEpoch::::insert(hotkey_account_id, netuid, hotkey_alpha); let balance_before = SubtensorModule::get_coldkey_balance(&coldkey_account_id); - mock::setup_reserves(netuid, amount_to_stake * 10, (amount_to_stake * 10).into()); + mock::setup_reserves( + netuid, + (amount_to_stake * 10).into(), + (amount_to_stake * 10).into(), + ); // Stake to hotkey account, and check if the result is ok - let (_, fee) = mock::swap_tao_to_alpha(netuid, amount); + let (_, fee) = mock::swap_tao_to_alpha(netuid, amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // Remove all stake @@ -1077,7 +1100,7 @@ fn test_staking_sets_div_variables() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // Verify that divident variables are still clear in the beginning @@ -1171,8 +1194,8 @@ fn test_add_stake_to_hotkey_account_ok() { // The stake that is now in the account, should equal the amount assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), - amount, - epsilon = 2 + amount.into(), + epsilon = 2.into() ); }); } @@ -1202,8 +1225,8 @@ fn test_remove_stake_from_hotkey_account() { // Prelimiary checks assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), - amount, - epsilon = 10 + amount.into(), + epsilon = 10.into() ); // Remove stake @@ -1215,7 +1238,10 @@ fn test_remove_stake_from_hotkey_account() { ); // The stake on the hotkey account should be 0 - assert_eq!(SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), + TaoCurrency::ZERO + ); }); } @@ -1230,13 +1256,13 @@ fn test_remove_stake_from_hotkey_account_registered_in_various_networks() { let neuron_uid = match SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey_id) { Ok(k) => k, - Err(e) => panic!("Error: {:?}", e), + Err(e) => panic!("Error: {e:?}"), }; let neuron_uid_ex = match SubtensorModule::get_uid_for_net_and_hotkey(netuid_ex, &hotkey_id) { Ok(k) => k, - Err(e) => panic!("Error: {:?}", e), + Err(e) => panic!("Error: {e:?}"), }; // Add some stake that can be removed @@ -1282,8 +1308,8 @@ fn test_remove_stake_from_hotkey_account_registered_in_various_networks() { #[test] fn test_increase_total_stake_ok() { new_test_ext(1).execute_with(|| { - let increment = 10000; - assert_eq!(SubtensorModule::get_total_stake(), 0); + let increment = TaoCurrency::from(10000); + assert_eq!(SubtensorModule::get_total_stake(), TaoCurrency::ZERO); SubtensorModule::increase_total_stake(increment); assert_eq!(SubtensorModule::get_total_stake(), increment); }); @@ -1295,8 +1321,8 @@ fn test_increase_total_stake_ok() { #[test] fn test_decrease_total_stake_ok() { new_test_ext(1).execute_with(|| { - let initial_total_stake = 10000; - let decrement = 5000; + let initial_total_stake = TaoCurrency::from(10000); + let decrement = TaoCurrency::from(5000); SubtensorModule::increase_total_stake(initial_total_stake); SubtensorModule::decrease_total_stake(decrement); @@ -1425,8 +1451,8 @@ fn test_has_enough_stake_yes() { assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), - intial_amount, - epsilon = 2 + intial_amount.into(), + epsilon = 2.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1461,8 +1487,8 @@ fn test_has_enough_stake_no() { assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), - intial_amount, - epsilon = 2 + intial_amount.into(), + epsilon = 2.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1494,7 +1520,7 @@ fn test_has_enough_stake_no_for_zero() { assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_id), - intial_amount + intial_amount.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1537,7 +1563,7 @@ fn test_non_existent_account() { // No subnets => no iteration => zero total stake assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&(U256::from(0))), - 0 + TaoCurrency::ZERO ); }); } @@ -1599,8 +1625,8 @@ fn test_clear_small_nominations() { let cold1 = U256::from(3); let cold2 = U256::from(4); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let amount = DefaultMinStake::::get() * 10; - let fee: u64 = DefaultMinStake::::get(); + let amount = DefaultMinStake::::get().to_u64() * 10; + let fee = DefaultMinStake::::get().to_u64(); let init_balance = amount + fee + ExistentialDeposit::get(); // Register hot1. @@ -1619,7 +1645,7 @@ fn test_clear_small_nominations() { RuntimeOrigin::signed(cold1), hot1, netuid, - amount + amount.into() )); let alpha_stake1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold1, netuid); @@ -1643,7 +1669,7 @@ fn test_clear_small_nominations() { RuntimeOrigin::signed(cold2), hot1, netuid, - amount + amount.into() )); let alpha_stake2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold2, netuid); @@ -2098,7 +2124,7 @@ fn test_get_total_delegated_stake_after_unstaking() { let delegate_coldkey = U256::from(1); let delegate_hotkey = U256::from(2); let delegator = U256::from(3); - let initial_stake = DefaultMinStake::::get() * 10; + let initial_stake = DefaultMinStake::::get().to_u64() * 10; let existential_deposit = ExistentialDeposit::get(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); @@ -2108,24 +2134,24 @@ fn test_get_total_delegated_stake_after_unstaking() { SubtensorModule::add_balance_to_coldkey_account(&delegator, initial_stake); // Delegate stake - let (_, fee) = mock::swap_tao_to_alpha(netuid, initial_stake); + let (_, fee) = mock::swap_tao_to_alpha(netuid, initial_stake.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(delegator), delegate_hotkey, netuid, - initial_stake + initial_stake.into() )); // Check initial delegated stake assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&delegator), - initial_stake - existential_deposit - fee, - epsilon = initial_stake / 100, + (initial_stake - existential_deposit - fee).into(), + epsilon = TaoCurrency::from(initial_stake / 100), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&delegate_hotkey), - initial_stake - existential_deposit - fee, - epsilon = initial_stake / 100, + (initial_stake - existential_deposit - fee).into(), + epsilon = TaoCurrency::from(initial_stake / 100), ); let delegated_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &delegate_hotkey, @@ -2151,10 +2177,10 @@ fn test_get_total_delegated_stake_after_unstaking() { let expected_delegated_stake = initial_stake - unstake_amount - existential_deposit - fee; // Debug prints - log::debug!("Initial stake: {}", initial_stake); - log::debug!("Unstake amount: {}", unstake_amount); - log::debug!("Existential deposit: {}", existential_deposit); - log::debug!("Expected delegated stake: {}", expected_delegated_stake); + log::debug!("Initial stake: {initial_stake}"); + log::debug!("Unstake amount: {unstake_amount}"); + log::debug!("Existential deposit: {existential_deposit}"); + log::debug!("Expected delegated stake: {expected_delegated_stake}"); log::debug!( "Actual delegated stake: {}", SubtensorModule::get_total_stake_for_coldkey(&delegate_coldkey) @@ -2163,13 +2189,13 @@ fn test_get_total_delegated_stake_after_unstaking() { // Check the total delegated stake after unstaking assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&delegator), - expected_delegated_stake, - epsilon = expected_delegated_stake / 1000, + expected_delegated_stake.into(), + epsilon = TaoCurrency::from(expected_delegated_stake / 1000), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&delegate_hotkey), - expected_delegated_stake, - epsilon = expected_delegated_stake / 1000, + expected_delegated_stake.into(), + epsilon = TaoCurrency::from(expected_delegated_stake / 1000), ); }); } @@ -2185,7 +2211,10 @@ fn test_get_total_delegated_stake_no_delegations() { register_ok_neuron(netuid, delegate, coldkey, 0); // Check that there's no delegated stake - assert_eq!(SubtensorModule::get_total_stake_for_coldkey(&delegate), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_coldkey(&delegate), + TaoCurrency::ZERO + ); }); } @@ -2197,7 +2226,7 @@ fn test_get_total_delegated_stake_single_delegator() { let delegate_coldkey = U256::from(1); let delegate_hotkey = U256::from(2); let delegator = U256::from(3); - let stake_amount = DefaultMinStake::::get() * 10 - 1; + let stake_amount = DefaultMinStake::::get().to_u64() * 10 - 1; let existential_deposit = ExistentialDeposit::get(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); @@ -2206,21 +2235,21 @@ fn test_get_total_delegated_stake_single_delegator() { // Add stake from delegator SubtensorModule::add_balance_to_coldkey_account(&delegator, stake_amount); - let (_, fee) = mock::swap_tao_to_alpha(netuid, stake_amount); + let (_, fee) = mock::swap_tao_to_alpha(netuid, stake_amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(delegator), delegate_hotkey, netuid, - stake_amount + stake_amount.into() )); // Debug prints - log::debug!("Delegate coldkey: {:?}", delegate_coldkey); - log::debug!("Delegate hotkey: {:?}", delegate_hotkey); - log::debug!("Delegator: {:?}", delegator); - log::debug!("Stake amount: {}", stake_amount); - log::debug!("Existential deposit: {}", existential_deposit); + log::debug!("Delegate coldkey: {delegate_coldkey:?}"); + log::debug!("Delegate hotkey: {delegate_hotkey:?}"); + log::debug!("Delegator: {delegator:?}"); + log::debug!("Stake amount: {stake_amount}"); + log::debug!("Existential deposit: {existential_deposit}"); log::debug!( "Total stake for hotkey: {}", SubtensorModule::get_total_stake_for_hotkey(&delegate_hotkey) @@ -2237,13 +2266,13 @@ fn test_get_total_delegated_stake_single_delegator() { assert_abs_diff_eq!( actual_delegated_stake, - expected_delegated_stake, - epsilon = expected_delegated_stake / 100, + expected_delegated_stake.into(), + epsilon = TaoCurrency::from(expected_delegated_stake / 100), ); assert_abs_diff_eq!( actual_delegator_stake, - expected_delegated_stake, - epsilon = expected_delegated_stake / 100, + expected_delegated_stake.into(), + epsilon = TaoCurrency::from(expected_delegated_stake / 100), ); }); } @@ -2258,15 +2287,18 @@ fn test_get_alpha_share_stake_multiple_delegators() { let coldkey1 = U256::from(3); let coldkey2 = U256::from(4); let existential_deposit = 2; - let stake1 = DefaultMinStake::::get() * 10; - let stake2 = DefaultMinStake::::get() * 10 - 1; + let stake1 = DefaultMinStake::::get() * 10.into(); + let stake2 = DefaultMinStake::::get() * 10.into() - 1.into(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); register_ok_neuron(netuid, hotkey1, coldkey1, 0); register_ok_neuron(netuid, hotkey2, coldkey2, 0); // Add stake from delegator1 - SubtensorModule::add_balance_to_coldkey_account(&coldkey1, stake1 + existential_deposit); + SubtensorModule::add_balance_to_coldkey_account( + &coldkey1, + stake1.to_u64() + existential_deposit, + ); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey1), hotkey1, @@ -2275,7 +2307,10 @@ fn test_get_alpha_share_stake_multiple_delegators() { )); // Add stake from delegator2 - SubtensorModule::add_balance_to_coldkey_account(&coldkey2, stake2 + existential_deposit); + SubtensorModule::add_balance_to_coldkey_account( + &coldkey2, + stake2.to_u64() + existential_deposit, + ); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey2), hotkey2, @@ -2310,8 +2345,8 @@ fn test_get_total_delegated_stake_exclude_owner_stake() { let delegate_coldkey = U256::from(1); let delegate_hotkey = U256::from(2); let delegator = U256::from(3); - let owner_stake = DefaultMinStake::::get() * 10; - let delegator_stake = DefaultMinStake::::get() * 10 - 1; + let owner_stake = DefaultMinStake::::get().to_u64() * 10; + let delegator_stake = DefaultMinStake::::get().to_u64() * 10 - 1; let netuid = add_dynamic_network(&delegate_hotkey, &delegate_coldkey); @@ -2321,17 +2356,17 @@ fn test_get_total_delegated_stake_exclude_owner_stake() { RuntimeOrigin::signed(delegate_coldkey), delegate_hotkey, netuid, - owner_stake + owner_stake.into() )); // Add delegator stake SubtensorModule::add_balance_to_coldkey_account(&delegator, delegator_stake); - let (_, fee) = mock::swap_tao_to_alpha(netuid, delegator_stake); + let (_, fee) = mock::swap_tao_to_alpha(netuid, delegator_stake.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(delegator), delegate_hotkey, netuid, - delegator_stake + delegator_stake.into() )); // Check the total delegated stake (should exclude owner's stake) @@ -2341,8 +2376,8 @@ fn test_get_total_delegated_stake_exclude_owner_stake() { assert_abs_diff_eq!( actual_delegated_stake, - expected_delegated_stake, - epsilon = expected_delegated_stake / 100 + expected_delegated_stake.into(), + epsilon = TaoCurrency::from(expected_delegated_stake / 100) ); }); } @@ -2393,13 +2428,13 @@ fn test_mining_emission_distribution_validator_valiminer_miner() { RuntimeOrigin::signed(validator_coldkey), validator_hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(validator_miner_coldkey), validator_miner_hotkey, netuid, - stake + stake.into() )); // Setup YUMA so that it creates emissions @@ -2436,9 +2471,21 @@ fn test_mining_emission_distribution_validator_valiminer_miner() { SubtensorModule::get_total_stake_for_coldkey(&miner_coldkey) - miner_stake_before; let total_emission = validator_emission + valiminer_emission + miner_emission; - assert_abs_diff_eq!(validator_emission, total_emission / 4, epsilon = 10); - assert_abs_diff_eq!(valiminer_emission, total_emission / 2, epsilon = 10); - assert_abs_diff_eq!(miner_emission, total_emission / 4, epsilon = 10); + assert_abs_diff_eq!( + validator_emission, + total_emission / 4.into(), + epsilon = 10.into() + ); + assert_abs_diff_eq!( + valiminer_emission, + total_emission / 2.into(), + epsilon = 10.into() + ); + assert_abs_diff_eq!( + miner_emission, + total_emission / 4.into(), + epsilon = 10.into() + ); }); } @@ -2462,7 +2509,7 @@ fn test_staking_too_little_fails() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - 1 + 1.into() ), Error::::AmountTooLow ); @@ -2479,15 +2526,14 @@ fn test_add_stake_fee_goes_to_subnet_tao() { let hotkey = U256::from(2); let coldkey = U256::from(3); let existential_deposit = ExistentialDeposit::get(); - let tao_to_stake = DefaultMinStake::::get() * 10; - let fee: u64 = 0; // FIXME: DefaultStakingFee is deprecated + let tao_to_stake = DefaultMinStake::::get() * 10.into(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); let subnet_tao_before = SubnetTAO::::get(netuid); // Add stake - SubtensorModule::add_balance_to_coldkey_account(&coldkey, tao_to_stake); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, tao_to_stake.to_u64()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), hotkey, @@ -2496,7 +2542,7 @@ fn test_add_stake_fee_goes_to_subnet_tao() { )); // Calculate expected stake - let expected_alpha = AlphaCurrency::from(tao_to_stake - existential_deposit - fee); + let expected_alpha = AlphaCurrency::from(tao_to_stake.to_u64() - existential_deposit); let actual_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); let subnet_tao_after = SubnetTAO::::get(netuid); @@ -2512,7 +2558,7 @@ fn test_add_stake_fee_goes_to_subnet_tao() { assert_abs_diff_eq!( subnet_tao_before + tao_to_stake, subnet_tao_after, - epsilon = 10 + epsilon = 10.into() ); }); } @@ -2526,14 +2572,14 @@ fn test_remove_stake_fee_goes_to_subnet_tao() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let tao_to_stake = DefaultMinStake::::get() * 10; + let tao_to_stake = DefaultMinStake::::get() * 10.into(); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); let subnet_tao_before = SubnetTAO::::get(netuid); // Add stake - SubtensorModule::add_balance_to_coldkey_account(&coldkey, tao_to_stake); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, tao_to_stake.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), hotkey, @@ -2556,12 +2602,16 @@ fn test_remove_stake_fee_goes_to_subnet_tao() { assert_abs_diff_eq!( subnet_tao_before, subnet_tao_after, - epsilon = alpha_to_unstake.to_u64() / 1000 + epsilon = (alpha_to_unstake.to_u64() / 1000).into() ); // User balance should decrease by 2x fee as a result of staking + unstaking let balance_after = SubtensorModule::get_coldkey_balance(&coldkey); - assert_abs_diff_eq!(balance_after, tao_to_stake, epsilon = tao_to_stake / 1000); + assert_abs_diff_eq!( + balance_after, + tao_to_stake.to_u64(), + epsilon = tao_to_stake.to_u64() / 1000 + ); }); } @@ -2588,7 +2638,7 @@ fn test_remove_stake_fee_realistic_values() { // This makes fee be equal ~0.0028 Alpha ~= 84000 rao let tao_reserve = 3_896_056_559_708_u64; let alpha_in = 128_011_331_299_964_u64; - mock::setup_reserves(netuid, tao_reserve, alpha_in.into()); + mock::setup_reserves(netuid, tao_reserve.into(), alpha_in.into()); AlphaDividendsPerSubnet::::insert(netuid, hotkey, alpha_divs); TotalHotkeyAlphaLastEpoch::::insert(hotkey, netuid, alpha_to_unstake); @@ -2615,336 +2665,13 @@ fn test_remove_stake_fee_realistic_values() { let balance_after = SubtensorModule::get_coldkey_balance(&coldkey); // FIXME since fee is calculated by SwapInterface and the values here are after fees, the // actual_fee is 0. but it's left here to discuss in review - let actual_fee = expected_tao - (balance_after - balance_before); - log::info!("Actual fee: {:?}", actual_fee); + let actual_fee = expected_tao.to_u64() - (balance_after - balance_before); + log::info!("Actual fee: {actual_fee:?}"); assert_abs_diff_eq!(actual_fee, expected_fee, epsilon = expected_fee / 1000); }); } -#[test] -fn test_stake_below_min_validate() { - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let hotkey = U256::from(2); - let coldkey = U256::from(3); - let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let amount_staked = { - let defaulte_stake = DefaultMinStake::::get(); - let fee = - ::SwapInterface::approx_fee_amount(netuid.into(), defaulte_stake); - let min_valid_stake = defaulte_stake + fee; - - min_valid_stake - 1 - }; - - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Add stake call - let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { - hotkey, - netuid, - amount_staked, - }); - - let info: DispatchInfo = - DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to insufficient stake - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::StakeAmountTooLow.into() - ); - - // Increase the stake to be equal to the minimum, but leave the balance low - let amount_staked = { - let min_stake = DefaultMinStake::::get(); - let fee = ::SwapInterface::approx_fee_amount(netuid.into(), min_stake); - - min_stake + fee * 2 - }; - let call_2 = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { - hotkey, - netuid, - amount_staked, - }); - - // Submit to the signed extension validate function - let result_low_balance = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call_2.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Still doesn't pass, but with a different reason (balance too low) - assert_eq!( - result_low_balance.unwrap_err(), - CustomTransactionError::BalanceTooLow.into() - ); - - // Increase the coldkey balance - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Submit to the signed extension validate function - let result_min_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call_2.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Now the call passes - assert_ok!(result_min_stake); - }); -} - -#[test] -fn test_stake_below_min_can_unstake() { - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let hotkey = U256::from(2); - let coldkey = U256::from(3); - let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let amount_staked = { - let defaulte_stake = DefaultMinStake::::get(); - let fee = - ::SwapInterface::approx_fee_amount(netuid.into(), defaulte_stake); - let min_valid_stake = defaulte_stake + fee; - - min_valid_stake - 1 - }; - - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Add stake call - let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { - hotkey, - netuid, - amount_staked, - }); - - let info: DispatchInfo = - DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to insufficient stake - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::StakeAmountTooLow.into() - ); - - // Increase the stake to be equal to the minimum, but leave the balance low - let amount_staked = { - let min_stake = DefaultMinStake::::get(); - let fee = ::SwapInterface::approx_fee_amount(netuid.into(), min_stake); - - min_stake + fee * 2 - }; - let call_2 = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { - hotkey, - netuid, - amount_staked, - }); - - // Submit to the signed extension validate function - let result_low_balance = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call_2.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Still doesn't pass, but with a different reason (balance too low) - assert_eq!( - result_low_balance.unwrap_err(), - CustomTransactionError::BalanceTooLow.into() - ); - - // Increase the coldkey balance - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Submit to the signed extension validate function - let result_min_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call_2.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Now the call passes - assert_ok!(result_min_stake); - }); -} - -// cargo test --package pallet-subtensor --lib -- tests::staking::test_add_stake_limit_validate --exact --show-output -#[test] -fn test_add_stake_limit_validate() { - // Testing the signed extension validate function - // correctly filters the `add_stake` transaction. - - new_test_ext(0).execute_with(|| { - let hotkey = U256::from(533453); - let coldkey = U256::from(55453); - let amount = 900_000_000_000; - - // add network - let netuid = add_dynamic_network(&hotkey, &coldkey); - - // Force-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve = 150_000_000_000_u64; - let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve); - SubnetAlphaIn::::insert(netuid, alpha_in); - let current_price = - ::SwapInterface::current_alpha_price(netuid.into()); - assert_eq!(current_price, U96F32::from_num(1.5)); - - // Give it some $$$ in his coldkey balance - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); - - // Setup limit price so that it doesn't peak above 4x of current price - // The amount that can be executed at this price is 450 TAO only - let limit_price = 6_000_000_000; - - // Add stake limit call - let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake_limit { - hotkey, - netuid, - amount_staked: amount, - limit_price, - allow_partial: false, - }); - - let info: DispatchInfo = - DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to slippage - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::SlippageTooHigh.into() - ); - }); -} - -// cargo test --package pallet-subtensor --lib -- tests::staking::test_remove_stake_limit_validate --exact --show-output -#[test] -fn test_remove_stake_limit_validate() { - // Testing the signed extension validate function - // correctly filters the `add_stake` transaction. - - new_test_ext(0).execute_with(|| { - let hotkey = U256::from(533453); - let coldkey = U256::from(55453); - let stake_amount = 300_000_000_000; - let unstake_amount = AlphaCurrency::from(150_000_000_000); - - // add network - let netuid = add_dynamic_network(&hotkey, &coldkey); - - // Give the neuron some stake to remove - SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, - &coldkey, - netuid, - stake_amount.into(), - ); - - // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve = 150_000_000_000_u64; - let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve); - SubnetAlphaIn::::insert(netuid, alpha_in); - let current_price = - ::SwapInterface::current_alpha_price(netuid.into()); - assert_eq!(current_price, U96F32::from_num(1.5)); - - // Setup limit price so that it doesn't drop by more than 10% from current price - let limit_price = 1_350_000_000; - - // Remove stake limit call - let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake_limit { - hotkey, - netuid, - amount_unstaked: unstake_amount, - limit_price, - allow_partial: false, - }); - - let info: DispatchInfo = - DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to slippage - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::SlippageTooHigh.into() - ); - }); -} - #[test] fn test_stake_overflow() { new_test_ext(1).execute_with(|| { @@ -2960,15 +2687,15 @@ fn test_stake_overflow() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); // Setup liquidity with 21M TAO values - mock::setup_reserves(netuid, amount, amount.into()); + mock::setup_reserves(netuid, amount.into(), amount.into()); // Stake and check if the result is ok - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // Check if stake has increased properly @@ -2980,180 +2707,8 @@ fn test_stake_overflow() { // Check if total stake has increased accordingly. assert_abs_diff_eq!( SubtensorModule::get_total_stake(), - amount + SubtensorModule::get_network_min_lock(), - epsilon = 1 - ); - }); -} - -#[test] -fn test_stake_low_liquidity_validate() { - // Testing the signed extension validate function - // correctly filters the `add_stake` transaction. - - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let hotkey = U256::from(2); - let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; - - let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Set the liquidity at lowest possible value so that all staking requests fail - - let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve.into()); - - // Add stake call - let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { - hotkey, - netuid, - amount_staked, - }); - - let info = DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to insufficient stake - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::InsufficientLiquidity.into() - ); - }); -} - -#[test] -fn test_unstake_low_liquidity_validate() { - // Testing the signed extension validate function - // correctly filters the `add_stake` transaction. - - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let hotkey = U256::from(2); - let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; // FIXME: DefaultStakingFee is deprecated - - let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Simulate stake for hotkey - let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); - - let alpha = SubtensorModule::stake_into_subnet( - &hotkey, - &coldkey, - netuid, - amount_staked, - ::SwapInterface::max_price(), - false, - ) - .unwrap(); - - // Set the liquidity at lowest possible value so that all staking requests fail - let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve.into()); - - // Remove stake call - let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake { - hotkey, - netuid, - amount_unstaked: alpha, - }); - - let info = DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to insufficient stake - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::InsufficientLiquidity.into() - ); - }); -} - -#[test] -fn test_unstake_all_validate() { - // Testing the signed extension validate function - // correctly filters the `unstake_all` transaction. - - new_test_ext(0).execute_with(|| { - let subnet_owner_coldkey = U256::from(1001); - let subnet_owner_hotkey = U256::from(1002); - let hotkey = U256::from(2); - let coldkey = U256::from(3); - let amount_staked = DefaultMinStake::::get() * 10; - - let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount_staked); - - // Simulate stake for hotkey - SubnetTAO::::insert(netuid, u64::MAX / 1000); - SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(u64::MAX / 1000)); - SubtensorModule::stake_into_subnet( - &hotkey, - &coldkey, - netuid, - amount_staked, - ::SwapInterface::max_price(), - false, - ) - .unwrap(); - - // Set the liquidity at lowest possible value so that all staking requests fail - let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve.into()); - - // unstake_all call - let call = RuntimeCall::SubtensorModule(SubtensorCall::unstake_all { hotkey }); - - let info: DispatchInfo = - DispatchInfoOf::<::RuntimeCall>::default(); - - let extension = SubtensorTransactionExtension::::new(); - // Submit to the signed extension validate function - let result_no_stake = extension.validate( - RawOrigin::Signed(coldkey).into(), - &call.clone(), - &info, - 10, - (), - &TxBaseImplication(()), - TransactionSource::External, - ); - - // Should fail due to insufficient stake - assert_eq!( - result_no_stake.unwrap_err(), - CustomTransactionError::StakeAmountTooLow.into() + SubtensorModule::get_network_min_lock() + amount.into(), + epsilon = 1.into() ); }); } @@ -3163,31 +2718,31 @@ fn test_max_amount_add_root() { new_test_ext(0).execute_with(|| { // 0 price on root => max is 0 assert_eq!( - SubtensorModule::get_max_amount_add(NetUid::ROOT, 0), + SubtensorModule::get_max_amount_add(NetUid::ROOT, TaoCurrency::ZERO), Err(Error::::ZeroMaxStakeAmount) ); // 0.999999... price on root => max is 0 assert_eq!( - SubtensorModule::get_max_amount_add(NetUid::ROOT, 999_999_999), + SubtensorModule::get_max_amount_add(NetUid::ROOT, TaoCurrency::from(999_999_999)), Err(Error::::ZeroMaxStakeAmount) ); // 1.0 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(NetUid::ROOT, 1_000_000_000), + SubtensorModule::get_max_amount_add(NetUid::ROOT, TaoCurrency::from(1_000_000_000)), Ok(u64::MAX) ); // 1.000...001 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(NetUid::ROOT, 1_000_000_001), + SubtensorModule::get_max_amount_add(NetUid::ROOT, TaoCurrency::from(1_000_000_001)), Ok(u64::MAX) ); // 2.0 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(NetUid::ROOT, 2_000_000_000), + SubtensorModule::get_max_amount_add(NetUid::ROOT, TaoCurrency::from(2_000_000_000)), Ok(u64::MAX) ); }); @@ -3201,31 +2756,31 @@ fn test_max_amount_add_stable() { // 0 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_add(netuid, 0), + SubtensorModule::get_max_amount_add(netuid, TaoCurrency::ZERO), Err(Error::::ZeroMaxStakeAmount) ); // 0.999999... price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_add(netuid, 999_999_999), + SubtensorModule::get_max_amount_add(netuid, TaoCurrency::from(999_999_999)), Err(Error::::ZeroMaxStakeAmount) ); // 1.0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(netuid, 1_000_000_000), + SubtensorModule::get_max_amount_add(netuid, TaoCurrency::from(1_000_000_000)), Ok(u64::MAX) ); // 1.000...001 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(netuid, 1_000_000_001), + SubtensorModule::get_max_amount_add(netuid, TaoCurrency::from(1_000_000_001)), Ok(u64::MAX) ); // 2.0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_add(netuid, 2_000_000_000), + SubtensorModule::get_max_amount_add(netuid, TaoCurrency::from(2_000_000_000)), Ok(u64::MAX) ); }); @@ -3302,11 +2857,17 @@ fn test_max_amount_add_dynamic() { let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); // Forse-set alpha in and tao reserve to achieve relative price of subnets - SubnetTAO::::insert(netuid, tao_in); + SubnetTAO::::insert(netuid, TaoCurrency::from(tao_in)); SubnetAlphaIn::::insert(netuid, alpha_in); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); if !alpha_in.is_zero() { let expected_price = U96F32::from_num(tao_in) / U96F32::from_num(alpha_in); @@ -3319,9 +2880,12 @@ fn test_max_amount_add_dynamic() { } match expected_max_swappable { - Err(e) => assert_err!(SubtensorModule::get_max_amount_add(netuid, limit_price), e), + Err(e) => assert_err!( + SubtensorModule::get_max_amount_add(netuid, limit_price.into()), + e + ), Ok(v) => assert_abs_diff_eq!( - SubtensorModule::get_max_amount_add(netuid, limit_price).unwrap(), + SubtensorModule::get_max_amount_add(netuid, limit_price.into()).unwrap(), v, epsilon = v / 100 ), @@ -3335,37 +2899,37 @@ fn test_max_amount_remove_root() { new_test_ext(0).execute_with(|| { // 0 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 0), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // 0.5 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 500_000_000), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::from(500_000_000)), Ok(AlphaCurrency::MAX) ); // 0.999999... price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 999_999_999), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::from(999_999_999)), Ok(AlphaCurrency::MAX) ); // 1.0 price on root => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 1_000_000_000), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::from(1_000_000_000)), Ok(AlphaCurrency::MAX) ); // 1.000...001 price on root => max is 0 assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 1_000_000_001), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::from(1_000_000_001)), Err(Error::::ZeroMaxStakeAmount) ); // 2.0 price on root => max is 0 assert_eq!( - SubtensorModule::get_max_amount_remove(NetUid::ROOT, 2_000_000_000), + SubtensorModule::get_max_amount_remove(NetUid::ROOT, TaoCurrency::from(2_000_000_000)), Err(Error::::ZeroMaxStakeAmount) ); }); @@ -3379,31 +2943,31 @@ fn test_max_amount_remove_stable() { // 0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(netuid, 0), + SubtensorModule::get_max_amount_remove(netuid, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // 0.999999... price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(netuid, 999_999_999), + SubtensorModule::get_max_amount_remove(netuid, TaoCurrency::from(999_999_999)), Ok(AlphaCurrency::MAX) ); // 1.0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_remove(netuid, 1_000_000_000), + SubtensorModule::get_max_amount_remove(netuid, TaoCurrency::from(1_000_000_000)), Ok(AlphaCurrency::MAX) ); // 1.000...001 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_remove(netuid, 1_000_000_001), + SubtensorModule::get_max_amount_remove(netuid, TaoCurrency::from(1_000_000_001)), Err(Error::::ZeroMaxStakeAmount) ); // 2.0 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_remove(netuid, 2_000_000_000), + SubtensorModule::get_max_amount_remove(netuid, TaoCurrency::from(2_000_000_000)), Err(Error::::ZeroMaxStakeAmount) ); }); @@ -3517,7 +3081,7 @@ fn test_max_amount_remove_dynamic() { |&(tao_in, alpha_in, limit_price, ref expected_max_swappable)| { let alpha_in = AlphaCurrency::from(alpha_in); // Forse-set alpha in and tao reserve to achieve relative price of subnets - SubnetTAO::::insert(netuid, tao_in); + SubnetTAO::::insert(netuid, TaoCurrency::from(tao_in)); SubnetAlphaIn::::insert(netuid, alpha_in); if !alpha_in.is_zero() { @@ -3530,13 +3094,14 @@ fn test_max_amount_remove_dynamic() { match expected_max_swappable { Err(_) => assert_err!( - SubtensorModule::get_max_amount_remove(netuid, limit_price), + SubtensorModule::get_max_amount_remove(netuid, limit_price.into()), Error::::ZeroMaxStakeAmount ), Ok(v) => { let v = AlphaCurrency::from(*v); assert_abs_diff_eq!( - SubtensorModule::get_max_amount_remove(netuid, limit_price).unwrap(), + SubtensorModule::get_max_amount_remove(netuid, limit_price.into()) + .unwrap(), v, epsilon = v / 100.into() ); @@ -3553,37 +3118,57 @@ fn test_max_amount_move_root_root() { new_test_ext(0).execute_with(|| { // 0 price on (root, root) exchange => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 0), + SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // 0.5 price on (root, root) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 500_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + NetUid::ROOT, + TaoCurrency::from(500_000_000) + ), Ok(AlphaCurrency::MAX) ); // 0.999999... price on (root, root) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 999_999_999), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + NetUid::ROOT, + TaoCurrency::from(999_999_999) + ), Ok(AlphaCurrency::MAX) ); // 1.0 price on (root, root) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 1_000_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + NetUid::ROOT, + TaoCurrency::from(1_000_000_000) + ), Ok(AlphaCurrency::MAX) ); // 1.000...001 price on (root, root) => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 1_000_000_001), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + NetUid::ROOT, + TaoCurrency::from(1_000_000_001) + ), Err(Error::::ZeroMaxStakeAmount) ); // 2.0 price on (root, root) => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 2_000_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + NetUid::ROOT, + TaoCurrency::from(2_000_000_000) + ), Err(Error::::ZeroMaxStakeAmount) ); }); @@ -3598,37 +3183,57 @@ fn test_max_amount_move_root_stable() { // 0 price on (root, stable) exchange => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 0), + SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // 0.5 price on (root, stable) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 500_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + netuid, + TaoCurrency::from(500_000_000) + ), Ok(AlphaCurrency::MAX) ); // 0.999999... price on (root, stable) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 999_999_999), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + netuid, + TaoCurrency::from(999_999_999) + ), Ok(AlphaCurrency::MAX) ); // 1.0 price on (root, stable) => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 1_000_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + netuid, + TaoCurrency::from(1_000_000_000) + ), Ok(AlphaCurrency::MAX) ); // 1.000...001 price on (root, stable) => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 1_000_000_001), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + netuid, + TaoCurrency::from(1_000_000_001) + ), Err(Error::::ZeroMaxStakeAmount) ); // 2.0 price on (root, stable) => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 2_000_000_000), + SubtensorModule::get_max_amount_move( + NetUid::ROOT, + netuid, + TaoCurrency::from(2_000_000_000) + ), Err(Error::::ZeroMaxStakeAmount) ); }); @@ -3648,7 +3253,7 @@ fn test_max_amount_move_stable_dynamic() { let dynamic_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); // Force-set alpha in and tao reserve to make price equal 0.5 - let tao_reserve = 50_000_000_000_u64; + let tao_reserve = TaoCurrency::from(50_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(dynamic_netuid, tao_reserve); SubnetAlphaIn::::insert(dynamic_netuid, alpha_in); @@ -3660,49 +3265,75 @@ fn test_max_amount_move_stable_dynamic() { // 0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 0), + SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // 2.0 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 2_000_000_000), + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::from(2_000_000_000) + ), Err(Error::::ZeroMaxStakeAmount) ); // 3.0 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 3_000_000_000), + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::from(3_000_000_000) + ), Err(Error::::ZeroMaxStakeAmount) ); // 2x price => max is 1x TAO assert_abs_diff_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 500_000_000) - .unwrap(), - AlphaCurrency::from(tao_reserve + (tao_reserve as f64 * 0.003) as u64), - epsilon = AlphaCurrency::from(tao_reserve / 100), + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::from(500_000_000) + ) + .unwrap(), + AlphaCurrency::from( + tao_reserve.to_u64() + (tao_reserve.to_u64() as f64 * 0.003) as u64 + ), + epsilon = AlphaCurrency::from(tao_reserve.to_u64() / 100), ); // Precision test: // 1.99999..9000 price => max > 0 assert!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 1_999_999_000) - .unwrap() + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::from(1_999_999_000) + ) + .unwrap() > AlphaCurrency::ZERO ); // Max price doesn't panic and returns something meaningful assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, u64::MAX), + SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, TaoCurrency::MAX), Err(Error::::ZeroMaxStakeAmount) ); assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, u64::MAX - 1), + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::MAX - 1.into() + ), Err(Error::::ZeroMaxStakeAmount) ); assert_eq!( - SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, u64::MAX / 2), + SubtensorModule::get_max_amount_move( + stable_netuid, + dynamic_netuid, + TaoCurrency::MAX / 2.into() + ), Err(Error::::ZeroMaxStakeAmount) ); }); @@ -3722,7 +3353,7 @@ fn test_max_amount_move_dynamic_stable() { let dynamic_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve = 150_000_000_000_u64; + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(dynamic_netuid, tao_reserve); SubnetAlphaIn::::insert(dynamic_netuid, alpha_in); @@ -3734,41 +3365,49 @@ fn test_max_amount_move_dynamic_stable() { // 0 price => max is u64::MAX assert_eq!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 0), + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, TaoCurrency::ZERO), Ok(AlphaCurrency::MAX) ); // Low price values don't blow things up assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1).unwrap() + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1.into()).unwrap() > AlphaCurrency::ZERO ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 2).unwrap() + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 2.into()).unwrap() > AlphaCurrency::ZERO ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 3).unwrap() + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 3.into()).unwrap() > AlphaCurrency::ZERO ); // 1.5000...1 price => max is 0 assert_eq!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1_500_000_001), + SubtensorModule::get_max_amount_move( + dynamic_netuid, + stable_netuid, + 1_500_000_001.into() + ), Err(Error::::ZeroMaxStakeAmount) ); // 1.5 price => max is 0 because of non-zero slippage assert_abs_diff_eq!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1_500_000_000) - .unwrap_or(AlphaCurrency::ZERO), + SubtensorModule::get_max_amount_move( + dynamic_netuid, + stable_netuid, + 1_500_000_000.into() + ) + .unwrap_or(AlphaCurrency::ZERO), AlphaCurrency::ZERO, epsilon = 10_000.into() ); // 1/4 price => max is 1x Alpha assert_abs_diff_eq!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 375_000_000) + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 375_000_000.into()) .unwrap(), alpha_in, epsilon = alpha_in / 1000.into(), @@ -3777,25 +3416,37 @@ fn test_max_amount_move_dynamic_stable() { // Precision test: // 1.499999.. price => max > 0 assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1_499_999_999) - .unwrap() + SubtensorModule::get_max_amount_move( + dynamic_netuid, + stable_netuid, + 1_499_999_999.into() + ) + .unwrap() > AlphaCurrency::ZERO ); // Max price doesn't panic and returns something meaningful assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX) + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, TaoCurrency::MAX) .unwrap_or(AlphaCurrency::ZERO) < 21_000_000_000_000_000.into() ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX - 1) - .unwrap_or(AlphaCurrency::ZERO) + SubtensorModule::get_max_amount_move( + dynamic_netuid, + stable_netuid, + TaoCurrency::MAX - 1.into() + ) + .unwrap_or(AlphaCurrency::ZERO) < 21_000_000_000_000_000.into() ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX / 2) - .unwrap_or(AlphaCurrency::ZERO) + SubtensorModule::get_max_amount_move( + dynamic_netuid, + stable_netuid, + TaoCurrency::MAX / 2.into() + ) + .unwrap_or(AlphaCurrency::ZERO) < 21_000_000_000_000_000.into() ); }); @@ -3999,9 +3650,9 @@ fn test_max_amount_move_dynamic_dynamic() { let alpha_in_2 = AlphaCurrency::from(alpha_in_2); let expected_max_swappable = AlphaCurrency::from(expected_max_swappable); // Forse-set alpha in and tao reserve to achieve relative price of subnets - SubnetTAO::::insert(origin_netuid, tao_in_1); + SubnetTAO::::insert(origin_netuid, TaoCurrency::from(tao_in_1)); SubnetAlphaIn::::insert(origin_netuid, alpha_in_1); - SubnetTAO::::insert(destination_netuid, tao_in_2); + SubnetTAO::::insert(destination_netuid, TaoCurrency::from(tao_in_2)); SubnetAlphaIn::::insert(destination_netuid, alpha_in_2); if !alpha_in_1.is_zero() && !alpha_in_2.is_zero() { @@ -4026,7 +3677,7 @@ fn test_max_amount_move_dynamic_dynamic() { SubtensorModule::get_max_amount_move( origin_netuid, destination_netuid, - limit_price + limit_price.into() ) .unwrap_or(AlphaCurrency::ZERO), expected_max_swappable, @@ -4048,9 +3699,9 @@ fn test_add_stake_limit_ok() { let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve = U96F32::from_num(150_000_000_000_u64); - let alpha_in = AlphaCurrency::from(100_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + let tao_reserve = TaoCurrency::from(150_000_000_000); + let alpha_in = AlphaCurrency::from(100_000_000_000); + mock::setup_reserves(netuid, tao_reserve, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -4061,7 +3712,7 @@ fn test_add_stake_limit_ok() { // Setup limit price so that it doesn't peak above 4x of current price // The amount that can be executed at this price is 450 TAO only // Alpha produced will be equal to 75 = 450*100/(450+150) - let limit_price = 24_000_000_000; + let limit_price = TaoCurrency::from(24_000_000_000); let expected_executed_stake = AlphaCurrency::from(75_000_000_000); // Add stake with slippage safety and check if the result is ok @@ -4069,7 +3720,7 @@ fn test_add_stake_limit_ok() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, + amount.into(), limit_price, true )); @@ -4119,9 +3770,9 @@ fn test_add_stake_limit_fill_or_kill() { let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); // Force-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in = AlphaCurrency::from(100_000_000_000_u64); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + let tao_reserve = TaoCurrency::from(150_000_000_000); + let alpha_in = AlphaCurrency::from(100_000_000_000); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); @@ -4135,7 +3786,7 @@ fn test_add_stake_limit_fill_or_kill() { // Setup limit price so that it doesn't peak above 4x of current price // The amount that can be executed at this price is 450 TAO only // Alpha produced will be equal to 25 = 100 - 450*100/(150+450) - let limit_price = 24_000_000_000; + let limit_price = TaoCurrency::from(24_000_000_000); // Add stake with slippage safety and check if it fails assert_noop!( @@ -4143,7 +3794,7 @@ fn test_add_stake_limit_fill_or_kill() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, + amount.into(), limit_price, false ), @@ -4151,7 +3802,7 @@ fn test_add_stake_limit_fill_or_kill() { ); // Lower the amount and it should succeed now - let amount_ok = 450_000_000_000; // fits the maximum + let amount_ok = TaoCurrency::from(450_000_000_000); // fits the maximum assert_ok!(SubtensorModule::add_stake_limit( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, @@ -4172,12 +3823,12 @@ fn test_add_stake_limit_partial_zero_max_stake_amount_error() { // Exact values from the error: // https://taostats.io/extrinsic/5338471-0009?network=finney let amount = 19980000000; - let limit_price = 26953618; - let tao_reserve: U96F32 = U96F32::from_num(5_032_494_439_940_u64); + let limit_price = TaoCurrency::from(26953618); + let tao_reserve = TaoCurrency::from(5_032_494_439_940); let alpha_in = AlphaCurrency::from(186_268_425_402_874); let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); @@ -4187,7 +3838,7 @@ fn test_add_stake_limit_partial_zero_max_stake_amount_error() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, + amount.into(), limit_price, true ), @@ -4211,9 +3862,9 @@ fn test_remove_stake_limit_ok() { ); // Forse-set sufficient reserves - let tao_reserve: U96F32 = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); // Stake to hotkey account, and check if the result is ok @@ -4221,7 +3872,7 @@ fn test_remove_stake_limit_ok() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - stake_amount + stake_amount.into() )); let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_account_id, @@ -4245,7 +3896,7 @@ fn test_remove_stake_limit_ok() { hotkey_account_id, netuid, alpha_before / 2.into(), - limit_price, + limit_price.into(), true )); let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -4283,16 +3934,16 @@ fn test_remove_stake_limit_fill_or_kill() { ); // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); // Setup limit price so that it doesn't drop by more than 10% from current price - let limit_price = 1_350_000_000; + let limit_price = TaoCurrency::from(1_350_000_000); // Remove stake with slippage safety - fails assert_noop!( @@ -4313,7 +3964,7 @@ fn test_remove_stake_limit_fill_or_kill() { hotkey_account_id, netuid, unstake_amount / 100.into(), - limit_price, + limit_price.into(), false ),); }); @@ -4333,10 +3984,10 @@ fn test_add_stake_specific_stake_into_subnet_fail() { U64F64::from_num(161_986_254).saturating_div(U64F64::from_num(u64::MAX)); let existing_stake = AlphaCurrency::from(36_711_495_953); - let tao_in = 2_409_892_148_947; + let tao_in = TaoCurrency::from(2_409_892_148_947); let alpha_in = AlphaCurrency::from(15_358_708_513_716); - let tao_staked = 200_000_000; + let tao_staked = TaoCurrency::from(200_000_000); //add network let netuid = add_dynamic_network(&sn_owner_coldkey, &sn_owner_coldkey); @@ -4346,7 +3997,7 @@ fn test_add_stake_specific_stake_into_subnet_fail() { // Check we have zero staked assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); // Set a hotkey pool for the hotkey @@ -4367,7 +4018,7 @@ fn test_add_stake_specific_stake_into_subnet_fail() { // Give TAO balance to coldkey SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id, - tao_staked + 1_000_000_000, + tao_staked.to_u64() + 1_000_000_000, ); // Add stake as new hotkey @@ -4375,7 +4026,7 @@ fn test_add_stake_specific_stake_into_subnet_fail() { ::SwapInterface::swap( netuid.into(), OrderType::Buy, - tao_staked, + tao_staked.into(), ::SwapInterface::max_price(), false, true, @@ -4424,7 +4075,7 @@ fn test_remove_99_9991_per_cent_stake_removes_all() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // Remove 99.9991% stake @@ -4449,12 +4100,12 @@ fn test_remove_99_9991_per_cent_stake_removes_all() { // Check that all alpha was unstaked and all TAO balance was returned (less fees) assert_abs_diff_eq!( SubtensorModule::get_coldkey_balance(&coldkey_account_id), - expected_balance, + expected_balance.to_u64(), epsilon = 10, ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), - 0 + TaoCurrency::ZERO ); let new_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_account_id, @@ -4481,12 +4132,12 @@ fn test_remove_99_9989_per_cent_stake_leaves_a_little() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); // Stake to hotkey account, and check if the result is ok - let (_, fee) = mock::swap_tao_to_alpha(netuid, amount); + let (_, fee) = mock::swap_tao_to_alpha(netuid, amount.into()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // Remove 99.9989% stake @@ -4515,7 +4166,7 @@ fn test_remove_99_9989_per_cent_stake_leaves_a_little() { epsilon = amount / 1000, ); assert_abs_diff_eq!( - SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), + SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id).to_u64(), (amount as f64 * 0.01) as u64, epsilon = amount / 1000, ); @@ -4558,11 +4209,11 @@ fn test_move_stake_limit_partial() { // Forse-set alpha in and tao reserve to make price equal 1.5 on both origin and destination, // but there's much more liquidity on destination, so its price wouldn't go up when restaked - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); + let tao_reserve = TaoCurrency::from(150_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(origin_netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(origin_netuid, tao_reserve); SubnetAlphaIn::::insert(origin_netuid, alpha_in); - SubnetTAO::::insert(destination_netuid, (tao_reserve * 100_000).to_num::()); + SubnetTAO::::insert(destination_netuid, tao_reserve * 100_000.into()); SubnetAlphaIn::::insert(destination_netuid, alpha_in * 100_000.into()); let current_price = ::SwapInterface::current_alpha_price(origin_netuid.into()); @@ -4570,7 +4221,7 @@ fn test_move_stake_limit_partial() { // The relative price between origin and destination subnets is 1. // Setup limit relative price so that it doesn't drop by more than 1% from current price - let limit_price = 990_000_000; + let limit_price = TaoCurrency::from(990_000_000); // Move stake with slippage safety - executes partially assert_ok!(SubtensorModule::swap_stake_limit( @@ -4619,13 +4270,9 @@ fn test_unstake_all_hits_liquidity_min() { ); // Setup the Alpha pool so that removing all the Alpha will bring liqudity below the minimum - let remaining_tao = I96F32::from_num(u64::from(mock::SwapMinimumReserve::get()) - 1); - let alpha_reserves = I110F18::from(stake_amount.to_u64() + 10_000_000); - mock::setup_reserves( - netuid, - remaining_tao.to_num(), - alpha_reserves.to_num::().into(), - ); + let remaining_tao = TaoCurrency::from(u64::from(mock::SwapMinimumReserve::get()) - 1); + let alpha_reserves = AlphaCurrency::from(stake_amount.to_u64() + 10_000_000); + mock::setup_reserves(netuid, remaining_tao, alpha_reserves); // Try to unstake, but we reduce liquidity too far @@ -4662,7 +4309,7 @@ fn test_unstake_all_alpha_hits_liquidity_min() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - stake_amount + stake_amount.into() )); // Setup the pool so that removing all the TAO will bring liqudity below the minimum @@ -4678,7 +4325,7 @@ fn test_unstake_all_alpha_hits_liquidity_min() { mock::setup_reserves( netuid, - tao_reserves.to_num::() / 100_u64, + (tao_reserves.to_num::() / 100_u64).into(), alpha_reserves.to_num::().into(), ); @@ -4718,13 +4365,17 @@ fn test_unstake_all_alpha_works() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - stake_amount + stake_amount.into() )); remove_stake_rate_limit_for_tests(&hotkey, &coldkey, netuid); // Setup the pool so that removing all the TAO will keep liq above min - mock::setup_reserves(netuid, stake_amount * 10, (stake_amount * 100).into()); + mock::setup_reserves( + netuid, + (stake_amount * 10).into(), + (stake_amount * 100).into(), + ); // Unstake all alpha to root assert_ok!(SubtensorModule::unstake_all_alpha( @@ -4766,14 +4417,14 @@ fn test_unstake_all_works() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - stake_amount + stake_amount.into() )); // Setup the pool so that removing all the TAO will keep liq above min mock::setup_reserves( netuid, - stake_amount * 10, - AlphaCurrency::from(stake_amount * 100), + (stake_amount * 10).into(), + (stake_amount * 100).into(), ); remove_stake_rate_limit_for_tests(&hotkey, &coldkey, netuid); @@ -4804,9 +4455,9 @@ fn test_stake_into_subnet_ok() { let netuid = add_dynamic_network(&owner_hotkey, &owner_coldkey); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()) .to_num::(); @@ -4826,8 +4477,8 @@ fn test_stake_into_subnet_ok() { &hotkey, &coldkey, netuid, - amount, - u64::MAX, + amount.into(), + TaoCurrency::MAX, false, )); let fee_rate = pallet_subtensor_swap::FeeRate::::get(NetUid::from(netuid)) as f64 @@ -4857,9 +4508,9 @@ fn test_stake_into_subnet_low_amount() { let netuid = add_dynamic_network(&owner_hotkey, &owner_coldkey); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()) .to_num::(); @@ -4879,8 +4530,8 @@ fn test_stake_into_subnet_low_amount() { &hotkey, &coldkey, netuid, - amount, - u64::MAX, + amount.into(), + TaoCurrency::MAX, false, )); let expected_stake = AlphaCurrency::from(((amount as f64) * 0.997 / current_price) as u64); @@ -4907,9 +4558,9 @@ fn test_unstake_from_subnet_low_amount() { let netuid = add_dynamic_network(&owner_hotkey, &owner_coldkey); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4926,8 +4577,8 @@ fn test_unstake_from_subnet_low_amount() { &hotkey, &coldkey, netuid, - amount, - u64::MAX, + amount.into(), + TaoCurrency::MAX, false, )); @@ -4939,7 +4590,7 @@ fn test_unstake_from_subnet_low_amount() { &coldkey, netuid, alpha, - u64::MIN, + TaoCurrency::ZERO, false, )); @@ -4964,9 +4615,9 @@ fn test_stake_into_subnet_prohibitive_limit() { SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4985,8 +4636,8 @@ fn test_stake_into_subnet_prohibitive_limit() { RuntimeOrigin::signed(coldkey), owner_hotkey, netuid, - amount, - 0, + amount.into(), + TaoCurrency::ZERO, true, ), Error::::ZeroMaxStakeAmount @@ -5020,9 +4671,9 @@ fn test_unstake_from_subnet_prohibitive_limit() { SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -5039,8 +4690,8 @@ fn test_unstake_from_subnet_prohibitive_limit() { &owner_hotkey, &coldkey, netuid, - amount, - u64::MAX, + amount.into(), + TaoCurrency::MAX, false, )); @@ -5058,7 +4709,7 @@ fn test_unstake_from_subnet_prohibitive_limit() { owner_hotkey, netuid, alpha, - u64::MAX, + TaoCurrency::MAX, true, ), Error::::ZeroMaxStakeAmount @@ -5095,9 +4746,9 @@ fn test_unstake_full_amount() { SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); // Forse-set alpha in and tao reserve to make price equal 0.01 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(1_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -5114,8 +4765,8 @@ fn test_unstake_full_amount() { &owner_hotkey, &coldkey, netuid, - amount, - u64::MAX, + amount.into(), + TaoCurrency::MAX, false, )); @@ -5205,20 +4856,20 @@ fn test_swap_fees_tao_correctness() { pallet_subtensor_swap::EnabledUserLiquidity::::insert(NetUid::from(netuid), true); // Forse-set alpha in and tao reserve to make price equal 0.25 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(400_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Check starting "total TAO" let total_tao_before = - user_balance_before + owner_balance_before + SubnetTAO::::get(netuid); + user_balance_before + owner_balance_before + SubnetTAO::::get(netuid).to_u64(); // Get alpha for owner assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(owner_coldkey), owner_hotkey, netuid, - amount, + amount.into(), )); let mut fees = (fee_rate * amount as f64) as u64; @@ -5247,8 +4898,8 @@ fn test_swap_fees_tao_correctness() { RuntimeOrigin::signed(coldkey), owner_hotkey, netuid, - amount, - (limit_price * u64::MAX as f64) as u64, + amount.into(), + ((limit_price * u64::MAX as f64) as u64).into(), true )); fees += (fee_rate * amount as f64) as u64; @@ -5270,11 +4921,13 @@ fn test_swap_fees_tao_correctness() { // Check ending "total TAO" let owner_balance_after = SubtensorModule::get_coldkey_balance(&owner_coldkey); let user_balance_after = SubtensorModule::get_coldkey_balance(&coldkey); - let total_tao_after = - user_balance_after + owner_balance_after + SubnetTAO::::get(netuid) + fees; + let total_tao_after = user_balance_after + + owner_balance_after + + SubnetTAO::::get(netuid).to_u64() + + fees; // Total TAO does not change, leave some epsilon for rounding - assert_abs_diff_eq!(total_tao_before, total_tao_after, epsilon = 2,); + assert_abs_diff_eq!(total_tao_before, total_tao_after, epsilon = 2); }); } @@ -5343,12 +4996,12 @@ fn test_remove_stake_full_limit_ok() { stake_amount, ); - let tao_reserve: U96F32 = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000_u64); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); - let limit_price = 90_000_000; + let limit_price = TaoCurrency::from(90_000_000); // Remove stake with slippage safety assert_ok!(SubtensorModule::remove_stake_full_limit( @@ -5391,12 +5044,12 @@ fn test_remove_stake_full_limit_fails_slippage_too_high() { stake_amount, ); - let tao_reserve: U96F32 = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); - let invalid_limit_price = 910_000_000; + let invalid_limit_price = TaoCurrency::from(910_000_000); // Remove stake with slippage safety assert_err!( @@ -5429,9 +5082,9 @@ fn test_remove_stake_full_limit_ok_with_no_limit_price() { stake_amount, ); - let tao_reserve: U96F32 = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(100_000_000_000); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); + SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); // Remove stake with slippage safety @@ -5464,7 +5117,7 @@ fn test_default_min_stake_sufficiency() { let owner_hotkey = U256::from(1); let owner_coldkey = U256::from(2); let coldkey = U256::from(4); - let min_tao_stake = DefaultMinStake::::get() * 2; + let min_tao_stake = DefaultMinStake::::get().to_u64() * 2; let amount = min_tao_stake; let owner_balance_before = amount * 10; let user_balance_before = amount * 100; @@ -5479,9 +5132,9 @@ fn test_default_min_stake_sufficiency() { // Set some extreme, but realistic TAO and Alpha reserves to minimize slippage // 1% of TAO max supply // 0.01 Alpha price - let tao_reserve = U96F32::from_num(210_000_000_000_000_u64); + let tao_reserve = TaoCurrency::from(210_000_000_000_000); let alpha_in = AlphaCurrency::from(21_000_000_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); let current_price_before = ::SwapInterface::current_alpha_price(netuid.into()); @@ -5490,7 +5143,7 @@ fn test_default_min_stake_sufficiency() { RuntimeOrigin::signed(coldkey), owner_hotkey, netuid, - amount, + amount.into(), )); let fee_stake = (fee_rate * amount as f64) as u64; let current_price_after_stake = @@ -5538,16 +5191,16 @@ fn test_update_position_fees() { pallet_subtensor_swap::EnabledUserLiquidity::::insert(NetUid::from(netuid), true); // Forse-set alpha in and tao reserve to make price equal 0.25 - let tao_reserve = U96F32::from_num(100_000_000_000_u64); + let tao_reserve = TaoCurrency::from(100_000_000_000); let alpha_in = AlphaCurrency::from(400_000_000_000); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); + mock::setup_reserves(netuid, tao_reserve, alpha_in); // Get alpha for owner assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(owner_coldkey), owner_hotkey, netuid, - amount, + amount.into(), )); // Add owner coldkey Alpha as concentrated liquidity @@ -5576,7 +5229,7 @@ fn test_update_position_fees() { RuntimeOrigin::signed(coldkey), owner_hotkey, netuid, - amount, + amount.into(), )); remove_stake_rate_limit_for_tests(&owner_hotkey, &coldkey, netuid); @@ -5705,11 +5358,17 @@ fn test_large_swap() { pallet_subtensor_swap::EnabledUserLiquidity::::insert(NetUid::from(netuid), true); // Force the swap to initialize - SubtensorModule::swap_tao_for_alpha(netuid, 0, 1_000_000_000_000, false).unwrap(); + SubtensorModule::swap_tao_for_alpha( + netuid, + TaoCurrency::ZERO, + 1_000_000_000_000.into(), + false, + ) + .unwrap(); setup_positions(netuid.into()); - let swap_amount = 100_000_000_000_000; + let swap_amount = TaoCurrency::from(100_000_000_000_000); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), owner_hotkey, @@ -5728,8 +5387,8 @@ fn test_stake_rate_limits() { let hot1 = U256::from(1); let cold1 = U256::from(3); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); - let amount = DefaultMinStake::::get() * 10; - let fee: u64 = DefaultMinStake::::get(); + let amount = DefaultMinStake::::get().to_u64() * 10; + let fee = DefaultMinStake::::get().to_u64(); let init_balance = amount + fee + ExistentialDeposit::get(); register_ok_neuron(netuid, hot1, cold1, 0); @@ -5741,7 +5400,7 @@ fn test_stake_rate_limits() { RuntimeOrigin::signed(cold1), hot1, netuid, - amount + fee + (amount + fee).into() )); assert_err!( diff --git a/pallets/subtensor/src/tests/staking2.rs b/pallets/subtensor/src/tests/staking2.rs index 973ec855bf..f5d57d02d3 100644 --- a/pallets/subtensor/src/tests/staking2.rs +++ b/pallets/subtensor/src/tests/staking2.rs @@ -6,7 +6,7 @@ use frame_support::{ weights::Weight, }; use sp_core::U256; -use subtensor_runtime_common::{AlphaCurrency, Currency}; +use subtensor_runtime_common::{AlphaCurrency, Currency, TaoCurrency}; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -18,13 +18,13 @@ use crate::*; fn test_stake_base_case() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); - let tao_to_swap = 1_000_000_000; // 1 TAO + let tao_to_swap = TaoCurrency::from(1_000_000_000); // 1 TAO // Set up the subnet with dynamic mechanism SubnetMechanism::::insert(netuid, 1); // Initialize subnet with some existing TAO and Alpha - let initial_subnet_tao = 10_000_000_000; // 10 TAO + let initial_subnet_tao = TaoCurrency::from(10_000_000_000); // 10 TAO let initial_subnet_alpha = AlphaCurrency::from(5_000_000_000); // 5 Alpha mock::setup_reserves(netuid, initial_subnet_tao, initial_subnet_alpha); SubnetAlphaOut::::insert(netuid, initial_subnet_alpha); @@ -38,7 +38,7 @@ fn test_stake_base_case() { SubtensorModule::swap_tao_for_alpha( netuid, tao_to_swap, - ::SwapInterface::max_price(), + ::SwapInterface::max_price().into(), false, ) .unwrap() @@ -54,7 +54,7 @@ fn test_stake_base_case() { // Check subnet updates assert_eq!( SubnetTAO::::get(netuid), - initial_subnet_tao + tao_to_swap - fee, + initial_subnet_tao + tao_to_swap - fee.into(), "Subnet TAO not updated correctly" ); assert_eq!( @@ -231,15 +231,9 @@ fn test_share_based_staking() { + stake_amount.to_u64() as f64 * (secondary_stake.to_u64() as f64 / total_hotkey_stake.to_u64() as f64); + log::info!("Primary final stake: {primary_final_stake} (expected: {primary_expected})"); log::info!( - "Primary final stake: {} (expected: {})", - primary_final_stake, - primary_expected - ); - log::info!( - "Secondary final stake: {} (expected: {})", - secondary_final_stake, - secondary_expected + "Secondary final stake: {secondary_final_stake} (expected: {secondary_expected})" ); assert!( @@ -350,9 +344,7 @@ fn test_share_based_staking() { ); let excessive_amount = available_stake + 1000.into(); log::info!( - "Attempting to remove excessive stake: {} + 1000 = {}", - available_stake, - excessive_amount + "Attempting to remove excessive stake: {available_stake} + 1000 = {excessive_amount}" ); SubtensorModule::decrease_stake_for_hotkey_and_coldkey_on_subnet( &primary_hotkey, @@ -365,10 +357,7 @@ fn test_share_based_staking() { &primary_coldkey, netuid, ); - log::info!( - "Stake after attempting excessive removal: {}", - after_excessive_removal - ); + log::info!("Stake after attempting excessive removal: {after_excessive_removal}"); assert!( after_excessive_removal == available_stake, "Removing more stake performs no action" @@ -674,7 +663,7 @@ fn test_stake_fee_api() { let alpha_divs = AlphaCurrency::from(100_000_000_000); let total_hotkey_alpha = AlphaCurrency::from(100_000_000_000); - let tao_in = 100_000_000_000; // 100 TAO + let tao_in = TaoCurrency::from(100_000_000_000); // 100 TAO let reciprocal_price = 2; // 1 / price let stake_amount = 100_000_000_000; @@ -682,9 +671,15 @@ fn test_stake_fee_api() { SubnetAlphaOut::::insert(netuid0, AlphaCurrency::from(100_000_000_000)); SubnetAlphaOut::::insert(netuid1, AlphaCurrency::from(100_000_000_000)); // Set pools using price - SubnetAlphaIn::::insert(netuid0, AlphaCurrency::from(tao_in * reciprocal_price)); + SubnetAlphaIn::::insert( + netuid0, + AlphaCurrency::from(tao_in.to_u64() * reciprocal_price), + ); SubnetTAO::::insert(netuid0, tao_in); - SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(tao_in * reciprocal_price)); + SubnetAlphaIn::::insert( + netuid1, + AlphaCurrency::from(tao_in.to_u64() * reciprocal_price), + ); SubnetTAO::::insert(netuid1, tao_in); // Setup alpha divs for hotkey1 @@ -820,7 +815,7 @@ fn test_stake_fee_calculation() { let alpha_divs = AlphaCurrency::from(100_000_000_000); let total_hotkey_alpha = AlphaCurrency::from(100_000_000_000); - let tao_in = 100_000_000_000; // 100 TAO + let tao_in = TaoCurrency::from(100_000_000_000); // 100 TAO let reciprocal_price = 2; // 1 / price let stake_amount = 100_000_000_000_u64; @@ -833,12 +828,12 @@ fn test_stake_fee_calculation() { mock::setup_reserves( netuid0, tao_in, - AlphaCurrency::from(tao_in * reciprocal_price), + AlphaCurrency::from(tao_in.to_u64() * reciprocal_price), ); mock::setup_reserves( netuid1, tao_in, - AlphaCurrency::from(tao_in * reciprocal_price), + AlphaCurrency::from(tao_in.to_u64() * reciprocal_price), ); // Setup alpha divs for hotkey1 diff --git a/pallets/subtensor/src/tests/subnet.rs b/pallets/subtensor/src/tests/subnet.rs index d2bab08d39..b60f3ffa41 100644 --- a/pallets/subtensor/src/tests/subnet.rs +++ b/pallets/subtensor/src/tests/subnet.rs @@ -5,7 +5,7 @@ use crate::*; use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::Config; use sp_core::U256; -use subtensor_runtime_common::AlphaCurrency; +use subtensor_runtime_common::{AlphaCurrency, TaoCurrency}; use super::mock; @@ -22,7 +22,7 @@ fn test_do_start_call_ok() { add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000.into(), 1_000_000_000.into()); // account 0 is the default owner for any subnet assert_eq!(SubnetOwner::::get(netuid), coldkey_account_id); @@ -64,11 +64,11 @@ fn test_do_start_call_fail_not_owner() { let tempo: u16 = 13; let coldkey_account_id = U256::from(0); let wrong_owner_account_id = U256::from(2); - let burn_cost = 1000; + let burn_cost = TaoCurrency::from(1000); //add network SubtensorModule::set_burn(netuid, burn_cost); add_network_without_emission_block(netuid, tempo, 0); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000.into(), 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -94,11 +94,11 @@ fn test_do_start_call_fail_with_cannot_start_call_now() { let netuid = NetUid::from(1); let tempo: u16 = 13; let coldkey_account_id = U256::from(0); - let burn_cost = 1000; + let burn_cost = TaoCurrency::from(1000); //add network SubtensorModule::set_burn(netuid, burn_cost); add_network_without_emission_block(netuid, tempo, 0); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000.into(), 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -123,13 +123,13 @@ fn test_do_start_call_fail_for_set_again() { let tempo: u16 = 13; let coldkey_account_id = U256::from(0); let hotkey_account_id = U256::from(1); - let burn_cost = 1000; + let burn_cost = TaoCurrency::from(1000); SubtensorModule::set_burn(netuid, burn_cost); add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000.into(), 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -170,7 +170,7 @@ fn test_do_start_call_ok_with_same_block_number_after_coinbase() { add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000.into(), 1_000_000_000.into()); assert_eq!(SubnetOwner::::get(netuid), coldkey_account_id); @@ -205,7 +205,7 @@ fn test_register_network_min_burn_at_default() { let cost = SubtensorModule::get_network_lock_cost(); // Give coldkey enough for lock - SubtensorModule::add_balance_to_coldkey_account(&sn_owner_coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&sn_owner_coldkey, cost.into()); // Register network assert_ok!(SubtensorModule::register_network( @@ -220,7 +220,7 @@ fn test_register_network_min_burn_at_default() { }; // Check min burn is set to default - assert_eq!(MinBurn::::get(netuid), InitialMinBurn::get()); + assert_eq!(MinBurn::::get(netuid), InitialMinBurn::get().into()); // Check registration allowed assert!(NetworkRegistrationAllowed::::get(netuid)); @@ -235,7 +235,7 @@ fn test_register_network_use_symbol_for_subnet_if_available() { let coldkey = U256::from(1_000_000 + i); let hotkey = U256::from(2_000_000 + i); let cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost.into()); assert_ok!(SubtensorModule::register_network( <::RuntimeOrigin>::signed(coldkey), @@ -266,7 +266,7 @@ fn test_register_network_use_next_available_symbol_if_symbol_for_subnet_is_taken let coldkey = U256::from(1_000_000 + i); let hotkey = U256::from(2_000_000 + i); let cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost.into()); assert_ok!(SubtensorModule::register_network( <::RuntimeOrigin>::signed(coldkey), @@ -294,7 +294,7 @@ fn test_register_network_use_next_available_symbol_if_symbol_for_subnet_is_taken let coldkey = U256::from(1_000_000 + 50); let hotkey = U256::from(2_000_000 + 50); let cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost.into()); assert_ok!(SubtensorModule::register_network( <::RuntimeOrigin>::signed(coldkey), @@ -321,7 +321,7 @@ fn test_register_network_use_default_symbol_if_all_symbols_are_taken() { let coldkey = U256::from(1_000_000 + i); let hotkey = U256::from(2_000_000 + i); let cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost.into()); assert_ok!(SubtensorModule::register_network( <::RuntimeOrigin>::signed(coldkey), @@ -333,7 +333,7 @@ fn test_register_network_use_default_symbol_if_all_symbols_are_taken() { let coldkey = U256::from(1_000_000 + 50); let hotkey = U256::from(2_000_000 + 50); let cost = SubtensorModule::get_network_lock_cost(); - SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost); + SubtensorModule::add_balance_to_coldkey_account(&coldkey, cost.into()); assert_ok!(SubtensorModule::register_network( <::RuntimeOrigin>::signed(coldkey), @@ -390,11 +390,11 @@ fn test_subtoken_enable_reject_trading_before_enable() { let hotkey_account_id: U256 = U256::from(1); let coldkey_account_id = U256::from(2); let hotkey_account_2_id: U256 = U256::from(3); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let stake_bal = AlphaCurrency::from(10_000_000_000); // 10 Alpha - let limit_price = 1_000_000_000; // not important + let limit_price = TaoCurrency::from(1_000_000_000); // not important add_network_disable_subtoken(netuid, 10, 0); add_network_disable_subtoken(netuid2, 10, 0); @@ -403,7 +403,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { assert!(!SubtokenEnabled::::get(netuid2)); // Set liq high enough to not trigger other errors - SubnetTAO::::set(netuid, 20_000_000_000); + SubnetTAO::::set(netuid, TaoCurrency::from(20_000_000_000)); SubnetAlphaIn::::set(netuid, AlphaCurrency::from(20_000_000_000)); // Register so staking *could* work @@ -428,7 +428,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() ), Error::::SubtokenDisabled ); @@ -438,7 +438,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, + amount.into(), limit_price, false ), @@ -566,16 +566,16 @@ fn test_subtoken_enable_trading_ok_with_enable() { let coldkey_account_id = U256::from(2); let hotkey_account_2_id: U256 = U256::from(3); // stake big enough - let stake_amount = DefaultMinStake::::get() * 10000; + let stake_amount = DefaultMinStake::::get() * 10000.into(); // unstake, transfer, swap just very little - let unstake_amount = AlphaCurrency::from(DefaultMinStake::::get() * 10); + let unstake_amount = AlphaCurrency::from(DefaultMinStake::::get().to_u64() * 10); add_network(netuid, 10, 0); add_network(netuid2, 10, 0); - let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); - mock::setup_reserves(netuid2, reserve, reserve.into()); + let reserve = stake_amount.to_u64() * 1000; + mock::setup_reserves(netuid, reserve.into(), reserve.into()); + mock::setup_reserves(netuid2, reserve.into(), reserve.into()); SubnetAlphaOut::::insert(netuid, AlphaCurrency::from(reserve)); SubnetAlphaOut::::insert(netuid2, AlphaCurrency::from(reserve)); @@ -585,7 +585,10 @@ fn test_subtoken_enable_trading_ok_with_enable() { register_ok_neuron(netuid, hotkey_account_2_id, coldkey_account_id, 0); register_ok_neuron(netuid2, hotkey_account_2_id, coldkey_account_id, 100); - SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, stake_amount * 10); + SubtensorModule::add_balance_to_coldkey_account( + &coldkey_account_id, + stake_amount.to_u64() * 10, + ); // all trading extrinsic should be possible now that subtoken is enabled. assert_ok!(SubtensorModule::add_stake( @@ -685,14 +688,17 @@ fn test_subtoken_enable_ok_for_burn_register_before_enable() { let coldkey_account_id = U256::from(2); let hotkey_account_2_id: U256 = U256::from(3); - let burn_cost = 1000; + let burn_cost = TaoCurrency::from(1000); // Set the burn cost SubtensorModule::set_burn(netuid, burn_cost); // Add the networks with subtoken disabled add_network_disable_subtoken(netuid, 10, 0); add_network_disable_subtoken(netuid2, 10, 0); // Give enough to burned register - SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, burn_cost * 2 + 5_000); + SubtensorModule::add_balance_to_coldkey_account( + &coldkey_account_id, + burn_cost.to_u64() * 2 + 5_000, + ); // Should be possible to burned register before enable is activated assert_ok!(SubtensorModule::burned_register( @@ -781,9 +787,7 @@ fn test_no_duplicates_in_symbol_static() { let symbol = SYMBOLS.get(usize::from(netuid)).unwrap(); assert!( seen.insert(symbol.to_vec()), - "Duplicate symbol found for netuid {}: {:?}", - netuid, - symbol + "Duplicate symbol found for netuid {netuid}: {symbol:?}" ); } } diff --git a/pallets/subtensor/src/tests/swap_coldkey.rs b/pallets/subtensor/src/tests/swap_coldkey.rs index bab264a3c6..1f1b9b113b 100644 --- a/pallets/subtensor/src/tests/swap_coldkey.rs +++ b/pallets/subtensor/src/tests/swap_coldkey.rs @@ -12,7 +12,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H256, U256}; use sp_runtime::{DispatchError, traits::TxBaseImplication}; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{AlphaCurrency, Currency, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, Currency, SubnetInfo, TaoCurrency}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; @@ -82,7 +82,7 @@ fn test_swap_total_coldkey_stake() { let other_coldkey = U256::from(3); let hotkey = U256::from(4); let other_hotkey = U256::from(5); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; let netuid = NetUid::from(1u16); add_network(netuid, 1, 0); @@ -91,19 +91,19 @@ fn test_swap_total_coldkey_stake() { register_ok_neuron(netuid, other_hotkey, other_coldkey, 1001000); let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), other_hotkey, netuid, - stake + stake.into() )); let total_stake_before_swap = SubtensorModule::get_total_stake_for_coldkey(&old_coldkey); @@ -116,7 +116,7 @@ fn test_swap_total_coldkey_stake() { assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), @@ -208,11 +208,11 @@ fn test_swap_with_no_stake() { assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), - 0 + TaoCurrency::ZERO ); }); } @@ -296,10 +296,10 @@ fn test_swap_idempotency() { let new_coldkey = U256::from(2); let hotkey = U256::from(3); let netuid = NetUid::from(1u16); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Add a network add_network(netuid, 1, 0); @@ -310,7 +310,7 @@ fn test_swap_idempotency() { <::RuntimeOrigin>::signed(old_coldkey), hotkey, netuid, - stake + stake.into() )); // Get stake before swap @@ -330,7 +330,7 @@ fn test_swap_idempotency() { assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), @@ -369,15 +369,15 @@ fn test_swap_with_max_values() { SubtensorModule::add_balance_to_coldkey_account(&old_coldkey2, max_stake + 1_000); let reserve = max_stake * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); - mock::setup_reserves(netuid2, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); + mock::setup_reserves(netuid2, reserve.into(), reserve.into()); // Stake to hotkey on each subnet. assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey, netuid, - max_stake + max_stake.into() )); let expected_stake1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, @@ -389,7 +389,7 @@ fn test_swap_with_max_values() { <::RuntimeOrigin>::signed(old_coldkey2), hotkey2, netuid2, - max_stake + max_stake.into() )); let expected_stake2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -411,21 +411,21 @@ fn test_swap_with_max_values() { assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), - expected_stake1.to_u64(), - epsilon = expected_stake1.to_u64() / 1000 + expected_stake1.to_u64().into(), + epsilon = TaoCurrency::from(expected_stake1.to_u64()) / 1000.into() ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey2), - 0 + TaoCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey2), - expected_stake2.to_u64(), - epsilon = expected_stake2.to_u64() / 1000 + expected_stake2.to_u64().into(), + epsilon = TaoCurrency::from(expected_stake2.to_u64()) / 1000.into() ); }); } @@ -437,7 +437,7 @@ fn test_swap_with_non_existent_new_coldkey() { let old_coldkey = U256::from(1); let new_coldkey = U256::from(2); let hotkey = U256::from(3); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; let netuid = NetUid::from(1); add_network(netuid, 1, 0); @@ -446,14 +446,14 @@ fn test_swap_with_non_existent_new_coldkey() { SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, stake + 1_000); let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Stake to hotkey. assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey, netuid, - stake + stake.into() )); let expected_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, @@ -470,7 +470,7 @@ fn test_swap_with_non_existent_new_coldkey() { assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); let actual_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -533,13 +533,13 @@ fn test_swap_effect_on_delegated_stake() { RuntimeOrigin::signed(old_coldkey), hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(delegator), hotkey, netuid, - stake + stake.into() )); let coldkey_stake_before = SubtensorModule::get_total_stake_for_coldkey(&old_coldkey); let delegator_stake_before = SubtensorModule::get_total_stake_for_coldkey(&delegator); @@ -554,17 +554,17 @@ fn test_swap_effect_on_delegated_stake() { assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), coldkey_stake_before, - epsilon = 500 + epsilon = 500.into() ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&delegator), delegator_stake_before, - epsilon = 500 + epsilon = 500.into() ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0, - epsilon = 500 + TaoCurrency::ZERO, + epsilon = 500.into() ); }); } @@ -581,7 +581,7 @@ fn test_swap_concurrent_modifications() { let additional_stake = 500_000_000_000; let reserve = (initial_stake + additional_stake) * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Setup initial state add_network(netuid, 1, 1); @@ -595,7 +595,7 @@ fn test_swap_concurrent_modifications() { <::RuntimeOrigin>::signed(new_coldkey), hotkey, netuid, - initial_stake + initial_stake.into() )); // Verify initial stake @@ -613,7 +613,7 @@ fn test_swap_concurrent_modifications() { <::RuntimeOrigin>::signed(new_coldkey), hotkey, netuid, - additional_stake + additional_stake.into() )); let stake_with_additional = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -676,13 +676,13 @@ fn test_do_swap_coldkey_success() { let hotkey1 = U256::from(3); let hotkey2 = U256::from(4); let netuid = NetUid::from(1u16); - let stake_amount1 = DefaultMinStake::::get() * 10; - let stake_amount2 = DefaultMinStake::::get() * 20; + let stake_amount1 = DefaultMinStake::::get().to_u64() * 10; + let stake_amount2 = DefaultMinStake::::get().to_u64() * 20; let swap_cost = SubtensorModule::get_key_swap_cost(); - let free_balance_old = 12345u64 + swap_cost; + let free_balance_old = 12345 + swap_cost.to_u64(); let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Setup initial state add_network(netuid, 13, 0); @@ -714,13 +714,13 @@ fn test_do_swap_coldkey_success() { <::RuntimeOrigin>::signed(old_coldkey), hotkey1, netuid, - stake_amount1 + stake_amount1.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey2, netuid, - stake_amount2 + stake_amount2.into() )); // Insert an Identity @@ -792,7 +792,7 @@ fn test_do_swap_coldkey_success() { ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); assert_eq!( Alpha::::get((hotkey1, new_coldkey, netuid)), @@ -815,7 +815,7 @@ fn test_do_swap_coldkey_success() { // Verify balance transfer assert_eq!( SubtensorModule::get_coldkey_balance(&new_coldkey), - free_balance_old - swap_cost + free_balance_old - swap_cost.to_u64() ); assert_eq!(SubtensorModule::get_coldkey_balance(&old_coldkey), 0); @@ -854,9 +854,9 @@ fn test_swap_stake_for_coldkey() { let new_coldkey = U256::from(2); let hotkey1 = U256::from(3); let hotkey2 = U256::from(4); - let stake_amount1 = DefaultMinStake::::get() * 10; - let stake_amount2 = DefaultMinStake::::get() * 20; - let stake_amount3 = DefaultMinStake::::get() * 30; + let stake_amount1 = DefaultMinStake::::get().to_u64() * 10; + let stake_amount2 = DefaultMinStake::::get().to_u64() * 20; + let stake_amount3 = DefaultMinStake::::get().to_u64() * 30; let mut weight = Weight::zero(); // Setup initial state @@ -874,14 +874,14 @@ fn test_swap_stake_for_coldkey() { ); let reserve = (stake_amount1 + stake_amount2 + stake_amount3) * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Stake to hotkeys assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey1, netuid, - stake_amount1 + stake_amount1.into() )); let expected_stake_alpha1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -893,7 +893,7 @@ fn test_swap_stake_for_coldkey() { <::RuntimeOrigin>::signed(old_coldkey), hotkey2, netuid, - stake_amount2 + stake_amount2.into() )); let expected_stake_alpha2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -909,7 +909,7 @@ fn test_swap_stake_for_coldkey() { <::RuntimeOrigin>::signed(new_coldkey), hotkey1, netuid, - stake_amount3 + stake_amount3.into() )); let expected_stake_alpha3 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -934,7 +934,7 @@ fn test_swap_stake_for_coldkey() { assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), initial_total_stake_for_old_coldkey + initial_total_stake_for_new_coldkey, - epsilon = 2 + epsilon = 2.into() ); // Verify ownership transfer @@ -1011,8 +1011,8 @@ fn test_swap_staking_hotkeys_for_coldkey() { let other_coldkey = U256::from(3); let hotkey1 = U256::from(4); let hotkey2 = U256::from(5); - let stake_amount1 = DefaultMinStake::::get() * 10; - let stake_amount2 = DefaultMinStake::::get() * 20; + let stake_amount1 = DefaultMinStake::::get().to_u64() * 10; + let stake_amount2 = DefaultMinStake::::get().to_u64() * 20; let mut weight = Weight::zero(); // Setup initial state @@ -1028,14 +1028,14 @@ fn test_swap_staking_hotkeys_for_coldkey() { register_ok_neuron(netuid, hotkey2, other_coldkey, 0); let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Stake to hotkeys assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey1, netuid, - stake_amount1 + stake_amount1.into() )); let expected_stake_alpha1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -1047,7 +1047,7 @@ fn test_swap_staking_hotkeys_for_coldkey() { <::RuntimeOrigin>::signed(old_coldkey), hotkey2, netuid, - stake_amount2 + stake_amount2.into() )); let expected_stake_alpha2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -1076,8 +1076,8 @@ fn test_swap_delegated_stake_for_coldkey() { let other_coldkey = U256::from(3); let hotkey1 = U256::from(4); let hotkey2 = U256::from(5); - let stake_amount1 = DefaultMinStake::::get() * 10; - let stake_amount2 = DefaultMinStake::::get() * 20; + let stake_amount1 = DefaultMinStake::::get().to_u64() * 10; + let stake_amount2 = DefaultMinStake::::get().to_u64() * 20; let mut weight = Weight::zero(); let netuid = NetUid::from(1); @@ -1087,7 +1087,7 @@ fn test_swap_delegated_stake_for_coldkey() { register_ok_neuron(netuid, hotkey2, other_coldkey, 0); let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Notice hotkey1 and hotkey2 are Owned by other_coldkey // old_coldkey and new_coldkey therefore delegates stake to them @@ -1102,7 +1102,7 @@ fn test_swap_delegated_stake_for_coldkey() { <::RuntimeOrigin>::signed(old_coldkey), hotkey1, netuid, - stake_amount1 + stake_amount1.into() )); let expected_stake_alpha1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -1110,12 +1110,12 @@ fn test_swap_delegated_stake_for_coldkey() { netuid, ); - let (expected_stake_alpha2, fee) = mock::swap_tao_to_alpha(netuid, stake_amount2); + let (expected_stake_alpha2, fee) = mock::swap_tao_to_alpha(netuid, stake_amount2.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), hotkey2, netuid, - stake_amount2 + stake_amount2.into() )); let expected_stake_alpha2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -1185,7 +1185,7 @@ fn test_swap_delegated_stake_for_coldkey() { ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0 + TaoCurrency::ZERO ); // Verify TotalHotkeyStake remains unchanged @@ -1248,8 +1248,8 @@ fn test_do_swap_coldkey_with_subnet_ownership() { let new_coldkey = U256::from(2); let hotkey = U256::from(3); let netuid = NetUid::from(1u16); - let stake_amount: u64 = 1000u64; - let swap_cost = SubtensorModule::get_key_swap_cost(); + let stake_amount = 1000; + let swap_cost = SubtensorModule::get_key_swap_cost().to_u64(); // Setup initial state add_network(netuid, 13, 0); @@ -1268,7 +1268,7 @@ fn test_do_swap_coldkey_with_subnet_ownership() { assert_ok!(SubtensorModule::do_swap_coldkey( &old_coldkey, &new_coldkey, - swap_cost + swap_cost.into() )); // Verify subnet ownership transfer @@ -1307,7 +1307,7 @@ fn test_coldkey_swap_total() { let netuid1 = NetUid::from(1); let netuid2 = NetUid::from(2); let netuid3 = NetUid::from(3); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; SubtensorModule::add_balance_to_coldkey_account(&coldkey, stake * 6); SubtensorModule::add_balance_to_coldkey_account(&delegate1, stake * 2); SubtensorModule::add_balance_to_coldkey_account(&delegate2, stake * 2); @@ -1317,9 +1317,9 @@ fn test_coldkey_swap_total() { SubtensorModule::add_balance_to_coldkey_account(&nominator3, stake * 2); let reserve = stake * 10; - mock::setup_reserves(netuid1, reserve, reserve.into()); - mock::setup_reserves(netuid2, reserve, reserve.into()); - mock::setup_reserves(netuid3, reserve, reserve.into()); + mock::setup_reserves(netuid1, reserve.into(), reserve.into()); + mock::setup_reserves(netuid2, reserve.into(), reserve.into()); + mock::setup_reserves(netuid3, reserve.into(), reserve.into()); // Setup initial state add_network(netuid1, 13, 0); @@ -1342,113 +1342,113 @@ fn test_coldkey_swap_total() { <::RuntimeOrigin>::signed(coldkey), hotkey1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), hotkey2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), hotkey3, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), delegate1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), delegate2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), delegate3, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate1), hotkey1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate2), hotkey2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate3), hotkey3, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate1), delegate1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate2), delegate2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(delegate3), delegate3, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator1), hotkey1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator2), hotkey2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator3), hotkey3, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator1), delegate1, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator2), delegate2, netuid1, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(nominator3), delegate3, netuid1, - stake + stake.into() )); assert_eq!( @@ -1525,7 +1525,10 @@ fn test_coldkey_swap_total() { SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), ck_stake ); - assert_eq!(SubtensorModule::get_total_stake_for_coldkey(&coldkey), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_coldkey(&coldkey), + TaoCurrency::ZERO + ); // Check everything is swapped. assert_eq!( @@ -1661,11 +1664,11 @@ fn test_coldkey_delegations() { let delegate = U256::from(2); let netuid = NetUid::from(0); // Stake to 0 let netuid2 = NetUid::from(1); // Stake to 1 - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); - mock::setup_reserves(netuid2, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); + mock::setup_reserves(netuid2, reserve.into(), reserve.into()); add_network(netuid, 13, 0); // root add_network(netuid2, 13, 0); @@ -1680,13 +1683,13 @@ fn test_coldkey_delegations() { // since the reserves are equal and we stake the same amount to both networks, we can reuse // this values for different networks. but you should take it into account in case of tests // changes - let (expected_stake, fee) = mock::swap_tao_to_alpha(netuid, stake); + let (expected_stake, fee) = mock::swap_tao_to_alpha(netuid, stake.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(coldkey), delegate, netuid, - stake + stake.into() )); // Add stake to netuid2 @@ -1694,7 +1697,7 @@ fn test_coldkey_delegations() { <::RuntimeOrigin>::signed(coldkey), delegate, netuid2, - stake + stake.into() )); // Perform the swap @@ -1706,17 +1709,20 @@ fn test_coldkey_delegations() { )); // Verify stake was moved for the delegate - let approx_total_stake = stake * 2 - fee * 2; + let approx_total_stake = TaoCurrency::from(stake * 2 - fee * 2); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&delegate), approx_total_stake, - epsilon = approx_total_stake / 100 + epsilon = approx_total_stake / 100.into() + ); + assert_eq!( + SubtensorModule::get_total_stake_for_coldkey(&coldkey), + TaoCurrency::ZERO ); - assert_eq!(SubtensorModule::get_total_stake_for_coldkey(&coldkey), 0); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), approx_total_stake, - epsilon = approx_total_stake / 100 + epsilon = approx_total_stake / 100.into() ); assert_eq!( expected_stake, @@ -1746,7 +1752,7 @@ fn test_schedule_swap_coldkey_success() { let swap_cost = SubtensorModule::get_key_swap_cost(); // Add balance to the old coldkey account - SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost + 1_000); + SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost.to_u64() + 1_000); // Schedule the coldkey swap assert_ok!(SubtensorModule::schedule_swap_coldkey( @@ -1785,7 +1791,7 @@ fn test_schedule_swap_coldkey_duplicate() { let swap_cost = SubtensorModule::get_key_swap_cost(); - SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost + 2_000); + SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost.to_u64() + 2_000); assert_ok!(SubtensorModule::schedule_swap_coldkey( <::RuntimeOrigin>::signed(old_coldkey), @@ -1811,10 +1817,10 @@ fn test_schedule_swap_coldkey_execution() { let new_coldkey = U256::from(2); let hotkey = U256::from(3); let netuid = NetUid::from(1u16); - let stake_amount = DefaultMinStake::::get() * 10; + let stake_amount = DefaultMinStake::::get().to_u64() * 10; let reserve = stake_amount * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); add_network(netuid, 13, 0); register_ok_neuron(netuid, hotkey, old_coldkey, 0); @@ -1823,7 +1829,7 @@ fn test_schedule_swap_coldkey_execution() { <::RuntimeOrigin>::signed(old_coldkey), hotkey, netuid, - stake_amount + stake_amount.into() )); // Check initial ownership @@ -1883,7 +1889,7 @@ fn test_schedule_swap_coldkey_execution() { ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey), - 0, + TaoCurrency::ZERO, "Old coldkey still has stake" ); @@ -1911,7 +1917,7 @@ fn test_direct_swap_coldkey_call_fails() { <::RuntimeOrigin>::signed(old_coldkey), old_coldkey, new_coldkey, - 0 + TaoCurrency::ZERO ), BadOrigin ); @@ -1928,7 +1934,7 @@ fn test_schedule_swap_coldkey_with_pending_swap() { let swap_cost = SubtensorModule::get_key_swap_cost(); - SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost + 1_000); + SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost.to_u64() + 1_000); assert_ok!(SubtensorModule::schedule_swap_coldkey( <::RuntimeOrigin>::signed(old_coldkey), @@ -1957,7 +1963,10 @@ fn test_schedule_swap_coldkey_failure_and_reschedule() { let swap_cost = SubtensorModule::get_key_swap_cost(); // Two swaps - SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, swap_cost + 1_000 * 2); + SubtensorModule::add_balance_to_coldkey_account( + &old_coldkey, + swap_cost.to_u64() + 1_000 * 2, + ); assert_ok!(SubtensorModule::schedule_swap_coldkey( <::RuntimeOrigin>::signed(old_coldkey), @@ -2018,14 +2027,14 @@ fn test_coldkey_swap_delegate_identity_updated() { let new_coldkey = U256::from(2); let netuid = NetUid::from(1); - let burn_cost = 10; + let burn_cost = TaoCurrency::from(10); let tempo = 1; SubtensorModule::set_burn(netuid, burn_cost); add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2071,14 +2080,14 @@ fn test_coldkey_swap_no_identity_no_changes() { let new_coldkey = U256::from(2); let netuid = NetUid::from(1); - let burn_cost = 10; + let burn_cost = TaoCurrency::from(10); let tempo = 1; SubtensorModule::set_burn(netuid, burn_cost); add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2109,13 +2118,13 @@ fn test_coldkey_swap_no_identity_no_changes_newcoldkey_exists() { let new_coldkey = U256::from(4); let netuid = NetUid::from(1); - let burn_cost = 10; + let burn_cost = TaoCurrency::from(10); let tempo = 1; SubtensorModule::set_burn(netuid, burn_cost); add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2189,7 +2198,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let stake = 100_000_000_000; let reserve = stake * 100; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); let who = coldkey; // The coldkey signs this transaction @@ -2224,7 +2233,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { <::RuntimeOrigin>::signed(who), hotkey, netuid, - stake + stake.into() )); // Schedule the coldkey for a swap @@ -2246,7 +2255,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { hotkey, netuid, - amount_staked: stake, + amount_staked: stake.into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2268,8 +2277,8 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake_limit { hotkey, netuid, - amount_staked: stake, - limit_price: stake, + amount_staked: stake.into(), + limit_price: stake.into(), allow_partial: false, }); let result = extension.validate( @@ -2317,7 +2326,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { origin_netuid: netuid, destination_netuid: netuid, alpha_amount: stake.into(), - limit_price: stake, + limit_price: stake.into(), allow_partial: false, }); let result = extension.validate( @@ -2471,7 +2480,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake { hotkey, netuid, - amount_unstaked: (DefaultMinStake::::get() * 2).into(), + amount_unstaked: (DefaultMinStake::::get().to_u64() * 2).into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2489,8 +2498,8 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake_limit { hotkey, netuid, - amount_unstaked: (DefaultMinStake::::get() * 2).into(), - limit_price: 123456789, // should be low enough + amount_unstaked: (DefaultMinStake::::get().to_u64() * 2).into(), + limit_price: 123456789.into(), // should be low enough allow_partial: true, }); let result = extension.validate( @@ -2524,7 +2533,7 @@ fn test_coldkey_in_swap_schedule_prevents_critical_calls() { let stake = 100_000_000_000; let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); let who = coldkey; // The coldkey signs this transaction @@ -2546,7 +2555,7 @@ fn test_coldkey_in_swap_schedule_prevents_critical_calls() { <::RuntimeOrigin>::signed(who), hotkey, netuid, - stake + stake.into() )); // Schedule the coldkey for a swap diff --git a/pallets/subtensor/src/tests/swap_hotkey.rs b/pallets/subtensor/src/tests/swap_hotkey.rs index 506bd77a9d..5a9ebf5127 100644 --- a/pallets/subtensor/src/tests/swap_hotkey.rs +++ b/pallets/subtensor/src/tests/swap_hotkey.rs @@ -8,7 +8,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H160, H256, U256}; use sp_runtime::SaturatedConversion; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::AlphaCurrency; +use subtensor_runtime_common::{AlphaCurrency, TaoCurrency}; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -67,25 +67,25 @@ fn test_swap_total_hotkey_stake() { let old_hotkey = U256::from(1); let new_hotkey = U256::from(2); let coldkey = U256::from(3); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let mut weight = Weight::zero(); //add network let netuid = add_dynamic_network(&old_hotkey, &coldkey); - mock::setup_reserves(netuid, amount * 100, (amount * 100).into()); + mock::setup_reserves(netuid, (amount * 100).into(), (amount * 100).into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); // Add stake - let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount); + let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount.into()); assert!(!expected_alpha.is_zero()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), old_hotkey, netuid, - amount + amount.into() )); // Check if stake has increased @@ -95,8 +95,8 @@ fn test_swap_total_hotkey_stake() { ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&new_hotkey), - 0, - epsilon = 1, + TaoCurrency::ZERO, + epsilon = 1.into(), ); // Swap hotkey @@ -110,8 +110,8 @@ fn test_swap_total_hotkey_stake() { // Verify that total hotkey stake swapped assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), - 0, - epsilon = 1, + TaoCurrency::ZERO, + epsilon = 1.into(), ); assert_eq!( TotalHotkeyAlpha::::get(new_hotkey, netuid), @@ -439,13 +439,13 @@ fn test_swap_hotkey_with_multiple_coldkeys() { RuntimeOrigin::signed(coldkey1), old_hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey2), old_hotkey, netuid, - stake / 2 + (stake / 2).into() )); let stake1_before = SubtensorModule::get_total_stake_for_coldkey(&coldkey1); let stake2_before = SubtensorModule::get_total_stake_for_coldkey(&coldkey2); @@ -514,7 +514,7 @@ fn test_swap_staking_hotkeys_multiple_coldkeys() { let coldkey2 = U256::from(4); let staker5 = U256::from(5); let mut weight = Weight::zero(); - let stake = 1_000_000_000; + let stake = TaoCurrency::from(1_000_000_000); // Set up initial state StakingHotkeys::::insert(coldkey1, vec![old_hotkey]); @@ -525,11 +525,11 @@ fn test_swap_staking_hotkeys_multiple_coldkeys() { SubtensorModule::create_account_if_non_existent(&coldkey1, &old_hotkey); SubtensorModule::add_balance_to_coldkey_account( &coldkey1, - stake + ExistentialDeposit::get(), + stake.to_u64() + ExistentialDeposit::get(), ); SubtensorModule::add_balance_to_coldkey_account( &coldkey2, - stake + ExistentialDeposit::get(), + stake.to_u64() + ExistentialDeposit::get(), ); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey1), @@ -606,7 +606,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { let coldkey2 = U256::from(4); let netuid1 = NetUid::from(1); let netuid2 = NetUid::from(2); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; let mut weight = Weight::zero(); // Set up initial state @@ -615,8 +615,8 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { register_ok_neuron(netuid1, old_hotkey, coldkey1, 1234); register_ok_neuron(netuid2, old_hotkey, coldkey1, 1234); - mock::setup_reserves(netuid1, stake * 100, (stake * 100).into()); - mock::setup_reserves(netuid2, stake * 100, (stake * 100).into()); + mock::setup_reserves(netuid1, (stake * 100).into(), (stake * 100).into()); + mock::setup_reserves(netuid2, (stake * 100).into(), (stake * 100).into()); // Add balance to both coldkeys SubtensorModule::add_balance_to_coldkey_account(&coldkey1, stake + 1_000); @@ -627,7 +627,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { <::RuntimeOrigin>::signed(coldkey1), old_hotkey, netuid1, - stake + stake.into() )); // Stake with coldkey2 also @@ -635,7 +635,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { <::RuntimeOrigin>::signed(coldkey2), old_hotkey, netuid2, - stake + stake.into() )); let ck1_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -651,7 +651,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { assert!(!ck1_stake.is_zero()); assert!(!ck2_stake.is_zero()); let total_hk_stake = SubtensorModule::get_total_stake_for_hotkey(&old_hotkey); - assert!(total_hk_stake > 0); + assert!(!total_hk_stake.is_zero()); assert_ok!(SubtensorModule::perform_hotkey_swap_on_all_subnets( &old_hotkey, @@ -724,7 +724,10 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { SubtensorModule::get_total_stake_for_hotkey(&new_hotkey), total_hk_stake ); - assert_eq!(SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), + TaoCurrency::ZERO + ); }); } @@ -744,7 +747,7 @@ fn test_swap_hotkey_tx_rate_limit_exceeded() { // Get the current transaction rate limit let current_tx_rate_limit = SubtensorModule::get_tx_rate_limit(); - log::info!("current_tx_rate_limit: {:?}", current_tx_rate_limit); + log::info!("current_tx_rate_limit: {current_tx_rate_limit:?}"); // Set the transaction rate limit SubtensorModule::set_tx_rate_limit(tx_rate_limit); @@ -894,7 +897,7 @@ fn test_swap_stake_success() { TotalHotkeyShares::::insert(old_hotkey, netuid, shares); Alpha::::insert((old_hotkey, coldkey, netuid), U64F64::from_num(amount)); AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, AlphaCurrency::from(amount)); - TaoDividendsPerSubnet::::insert(netuid, old_hotkey, amount); + TaoDividendsPerSubnet::::insert(netuid, old_hotkey, TaoCurrency::from(amount)); // Perform the swap SubtensorModule::perform_hotkey_swap_on_all_subnets( @@ -945,10 +948,13 @@ fn test_swap_stake_success() { AlphaDividendsPerSubnet::::get(netuid, new_hotkey), amount.into() ); - assert_eq!(TaoDividendsPerSubnet::::get(netuid, old_hotkey), 0); + assert_eq!( + TaoDividendsPerSubnet::::get(netuid, old_hotkey), + TaoCurrency::ZERO + ); assert_eq!( TaoDividendsPerSubnet::::get(netuid, new_hotkey), - amount + amount.into() ); }); } @@ -1041,7 +1047,7 @@ fn test_swap_hotkey_error_cases() { Error::::NotEnoughBalanceToPaySwapHotKey ); - let initial_balance = SubtensorModule::get_key_swap_cost() + 1000; + let initial_balance = SubtensorModule::get_key_swap_cost().to_u64() + 1000; SubtensorModule::add_balance_to_coldkey_account(&coldkey, initial_balance); // Test new hotkey same as old @@ -1088,7 +1094,10 @@ fn test_swap_hotkey_error_cases() { )); // Check balance after swap - assert_eq!(Balances::free_balance(coldkey), initial_balance - swap_cost); + assert_eq!( + Balances::free_balance(coldkey), + initial_balance - swap_cost.to_u64() + ); }); } diff --git a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs index de012d4074..314f72c2bd 100644 --- a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs +++ b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs @@ -5,7 +5,7 @@ use codec::Encode; use frame_support::weights::Weight; use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::{Config, RawOrigin}; -use subtensor_runtime_common::{AlphaCurrency, Currency}; +use subtensor_runtime_common::{AlphaCurrency, Currency, TaoCurrency}; use super::mock::*; use crate::*; @@ -69,7 +69,7 @@ fn test_swap_total_hotkey_stake() { let old_hotkey = U256::from(1); let new_hotkey = U256::from(2); let coldkey = U256::from(3); - let amount = DefaultMinStake::::get() * 10; + let amount = DefaultMinStake::::get().to_u64() * 10; let fee = (amount as f64 * 0.003) as u64; @@ -84,19 +84,19 @@ fn test_swap_total_hotkey_stake() { RuntimeOrigin::signed(coldkey), old_hotkey, netuid, - amount + amount.into() )); // Check if stake has increased assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), - amount - fee, - epsilon = amount / 100, + (amount - fee).into(), + epsilon = TaoCurrency::from(amount / 100), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&new_hotkey), - 0, - epsilon = 1, + TaoCurrency::ZERO, + epsilon = 1.into(), ); // Swap hotkey @@ -111,13 +111,13 @@ fn test_swap_total_hotkey_stake() { // Verify that total hotkey stake swapped assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), - 0, - epsilon = 1, + TaoCurrency::ZERO, + epsilon = 1.into(), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&new_hotkey), - amount - fee, - epsilon = amount / 100, + TaoCurrency::from(amount - fee), + epsilon = TaoCurrency::from(amount / 100), ); }); } @@ -450,13 +450,13 @@ fn test_swap_hotkey_with_multiple_coldkeys() { RuntimeOrigin::signed(coldkey1), old_hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey2), old_hotkey, netuid, - stake / 2 + TaoCurrency::from(stake / 2) )); let stake1_before = SubtensorModule::get_total_stake_for_coldkey(&coldkey1); let stake2_before = SubtensorModule::get_total_stake_for_coldkey(&coldkey2); @@ -560,13 +560,13 @@ fn test_swap_staking_hotkeys_multiple_coldkeys() { RuntimeOrigin::signed(coldkey1), old_hotkey, netuid, - stake + stake.into() )); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey2), old_hotkey, netuid, - stake + stake.into() )); System::set_block_number(System::block_number() + HotkeySwapOnSubnetInterval::get()); @@ -635,7 +635,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { let coldkey2 = U256::from(5); let netuid1 = NetUid::from(1); let netuid2 = NetUid::from(2); - let stake = DefaultMinStake::::get() * 10; + let stake = DefaultMinStake::::get().to_u64() * 10; // Set up initial state add_network(netuid1, 1, 1); @@ -652,7 +652,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { <::RuntimeOrigin>::signed(coldkey1), old_hotkey, netuid1, - stake + stake.into() )); // Stake with coldkey2 also @@ -660,7 +660,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { <::RuntimeOrigin>::signed(coldkey2), old_hotkey, netuid2, - stake + stake.into() )); let ck1_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -676,7 +676,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { assert!(!ck1_stake.is_zero()); assert!(!ck2_stake.is_zero()); let total_hk_stake = SubtensorModule::get_total_stake_for_hotkey(&old_hotkey); - assert!(total_hk_stake > 0); + assert!(!total_hk_stake.is_zero()); System::set_block_number(System::block_number() + HotkeySwapOnSubnetInterval::get()); assert_ok!(SubtensorModule::do_swap_hotkey( @@ -764,7 +764,10 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { + SubtensorModule::get_total_stake_for_hotkey(&new_hotkey_2), total_hk_stake ); - assert_eq!(SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), 0); + assert_eq!( + SubtensorModule::get_total_stake_for_hotkey(&old_hotkey), + TaoCurrency::ZERO + ); }); } @@ -784,7 +787,7 @@ fn test_swap_hotkey_tx_rate_limit_exceeded() { // Get the current transaction rate limit let current_tx_rate_limit = SubtensorModule::get_tx_rate_limit(); - log::info!("current_tx_rate_limit: {:?}", current_tx_rate_limit); + log::info!("current_tx_rate_limit: {current_tx_rate_limit:?}"); // Set the transaction rate limit SubtensorModule::set_tx_rate_limit(tx_rate_limit); @@ -947,7 +950,7 @@ fn test_swap_stake_success() { TotalHotkeyShares::::insert(old_hotkey, netuid, U64F64::from_num(shares)); Alpha::::insert((old_hotkey, coldkey, netuid), U64F64::from_num(amount)); AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, AlphaCurrency::from(amount)); - TaoDividendsPerSubnet::::insert(netuid, old_hotkey, amount); + TaoDividendsPerSubnet::::insert(netuid, old_hotkey, TaoCurrency::from(amount)); // Perform the swap System::set_block_number(System::block_number() + HotkeySwapOnSubnetInterval::get()); @@ -999,10 +1002,13 @@ fn test_swap_stake_success() { AlphaDividendsPerSubnet::::get(netuid, new_hotkey), AlphaCurrency::from(amount) ); - assert_eq!(TaoDividendsPerSubnet::::get(netuid, old_hotkey), 0); + assert_eq!( + TaoDividendsPerSubnet::::get(netuid, old_hotkey), + TaoCurrency::ZERO + ); assert_eq!( TaoDividendsPerSubnet::::get(netuid, new_hotkey), - amount + amount.into() ); }); } @@ -1035,7 +1041,7 @@ fn test_swap_hotkey_error_cases() { Error::::NotEnoughBalanceToPaySwapHotKey ); - let initial_balance = SubtensorModule::get_key_swap_cost() + 1000; + let initial_balance = SubtensorModule::get_key_swap_cost().to_u64() + 1000; SubtensorModule::add_balance_to_coldkey_account(&coldkey, initial_balance); // Test new hotkey same as old @@ -1553,7 +1559,7 @@ fn test_swap_hotkey_registered_on_other_subnet() { TotalNetworks::::put(1); LastTxBlock::::insert(coldkey, 0); - let initial_balance = SubtensorModule::get_key_swap_cost() + 1000; + let initial_balance = SubtensorModule::get_key_swap_cost().to_u64() + 1000; SubtensorModule::add_balance_to_coldkey_account(&coldkey, initial_balance); // Test new hotkey already registered on other subnet diff --git a/pallets/subtensor/src/tests/weights.rs b/pallets/subtensor/src/tests/weights.rs index cec33a940c..38def83714 100644 --- a/pallets/subtensor/src/tests/weights.rs +++ b/pallets/subtensor/src/tests/weights.rs @@ -1,6 +1,7 @@ #![allow(clippy::indexing_slicing, clippy::unwrap_used)] use ark_serialize::CanonicalDeserialize; +use ark_serialize::CanonicalSerialize; use frame_support::{ assert_err, assert_ok, dispatch::{DispatchClass, DispatchResult, GetDispatchInfo, Pays}, @@ -18,6 +19,7 @@ use sp_runtime::{ }; use sp_std::collections::vec_deque::VecDeque; use substrate_fixed::types::I32F32; +use subtensor_runtime_common::TaoCurrency; use subtensor_swap_interface::SwapHandler; use tle::{ curves::drand::TinyBLS381, @@ -29,7 +31,7 @@ use w3f_bls::EngineBLS; use super::mock; use super::mock::*; -use crate::coinbase::reveal_commits::WeightsTlockPayload; +use crate::coinbase::reveal_commits::{LegacyWeightsTlockPayload, WeightsTlockPayload}; use crate::*; /*************************** @@ -92,9 +94,9 @@ fn test_set_rootweights_validate() { SubtensorModule::add_balance_to_coldkey_account(&hotkey, u64::MAX); - let min_stake = 500_000_000_000; + let min_stake = TaoCurrency::from(500_000_000_000); // Set the minimum stake - SubtensorModule::set_stake_threshold(min_stake); + SubtensorModule::set_stake_threshold(min_stake.into()); // Verify stake is less than minimum assert!(SubtensorModule::get_total_stake_for_hotkey(&hotkey) < min_stake); @@ -124,7 +126,7 @@ fn test_set_rootweights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - min_stake + fee + min_stake + fee.into() )); // Verify stake is equal to minimum @@ -151,7 +153,7 @@ fn test_set_rootweights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - DefaultMinStake::::get() * 10 + DefaultMinStake::::get() * 10.into() )); // Verify stake is more than minimum @@ -232,7 +234,7 @@ fn test_commit_weights_validate() { let min_stake = 500_000_000_000; let reserve = min_stake * 1000; - mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid, reserve.into(), reserve.into()); // Stake some TAO and read what get_total_stake_for_hotkey it gets // It will be a different value due to the slippage @@ -240,12 +242,12 @@ fn test_commit_weights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - min_stake + min_stake.into() )); let min_stake_with_slippage = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // Set the minimum stake above what hotkey has - SubtensorModule::set_stake_threshold(min_stake_with_slippage + 1); + SubtensorModule::set_stake_threshold(min_stake_with_slippage.to_u64() + 1); // Submit to the signed extension validate function let info = crate::DispatchInfoOf::<::RuntimeCall>::default(); @@ -268,7 +270,7 @@ fn test_commit_weights_validate() { ); // Set the minimum stake equal to what hotkey has - SubtensorModule::set_stake_threshold(min_stake_with_slippage); + SubtensorModule::set_stake_threshold(min_stake_with_slippage.into()); // Submit to the signed extension validate function let result_min_stake = extension.validate( @@ -288,7 +290,7 @@ fn test_commit_weights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - DefaultMinStake::::get() * 10 + DefaultMinStake::::get() * 10.into() )); // Verify stake is more than minimum @@ -355,17 +357,17 @@ fn test_set_weights_validate() { // Create netuid add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); + mock::setup_reserves(netuid, 1_000_000_000_000.into(), 1_000_000_000_000.into()); // Register the hotkey SubtensorModule::append_neuron(netuid, &hotkey, 0); crate::Owner::::insert(hotkey, coldkey); SubtensorModule::add_balance_to_coldkey_account(&hotkey, u64::MAX); - let min_stake = 500_000_000_000; + let min_stake = TaoCurrency::from(500_000_000_000); // Set the minimum stake - SubtensorModule::set_stake_threshold(min_stake); + SubtensorModule::set_stake_threshold(min_stake.into()); // Verify stake is less than minimum assert!(SubtensorModule::get_total_stake_for_hotkey(&hotkey) < min_stake); @@ -390,18 +392,20 @@ fn test_set_weights_validate() { ); // Increase the stake and make it to be equal to the minimum threshold - let fee = - ::SwapInterface::approx_fee_amount(netuid.into(), min_stake); + let fee = ::SwapInterface::approx_fee_amount( + netuid.into(), + min_stake.into(), + ); assert_ok!(SubtensorModule::do_add_stake( RuntimeOrigin::signed(hotkey), hotkey, netuid, - min_stake + fee + min_stake + fee.into() )); let min_stake_with_slippage = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // Set the minimum stake to what the hotkey has - SubtensorModule::set_stake_threshold(min_stake_with_slippage); + SubtensorModule::set_stake_threshold(min_stake_with_slippage.into()); // Submit to the signed extension validate function let result_min_stake = extension.validate( @@ -452,9 +456,9 @@ fn test_reveal_weights_validate() { crate::Owner::::insert(hotkey, coldkey); SubtensorModule::add_balance_to_coldkey_account(&hotkey, u64::MAX); - let min_stake = 500_000_000_000; + let min_stake = TaoCurrency::from(500_000_000_000); // Set the minimum stake - SubtensorModule::set_stake_threshold(min_stake); + SubtensorModule::set_stake_threshold(min_stake.into()); // Verify stake is less than minimum assert!(SubtensorModule::get_total_stake_for_hotkey(&hotkey) < min_stake); @@ -484,7 +488,7 @@ fn test_reveal_weights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - min_stake + fee + min_stake + fee.into() )); // Verify stake is equal to minimum @@ -511,7 +515,7 @@ fn test_reveal_weights_validate() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - DefaultMinStake::::get() * 10 + DefaultMinStake::::get() * 10.into() )); // Verify stake is more than minimum @@ -621,14 +625,14 @@ fn test_set_stake_threshold_failed() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - 19_000_000_000_000 + 19_000_000_000_000.into() )); assert!(!SubtensorModule::check_weights_min_stake(&hotkey, netuid)); assert_ok!(SubtensorModule::do_add_stake( RuntimeOrigin::signed(hotkey), hotkey, netuid, - 20_000_000_000_000 + 20_000_000_000_000.into() )); assert!(SubtensorModule::check_weights_min_stake(&hotkey, netuid)); @@ -649,7 +653,7 @@ fn test_set_stake_threshold_failed() { RuntimeOrigin::signed(hotkey), hotkey, netuid, - 100_000_000_000_000 + 100_000_000_000_000.into() )); assert_ok!(SubtensorModule::set_weights( RuntimeOrigin::signed(hotkey), @@ -2188,7 +2192,7 @@ fn test_tempo_change_during_commit_reveal_process() { ); let tempo_before_next_reveal: u16 = 200; - log::info!("Changing tempo to {}", tempo_before_next_reveal); + log::info!("Changing tempo to {tempo_before_next_reveal}"); SubtensorModule::set_tempo(netuid, tempo_before_next_reveal); step_epochs(1, netuid); @@ -2221,7 +2225,7 @@ fn test_tempo_change_during_commit_reveal_process() { ); let tempo: u16 = 150; - log::info!("Changing tempo to {}", tempo); + log::info!("Changing tempo to {tempo}"); SubtensorModule::set_tempo(netuid, tempo); step_epochs(1, netuid); @@ -2244,7 +2248,7 @@ fn test_tempo_change_during_commit_reveal_process() { ); let tempo: u16 = 1050; - log::info!("Changing tempo to {}", tempo); + log::info!("Changing tempo to {tempo}"); SubtensorModule::set_tempo(netuid, tempo); assert_ok!(SubtensorModule::commit_weights( @@ -2258,7 +2262,7 @@ fn test_tempo_change_during_commit_reveal_process() { ); let tempo: u16 = 805; - log::info!("Changing tempo to {}", tempo); + log::info!("Changing tempo to {tempo}"); SubtensorModule::set_tempo(netuid, tempo); step_epochs(1, netuid); @@ -3106,9 +3110,7 @@ fn test_tempo_and_reveal_period_change_during_commit_reveal_process() { SubtensorModule::set_tempo(netuid, new_tempo); SubtensorModule::set_reveal_period(netuid, new_reveal_period); log::info!( - "Changed tempo to {} and reveal period to {}", - new_tempo, - new_reveal_period + "Changed tempo to {new_tempo} and reveal period to {new_reveal_period}" ); // Step 3: Advance blocks to reach the reveal epoch according to new tempo and reveal period @@ -3162,9 +3164,7 @@ fn test_tempo_and_reveal_period_change_during_commit_reveal_process() { SubtensorModule::set_tempo(netuid, new_tempo_after_reveal); SubtensorModule::set_reveal_period(netuid, new_reveal_period_after_reveal); log::info!( - "Changed tempo to {} and reveal period to {} after reveal", - new_tempo_after_reveal, - new_reveal_period_after_reveal + "Changed tempo to {new_tempo_after_reveal} and reveal period to {new_reveal_period_after_reveal} after reveal" ); // Step 5: Commit again @@ -4229,11 +4229,10 @@ fn test_highly_concurrent_commits_and_reveals_with_multiple_hotkeys() { || e == Error::::ExpiredWeightCommit.into() || e == Error::::InvalidRevealCommitHashNotMatch.into() { - log::info!("Expected error during reveal after epoch advancement: {:?}", e); + log::info!("Expected error during reveal after epoch advancement: {e:?}"); } else { panic!( - "Unexpected error during reveal: {:?}, expected RevealTooEarly, ExpiredWeightCommit, or InvalidRevealCommitHashNotMatch", - e + "Unexpected error during reveal: {e:?}, expected RevealTooEarly, ExpiredWeightCommit, or InvalidRevealCommitHashNotMatch" ); } } @@ -4275,12 +4274,11 @@ fn test_highly_concurrent_commits_and_reveals_with_multiple_hotkeys() { || e == Error::::ExpiredWeightCommit.into() || e == Error::::InvalidRevealCommitHashNotMatch.into() { - log::info!("Expected error during reveal after epoch advancement: {:?}", e); + log::info!("Expected error during reveal after epoch advancement: {e:?}"); break; } else { panic!( - "Unexpected error during reveal after epoch advancement: {:?}, expected RevealTooEarly, ExpiredWeightCommit, or InvalidRevealCommitHashNotMatch", - e + "Unexpected error during reveal after epoch advancement: {e:?}, expected RevealTooEarly, ExpiredWeightCommit, or InvalidRevealCommitHashNotMatch" ); } } @@ -4311,8 +4309,7 @@ fn test_highly_concurrent_commits_and_reveals_with_multiple_hotkeys() { assert_eq!( reveal_result, Err(Error::::ExpiredWeightCommit.into()), - "Expected ExpiredWeightCommit error, got {:?}", - reveal_result + "Expected ExpiredWeightCommit error, got {reveal_result:?}" ); } } @@ -4734,8 +4731,6 @@ pub fn tlock_encrypt_decrypt_drand_quicknet_works() { #[test] fn test_reveal_crv3_commits_success() { new_test_ext(100).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey1: AccountId = U256::from(1); let hotkey2: AccountId = U256::from(2); @@ -4774,6 +4769,7 @@ fn test_reveal_crv3_commits_success() { let version_key = SubtensorModule::get_weights_version_key(netuid); let payload = WeightsTlockPayload { + hotkey: hotkey1.encode(), values: vec![10, 20], uids: vec![neuron_uid1, neuron_uid2], version_key, @@ -4815,15 +4811,15 @@ fn test_reveal_crv3_commits_success() { ); log::debug!( - "Commit bytes now contain {:#?}", - commit_bytes + "Commit bytes now contain {commit_bytes:#?}" ); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, commit_bytes.clone().try_into().expect("Failed to convert commit bytes into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") @@ -4871,16 +4867,14 @@ fn test_reveal_crv3_commits_success() { assert!( rounded_actual_weight != 0, - "Actual weight for uid {} is zero", - uid_a + "Actual weight for uid {uid_a} is zero" ); let expected_weight = w_b.to_num::(); assert_eq!( rounded_actual_weight, expected_weight, - "Weight mismatch for uid {}: expected {}, got {}", - uid_a, expected_weight, rounded_actual_weight + "Weight mismatch for uid {uid_a}: expected {expected_weight}, got {rounded_actual_weight}" ); } }); @@ -4890,8 +4884,6 @@ fn test_reveal_crv3_commits_success() { #[test] fn test_reveal_crv3_commits_cannot_reveal_after_reveal_epoch() { new_test_ext(100).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey1: AccountId = U256::from(1); let hotkey2: AccountId = U256::from(2); @@ -4915,6 +4907,7 @@ fn test_reveal_crv3_commits_cannot_reveal_after_reveal_epoch() { let version_key = SubtensorModule::get_weights_version_key(netuid); let payload = WeightsTlockPayload { + hotkey: hotkey1.encode(), values: vec![10, 20], uids: vec![neuron_uid1, neuron_uid2], version_key, @@ -4950,14 +4943,15 @@ fn test_reveal_crv3_commits_cannot_reveal_after_reveal_epoch() { ct.serialize_compressed(&mut commit_bytes) .expect("Failed to serialize commit"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, commit_bytes .clone() .try_into() .expect("Failed to convert commit bytes into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); // Do NOT insert the pulse at this time; this simulates the missing pulse during the reveal epoch @@ -5027,14 +5021,15 @@ fn test_do_commit_crv3_weights_success() { SubtensorModule::set_weights_set_rate_limit(netuid, 0); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data .clone() .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); let cur_epoch = @@ -5062,13 +5057,14 @@ fn test_do_commit_crv3_weights_disabled() { SubtensorModule::set_commit_reveal_weights_enabled(netuid, false); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::CommitRevealDisabled ); @@ -5091,13 +5087,14 @@ fn test_do_commit_crv3_weights_hotkey_not_registered() { SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(unregistered_hotkey), netuid, commit_data .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::HotKeyNotRegisteredInSubNet ); @@ -5122,25 +5119,27 @@ fn test_do_commit_crv3_weights_committing_too_fast() { SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey).expect("Expected uid"); SubtensorModule::set_last_update_for_uid(netuid, neuron_uid, 0); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data_1 .clone() .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data_2 .clone() .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::CommittingWeightsTooFast ); @@ -5148,27 +5147,29 @@ fn test_do_commit_crv3_weights_committing_too_fast() { step_block(2); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data_2 .clone() .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::CommittingWeightsTooFast ); step_block(3); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data_2 .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); }); } @@ -5195,11 +5196,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { .try_into() .expect("Failed to convert commit data into bounded vector"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, bounded_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); } @@ -5210,11 +5212,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { .expect("Failed to convert new commit data into bounded vector"); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, bounded_new_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::TooManyUnrevealedCommits ); @@ -5225,11 +5228,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { .try_into() .expect("Failed to convert commit data into bounded vector"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey2), netuid, bounded_commit_data_hotkey2, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); // Hotkey2 can submit up to 10 commits @@ -5239,11 +5243,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { .try_into() .expect("Failed to convert commit data into bounded vector"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey2), netuid, bounded_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); } @@ -5254,11 +5259,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { .expect("Failed to convert new commit data into bounded vector"); assert_err!( - SubtensorModule::do_commit_crv3_weights( + SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey2), netuid, bounded_new_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() ), Error::::TooManyUnrevealedCommits ); @@ -5269,11 +5275,12 @@ fn test_do_commit_crv3_weights_too_many_unrevealed_commits() { let bounded_new_commit_data = new_commit_data .try_into() .expect("Failed to convert new commit data into bounded vector"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, bounded_new_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); }); } @@ -5297,11 +5304,12 @@ fn test_reveal_crv3_commits_decryption_failure() { .try_into() .expect("Failed to convert commit bytes into bounded vector"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, bounded_commit_bytes, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); step_epochs(1, netuid); @@ -5333,8 +5341,6 @@ fn test_reveal_crv3_commits_decryption_failure() { #[test] fn test_reveal_crv3_commits_multiple_commits_some_fail_some_succeed() { new_test_ext(100).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey1: AccountId = U256::from(1); let hotkey2: AccountId = U256::from(2); @@ -5352,6 +5358,7 @@ fn test_reveal_crv3_commits_multiple_commits_some_fail_some_succeed() { .expect("Failed to get neuron UID for hotkey1"); let version_key = SubtensorModule::get_weights_version_key(netuid); let valid_payload = WeightsTlockPayload { + hotkey: hotkey1.encode(), values: vec![10], uids: vec![neuron_uid1], version_key, @@ -5404,17 +5411,19 @@ fn test_reveal_crv3_commits_multiple_commits_some_fail_some_succeed() { .expect("Failed to serialize invalid commit"); // Insert both commits - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey1), netuid, commit_bytes_valid.try_into().expect("Failed to convert valid commit data"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey2), netuid, commit_bytes_invalid.try_into().expect("Failed to convert invalid commit data"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); // Insert the pulse @@ -5457,8 +5466,6 @@ fn test_reveal_crv3_commits_multiple_commits_some_fail_some_succeed() { #[test] fn test_reveal_crv3_commits_do_set_weights_failure() { new_test_ext(1).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey: AccountId = U256::from(1); let reveal_round: u64 = 1000; @@ -5472,6 +5479,7 @@ fn test_reveal_crv3_commits_do_set_weights_failure() { // Prepare payload with mismatched uids and values lengths let version_key = SubtensorModule::get_weights_version_key(netuid); let payload = WeightsTlockPayload { + hotkey: hotkey.encode(), values: vec![10, 20], // Length 2 uids: vec![0], // Length 1 version_key, @@ -5506,11 +5514,12 @@ fn test_reveal_crv3_commits_do_set_weights_failure() { ct.serialize_compressed(&mut commit_bytes) .expect("Failed to serialize commit"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_bytes.try_into().expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") @@ -5543,8 +5552,6 @@ fn test_reveal_crv3_commits_do_set_weights_failure() { #[test] fn test_reveal_crv3_commits_payload_decoding_failure() { new_test_ext(1).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey: AccountId = U256::from(1); let reveal_round: u64 = 1000; @@ -5585,11 +5592,12 @@ fn test_reveal_crv3_commits_payload_decoding_failure() { ct.serialize_compressed(&mut commit_bytes) .expect("Failed to serialize commit"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_bytes.try_into().expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") @@ -5622,8 +5630,6 @@ fn test_reveal_crv3_commits_payload_decoding_failure() { #[test] fn test_reveal_crv3_commits_signature_deserialization_failure() { new_test_ext(1).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey: AccountId = U256::from(1); let reveal_round: u64 = 1000; @@ -5636,6 +5642,7 @@ fn test_reveal_crv3_commits_signature_deserialization_failure() { let version_key = SubtensorModule::get_weights_version_key(netuid); let payload = WeightsTlockPayload { + hotkey: hotkey.encode(), values: vec![10, 20], uids: vec![0, 1], version_key, @@ -5670,11 +5677,12 @@ fn test_reveal_crv3_commits_signature_deserialization_failure() { ct.serialize_compressed(&mut commit_bytes) .expect("Failed to serialize commit"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_bytes.try_into().expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); pallet_drand::Pulses::::insert( @@ -5734,11 +5742,12 @@ fn test_do_commit_crv3_weights_commit_size_exceeds_limit() { .expect("Failed to create BoundedVec with data at max size"); // Now call the function with valid data at max size - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, bounded_commit_data, - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); }); } @@ -5767,8 +5776,6 @@ fn test_reveal_crv3_commits_with_empty_commit_queue() { #[test] fn test_reveal_crv3_commits_with_incorrect_identity_message() { new_test_ext(1).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); let hotkey: AccountId = U256::from(1); let reveal_round: u64 = 1000; @@ -5784,6 +5791,7 @@ fn test_reveal_crv3_commits_with_incorrect_identity_message() { .expect("Failed to get neuron UID for hotkey"); let version_key = SubtensorModule::get_weights_version_key(netuid); let payload = WeightsTlockPayload { + hotkey: hotkey.encode(), values: vec![10], uids: vec![neuron_uid], version_key, @@ -5819,11 +5827,12 @@ fn test_reveal_crv3_commits_with_incorrect_identity_message() { ct.serialize_compressed(&mut commit_bytes) .expect("Failed to serialize commit"); - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_bytes.try_into().expect("Failed to convert commit data into bounded vector"), - reveal_round + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") @@ -5867,13 +5876,14 @@ fn test_multiple_commits_by_same_hotkey_within_limit() { for i in 0..10 { let commit_data: Vec = vec![i; 5]; - assert_ok!(SubtensorModule::do_commit_crv3_weights( + assert_ok!(SubtensorModule::do_commit_timelocked_weights( RuntimeOrigin::signed(hotkey), netuid, commit_data .try_into() .expect("Failed to convert commit data into bounded vector"), - reveal_round + i as u64 + reveal_round + i as u64, + SubtensorModule::get_commit_reveal_weights_version() )); } @@ -5894,61 +5904,54 @@ fn test_reveal_crv3_commits_removes_past_epoch_commits() { new_test_ext(100).execute_with(|| { let netuid = NetUid::from(1); let hotkey: AccountId = U256::from(1); - let reveal_round: u64 = 1000; + let reveal_round: u64 = 1_000; - // Initialize network and neuron - add_network(netuid, 5, 0); + add_network(netuid, /*tempo*/ 5, 0); register_ok_neuron(netuid, hotkey, U256::from(2), 100_000); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); - SubtensorModule::set_reveal_period(netuid, 1); + SubtensorModule::set_reveal_period(netuid, 1); // reveal_period = 1 epoch SubtensorModule::set_weights_set_rate_limit(netuid, 0); - let current_block = SubtensorModule::get_current_block_as_u64(); - let current_epoch = SubtensorModule::get_epoch_index(netuid, current_block); + // --------------------------------------------------------------------- + // Put dummy commits into the two epochs immediately *before* current. + // --------------------------------------------------------------------- + let cur_block = SubtensorModule::get_current_block_as_u64(); + let cur_epoch = SubtensorModule::get_epoch_index(netuid, cur_block); + let past_epoch = cur_epoch.saturating_sub(2); // definitely < reveal_epoch + let reveal_epoch = cur_epoch.saturating_sub(1); // == cur_epoch - reveal_period + + for &epoch in &[past_epoch, reveal_epoch] { + let bounded_commit = vec![epoch as u8; 5].try_into().expect("bounded vec"); - // Simulate commits in past epochs - let past_epochs = vec![current_epoch - 2, current_epoch - 1]; - for epoch in &past_epochs { - let commit_data: Vec = vec![*epoch as u8; 5]; - let bounded_commit_data = commit_data - .clone() - .try_into() - .expect("Failed to convert commit data into bounded vector"); assert_ok!(CRV3WeightCommitsV2::::try_mutate( netuid, - *epoch, - |commits| -> DispatchResult { - commits.push_back((hotkey, current_block, bounded_commit_data, reveal_round)); + epoch, + |q| -> DispatchResult { + q.push_back((hotkey, cur_block, bounded_commit, reveal_round)); Ok(()) } )); } - for epoch in &past_epochs { - let commits = CRV3WeightCommitsV2::::get(netuid, *epoch); - assert!( - !commits.is_empty(), - "Expected commits to be present for past epoch {}", - epoch - ); - } + // Sanity – both epochs presently hold a commit. + assert!(!CRV3WeightCommitsV2::::get(netuid, past_epoch).is_empty()); + assert!(!CRV3WeightCommitsV2::::get(netuid, reveal_epoch).is_empty()); + // --------------------------------------------------------------------- + // Run the reveal pass WITHOUT a pulse – only expiry housekeeping runs. + // --------------------------------------------------------------------- assert_ok!(SubtensorModule::reveal_crv3_commits(netuid)); - for epoch in &past_epochs { - let commits = CRV3WeightCommitsV2::::get(netuid, *epoch); - assert!( - commits.is_empty(), - "Expected commits for past epoch {} to be removed", - epoch - ); - } + // past_epoch (< reveal_epoch) must be gone + assert!( + CRV3WeightCommitsV2::::get(netuid, past_epoch).is_empty(), + "expired epoch {past_epoch} should be cleared" + ); - let current_epoch_commits = CRV3WeightCommitsV2::::get(netuid, current_epoch); + // reveal_epoch queue is *kept* because its commit could still be revealed later. assert!( - current_epoch_commits.is_empty(), - "Expected no commits for current epoch {}", - current_epoch + !CRV3WeightCommitsV2::::get(netuid, reveal_epoch).is_empty(), + "reveal-epoch {reveal_epoch} must be retained until commit can be revealed" ); }); } @@ -5957,188 +5960,110 @@ fn test_reveal_crv3_commits_removes_past_epoch_commits() { #[test] fn test_reveal_crv3_commits_multiple_valid_commits_all_processed() { new_test_ext(100).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); - let reveal_round: u64 = 1000; + let reveal_round: u64 = 1_000; - // Initialize the network + // ───── network parameters ─────────────────────────────────────────── add_network(netuid, 5, 0); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); SubtensorModule::set_reveal_period(netuid, 1); SubtensorModule::set_weights_set_rate_limit(netuid, 0); + SubtensorModule::set_stake_threshold(0); SubtensorModule::set_max_registrations_per_block(netuid, 100); SubtensorModule::set_target_registrations_per_interval(netuid, 100); - // Register multiple neurons (e.g., 5 neurons) - let num_neurons = 5; - let mut hotkeys = Vec::new(); - let mut neuron_uids = Vec::new(); - for i in 0..num_neurons { - let hotkey: AccountId = U256::from(i + 1); - register_ok_neuron(netuid, hotkey, U256::from(i + 100), 100_000); + // pulse for round 1000 + let sig_bytes = hex::decode( + "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e\ + 342b73a8dd2bacbe47e4b6b63ed5e39", + ) + .unwrap(); + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().unwrap(), + signature: sig_bytes.try_into().unwrap(), + }, + ); + + // ───── five neurons (hotkeys 1‑5) ─────────────────────────────────── + let hotkeys: Vec<_> = (1..=5).map(U256::from).collect(); + for (i, hk) in hotkeys.iter().enumerate() { + let cold: AccountId = U256::from(i + 100); + + register_ok_neuron(netuid, *hk, cold, 100_000); SubtensorModule::set_validator_permit_for_uid(netuid, i as u16, true); - hotkeys.push(hotkey); - neuron_uids.push( - SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey) - .expect("Failed to get neuron UID"), - ); - } - let version_key = SubtensorModule::get_weights_version_key(netuid); + // add minimal stake so `do_set_weights` will succeed + SubtensorModule::add_balance_to_coldkey_account(&cold, 1); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + hk, + &cold, + netuid, + 1.into(), + ); - // Prepare payloads and commits for each hotkey - let esk = [2; 32]; - let pk_bytes = hex::decode("83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a") - .expect("Failed to decode public key bytes"); - let pub_key = ::PublicKeyGroup::deserialize_compressed(&*pk_bytes) - .expect("Failed to deserialize public key"); + step_block(1); // avoids TooManyRegistrationsThisBlock + } - let message = { - let mut hasher = sha2::Sha256::new(); - hasher.update(reveal_round.to_be_bytes()); - hasher.finalize().to_vec() - }; - let identity = Identity::new(b"", vec![message]); + // ───── create & submit commits for each hotkey ────────────────────── + let esk = [2u8; 32]; + let pk_bytes = hex::decode( + "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c\ + 8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb\ + 5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a", + ) + .unwrap(); + let pk = + ::PublicKeyGroup::deserialize_compressed(&*pk_bytes).unwrap(); - let mut commits = Vec::new(); - for (i, hotkey) in hotkeys.iter().enumerate() { - // Each neuron will assign weights to all neurons, including itself - let values: Vec = (0..num_neurons as u16) - .map(|v| (v + i as u16 + 1) * 10) - .collect(); + for (i, hk) in hotkeys.iter().enumerate() { let payload = WeightsTlockPayload { - values: values.clone(), - uids: neuron_uids.clone(), - version_key, + hotkey: hk.encode(), + values: vec![10, 20, 30, 40, 50], + uids: (0..5).map(|u| u as u16).collect(), + version_key: SubtensorModule::get_weights_version_key(netuid), }; - let serialized_payload = payload.encode(); - - let rng = ChaCha20Rng::seed_from_u64(i as u64); + let id_msg = { + let mut h = sha2::Sha256::new(); + h.update(reveal_round.to_be_bytes()); + h.finalize().to_vec() + }; let ct = tle::( - pub_key, + pk, esk, - &serialized_payload, - identity.clone(), - rng, + &payload.encode(), + Identity::new(b"", vec![id_msg]), + ChaCha20Rng::seed_from_u64(i as u64), ) - .expect("Encryption failed"); + .unwrap(); let mut commit_bytes = Vec::new(); - ct.serialize_compressed(&mut commit_bytes) - .expect("Failed to serialize commit"); + ct.serialize_compressed(&mut commit_bytes).unwrap(); - // Submit the commit - assert_ok!(SubtensorModule::do_commit_crv3_weights( - RuntimeOrigin::signed(*hotkey), + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(*hk), netuid, - commit_bytes - .try_into() - .expect("Failed to convert commit data"), - reveal_round + commit_bytes.try_into().unwrap(), + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); - - // Store the expected weights for later comparison - commits.push((hotkey, payload)); } - // Insert the pulse - let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") - .expect("Failed to decode signature bytes"); - - pallet_drand::Pulses::::insert( - reveal_round, - Pulse { - round: reveal_round, - randomness: vec![0; 32] - .try_into() - .expect("Failed to convert randomness vector"), - signature: sig_bytes - .try_into() - .expect("Failed to convert signature bytes"), - }, - ); - - // Advance epoch to trigger reveal - step_epochs(1, netuid); - - // Verify weights for all hotkeys - let weights_sparse = SubtensorModule::get_weights_sparse(netuid); - - // Set acceptable delta for `I32F32` weights - let delta = I32F32::from_num(0.0001); - - for (hotkey, expected_payload) in commits { - let neuron_uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, hotkey) - .expect("Failed to get neuron UID for hotkey") as usize; - let weights = weights_sparse - .get(neuron_uid) - .cloned() - .unwrap_or_default(); + // advance reveal_period + 1 epochs → 2 epochs + step_epochs(2, netuid); + // ───── assertions ─────────────────────────────────────────────────── + let w_sparse = SubtensorModule::get_weights_sparse(netuid); + for hk in hotkeys { + let uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hk).unwrap() as usize; assert!( - !weights.is_empty(), - "Weights for neuron_uid {} should be set", - neuron_uid + !w_sparse.get(uid).unwrap_or(&Vec::new()).is_empty(), + "weights for uid {uid} should be set" ); - - // Normalize expected weights - let expected_weights: Vec<(u16, I32F32)> = expected_payload - .uids - .iter() - .zip(expected_payload.values.iter()) - .map(|(&uid, &value)| (uid, I32F32::from_num(value))) - .collect(); - - let total_expected_weight: I32F32 = - expected_weights.iter().map(|&(_, w)| w).sum(); - - let normalized_expected_weights: Vec<(u16, I32F32)> = expected_weights - .iter() - .map(|&(uid, w)| (uid, w / total_expected_weight * I32F32::from_num(30))) - .collect(); - - // Normalize actual weights - let total_weight: I32F32 = weights.iter().map(|&(_, w)| w).sum(); - - let normalized_weights: Vec<(u16, I32F32)> = weights - .iter() - .map(|&(uid, w)| (uid, w / total_weight * I32F32::from_num(30))) - .collect(); - - // Compare expected and actual weights with acceptable delta - for ((uid_expected, weight_expected), (uid_actual, weight_actual)) in - normalized_expected_weights.iter().zip(normalized_weights.iter()) - { - assert_eq!( - uid_expected, uid_actual, - "UID mismatch: expected {}, got {}", - uid_expected, uid_actual - ); - - let diff = (*weight_expected - *weight_actual).abs(); - assert!( - diff <= delta, - "Weight mismatch for uid {}: expected {}, got {}, diff {}", - uid_expected, - weight_expected, - weight_actual, - diff - ); - } } - - // Verify that commits storage is empty - let cur_epoch = SubtensorModule::get_epoch_index( - netuid, - SubtensorModule::get_current_block_as_u64(), - ); - let commits = CRV3WeightCommitsV2::::get(netuid, cur_epoch); - assert!( - commits.is_empty(), - "Expected no commits left in storage after reveal" - ); }); } @@ -6146,186 +6071,110 @@ fn test_reveal_crv3_commits_multiple_valid_commits_all_processed() { #[test] fn test_reveal_crv3_commits_max_neurons() { new_test_ext(100).execute_with(|| { - use ark_serialize::CanonicalSerialize; - let netuid = NetUid::from(1); - let reveal_round: u64 = 1000; + let reveal_round: u64 = 1_000; + // ───── network parameters ─────────────────────────────────────────── add_network(netuid, 5, 0); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); SubtensorModule::set_reveal_period(netuid, 1); SubtensorModule::set_weights_set_rate_limit(netuid, 0); - SubtensorModule::set_max_registrations_per_block(netuid, 10000); - SubtensorModule::set_target_registrations_per_interval(netuid, 10000); - SubtensorModule::set_max_allowed_uids(netuid, 10024); - - let num_neurons = 1_024; - let mut hotkeys = Vec::new(); - let mut neuron_uids = Vec::new(); - for i in 0..num_neurons { - let hotkey: AccountId = U256::from(i + 1); - register_ok_neuron(netuid, hotkey, U256::from(i + 100), 100_000); - SubtensorModule::set_validator_permit_for_uid(netuid, i as u16, true); - hotkeys.push(hotkey); - neuron_uids.push( - SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey) - .expect("Failed to get neuron UID"), + SubtensorModule::set_stake_threshold(0); + SubtensorModule::set_max_registrations_per_block(netuid, 10_000); + SubtensorModule::set_target_registrations_per_interval(netuid, 10_000); + SubtensorModule::set_max_allowed_uids(netuid, 10_024); + + // ───── register 1 024 neurons ─────────────────────────────────────── + for i in 0..1_024u16 { + let hk: AccountId = U256::from(i as u64 + 1); + let cold: AccountId = U256::from(i as u64 + 10_000); + + register_ok_neuron(netuid, hk, cold, 100_000); + SubtensorModule::set_validator_permit_for_uid(netuid, i, true); + + // give each neuron a nominal stake (safe even if not needed) + SubtensorModule::add_balance_to_coldkey_account(&cold, 1); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hk, + &cold, + netuid, + 1.into(), ); - } - let version_key = SubtensorModule::get_weights_version_key(netuid); + step_block(1); // avoid registration‑limit panic + } - // Prepare payloads and commits for 3 hotkeys - let esk = [2; 32]; - let pk_bytes = hex::decode("83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a") - .expect("Failed to decode public key bytes"); - let pub_key = ::PublicKeyGroup::deserialize_compressed(&*pk_bytes) - .expect("Failed to deserialize public key"); + // ───── pulse for round 1000 ───────────────────────────────────────── + let sig_bytes = hex::decode( + "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e\ + 342b73a8dd2bacbe47e4b6b63ed5e39", + ) + .unwrap(); + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().unwrap(), + signature: sig_bytes.try_into().unwrap(), + }, + ); - let message = { - let mut hasher = sha2::Sha256::new(); - hasher.update(reveal_round.to_be_bytes()); - hasher.finalize().to_vec() - }; - let identity = Identity::new(b"", vec![message]); + // ───── three committing hotkeys ───────────────────────────────────── + let esk = [2u8; 32]; + let pk_bytes = hex::decode( + "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c\ + 8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb\ + 5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a", + ) + .unwrap(); + let pk = + ::PublicKeyGroup::deserialize_compressed(&*pk_bytes).unwrap(); + let committing_hotkeys = [U256::from(1), U256::from(2), U256::from(3)]; - let hotkeys_to_commit = &hotkeys[0..3]; // First 3 hotkeys will submit weight commits - let mut commits = Vec::new(); - for (i, hotkey) in hotkeys_to_commit.iter().enumerate() { - // Each neuron will assign weights to all neurons - let values: Vec = vec![10; num_neurons]; // Assign weight of 10 to each neuron + for (i, hk) in committing_hotkeys.iter().enumerate() { let payload = WeightsTlockPayload { - values: values.clone(), - uids: neuron_uids.clone(), - version_key, + hotkey: hk.encode(), + values: vec![10u16; 1_024], + uids: (0..1_024).collect(), + version_key: SubtensorModule::get_weights_version_key(netuid), + }; + let id_msg = { + let mut h = sha2::Sha256::new(); + h.update(reveal_round.to_be_bytes()); + h.finalize().to_vec() }; - let serialized_payload = payload.encode(); - - let rng = ChaCha20Rng::seed_from_u64(i as u64); - let ct = tle::( - pub_key, + pk, esk, - &serialized_payload, - identity.clone(), - rng, + &payload.encode(), + Identity::new(b"", vec![id_msg]), + ChaCha20Rng::seed_from_u64(i as u64), ) - .expect("Encryption failed"); - + .unwrap(); let mut commit_bytes = Vec::new(); - ct.serialize_compressed(&mut commit_bytes) - .expect("Failed to serialize commit"); + ct.serialize_compressed(&mut commit_bytes).unwrap(); - // Submit the commit - assert_ok!(SubtensorModule::do_commit_crv3_weights( - RuntimeOrigin::signed(*hotkey), + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(*hk), netuid, - commit_bytes - .try_into() - .expect("Failed to convert commit data"), - reveal_round + commit_bytes.try_into().unwrap(), + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() )); - - // Store the expected weights for later comparison - commits.push((hotkey, payload)); } - // Insert the pulse - let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") - .expect("Failed to decode signature bytes"); - - pallet_drand::Pulses::::insert( - reveal_round, - Pulse { - round: reveal_round, - randomness: vec![0; 32] - .try_into() - .expect("Failed to convert randomness vector"), - signature: sig_bytes - .try_into() - .expect("Failed to convert signature bytes"), - }, - ); - - // Advance epoch to trigger reveal - step_epochs(1, netuid); - - // Verify weights for the hotkeys that submitted commits - let weights_sparse = SubtensorModule::get_weights_sparse(netuid); - - // Set acceptable delta for `I32F32` weights - let delta = I32F32::from_num(0.0001); // Adjust delta as needed - - for (hotkey, expected_payload) in commits { - let neuron_uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, hotkey) - .expect("Failed to get neuron UID for hotkey") as usize; - let weights = weights_sparse - .get(neuron_uid) - .cloned() - .unwrap_or_default(); + // ───── advance reveal_period + 1 epochs ───────────────────────────── + step_epochs(2, netuid); + // ───── verify weights ─────────────────────────────────────────────── + let w_sparse = SubtensorModule::get_weights_sparse(netuid); + for hk in &committing_hotkeys { + let uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, hk).unwrap() as usize; assert!( - !weights.is_empty(), - "Weights for neuron_uid {} should be set", - neuron_uid + !w_sparse.get(uid).unwrap_or(&Vec::new()).is_empty(), + "weights for uid {uid} should be set" ); - - // Normalize expected weights - let expected_weights: Vec<(u16, I32F32)> = expected_payload - .uids - .iter() - .zip(expected_payload.values.iter()) - .map(|(&uid, &value)| (uid, I32F32::from_num(value))) - .collect(); - - let total_expected_weight: I32F32 = - expected_weights.iter().map(|&(_, w)| w).sum(); - - let normalized_expected_weights: Vec<(u16, I32F32)> = expected_weights - .iter() - .map(|&(uid, w)| (uid, w / total_expected_weight * I32F32::from_num(30))) - .collect(); - - // Normalize actual weights - let total_weight: I32F32 = weights.iter().map(|&(_, w)| w).sum(); - - let normalized_weights: Vec<(u16, I32F32)> = weights - .iter() - .map(|&(uid, w)| (uid, w / total_weight * I32F32::from_num(30))) - .collect(); - - // Compare expected and actual weights with acceptable delta - for ((uid_expected, weight_expected), (uid_actual, weight_actual)) in - normalized_expected_weights.iter().zip(normalized_weights.iter()) - { - assert_eq!( - uid_expected, uid_actual, - "UID mismatch: expected {}, got {}", - uid_expected, uid_actual - ); - - let diff = (*weight_expected - *weight_actual).abs(); - assert!( - diff <= delta, - "Weight mismatch for uid {}: expected {}, got {}, diff {}", - uid_expected, - weight_expected, - weight_actual, - diff - ); - } } - - // Verify that commits storage is empty - let cur_epoch = SubtensorModule::get_epoch_index( - netuid, - SubtensorModule::get_current_block_as_u64(), - ); - let commits = CRV3WeightCommitsV2::::get(netuid, cur_epoch); - assert!( - commits.is_empty(), - "Expected no commits left in storage after reveal" - ); }); } @@ -6437,3 +6286,524 @@ fn test_get_first_block_of_epoch_step_blocks_and_assert_with_until_next() { } }); } + +#[test] +fn test_reveal_crv3_commits_hotkey_check() { + new_test_ext(100).execute_with(|| { + // Failure case: hotkey mismatch + let netuid = NetUid::from(1); + let hotkey1: AccountId = U256::from(1); + let hotkey2: AccountId = U256::from(2); + let reveal_round: u64 = 1000; + + add_network(netuid, 5, 0); + register_ok_neuron(netuid, hotkey1, U256::from(3), 100_000); + register_ok_neuron(netuid, hotkey2, U256::from(4), 100_000); + SubtensorModule::set_stake_threshold(0); + SubtensorModule::set_weights_set_rate_limit(netuid, 0); + SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); + SubtensorModule::set_reveal_period(netuid, 3); + + let neuron_uid1 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey1) + .expect("Failed to get neuron UID for hotkey1"); + let neuron_uid2 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey2) + .expect("Failed to get neuron UID for hotkey2"); + + SubtensorModule::set_validator_permit_for_uid(netuid, neuron_uid1, true); + SubtensorModule::set_validator_permit_for_uid(netuid, neuron_uid2, true); + SubtensorModule::add_balance_to_coldkey_account(&U256::from(3), 1); + SubtensorModule::add_balance_to_coldkey_account(&U256::from(4), 1); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey1, + &(U256::from(3)), + netuid, + 1.into(), + ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey2, + &(U256::from(4)), + netuid, + 1.into(), + ); + + let version_key = SubtensorModule::get_weights_version_key(netuid); + + let payload = WeightsTlockPayload { + hotkey: hotkey2.encode(), // Mismatch: using hotkey2 instead of hotkey1 + values: vec![10, 20], + uids: vec![neuron_uid1, neuron_uid2], + version_key, + }; + + let serialized_payload = payload.encode(); + + let esk = [2; 32]; + let rng = ChaCha20Rng::seed_from_u64(0); + + let pk_bytes = hex::decode("83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a") + .expect("Failed to decode public key bytes"); + let pub_key = ::PublicKeyGroup::deserialize_compressed(&*pk_bytes) + .expect("Failed to deserialize public key"); + + let message = { + let mut hasher = sha2::Sha256::new(); + hasher.update(reveal_round.to_be_bytes()); + hasher.finalize().to_vec() + }; + let identity = Identity::new(b"", vec![message]); + + let ct = tle::( + pub_key, + esk, + &serialized_payload, + identity, + rng, + ) + .expect("Encryption failed"); + + let mut commit_bytes = Vec::new(); + ct.serialize_compressed(&mut commit_bytes) + .expect("Failed to serialize commit"); + + assert!( + !commit_bytes.is_empty(), + "commit_bytes is empty after serialization" + ); + + log::debug!( + "Commit bytes now contain {commit_bytes:#?}" + ); + + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(hotkey1), + netuid, + commit_bytes.clone().try_into().expect("Failed to convert commit bytes into bounded vector"), + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() + )); + + let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") + .expect("Failed to decode signature bytes"); + + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().expect("Failed to convert randomness vector"), + signature: sig_bytes.try_into().expect("Failed to convert signature bytes"), + }, + ); + + // Step epochs to run the epoch via the blockstep + step_epochs(3, netuid); + + let weights_sparse = SubtensorModule::get_weights_sparse(netuid); + let weights = weights_sparse.get(neuron_uid1 as usize).cloned().unwrap_or_default(); + + assert!( + weights.is_empty(), + "Weights for neuron_uid1 should be empty due to hotkey mismatch." + ); + }); + + new_test_ext(100).execute_with(|| { + // Success case: hotkey match + let netuid = NetUid::from(1); + let hotkey1: AccountId = U256::from(1); + let hotkey2: AccountId = U256::from(2); + let reveal_round: u64 = 1000; + + add_network(netuid, 5, 0); + register_ok_neuron(netuid, hotkey1, U256::from(3), 100_000); + register_ok_neuron(netuid, hotkey2, U256::from(4), 100_000); + SubtensorModule::set_stake_threshold(0); + SubtensorModule::set_weights_set_rate_limit(netuid, 0); + SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); + SubtensorModule::set_reveal_period(netuid, 3); + + let neuron_uid1 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey1) + .expect("Failed to get neuron UID for hotkey1"); + let neuron_uid2 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey2) + .expect("Failed to get neuron UID for hotkey2"); + + SubtensorModule::set_validator_permit_for_uid(netuid, neuron_uid1, true); + SubtensorModule::set_validator_permit_for_uid(netuid, neuron_uid2, true); + SubtensorModule::add_balance_to_coldkey_account(&U256::from(3), 1); + SubtensorModule::add_balance_to_coldkey_account(&U256::from(4), 1); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey1, + &(U256::from(3)), + netuid, + 1.into(), + ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey2, + &(U256::from(4)), + netuid, + 1.into(), + ); + + let version_key = SubtensorModule::get_weights_version_key(netuid); + + let payload = WeightsTlockPayload { + hotkey: hotkey1.encode(), // Match: using hotkey1 + values: vec![10, 20], + uids: vec![neuron_uid1, neuron_uid2], + version_key, + }; + + let serialized_payload = payload.encode(); + + let esk = [2; 32]; + let rng = ChaCha20Rng::seed_from_u64(0); + + let pk_bytes = hex::decode("83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a") + .expect("Failed to decode public key bytes"); + let pub_key = ::PublicKeyGroup::deserialize_compressed(&*pk_bytes) + .expect("Failed to deserialize public key"); + + let message = { + let mut hasher = sha2::Sha256::new(); + hasher.update(reveal_round.to_be_bytes()); + hasher.finalize().to_vec() + }; + let identity = Identity::new(b"", vec![message]); + + let ct = tle::( + pub_key, + esk, + &serialized_payload, + identity, + rng, + ) + .expect("Encryption failed"); + + let mut commit_bytes = Vec::new(); + ct.serialize_compressed(&mut commit_bytes) + .expect("Failed to serialize commit"); + + assert!( + !commit_bytes.is_empty(), + "commit_bytes is empty after serialization" + ); + + log::debug!( + "Commit bytes now contain {commit_bytes:#?}" + ); + + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(hotkey1), + netuid, + commit_bytes.clone().try_into().expect("Failed to convert commit bytes into bounded vector"), + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() + )); + + let sig_bytes = hex::decode("b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e342b73a8dd2bacbe47e4b6b63ed5e39") + .expect("Failed to decode signature bytes"); + + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().expect("Failed to convert randomness vector"), + signature: sig_bytes.try_into().expect("Failed to convert signature bytes"), + }, + ); + + // Step epochs to run the epoch via the blockstep + step_epochs(3, netuid); + + let weights_sparse = SubtensorModule::get_weights_sparse(netuid); + let weights = weights_sparse.get(neuron_uid1 as usize).cloned().unwrap_or_default(); + + assert!( + !weights.is_empty(), + "Weights for neuron_uid1 are empty, expected weights to be set." + ); + + let expected_weights: Vec<(u16, I32F32)> = payload + .uids + .iter() + .zip(payload.values.iter()) + .map(|(&uid, &value)| (uid, I32F32::from_num(value))) + .collect(); + + let total_weight: I32F32 = weights.iter().map(|(_, w)| *w).sum(); + + let normalized_weights: Vec<(u16, I32F32)> = weights + .iter() + .map(|&(uid, w)| (uid, w * I32F32::from_num(30) / total_weight)) + .collect(); + + for ((uid_a, w_a), (uid_b, w_b)) in normalized_weights.iter().zip(expected_weights.iter()) { + assert_eq!(uid_a, uid_b); + + let actual_weight_f64: f64 = w_a.to_num::(); + let rounded_actual_weight = actual_weight_f64.round() as i64; + + assert!( + rounded_actual_weight != 0, + "Actual weight for uid {uid_a} is zero" + ); + + let expected_weight = w_b.to_num::(); + + assert_eq!( + rounded_actual_weight, expected_weight, + "Weight mismatch for uid {uid_a}: expected {expected_weight}, got {rounded_actual_weight}" + ); + } + }); +} + +#[test] +fn test_reveal_crv3_commits_retry_on_missing_pulse() { + new_test_ext(100).execute_with(|| { + let netuid = NetUid::from(1); + let hotkey: AccountId = U256::from(1); + let reveal_round: u64 = 1_000; + + // ─── network & neuron ─────────────────────────────────────────────── + add_network(netuid, 5, 0); + register_ok_neuron(netuid, hotkey, U256::from(3), 100_000); + SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); + SubtensorModule::set_reveal_period(netuid, 3); + SubtensorModule::set_weights_set_rate_limit(netuid, 0); + SubtensorModule::set_stake_threshold(0); + + let uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey).unwrap(); + SubtensorModule::set_validator_permit_for_uid(netuid, uid, true); + + // ─── craft commit ─────────────────────────────────────────────────── + let payload = WeightsTlockPayload { + hotkey: hotkey.encode(), + values: vec![10], + uids: vec![uid], + version_key: SubtensorModule::get_weights_version_key(netuid), + }; + let esk = [2u8; 32]; + let pk_bytes = hex::decode( + "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c\ + 8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb\ + 5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a", + ) + .unwrap(); + let pk = + ::PublicKeyGroup::deserialize_compressed(&*pk_bytes).unwrap(); + let id_msg = { + let mut h = sha2::Sha256::new(); + h.update(reveal_round.to_be_bytes()); + h.finalize().to_vec() + }; + let ct = tle::( + pk, + esk, + &payload.encode(), + Identity::new(b"", vec![id_msg]), + ChaCha20Rng::seed_from_u64(0), + ) + .unwrap(); + let mut commit_bytes = Vec::new(); + ct.serialize_compressed(&mut commit_bytes).unwrap(); + + // submit commit + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(hotkey), + netuid, + commit_bytes.clone().try_into().unwrap(), + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() + )); + + // epoch in which commit was stored + let stored_epoch = CRV3WeightCommitsV2::::iter_prefix(netuid) + .next() + .map(|(e, _)| e) + .expect("commit stored"); + + // first block of reveal epoch (commit_epoch + RP) + let first_reveal_epoch = stored_epoch + SubtensorModule::get_reveal_period(netuid); + let first_reveal_block = + SubtensorModule::get_first_block_of_epoch(netuid, first_reveal_epoch); + run_to_block_no_epoch(netuid, first_reveal_block); + + // run *one* block inside reveal epoch without pulse → commit should stay queued + step_block(1); + assert!( + !CRV3WeightCommitsV2::::get(netuid, stored_epoch).is_empty(), + "commit must remain queued when pulse is missing" + ); + + // ─── insert pulse & step one more block ───────────────────────────── + let sig_bytes = hex::decode( + "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e\ + 342b73a8dd2bacbe47e4b6b63ed5e39", + ) + .unwrap(); + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().unwrap(), + signature: sig_bytes.try_into().unwrap(), + }, + ); + + step_block(1); // automatic reveal runs here + + let weights = SubtensorModule::get_weights_sparse(netuid) + .get(uid as usize) + .cloned() + .unwrap_or_default(); + assert!(!weights.is_empty(), "weights must be set after pulse"); + + assert!( + CRV3WeightCommitsV2::::get(netuid, stored_epoch).is_empty(), + "queue should be empty after successful reveal" + ); + }); +} + +#[test] +fn test_reveal_crv3_commits_legacy_payload_success() { + new_test_ext(100).execute_with(|| { + // ───────────────────────────────────── + // 1 ▸ network + neurons + // ───────────────────────────────────── + let netuid = NetUid::from(1); + let hotkey1: AccountId = U256::from(1); + let hotkey2: AccountId = U256::from(2); + let reveal_round: u64 = 1_000; + + add_network(netuid, /*tempo*/ 5, /*modality*/ 0); + register_ok_neuron(netuid, hotkey1, U256::from(3), 100_000); + register_ok_neuron(netuid, hotkey2, U256::from(4), 100_000); + + SubtensorModule::set_stake_threshold(0); + SubtensorModule::set_weights_set_rate_limit(netuid, 0); + SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); + SubtensorModule::set_reveal_period(netuid, 3); + + let uid1 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey1).unwrap(); + let uid2 = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey2).unwrap(); + + SubtensorModule::set_validator_permit_for_uid(netuid, uid1, true); + SubtensorModule::set_validator_permit_for_uid(netuid, uid2, true); + + SubtensorModule::add_balance_to_coldkey_account(&U256::from(3), 1); + SubtensorModule::add_balance_to_coldkey_account(&U256::from(4), 1); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey1, + &U256::from(3), + netuid, + 1.into(), + ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey2, + &U256::from(4), + netuid, + 1.into(), + ); + + // ───────────────────────────────────── + // 2 ▸ craft legacy payload (NO hotkey) + // ───────────────────────────────────── + let legacy_payload = LegacyWeightsTlockPayload { + uids: vec![uid1, uid2], + values: vec![10, 20], + version_key: SubtensorModule::get_weights_version_key(netuid), + }; + let serialized_payload = legacy_payload.encode(); + + // encrypt with TLE + let esk = [2u8; 32]; + let rng = ChaCha20Rng::seed_from_u64(0); + + let pk_bytes = hex::decode( + "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c\ + 8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb\ + 5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a", + ) + .unwrap(); + let pk = + ::PublicKeyGroup::deserialize_compressed(&*pk_bytes).unwrap(); + + let msg_hash = { + let mut h = sha2::Sha256::new(); + h.update(reveal_round.to_be_bytes()); + h.finalize().to_vec() + }; + let identity = Identity::new(b"", vec![msg_hash]); + + let ct = tle::( + pk, + esk, + &serialized_payload, + identity, + rng, + ) + .expect("encryption must succeed"); + + let mut commit_bytes = Vec::new(); + ct.serialize_compressed(&mut commit_bytes).unwrap(); + let bounded_commit: BoundedVec<_, ConstU32> = + commit_bytes.clone().try_into().unwrap(); + + // ───────────────────────────────────── + // 3 ▸ put commit on‑chain + // ───────────────────────────────────── + assert_ok!(SubtensorModule::do_commit_timelocked_weights( + RuntimeOrigin::signed(hotkey1), + netuid, + bounded_commit, + reveal_round, + SubtensorModule::get_commit_reveal_weights_version() + )); + + // insert pulse so reveal can succeed the first time + let sig_bytes = hex::decode( + "b44679b9a59af2ec876b1a6b1ad52ea9b1615fc3982b19576350f93447cb1125e3\ + 42b73a8dd2bacbe47e4b6b63ed5e39", + ) + .unwrap(); + pallet_drand::Pulses::::insert( + reveal_round, + Pulse { + round: reveal_round, + randomness: vec![0; 32].try_into().unwrap(), + signature: sig_bytes.try_into().unwrap(), + }, + ); + + let commit_block = SubtensorModule::get_current_block_as_u64(); + let commit_epoch = SubtensorModule::get_epoch_index(netuid, commit_block); + + // ───────────────────────────────────── + // 4 ▸ advance epochs to trigger reveal + // ───────────────────────────────────── + step_epochs(3, netuid); + + // ───────────────────────────────────── + // 5 ▸ assertions + // ───────────────────────────────────── + let weights_sparse = SubtensorModule::get_weights_sparse(netuid); + let w1 = weights_sparse + .get(uid1 as usize) + .cloned() + .unwrap_or_default(); + assert!(!w1.is_empty(), "weights must be set for uid1"); + + // find raw values for uid1 & uid2 + let w_map: std::collections::HashMap<_, _> = w1.into_iter().collect(); + let v1 = *w_map.get(&uid1).expect("uid1 weight"); + let v2 = *w_map.get(&uid2).expect("uid2 weight"); + assert!(v2 > v1, "uid2 weight should be greater than uid1 (20 > 10)"); + + // commit should be gone + assert!( + CRV3WeightCommitsV2::::get(netuid, commit_epoch).is_empty(), + "commit storage should be cleaned after reveal" + ); + }); +} diff --git a/pallets/subtensor/src/utils/identity.rs b/pallets/subtensor/src/utils/identity.rs index 059fe2a7a2..1904d0e682 100644 --- a/pallets/subtensor/src/utils/identity.rs +++ b/pallets/subtensor/src/utils/identity.rs @@ -138,7 +138,7 @@ impl Pallet { SubnetIdentitiesV3::::insert(netuid, identity.clone()); // Log the identity set event - log::debug!("SubnetIdentitySet( netuid:{:?} ) ", netuid); + log::debug!("SubnetIdentitySet( netuid:{netuid:?} ) "); // Emit an event to notify that an identity has been set Self::deposit_event(Event::SubnetIdentitySet(netuid)); diff --git a/pallets/subtensor/src/utils/misc.rs b/pallets/subtensor/src/utils/misc.rs index 2481d56a6c..c7b93535f3 100644 --- a/pallets/subtensor/src/utils/misc.rs +++ b/pallets/subtensor/src/utils/misc.rs @@ -8,7 +8,7 @@ use sp_core::Get; use sp_core::U256; use sp_runtime::Saturating; use substrate_fixed::types::{I32F32, U96F32}; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; impl Pallet { pub fn ensure_subnet_owner_or_root( @@ -71,7 +71,7 @@ impl Pallet { // ======================== // ==== Global Getters ==== // ======================== - pub fn get_total_issuance() -> u64 { + pub fn get_total_issuance() -> TaoCurrency { TotalIssuance::::get() } pub fn get_current_block_as_u64() -> u64 { @@ -137,12 +137,12 @@ impl Pallet { Active::::insert(netuid, updated_active_vec); } pub fn set_pruning_score_for_uid(netuid: NetUid, uid: u16, pruning_score: u16) { - log::debug!("netuid = {:?}", netuid); + log::debug!("netuid = {netuid:?}"); log::debug!( "SubnetworkN::::get( netuid ) = {:?}", SubnetworkN::::get(netuid) ); - log::debug!("uid = {:?}", uid); + log::debug!("uid = {uid:?}"); assert!(uid < SubnetworkN::::get(netuid)); PruningScores::::mutate(netuid, |v| { if let Some(s) = v.get_mut(uid as usize) { @@ -270,25 +270,25 @@ impl Pallet { // ======================== // === Token Management === // ======================== - pub fn burn_tokens(amount: u64) { + pub fn burn_tokens(amount: TaoCurrency) { TotalIssuance::::put(TotalIssuance::::get().saturating_sub(amount)); } - pub fn coinbase(amount: u64) { + pub fn coinbase(amount: TaoCurrency) { TotalIssuance::::put(TotalIssuance::::get().saturating_add(amount)); } - pub fn set_subnet_locked_balance(netuid: NetUid, amount: u64) { + pub fn set_subnet_locked_balance(netuid: NetUid, amount: TaoCurrency) { SubnetLocked::::insert(netuid, amount); } - pub fn get_subnet_locked_balance(netuid: NetUid) -> u64 { + pub fn get_subnet_locked_balance(netuid: NetUid) -> TaoCurrency { SubnetLocked::::get(netuid) } - pub fn get_total_subnet_locked() -> u64 { + pub fn get_total_subnet_locked() -> TaoCurrency { let mut total_subnet_locked: u64 = 0; for (_, locked) in SubnetLocked::::iter() { - total_subnet_locked.saturating_accrue(locked); + total_subnet_locked.saturating_accrue(locked.into()); } - total_subnet_locked + total_subnet_locked.into() } // ======================== @@ -481,7 +481,13 @@ impl Pallet { CommitRevealWeightsEnabled::::set(netuid, enabled); Self::deposit_event(Event::CommitRevealEnabled(netuid, enabled)); } - + pub fn get_commit_reveal_weights_version() -> u16 { + CommitRevealWeightsVersion::::get() + } + pub fn set_commit_reveal_weights_version(version: u16) { + CommitRevealWeightsVersion::::set(version); + Self::deposit_event(Event::CommitRevealVersionSet(version)); + } pub fn get_rho(netuid: NetUid) -> u16 { Rho::::get(netuid) } @@ -528,25 +534,25 @@ impl Pallet { )); } - pub fn get_burn_as_u64(netuid: NetUid) -> u64 { + pub fn get_burn(netuid: NetUid) -> TaoCurrency { Burn::::get(netuid) } - pub fn set_burn(netuid: NetUid, burn: u64) { + pub fn set_burn(netuid: NetUid, burn: TaoCurrency) { Burn::::insert(netuid, burn); } - pub fn get_min_burn_as_u64(netuid: NetUid) -> u64 { + pub fn get_min_burn(netuid: NetUid) -> TaoCurrency { MinBurn::::get(netuid) } - pub fn set_min_burn(netuid: NetUid, min_burn: u64) { + pub fn set_min_burn(netuid: NetUid, min_burn: TaoCurrency) { MinBurn::::insert(netuid, min_burn); Self::deposit_event(Event::MinBurnSet(netuid, min_burn)); } - pub fn get_max_burn_as_u64(netuid: NetUid) -> u64 { + pub fn get_max_burn(netuid: NetUid) -> TaoCurrency { MaxBurn::::get(netuid) } - pub fn set_max_burn(netuid: NetUid, max_burn: u64) { + pub fn set_max_burn(netuid: NetUid, max_burn: TaoCurrency) { MaxBurn::::insert(netuid, max_burn); Self::deposit_event(Event::MaxBurnSet(netuid, max_burn)); } @@ -627,18 +633,18 @@ impl Pallet { StakingHotkeys::::get(coldkey) } - pub fn set_total_issuance(total_issuance: u64) { + pub fn set_total_issuance(total_issuance: TaoCurrency) { TotalIssuance::::put(total_issuance); } - pub fn get_rao_recycled(netuid: NetUid) -> u64 { + pub fn get_rao_recycled(netuid: NetUid) -> TaoCurrency { RAORecycledForRegistration::::get(netuid) } - pub fn set_rao_recycled(netuid: NetUid, rao_recycled: u64) { + pub fn set_rao_recycled(netuid: NetUid, rao_recycled: TaoCurrency) { RAORecycledForRegistration::::insert(netuid, rao_recycled); Self::deposit_event(Event::RAORecycledForRegistrationSet(netuid, rao_recycled)); } - pub fn increase_rao_recycled(netuid: NetUid, inc_rao_recycled: u64) { + pub fn increase_rao_recycled(netuid: NetUid, inc_rao_recycled: TaoCurrency) { let curr_rao_recycled = Self::get_rao_recycled(netuid); let rao_recycled = curr_rao_recycled.saturating_add(inc_rao_recycled); Self::set_rao_recycled(netuid, rao_recycled); @@ -678,6 +684,7 @@ impl Pallet { // Return the default minimum stake multiplied by factor // 21M * 10^9 * 10^6 fits u64, hence no need for fixed type usage here DefaultMinStake::::get() + .to_u64() .saturating_mul(factor) .safe_div(1_000_000) } @@ -686,8 +693,8 @@ impl Pallet { NominatorMinRequiredStake::::put(min_stake); } - pub fn get_key_swap_cost() -> u64 { - T::KeySwapCost::get() + pub fn get_key_swap_cost() -> TaoCurrency { + T::KeySwapCost::get().into() } pub fn get_alpha_values(netuid: NetUid) -> (u16, u16) { diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 6136d7bd50..4ade47eeef 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -10,14 +10,15 @@ impl Pallet { let currency_issuance = ::Currency::total_issuance(); // Calculate the expected total issuance - let expected_total_issuance = currency_issuance.saturating_add(TotalStake::::get()); + let expected_total_issuance = + currency_issuance.saturating_add(TotalStake::::get().into()); // Verify the diff between calculated TI and actual TI is less than delta // // These values can be off slightly due to float rounding errors. // They are corrected every runtime upgrade. let delta = 1000; - let total_issuance = TotalIssuance::::get(); + let total_issuance = TotalIssuance::::get().to_u64(); let diff = if total_issuance > expected_total_issuance { total_issuance.checked_sub(expected_total_issuance) @@ -38,16 +39,17 @@ impl Pallet { #[allow(dead_code)] pub(crate) fn check_total_stake() -> Result<(), sp_runtime::TryRuntimeError> { // Calculate the total staked amount - let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { - let acc = acc.saturating_add(stake); + let total_staked = + SubnetTAO::::iter().fold(TaoCurrency::ZERO, |acc, (netuid, stake)| { + let acc = acc.saturating_add(stake); - if netuid.is_root() { - // root network doesn't have initial pool TAO - acc - } else { - acc.saturating_sub(Self::get_network_min_lock()) - } - }); + if netuid.is_root() { + // root network doesn't have initial pool TAO + acc + } else { + acc.saturating_sub(Self::get_network_min_lock()) + } + }); log::warn!( "total_staked: {}, TotalStake: {}", diff --git a/pallets/swap-interface/Cargo.toml b/pallets/swap-interface/Cargo.toml index 5af146881c..a5ae9ac75f 100644 --- a/pallets/swap-interface/Cargo.toml +++ b/pallets/swap-interface/Cargo.toml @@ -4,11 +4,11 @@ version = "0.1.0" edition.workspace = true [dependencies] -codec = { workspace = true } -frame-support = { workspace = true } -scale-info = { workspace = true } -substrate-fixed = { workspace = true } -subtensor-runtime-common = { workspace = true } +codec = { workspace = true, features = ["derive"] } +frame-support.workspace = true +scale-info.workspace = true +substrate-fixed.workspace = true +subtensor-runtime-common.workspace = true [lints] workspace = true diff --git a/pallets/swap-interface/src/lib.rs b/pallets/swap-interface/src/lib.rs index fce3d53f18..a0b39e151f 100644 --- a/pallets/swap-interface/src/lib.rs +++ b/pallets/swap-interface/src/lib.rs @@ -2,7 +2,7 @@ use frame_support::pallet_prelude::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OrderType { @@ -28,7 +28,11 @@ pub trait SwapHandler { fn current_alpha_price(netuid: NetUid) -> U96F32; fn max_price() -> u64; fn min_price() -> u64; - fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: AlphaCurrency); + fn adjust_protocol_liquidity( + netuid: NetUid, + tao_delta: TaoCurrency, + alpha_delta: AlphaCurrency, + ); fn is_user_liquidity_enabled(netuid: NetUid) -> bool; } diff --git a/pallets/swap/Cargo.toml b/pallets/swap/Cargo.toml index 7cf8e98191..a013b8468e 100644 --- a/pallets/swap/Cargo.toml +++ b/pallets/swap/Cargo.toml @@ -1,33 +1,33 @@ [package] name = "pallet-subtensor-swap" version = "0.1.0" -edition = { workspace = true } +edition.workspace = true [dependencies] -alloy-primitives = { workspace = true } -approx = { workspace = true } -codec = { workspace = true } +alloy-primitives.workspace = true +approx.workspace = true +codec = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true, optional = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -log = { workspace = true } -safe-math = { workspace = true } -scale-info = { workspace = true } +frame-support.workspace = true +frame-system.workspace = true +log.workspace = true +safe-math.workspace = true +scale-info = { workspace = true, features = ["derive"] } serde = { workspace = true, optional = true } -sp-arithmetic = { workspace = true } -sp-core = { workspace = true } -sp-io = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -substrate-fixed = { workspace = true } +sp-arithmetic.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true +substrate-fixed.workspace = true -pallet-subtensor-swap-runtime-api = { workspace = true } -subtensor-macros = { workspace = true } -subtensor-runtime-common = {workspace = true} -subtensor-swap-interface = { workspace = true } +pallet-subtensor-swap-runtime-api.workspace = true +subtensor-macros.workspace = true +subtensor-runtime-common.workspace = true +subtensor-swap-interface.workspace = true [dev-dependencies] -sp-tracing = { workspace = true } +sp-tracing.workspace = true [lints] workspace = true diff --git a/pallets/swap/rpc/Cargo.toml b/pallets/swap/rpc/Cargo.toml index cc5fbc9067..8c1b692f60 100644 --- a/pallets/swap/rpc/Cargo.toml +++ b/pallets/swap/rpc/Cargo.toml @@ -2,15 +2,15 @@ name = "pallet-subtensor-swap-rpc" version = "1.0.0" description = "RPC interface for the Swap pallet" -edition = { workspace = true } +edition.workspace = true [dependencies] -codec = { workspace = true } -jsonrpsee = { workspace = true } -sp-api = { workspace = true } -sp-blockchain = { workspace = true } -sp-runtime = { workspace = true } -pallet-subtensor-swap-runtime-api = { workspace = true } +codec = { workspace = true, features = ["derive"] } +jsonrpsee.workspace = true +sp-api.workspace = true +sp-blockchain.workspace = true +sp-runtime.workspace = true +pallet-subtensor-swap-runtime-api.workspace = true [features] default = ["std"] diff --git a/pallets/swap/rpc/src/lib.rs b/pallets/swap/rpc/src/lib.rs index e8fa85493d..a2825062db 100644 --- a/pallets/swap/rpc/src/lib.rs +++ b/pallets/swap/rpc/src/lib.rs @@ -72,7 +72,7 @@ where let at = at.unwrap_or_else(|| self.client.info().best_hash); api.current_alpha_price(at, netuid).map_err(|e| { - Error::RuntimeError(format!("Unable to get current alpha price: {:?}", e)).into() + Error::RuntimeError(format!("Unable to get current alpha price: {e:?}")).into() }) } } diff --git a/pallets/swap/runtime-api/Cargo.toml b/pallets/swap/runtime-api/Cargo.toml index d871adb651..6030f5ab88 100644 --- a/pallets/swap/runtime-api/Cargo.toml +++ b/pallets/swap/runtime-api/Cargo.toml @@ -2,19 +2,14 @@ name = "pallet-subtensor-swap-runtime-api" version = "1.0.0" description = "Runtime API for the Swap pallet" -edition = { workspace = true } +edition.workspace = true [dependencies] -codec = { workspace = true } -scale-info = { workspace = true } -sp-api = { workspace = true } -sp-std = { workspace = true } +codec = { workspace = true, features = ["derive"] } +scale-info.workspace = true +sp-api.workspace = true +sp-std.workspace = true [features] default = ["std"] -std = [ - "codec/std", - "scale-info/std", - "sp-api/std", - "sp-std/std", -] +std = ["codec/std", "scale-info/std", "sp-api/std", "sp-std/std"] diff --git a/pallets/swap/src/mock.rs b/pallets/swap/src/mock.rs index 014c6ce4fe..78a8f925c8 100644 --- a/pallets/swap/src/mock.rs +++ b/pallets/swap/src/mock.rs @@ -14,7 +14,7 @@ use sp_runtime::{ BuildStorage, traits::{BlakeTwo256, IdentityLookup}, }; -use subtensor_runtime_common::{AlphaCurrency, BalanceOps, NetUid, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, BalanceOps, NetUid, SubnetInfo, TaoCurrency}; use crate::pallet::EnabledUserLiquidity; @@ -87,12 +87,13 @@ parameter_types! { pub struct MockLiquidityProvider; impl SubnetInfo for MockLiquidityProvider { - fn tao_reserve(netuid: NetUid) -> u64 { + fn tao_reserve(netuid: NetUid) -> TaoCurrency { match netuid.into() { 123u16 => 10_000, WRAPPING_FEES_NETUID => 100_000_000_000, _ => 1_000_000_000_000, } + .into() } fn alpha_reserve(netuid: NetUid) -> AlphaCurrency { @@ -119,13 +120,14 @@ impl SubnetInfo for MockLiquidityProvider { pub struct MockBalanceOps; impl BalanceOps for MockBalanceOps { - fn tao_balance(account_id: &AccountId) -> u64 { + fn tao_balance(account_id: &AccountId) -> TaoCurrency { match *account_id { OK_COLDKEY_ACCOUNT_ID => 100_000_000_000_000, OK_COLDKEY_ACCOUNT_ID_2 => 100_000_000_000_000, OK_COLDKEY_ACCOUNT_ID_RICH => 900_000_000_000_000_000_u64, _ => 1_000_000_000, } + .into() } fn alpha_balance( @@ -144,9 +146,12 @@ impl BalanceOps for MockBalanceOps { .into() } - fn increase_balance(_coldkey: &AccountId, _tao: u64) {} + fn increase_balance(_coldkey: &AccountId, _tao: TaoCurrency) {} - fn decrease_balance(_coldkey: &AccountId, tao: u64) -> Result { + fn decrease_balance( + _coldkey: &AccountId, + tao: TaoCurrency, + ) -> Result { Ok(tao) } @@ -168,8 +173,8 @@ impl BalanceOps for MockBalanceOps { Ok(alpha) } - fn increase_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} - fn decrease_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} + fn increase_provided_tao_reserve(_netuid: NetUid, _tao: TaoCurrency) {} + fn decrease_provided_tao_reserve(_netuid: NetUid, _tao: TaoCurrency) {} fn increase_provided_alpha_reserve(_netuid: NetUid, _alpha: AlphaCurrency) {} fn decrease_provided_alpha_reserve(_netuid: NetUid, _alpha: AlphaCurrency) {} } diff --git a/pallets/swap/src/pallet/impls.rs b/pallets/swap/src/pallet/impls.rs index 32e0ec563c..deebabd673 100644 --- a/pallets/swap/src/pallet/impls.rs +++ b/pallets/swap/src/pallet/impls.rs @@ -7,7 +7,9 @@ use safe_math::*; use sp_arithmetic::helpers_128bit; use sp_runtime::traits::AccountIdConversion; use substrate_fixed::types::{I64F64, U64F64, U96F32}; -use subtensor_runtime_common::{AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo}; +use subtensor_runtime_common::{ + AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo, TaoCurrency, +}; use subtensor_swap_interface::{SwapHandler, SwapResult}; use super::pallet::*; @@ -21,9 +23,9 @@ const MAX_SWAP_ITERATIONS: u16 = 1000; #[derive(Debug, PartialEq)] pub struct UpdateLiquidityResult { - pub tao: u64, + pub tao: TaoCurrency, pub alpha: AlphaCurrency, - pub fee_tao: u64, + pub fee_tao: TaoCurrency, pub fee_alpha: AlphaCurrency, pub removed: bool, pub tick_low: TickIndex, @@ -32,9 +34,9 @@ pub struct UpdateLiquidityResult { #[derive(Debug, PartialEq)] pub struct RemoveLiquidityResult { - pub tao: u64, + pub tao: TaoCurrency, pub alpha: AlphaCurrency, - pub fee_tao: u64, + pub fee_tao: TaoCurrency, pub fee_alpha: AlphaCurrency, pub tick_low: TickIndex, pub tick_high: TickIndex, @@ -232,7 +234,7 @@ impl SwapStep { // Hold the fees Pallet::::add_fees(self.netuid, self.order_type, self.fee); let delta_out = Pallet::::convert_deltas(self.netuid, self.order_type, self.delta_in); - log::trace!("\tDelta Out : {:?}", delta_out); + log::trace!("\tDelta Out : {delta_out:?}"); if self.action == SwapStepAction::Crossing { let mut tick = Ticks::::get(self.netuid, self.edge_tick).unwrap_or_default(); @@ -336,7 +338,7 @@ impl Pallet { // Protocol liquidity makes one position from TickIndex::MIN to TickIndex::MAX // We are using the sp_arithmetic sqrt here, which works for u128 let liquidity = helpers_128bit::sqrt( - (tao_reserve as u128).saturating_mul(u64::from(alpha_reserve) as u128), + (tao_reserve.to_u64() as u128).saturating_mul(alpha_reserve.to_u64() as u128), ) as u64; let protocol_account_id = Self::protocol_account_id(); @@ -356,7 +358,7 @@ impl Pallet { /// Adjusts protocol liquidity with new values of TAO and Alpha reserve pub(super) fn adjust_protocol_liquidity( netuid: NetUid, - tao_delta: u64, + tao_delta: TaoCurrency, alpha_delta: AlphaCurrency, ) { // Update protocol position with new liquidity @@ -366,12 +368,20 @@ impl Pallet { .collect::>(); if let Some(position) = positions.get_mut(0) { + // Claim protocol fees and add them to liquidity + let (tao_fees, alpha_fees) = position.collect_fees(); + + // Adjust liquidity let current_sqrt_price = Pallet::::current_price_sqrt(netuid); let maybe_token_amounts = position.to_token_amounts(current_sqrt_price); if let Ok((tao, alpha)) = maybe_token_amounts { // Get updated reserves, calculate liquidity - let new_tao_reserve = tao.saturating_add(tao_delta); - let new_alpha_reserve = alpha.saturating_add(alpha_delta.to_u64()); + let new_tao_reserve = tao + .saturating_add(tao_delta.to_u64()) + .saturating_add(tao_fees); + let new_alpha_reserve = alpha + .saturating_add(alpha_delta.to_u64()) + .saturating_add(alpha_fees); let new_liquidity = helpers_128bit::sqrt( (new_tao_reserve as u128).saturating_mul(new_alpha_reserve as u128), ) as u64; @@ -444,8 +454,8 @@ impl Pallet { // Check if reserves are overused if let Ok(ref swap_result) = result { let checked_reserve = match order_type { - OrderType::Buy => u64::from(alpha_reserve), - OrderType::Sell => tao_reserve, + OrderType::Buy => alpha_reserve.to_u64(), + OrderType::Sell => tao_reserve.to_u64(), }; if checked_reserve < swap_result.amount_paid_out { @@ -467,12 +477,13 @@ impl Pallet { ) -> Result> { match order_type { OrderType::Buy => ensure!( - u64::from(T::SubnetInfo::alpha_reserve(netuid.into())) + T::SubnetInfo::alpha_reserve(netuid.into()).to_u64() >= T::MinimumReserve::get().get(), Error::::ReservesTooLow ), OrderType::Sell => ensure!( - T::SubnetInfo::tao_reserve(netuid.into()) >= T::MinimumReserve::get().get(), + T::SubnetInfo::tao_reserve(netuid.into()).to_u64() + >= T::MinimumReserve::get().get(), Error::::ReservesTooLow ), } @@ -498,11 +509,11 @@ impl Pallet { let mut fee_acc: u64 = 0; log::trace!("======== Start Swap ========"); - log::trace!("Amount Remaining: {}", amount_remaining); + log::trace!("Amount Remaining: {amount_remaining}"); // Swap one tick at a time until we reach one of the stop conditions while amount_remaining > 0 { - log::trace!("\nIteration: {}", iteration_counter); + log::trace!("\nIteration: {iteration_counter}"); log::trace!( "\tCurrent Liquidity: {}", CurrentLiquidity::::get(netuid) @@ -541,7 +552,7 @@ impl Pallet { ); } - log::trace!("\nAmount Paid Out: {}", amount_paid_out); + log::trace!("\nAmount Paid Out: {amount_paid_out}"); log::trace!("======== End Swap ========"); let (tao_reserve_delta, alpha_reserve_delta) = match order_type { @@ -842,7 +853,7 @@ impl Pallet { let position_id = position.id; ensure!( - T::BalanceOps::tao_balance(coldkey_account_id) >= tao + T::BalanceOps::tao_balance(coldkey_account_id) >= TaoCurrency::from(tao) && T::BalanceOps::alpha_balance( netuid.into(), coldkey_account_id, @@ -938,9 +949,9 @@ impl Pallet { Positions::::remove((netuid, coldkey_account_id, position_id)); Ok(RemoveLiquidityResult { - tao, + tao: tao.into(), alpha: alpha.into(), - fee_tao, + fee_tao: fee_tao.into(), fee_alpha: fee_alpha.into(), tick_low: position.tick_low, tick_high: position.tick_high, @@ -1010,7 +1021,8 @@ impl Pallet { if liquidity_delta > 0 { // Check that user has enough balances ensure!( - T::BalanceOps::tao_balance(coldkey_account_id) >= tao + T::BalanceOps::tao_balance(coldkey_account_id) + >= TaoCurrency::from(tao.saturating_to_num::()) && T::BalanceOps::alpha_balance(netuid, coldkey_account_id, hotkey_account_id) >= AlphaCurrency::from(alpha.saturating_to_num::()), Error::::InsufficientBalance @@ -1061,9 +1073,9 @@ impl Pallet { } Ok(UpdateLiquidityResult { - tao: tao.saturating_to_num::(), + tao: tao.saturating_to_num::().into(), alpha: alpha.saturating_to_num::().into(), - fee_tao, + fee_tao: fee_tao.into(), fee_alpha: fee_alpha.into(), removed: remove, tick_low: position.tick_low, @@ -1274,7 +1286,11 @@ impl SwapHandler for Pallet { .saturating_to_num() } - fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: AlphaCurrency) { + fn adjust_protocol_liquidity( + netuid: NetUid, + tao_delta: TaoCurrency, + alpha_delta: AlphaCurrency, + ) { Self::adjust_protocol_liquidity(netuid, tao_delta, alpha_delta); } diff --git a/pallets/swap/src/pallet/mod.rs b/pallets/swap/src/pallet/mod.rs index 1630a44c07..894099de7f 100644 --- a/pallets/swap/src/pallet/mod.rs +++ b/pallets/swap/src/pallet/mod.rs @@ -4,7 +4,9 @@ use core::ops::Neg; use frame_support::{PalletId, pallet_prelude::*, traits::Get}; use frame_system::pallet_prelude::*; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo}; +use subtensor_runtime_common::{ + AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo, TaoCurrency, +}; use crate::{ position::{Position, PositionId}, @@ -163,7 +165,7 @@ mod pallet { /// The amount of liquidity added to the position liquidity: u64, /// The amount of TAO tokens committed to the position - tao: u64, + tao: TaoCurrency, /// The amount of Alpha tokens committed to the position alpha: AlphaCurrency, /// the lower tick @@ -185,11 +187,11 @@ mod pallet { /// The amount of liquidity removed from the position liquidity: u64, /// The amount of TAO tokens returned to the user - tao: u64, + tao: TaoCurrency, /// The amount of Alpha tokens returned to the user alpha: AlphaCurrency, /// The amount of TAO fees earned from the position - fee_tao: u64, + fee_tao: TaoCurrency, /// The amount of Alpha fees earned from the position fee_alpha: AlphaCurrency, /// the lower tick @@ -216,7 +218,7 @@ mod pallet { /// The amount of Alpha tokens returned to the user alpha: i64, /// The amount of TAO fees earned from the position - fee_tao: u64, + fee_tao: TaoCurrency, /// The amount of Alpha fees earned from the position fee_alpha: AlphaCurrency, /// the lower tick @@ -373,6 +375,7 @@ mod pallet { liquidity, )?; let alpha = AlphaCurrency::from(alpha); + let tao = TaoCurrency::from(tao); // Remove TAO and Alpha balances or fail transaction if they can't be removed exactly let tao_provided = T::BalanceOps::decrease_balance(&coldkey, tao)?; @@ -509,7 +512,7 @@ mod pallet { netuid, position_id, liquidity: liquidity_delta, - tao: result.tao as i64, + tao: result.tao.to_u64() as i64, alpha: result.alpha.to_u64() as i64, fee_tao: result.fee_tao, fee_alpha: result.fee_alpha, @@ -543,7 +546,7 @@ mod pallet { netuid, position_id, liquidity: liquidity_delta, - tao: (result.tao as i64).neg(), + tao: (result.tao.to_u64() as i64).neg(), alpha: (result.alpha.to_u64() as i64).neg(), fee_tao: result.fee_tao, fee_alpha: result.fee_alpha, @@ -554,7 +557,7 @@ mod pallet { } // Credit accrued fees to user account (no matter if liquidity is added or removed) - if result.fee_tao > 0 { + if result.fee_tao > TaoCurrency::ZERO { T::BalanceOps::increase_balance(&coldkey, result.fee_tao); } if !result.fee_alpha.is_zero() { diff --git a/pallets/swap/src/pallet/tests.rs b/pallets/swap/src/pallet/tests.rs index 12bd19813a..4c3a890c9b 100644 --- a/pallets/swap/src/pallet/tests.rs +++ b/pallets/swap/src/pallet/tests.rs @@ -176,7 +176,8 @@ fn test_swap_initialization() { // Calculate expected liquidity let expected_liquidity = - helpers_128bit::sqrt((tao as u128).saturating_mul(u64::from(alpha) as u128)) as u64; + helpers_128bit::sqrt((tao.to_u64() as u128).saturating_mul(alpha.to_u64() as u128)) + as u64; // Get the protocol account let protocol_account_id = Pallet::::protocol_account_id(); @@ -515,14 +516,14 @@ fn test_remove_liquidity_basic() { let remove_result = Pallet::::do_remove_liquidity(netuid, &OK_COLDKEY_ACCOUNT_ID, position_id) .unwrap(); - assert_abs_diff_eq!(remove_result.tao, tao, epsilon = tao / 1000); + assert_abs_diff_eq!(remove_result.tao.to_u64(), tao, epsilon = tao / 1000); assert_abs_diff_eq!( u64::from(remove_result.alpha), alpha, epsilon = alpha / 1000 ); - assert_eq!(remove_result.fee_tao, 0); - assert_eq!(remove_result.fee_alpha, 0.into()); + assert_eq!(remove_result.fee_tao, TaoCurrency::ZERO); + assert_eq!(remove_result.fee_alpha, AlphaCurrency::ZERO); // Liquidity position is removed assert_eq!( @@ -654,8 +655,8 @@ fn test_modify_position_basic() { alpha / 10, epsilon = alpha / 1000 ); - assert!(modify_result.fee_tao > 0); - assert_eq!(modify_result.fee_alpha, 0.into()); + assert!(modify_result.fee_tao > TaoCurrency::ZERO); + assert_eq!(modify_result.fee_alpha, AlphaCurrency::ZERO); // Liquidity position is reduced assert_eq!( @@ -709,8 +710,8 @@ fn test_modify_position_basic() { alpha / 100, epsilon = alpha / 1000 ); - assert_eq!(modify_result.fee_tao, 0); - assert_eq!(modify_result.fee_alpha, 0.into()); + assert_eq!(modify_result.fee_tao, TaoCurrency::ZERO); + assert_eq!(modify_result.fee_alpha, AlphaCurrency::ZERO); }); }); } @@ -821,9 +822,8 @@ fn test_swap_basic() { assert_eq!( position.liquidity, helpers_128bit::sqrt( - MockLiquidityProvider::tao_reserve(netuid.into()) as u128 - * u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())) - as u128 + MockLiquidityProvider::tao_reserve(netuid.into()).to_u64() as u128 + * MockLiquidityProvider::alpha_reserve(netuid.into()).to_u64() as u128 ) as u64 ); assert_eq!(position.tick_low, tick_low); @@ -931,9 +931,9 @@ fn test_swap_single_position() { ////////////////////////////////////////////// // Initialize pool and add the user position assert_ok!(Pallet::::maybe_initialize_v3(netuid)); - let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()); + let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()).to_u64(); let alpha_reserve = - u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())); + MockLiquidityProvider::alpha_reserve(netuid.into()).to_u64(); let protocol_liquidity = (tao_reserve as f64 * alpha_reserve as f64).sqrt(); // Add liquidity @@ -1236,8 +1236,8 @@ fn test_swap_multiple_positions() { epsilon = output_amount / 10. ); - let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()); - let alpha_reserve = u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())); + let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()).to_u64(); + let alpha_reserve = MockLiquidityProvider::alpha_reserve(netuid.into()).to_u64(); let output_amount = output_amount as u64; assert!(output_amount > 0); @@ -1715,7 +1715,7 @@ fn bbox(t: U64F64, a: U64F64, b: U64F64) -> U64F64 { fn print_current_price(netuid: NetUid) { let current_sqrt_price = Pallet::::current_price_sqrt(netuid).to_num::(); let current_price = current_sqrt_price * current_sqrt_price; - log::trace!("Current price: {:.6}", current_price); + log::trace!("Current price: {current_price:.6}"); } /// RUST_LOG=pallet_subtensor_swap=trace cargo test --package pallet-subtensor-swap --lib -- pallet::tests::test_wrapping_fees --exact --show-output --nocapture @@ -1797,7 +1797,7 @@ fn test_wrapping_fees() { let fee_rate = FeeRate::::get(netuid) as f64 / u16::MAX as f64; - log::trace!("fee_rate: {:.6}", fee_rate); + log::trace!("fee_rate: {fee_rate:.6}"); log::trace!("position.liquidity: {}", position.liquidity); log::trace!( "initial_box_price: {:.6}", @@ -1819,7 +1819,7 @@ fn test_wrapping_fees() { let (fee_tao, fee_alpha) = position.collect_fees(); - log::trace!("Collected fees: TAO: {}, ALPHA: {}", fee_tao, fee_alpha); + log::trace!("Collected fees: TAO: {fee_tao}, ALPHA: {fee_alpha}"); assert_abs_diff_eq!(fee_tao, expected_fee_tao, epsilon = 1); assert_abs_diff_eq!(fee_alpha, expected_fee_alpha, epsilon = 1); diff --git a/pallets/swap/src/position.rs b/pallets/swap/src/position.rs index 542aa389ad..5a57928a93 100644 --- a/pallets/swap/src/position.rs +++ b/pallets/swap/src/position.rs @@ -1,6 +1,6 @@ use core::marker::PhantomData; -use codec::{Decode, Encode, MaxEncodedLen}; +use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use frame_support::pallet_prelude::*; use safe_math::*; use substrate_fixed::types::{I64F64, U64F64}; @@ -159,9 +159,19 @@ impl Position { } } -#[freeze_struct("1f02550d787d80da")] +#[freeze_struct("8501fa251c9d74c")] #[derive( - Clone, Copy, Decode, Default, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Default, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, )] pub struct PositionId(u128); diff --git a/pallets/swap/src/tick.rs b/pallets/swap/src/tick.rs index 20a19007d7..d3493fde45 100644 --- a/pallets/swap/src/tick.rs +++ b/pallets/swap/src/tick.rs @@ -7,7 +7,7 @@ use core::hash::Hash; use core::ops::{Add, AddAssign, BitOr, Deref, Neg, Shl, Shr, Sub, SubAssign}; use alloy_primitives::{I256, U256}; -use codec::{Decode, Encode, Error as CodecError, Input, MaxEncodedLen}; +use codec::{Decode, DecodeWithMemTracking, Encode, Error as CodecError, Input, MaxEncodedLen}; use frame_support::pallet_prelude::*; use safe_math::*; use sp_std::vec; @@ -95,13 +95,14 @@ impl Tick { } /// Struct representing a tick index -#[freeze_struct("31577b3ad1f55092")] +#[freeze_struct("13c1f887258657f2")] #[derive( Debug, Default, Clone, Copy, Encode, + DecodeWithMemTracking, TypeInfo, MaxEncodedLen, PartialEq, diff --git a/pallets/transaction-fee/Cargo.toml b/pallets/transaction-fee/Cargo.toml new file mode 100644 index 0000000000..b5f08ac7c3 --- /dev/null +++ b/pallets/transaction-fee/Cargo.toml @@ -0,0 +1,85 @@ +[package] +name = "subtensor-transaction-fee" +version = "0.1.0" +edition.workspace = true + +[dependencies] +codec.workspace = true +frame-support.workspace = true +frame-system.workspace = true +log.workspace = true +pallet-balances = { workspace = true, default-features = false } +pallet-subtensor.workspace = true +pallet-subtensor-swap.workspace = true +pallet-transaction-payment.workspace = true +smallvec.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true +substrate-fixed.workspace = true +subtensor-runtime-common.workspace = true +subtensor-swap-interface.workspace = true +pallet-crowdloan = { workspace = true, default-features = false } +pallet-drand = { workspace = true, default-features = false } +pallet-grandpa = { workspace = true, default-features = false, optional = true } +pallet-preimage = { workspace = true, default-features = false, optional = true } +pallet-scheduler = { workspace = true, default-features = false, optional = true } + +[dev-dependencies] +frame-executive.workspace = true +pallet-evm-chain-id.workspace = true +scale-info.workspace = true +sp-consensus-aura.workspace = true +sp-consensus-grandpa.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-tracing.workspace = true +sp-weights.workspace = true + +[lints] +workspace = true + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-executive/std", + "frame-support/std", + "frame-system/std", + "log/std", + "pallet-balances/std", + "pallet-crowdloan/std", + "pallet-drand/std", + "pallet-evm-chain-id/std", + "pallet-grandpa/std", + "pallet-preimage/std", + "pallet-scheduler/std", + "pallet-subtensor/std", + "pallet-subtensor-swap/std", + "pallet-transaction-payment/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", + "sp-consensus-aura/std", + "sp-consensus-grandpa/std", + "sp-core/std", + "sp-io/std", + "sp-tracing/std", + "sp-weights/std", + "substrate-fixed/std", + "subtensor-runtime-common/std", + "subtensor-swap-interface/std", +] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "pallet-transaction-payment/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-crowdloan/runtime-benchmarks", + "pallet-drand/runtime-benchmarks", + "pallet-grandpa/runtime-benchmarks", + "pallet-preimage/runtime-benchmarks", + "pallet-scheduler/runtime-benchmarks", + "pallet-subtensor/runtime-benchmarks", + "pallet-subtensor-swap/runtime-benchmarks", +] diff --git a/pallets/transaction-fee/src/lib.rs b/pallets/transaction-fee/src/lib.rs new file mode 100644 index 0000000000..42ba69c841 --- /dev/null +++ b/pallets/transaction-fee/src/lib.rs @@ -0,0 +1,419 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +// FRAME +use frame_support::{ + pallet_prelude::*, + traits::{ + Imbalance, IsSubType, OnUnbalanced, + fungible::{ + Balanced, Credit, Debt, DecreaseIssuance, Imbalance as FungibleImbalance, + IncreaseIssuance, Inspect, + }, + tokens::{Precision, WithdrawConsequence}, + }, + weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial}, +}; + +// Runtime +use sp_runtime::{ + Perbill, Saturating, + traits::{DispatchInfoOf, PostDispatchInfoOf}, +}; + +// Pallets +use pallet_subtensor::Call as SubtensorCall; +use pallet_transaction_payment::Config as PTPConfig; +use pallet_transaction_payment::OnChargeTransaction; +use subtensor_swap_interface::SwapHandler; + +// Misc +use core::marker::PhantomData; +use smallvec::smallvec; +use sp_std::vec::Vec; +use substrate_fixed::types::U96F32; +use subtensor_runtime_common::{Balance, Currency, NetUid}; + +// Tests +#[cfg(test)] +mod tests; + +type AccountIdOf = ::AccountId; +type CallOf = ::RuntimeCall; + +pub struct LinearWeightToFee; +impl WeightToFeePolynomial for LinearWeightToFee { + type Balance = Balance; + + fn polynomial() -> WeightToFeeCoefficients { + let coefficient = WeightToFeeCoefficient { + coeff_integer: 0, + coeff_frac: Perbill::from_parts(50_000), // 0.05 unit per weight + negative: false, + degree: 1, + }; + + smallvec![coefficient] + } +} + +/// Trait that allows working with Alpha +pub trait AlphaFeeHandler { + fn can_withdraw_in_alpha( + coldkey: &AccountIdOf, + alpha_vec: &[(AccountIdOf, NetUid)], + tao_amount: u64, + ) -> bool; + fn withdraw_in_alpha( + coldkey: &AccountIdOf, + alpha_vec: &[(AccountIdOf, NetUid)], + tao_amount: u64, + ); + fn get_all_netuids_for_coldkey_and_hotkey( + coldkey: &AccountIdOf, + hotkey: &AccountIdOf, + ) -> Vec; +} + +/// Deduct the transaction fee from the Subtensor Pallet TotalIssuance when charging the transaction +/// fee. +pub struct TransactionFeeHandler(core::marker::PhantomData); +impl Default for TransactionFeeHandler { + fn default() -> Self { + Self(core::marker::PhantomData) + } +} + +impl + OnUnbalanced< + FungibleImbalance< + u64, + DecreaseIssuance, pallet_balances::Pallet>, + IncreaseIssuance, pallet_balances::Pallet>, + >, + > for TransactionFeeHandler +where + T: frame_system::Config, + T: pallet_subtensor::Config, + T: pallet_balances::Config, +{ + fn on_nonzero_unbalanced( + imbalance: FungibleImbalance< + u64, + DecreaseIssuance, pallet_balances::Pallet>, + IncreaseIssuance, pallet_balances::Pallet>, + >, + ) { + let ti_before = pallet_subtensor::TotalIssuance::::get(); + pallet_subtensor::TotalIssuance::::put( + ti_before.saturating_sub(imbalance.peek().into()), + ); + drop(imbalance); + } +} + +/// Handle Alpha fees +impl AlphaFeeHandler for TransactionFeeHandler +where + T: frame_system::Config, + T: pallet_subtensor::Config, + T: pallet_subtensor_swap::Config, +{ + /// This function checks if tao_amount fee can be withdraw in Alpha currency + /// by converting Alpha to TAO at the current price and ignoring slippage. + /// + /// If this function returns true, the transaction will be included in the block + /// and Alpha will be withdraw from the account, no matter whether transaction + /// is successful or not. + /// + /// If this function returns true, but at the time of execution the Alpha price + /// changes and it becomes impossible to pay tx fee with the Alpha balance, + /// the transaction still executes and all Alpha is withdrawn from the account. + fn can_withdraw_in_alpha( + coldkey: &AccountIdOf, + alpha_vec: &[(AccountIdOf, NetUid)], + tao_amount: u64, + ) -> bool { + if alpha_vec.is_empty() { + // Alpha vector is empty, nothing to withdraw + return false; + } + + // Divide tao_amount among all alpha entries + let tao_per_entry = tao_amount.checked_div(alpha_vec.len() as u64).unwrap_or(0); + + // The rule here is that we should be able to withdraw at least from one entry. + // This is not ideal because it may not pay all fees, but UX is the priority + // and this approach still provides spam protection. + alpha_vec.iter().any(|(hotkey, netuid)| { + let alpha_balance = U96F32::saturating_from_num( + pallet_subtensor::Pallet::::get_stake_for_hotkey_and_coldkey_on_subnet( + hotkey, coldkey, *netuid, + ), + ); + let alpha_price = pallet_subtensor_swap::Pallet::::current_alpha_price(*netuid); + alpha_price.saturating_mul(alpha_balance) >= tao_per_entry + }) + } + + fn withdraw_in_alpha( + coldkey: &AccountIdOf, + alpha_vec: &[(AccountIdOf, NetUid)], + tao_amount: u64, + ) { + if alpha_vec.is_empty() { + return; + } + + let tao_per_entry = tao_amount.checked_div(alpha_vec.len() as u64).unwrap_or(0); + + alpha_vec.iter().for_each(|(hotkey, netuid)| { + // Divide tao_amount evenly among all alpha entries + let alpha_balance = U96F32::saturating_from_num( + pallet_subtensor::Pallet::::get_stake_for_hotkey_and_coldkey_on_subnet( + hotkey, coldkey, *netuid, + ), + ); + let alpha_price = pallet_subtensor_swap::Pallet::::current_alpha_price(*netuid); + let alpha_fee = U96F32::saturating_from_num(tao_per_entry) + .checked_div(alpha_price) + .unwrap_or(alpha_balance) + .min(alpha_balance) + .saturating_to_num::(); + + pallet_subtensor::Pallet::::decrease_stake_for_hotkey_and_coldkey_on_subnet( + hotkey, + coldkey, + *netuid, + alpha_fee.into(), + ); + }); + } + + fn get_all_netuids_for_coldkey_and_hotkey( + coldkey: &AccountIdOf, + hotkey: &AccountIdOf, + ) -> Vec { + pallet_subtensor::Pallet::::get_all_subnet_netuids() + .into_iter() + .filter(|netuid| pallet_subtensor::SubtokenEnabled::::get(netuid)) + .filter(|netuid| { + pallet_subtensor::Pallet::::get_stake_for_hotkey_and_coldkey_on_subnet( + hotkey, coldkey, *netuid, + ) != 0.into() + }) + .collect() + } +} + +/// Enum that describes either a withdrawn amount of transaction fee in TAO or the +/// fact that fee was charged in Alpha (without an amount because it is not needed) +pub enum WithdrawnFee>> { + Tao(Credit, F>), + Alpha, +} + +/// Custom OnChargeTransaction implementation based on standard FungibleAdapter from transaction_payment +/// FRAME pallet +/// +pub struct SubtensorTxFeeHandler(PhantomData<(F, OU)>); + +/// This implementation contains the list of calls that require paying transaction +/// fees in Alpha +impl SubtensorTxFeeHandler { + /// Returns Vec<(hotkey, netuid)> if the given call should pay fees in Alpha instead of TAO. + /// The vector represents all subnets where this hotkey has any alpha stake. Fees will be + /// distributed evenly between subnets in case of multiple subnets. + pub fn fees_in_alpha(who: &AccountIdOf, call: &CallOf) -> Vec<(AccountIdOf, NetUid)> + where + T: frame_system::Config + pallet_subtensor::Config, + CallOf: IsSubType>, + OU: AlphaFeeHandler, + { + let mut alpha_vec: Vec<(AccountIdOf, NetUid)> = Vec::new(); + + // Otherwise, switch to Alpha for the extrinsics that assume converting Alpha + // to TAO + // TODO: Populate the list + match call.is_sub_type() { + Some(SubtensorCall::remove_stake { hotkey, netuid, .. }) => { + alpha_vec.push((hotkey.clone(), *netuid)) + } + Some(SubtensorCall::remove_stake_limit { hotkey, netuid, .. }) => { + alpha_vec.push((hotkey.clone(), *netuid)) + } + Some(SubtensorCall::remove_stake_full_limit { hotkey, netuid, .. }) => { + alpha_vec.push((hotkey.clone(), *netuid)) + } + Some(SubtensorCall::unstake_all { hotkey, .. }) => { + let netuids = OU::get_all_netuids_for_coldkey_and_hotkey(who, hotkey); + netuids + .into_iter() + .for_each(|netuid| alpha_vec.push((hotkey.clone(), netuid))); + } + Some(SubtensorCall::unstake_all_alpha { hotkey, .. }) => { + let netuids = OU::get_all_netuids_for_coldkey_and_hotkey(who, hotkey); + netuids + .into_iter() + .for_each(|netuid| alpha_vec.push((hotkey.clone(), netuid))); + } + Some(SubtensorCall::move_stake { + origin_hotkey, + destination_hotkey: _, + origin_netuid, + .. + }) => alpha_vec.push((origin_hotkey.clone(), *origin_netuid)), + Some(SubtensorCall::transfer_stake { + destination_coldkey: _, + hotkey, + origin_netuid, + .. + }) => alpha_vec.push((hotkey.clone(), *origin_netuid)), + Some(SubtensorCall::swap_stake { + hotkey, + origin_netuid, + .. + }) => alpha_vec.push((hotkey.clone(), *origin_netuid)), + Some(SubtensorCall::swap_stake_limit { + hotkey, + origin_netuid, + .. + }) => alpha_vec.push((hotkey.clone(), *origin_netuid)), + Some(SubtensorCall::recycle_alpha { + hotkey, + amount: _, + netuid, + }) => alpha_vec.push((hotkey.clone(), *netuid)), + Some(SubtensorCall::burn_alpha { + hotkey, + amount: _, + netuid, + }) => alpha_vec.push((hotkey.clone(), *netuid)), + _ => {} + } + + alpha_vec + } +} + +impl OnChargeTransaction for SubtensorTxFeeHandler +where + T: PTPConfig + pallet_subtensor::Config, + CallOf: IsSubType>, + F: Balanced, + OU: OnUnbalanced> + AlphaFeeHandler, + >>::Balance: Into, +{ + type LiquidityInfo = Option>; + type Balance = ::AccountId>>::Balance; + + fn withdraw_fee( + who: &AccountIdOf, + call: &CallOf, + _dispatch_info: &DispatchInfoOf>, + fee: Self::Balance, + _tip: Self::Balance, + ) -> Result { + if fee.is_zero() { + return Ok(None); + } + + // Traditional fees in TAO + match F::withdraw( + who, + fee, + Precision::Exact, + frame_support::traits::tokens::Preservation::Preserve, + frame_support::traits::tokens::Fortitude::Polite, + ) { + Ok(imbalance) => Ok(Some(WithdrawnFee::Tao(imbalance))), + Err(_) => { + let alpha_vec = Self::fees_in_alpha::(who, call); + if !alpha_vec.is_empty() { + let fee_u64: u64 = fee.into(); + OU::withdraw_in_alpha(who, &alpha_vec, fee_u64); + return Ok(Some(WithdrawnFee::Alpha)); + } + Err(InvalidTransaction::Payment.into()) + } + } + } + + fn can_withdraw_fee( + who: &AccountIdOf, + call: &CallOf, + _dispatch_info: &DispatchInfoOf>, + fee: Self::Balance, + _tip: Self::Balance, + ) -> Result<(), TransactionValidityError> { + if fee.is_zero() { + return Ok(()); + } + + // Prefer traditional fees in TAO + match F::can_withdraw(who, fee) { + WithdrawConsequence::Success => Ok(()), + _ => { + // Fallback to fees in Alpha if possible + let alpha_vec = Self::fees_in_alpha::(who, call); + if !alpha_vec.is_empty() { + let fee_u64: u64 = fee.into(); + if OU::can_withdraw_in_alpha(who, &alpha_vec, fee_u64) { + return Ok(()); + } + } + Err(InvalidTransaction::Payment.into()) + } + } + } + + fn correct_and_deposit_fee( + who: &AccountIdOf, + _dispatch_info: &DispatchInfoOf>, + _post_info: &PostDispatchInfoOf>, + corrected_fee: Self::Balance, + tip: Self::Balance, + already_withdrawn: Self::LiquidityInfo, + ) -> Result<(), TransactionValidityError> { + if let Some(withdrawn) = already_withdrawn { + // Fee may be paid in TAO or in Alpha. Only refund and update total issuance for + // TAO fees because Alpha fees are charged precisely and do not need any adjustments + match withdrawn { + WithdrawnFee::Tao(paid) => { + // Calculate how much refund we should return + let refund_amount = paid.peek().saturating_sub(corrected_fee); + // refund to the account that paid the fees if it exists. otherwise, don't refund + // anything. + let refund_imbalance = if F::total_balance(who) > F::Balance::zero() { + F::deposit(who, refund_amount, Precision::BestEffort) + .unwrap_or_else(|_| Debt::::zero()) + } else { + Debt::::zero() + }; + // merge the imbalance caused by paying the fees and refunding parts of it again. + let adjusted_paid: Credit = + paid.offset(refund_imbalance).same().map_err(|_| { + TransactionValidityError::Invalid(InvalidTransaction::Payment) + })?; + // Call someone else to handle the imbalance (fee and tip separately) + let (tip, fee) = adjusted_paid.split(tip); + OU::on_unbalanceds(Some(fee).into_iter().chain(Some(tip))); + } + WithdrawnFee::Alpha => { + // Subtensor does not refund Alpha fees, charges are final + } + } + } + + Ok(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn endow_account(who: &AccountIdOf, amount: Self::Balance) { + let _ = F::deposit(who, amount, Precision::BestEffort); + } + + #[cfg(feature = "runtime-benchmarks")] + fn minimum_balance() -> Self::Balance { + F::minimum_balance() + } +} diff --git a/pallets/transaction-fee/src/tests/mock.rs b/pallets/transaction-fee/src/tests/mock.rs new file mode 100644 index 0000000000..c2f5caa432 --- /dev/null +++ b/pallets/transaction-fee/src/tests/mock.rs @@ -0,0 +1,716 @@ +#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] + +use core::num::NonZeroU64; + +use crate::TransactionFeeHandler; +use frame_support::{ + PalletId, assert_ok, derive_impl, parameter_types, + traits::{Everything, Hooks, InherentBuilder, PrivilegeCmp}, + weights::IdentityFee, +}; +use frame_system::{ + self as system, EnsureNever, EnsureRoot, RawOrigin, limits, offchain::CreateTransactionBase, +}; +pub use pallet_subtensor::*; +pub use sp_core::U256; +use sp_core::{ConstU64, H256}; +use sp_runtime::{ + BuildStorage, KeyTypeId, Perbill, + testing::TestXt, + traits::{BlakeTwo256, ConstU32, IdentityLookup, One}, +}; +use sp_std::cmp::Ordering; +use sp_weights::Weight; +pub use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; +use subtensor_swap_interface::{OrderType, SwapHandler}; + +use crate::SubtensorTxFeeHandler; +use pallet_transaction_payment::{ConstFeeMultiplier, Multiplier}; + +pub const TAO: u64 = 1_000_000_000; + +pub type Block = sp_runtime::generic::Block< + sp_runtime::generic::Header, + UncheckedExtrinsic, +>; + +// Configure a mock runtime to test the pallet. +frame_support::construct_runtime!( + pub enum Test { + System: frame_system = 1, + Balances: pallet_balances = 2, + SubtensorModule: pallet_subtensor::{Pallet, Call, Storage, Event, Error} = 4, + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 5, + Drand: pallet_drand::{Pallet, Call, Storage, Event} = 6, + Grandpa: pallet_grandpa = 7, + EVMChainId: pallet_evm_chain_id = 8, + Swap: pallet_subtensor_swap::{Pallet, Call, Storage, Event} = 9, + Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 10, + Crowdloan: pallet_crowdloan::{Pallet, Call, Storage, Event} = 11, + TransactionPayment: pallet_transaction_payment = 12, + } +); + +#[allow(dead_code)] +pub type SubtensorCall = pallet_subtensor::Call; + +#[allow(dead_code)] +pub type SubtensorEvent = pallet_subtensor::Event; + +#[allow(dead_code)] +pub type BalanceCall = pallet_balances::Call; + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; +} + +#[allow(dead_code)] +pub type AccountId = U256; + +// The address format for describing accounts. +#[allow(dead_code)] +pub type Address = AccountId; + +// Balance of an account. +#[allow(dead_code)] +pub type Balance = u64; + +// An index to a block. +#[allow(dead_code)] +pub type BlockNumber = u64; + +pub type TestAuthId = test_crypto::TestAuthId; + +pub type TransactionExtensions = ( + frame_system::CheckNonZeroSender, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, +); + +pub type UncheckedExtrinsic = TestXt; + +impl frame_support::traits::OnRuntimeUpgrade for Test { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + frame_support::weights::Weight::zero() + } +} +impl frame_support::traits::BeforeAllRuntimeMigrations for Test { + fn before_all_runtime_migrations() -> frame_support::weights::Weight { + frame_support::weights::Weight::zero() + } +} +impl frame_support::traits::OnInitialize for Test { + fn on_initialize(_n: BlockNumber) -> frame_support::weights::Weight { + frame_support::weights::Weight::zero() + } +} +impl frame_support::traits::OnFinalize for Test { + fn on_finalize(_n: BlockNumber) {} +} +impl frame_support::traits::OnIdle for Test { + fn on_idle( + _n: BlockNumber, + _remaining_weight: frame_support::weights::Weight, + ) -> frame_support::weights::Weight { + frame_support::weights::Weight::zero() + } +} +impl frame_support::traits::OnPoll for Test { + fn on_poll(_n: BlockNumber, _remaining_weight: &mut frame_support::weights::WeightMeter) {} +} +impl frame_support::traits::OffchainWorker for Test { + fn offchain_worker(_n: BlockNumber) {} +} + +parameter_types! { + pub const OperationalFeeMultiplier: u8 = 5; + pub FeeMultiplier: Multiplier = Multiplier::one(); +} + +impl pallet_transaction_payment::Config for Test { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = SubtensorTxFeeHandler>; + // Convert dispatch weight to a chargeable fee. + type WeightToFee = crate::LinearWeightToFee; + type OperationalFeeMultiplier = OperationalFeeMultiplier; + type LengthToFee = IdentityFee; + type FeeMultiplierUpdate = ConstFeeMultiplier; + type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight; +} + +parameter_types! { + pub const InitialMinAllowedWeights: u16 = 0; + pub const InitialEmissionValue: u16 = 0; + pub const InitialMaxWeightsLimit: u16 = u16::MAX; + pub BlockWeights: limits::BlockWeights = limits::BlockWeights::with_sensible_defaults( + Weight::from_parts(2_000_000_000_000, u64::MAX), + Perbill::from_percent(75), + ); + pub const ExistentialDeposit: Balance = 1; + pub const TransactionByteFee: Balance = 100; + pub const SDebug:u64 = 1; + pub const InitialRho: u16 = 30; + pub const InitialAlphaSigmoidSteepness: i16 = 1000; + pub const InitialKappa: u16 = 32_767; + pub const InitialTempo: u16 = 0; + pub const SelfOwnership: u64 = 2; + pub const InitialImmunityPeriod: u16 = 2; + pub const InitialMaxAllowedUids: u16 = 2; + pub const InitialBondsMovingAverage: u64 = 900_000; + pub const InitialBondsPenalty: u16 = u16::MAX; + pub const InitialBondsResetOn: bool = false; + pub const InitialStakePruningMin: u16 = 0; + pub const InitialFoundationDistribution: u64 = 0; + pub const InitialDefaultDelegateTake: u16 = 11_796; // 18% honest number. + pub const InitialMinDelegateTake: u16 = 5_898; // 9%; + pub const InitialDefaultChildKeyTake: u16 = 0; // Allow 0 % + pub const InitialMinChildKeyTake: u16 = 0; // Allow 0 % + pub const InitialMaxChildKeyTake: u16 = 11_796; // 18 %; + pub const InitialWeightsVersionKey: u16 = 0; + pub const InitialServingRateLimit: u64 = 0; // No limit. + pub const InitialTxRateLimit: u64 = 0; // Disable rate limit for testing + pub const InitialTxDelegateTakeRateLimit: u64 = 0; // Disable rate limit for testing + pub const InitialTxChildKeyTakeRateLimit: u64 = 0; // Disable rate limit for testing + pub const InitialBurn: u64 = 0; + pub const InitialMinBurn: u64 = 500_000; + pub const InitialMaxBurn: u64 = 1_000_000_000; + pub const InitialValidatorPruneLen: u64 = 0; + pub const InitialScalingLawPower: u16 = 50; + pub const InitialMaxAllowedValidators: u16 = 100; + pub const InitialIssuance: u64 = 0; + pub const InitialDifficulty: u64 = 10000; + pub const InitialActivityCutoff: u16 = 5000; + pub const InitialAdjustmentInterval: u16 = 100; + pub const InitialAdjustmentAlpha: u64 = 0; // no weight to previous value. + pub const InitialMaxRegistrationsPerBlock: u16 = 3; + pub const InitialTargetRegistrationsPerInterval: u16 = 2; + pub const InitialPruningScore : u16 = u16::MAX; + pub const InitialRegistrationRequirement: u16 = u16::MAX; // Top 100% + pub const InitialMinDifficulty: u64 = 1; + pub const InitialMaxDifficulty: u64 = u64::MAX; + pub const InitialRAORecycledForRegistration: u64 = 0; + pub const InitialSenateRequiredStakePercentage: u64 = 2; // 2 percent of total stake + pub const InitialNetworkImmunityPeriod: u64 = 7200 * 7; + pub const InitialNetworkMinAllowedUids: u16 = 128; + pub const InitialNetworkMinLockCost: u64 = 100_000_000_000; + pub const InitialSubnetOwnerCut: u16 = 0; // 0%. 100% of rewards go to validators + miners. + pub const InitialNetworkLockReductionInterval: u64 = 2; // 2 blocks. + // pub const InitialSubnetLimit: u16 = 10; // (DEPRECATED) + pub const InitialNetworkRateLimit: u64 = 0; + pub const InitialKeySwapCost: u64 = 1_000_000_000; + pub const InitialAlphaHigh: u16 = 58982; // Represents 0.9 as per the production default + pub const InitialAlphaLow: u16 = 45875; // Represents 0.7 as per the production default + pub const InitialLiquidAlphaOn: bool = false; // Default value for LiquidAlphaOn + pub const InitialYuma3On: bool = false; // Default value for Yuma3On + // pub const InitialHotkeyEmissionTempo: u64 = 1; // (DEPRECATED) + // pub const InitialNetworkMaxStake: u64 = u64::MAX; // (DEPRECATED) + pub const InitialColdkeySwapScheduleDuration: u64 = 5 * 24 * 60 * 60 / 12; // 5 days + pub const InitialColdkeySwapRescheduleDuration: u64 = 24 * 60 * 60 / 12; // 1 day + pub const InitialDissolveNetworkScheduleDuration: u64 = 5 * 24 * 60 * 60 / 12; // 5 days + pub const InitialTaoWeight: u64 = u64::MAX/10; // 10% global weight. + pub const InitialEmaPriceHalvingPeriod: u64 = 201_600_u64; // 4 weeks + pub const DurationOfStartCall: u64 = 7 * 24 * 60 * 60 / 12; // 7 days + pub const InitialKeySwapOnSubnetCost: u64 = 10_000_000; + pub const HotkeySwapOnSubnetInterval: u64 = 7 * 24 * 60 * 60 / 12; // 7 days + pub const LeaseDividendsDistributionInterval: u32 = 100; // 100 blocks +} + +impl pallet_subtensor::Config for Test { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type InitialIssuance = InitialIssuance; + type SudoRuntimeCall = RuntimeCall; + type CouncilOrigin = EnsureNever; + type SenateMembers = (); + type TriumvirateInterface = (); + type Scheduler = Scheduler; + type InitialMinAllowedWeights = InitialMinAllowedWeights; + type InitialEmissionValue = InitialEmissionValue; + type InitialMaxWeightsLimit = InitialMaxWeightsLimit; + type InitialTempo = InitialTempo; + type InitialDifficulty = InitialDifficulty; + type InitialAdjustmentInterval = InitialAdjustmentInterval; + type InitialAdjustmentAlpha = InitialAdjustmentAlpha; + type InitialTargetRegistrationsPerInterval = InitialTargetRegistrationsPerInterval; + type InitialRho = InitialRho; + type InitialAlphaSigmoidSteepness = InitialAlphaSigmoidSteepness; + type InitialKappa = InitialKappa; + type InitialMaxAllowedUids = InitialMaxAllowedUids; + type InitialValidatorPruneLen = InitialValidatorPruneLen; + type InitialScalingLawPower = InitialScalingLawPower; + type InitialImmunityPeriod = InitialImmunityPeriod; + type InitialActivityCutoff = InitialActivityCutoff; + type InitialMaxRegistrationsPerBlock = InitialMaxRegistrationsPerBlock; + type InitialPruningScore = InitialPruningScore; + type InitialBondsMovingAverage = InitialBondsMovingAverage; + type InitialBondsPenalty = InitialBondsPenalty; + type InitialBondsResetOn = InitialBondsResetOn; + type InitialMaxAllowedValidators = InitialMaxAllowedValidators; + type InitialDefaultDelegateTake = InitialDefaultDelegateTake; + type InitialMinDelegateTake = InitialMinDelegateTake; + type InitialDefaultChildKeyTake = InitialDefaultChildKeyTake; + type InitialMinChildKeyTake = InitialMinChildKeyTake; + type InitialMaxChildKeyTake = InitialMaxChildKeyTake; + type InitialWeightsVersionKey = InitialWeightsVersionKey; + type InitialMaxDifficulty = InitialMaxDifficulty; + type InitialMinDifficulty = InitialMinDifficulty; + type InitialServingRateLimit = InitialServingRateLimit; + type InitialTxRateLimit = InitialTxRateLimit; + type InitialTxDelegateTakeRateLimit = InitialTxDelegateTakeRateLimit; + type InitialTxChildKeyTakeRateLimit = InitialTxChildKeyTakeRateLimit; + type InitialBurn = InitialBurn; + type InitialMaxBurn = InitialMaxBurn; + type InitialMinBurn = InitialMinBurn; + type InitialRAORecycledForRegistration = InitialRAORecycledForRegistration; + type InitialSenateRequiredStakePercentage = InitialSenateRequiredStakePercentage; + type InitialNetworkImmunityPeriod = InitialNetworkImmunityPeriod; + type InitialNetworkMinAllowedUids = InitialNetworkMinAllowedUids; + type InitialNetworkMinLockCost = InitialNetworkMinLockCost; + type InitialSubnetOwnerCut = InitialSubnetOwnerCut; + type InitialNetworkLockReductionInterval = InitialNetworkLockReductionInterval; + type InitialNetworkRateLimit = InitialNetworkRateLimit; + type KeySwapCost = InitialKeySwapCost; + type AlphaHigh = InitialAlphaHigh; + type AlphaLow = InitialAlphaLow; + type LiquidAlphaOn = InitialLiquidAlphaOn; + type Yuma3On = InitialYuma3On; + type Preimages = (); + type InitialColdkeySwapScheduleDuration = InitialColdkeySwapScheduleDuration; + type InitialColdkeySwapRescheduleDuration = InitialColdkeySwapRescheduleDuration; + type InitialDissolveNetworkScheduleDuration = InitialDissolveNetworkScheduleDuration; + type InitialTaoWeight = InitialTaoWeight; + type InitialEmaPriceHalvingPeriod = InitialEmaPriceHalvingPeriod; + type DurationOfStartCall = DurationOfStartCall; + type SwapInterface = Swap; + type KeySwapOnSubnetCost = InitialKeySwapOnSubnetCost; + type HotkeySwapOnSubnetInterval = HotkeySwapOnSubnetInterval; + type ProxyInterface = (); + type LeaseDividendsDistributionInterval = LeaseDividendsDistributionInterval; +} + +parameter_types! { + pub const PreimageMaxSize: u32 = 4096 * 1024; + pub const PreimageBaseDeposit: Balance = 1; + pub const PreimageByteDeposit: Balance = 1; +} + +impl pallet_preimage::Config for Test { + type WeightInfo = pallet_preimage::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type Consideration = (); +} + +parameter_types! { + pub const CrowdloanPalletId: PalletId = PalletId(*b"bt/cloan"); + pub const MinimumDeposit: u64 = 50; + pub const AbsoluteMinimumContribution: u64 = 10; + pub const MinimumBlockDuration: u64 = 20; + pub const MaximumBlockDuration: u64 = 100; + pub const RefundContributorsLimit: u32 = 5; + pub const MaxContributors: u32 = 10; +} + +impl pallet_crowdloan::Config for Test { + type PalletId = CrowdloanPalletId; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_crowdloan::weights::SubstrateWeight; + type Preimages = Preimage; + type MinimumDeposit = MinimumDeposit; + type AbsoluteMinimumContribution = AbsoluteMinimumContribution; + type MinimumBlockDuration = MinimumBlockDuration; + type MaximumBlockDuration = MaximumBlockDuration; + type RefundContributorsLimit = RefundContributorsLimit; + type MaxContributors = MaxContributors; +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl system::Config for Test { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = U256; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type Block = Block; + type Nonce = u64; +} + +impl pallet_grandpa::Config for Test { + type RuntimeEvent = RuntimeEvent; + + type KeyOwnerProof = sp_core::Void; + + type WeightInfo = (); + type MaxAuthorities = ConstU32<32>; + type MaxSetIdSessionEntries = ConstU64<0>; + type MaxNominators = ConstU32<20>; + + type EquivocationReportSystem = (); +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] +impl pallet_balances::Config for Test { + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type Balance = u64; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ConstU64<1>; + type AccountStore = System; + type WeightInfo = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type RuntimeHoldReason = (); +} + +// Swap-related parameter types +parameter_types! { + pub const SwapProtocolId: PalletId = PalletId(*b"ten/swap"); + pub const SwapMaxFeeRate: u16 = 10000; // 15.26% + pub const SwapMaxPositions: u32 = 100; + pub const SwapMinimumLiquidity: u64 = 1_000; + pub const SwapMinimumReserve: NonZeroU64 = NonZeroU64::new(1_000_000).unwrap(); +} + +impl pallet_subtensor_swap::Config for Test { + type RuntimeEvent = RuntimeEvent; + type SubnetInfo = SubtensorModule; + type BalanceOps = SubtensorModule; + type ProtocolId = SwapProtocolId; + type MaxFeeRate = SwapMaxFeeRate; + type MaxPositions = SwapMaxPositions; + type MinimumLiquidity = SwapMinimumLiquidity; + type MinimumReserve = SwapMinimumReserve; + type WeightInfo = (); +} + +pub struct OriginPrivilegeCmp; + +impl PrivilegeCmp for OriginPrivilegeCmp { + fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option { + None + } +} + +parameter_types! { + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * + BlockWeights::get().max_block; + pub const MaxScheduledPerBlock: u32 = 50; + pub const NoPreimagePostponement: Option = Some(10); +} + +impl pallet_scheduler::Config for Test { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeEvent = RuntimeEvent; + type PalletsOrigin = OriginCaller; + type RuntimeCall = RuntimeCall; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = EnsureRoot; + type MaxScheduledPerBlock = MaxScheduledPerBlock; + type WeightInfo = pallet_scheduler::weights::SubstrateWeight; + type OriginPrivilegeCmp = OriginPrivilegeCmp; + type Preimages = (); + type BlockNumberProvider = System; +} + +impl pallet_evm_chain_id::Config for Test {} +impl pallet_drand::Config for Test { + type RuntimeEvent = RuntimeEvent; + type AuthorityId = TestAuthId; + type Verifier = pallet_drand::verifier::QuicknetVerifier; + type UnsignedPriority = ConstU64<{ 1 << 20 }>; + type HttpFetchTimeout = ConstU64<1_000>; +} + +impl frame_system::offchain::SigningTypes for Test { + type Public = test_crypto::Public; + type Signature = test_crypto::Signature; +} + +pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"test"); + +mod test_crypto { + use super::KEY_TYPE; + use sp_core::U256; + use sp_core::sr25519::{Public as Sr25519Public, Signature as Sr25519Signature}; + use sp_runtime::{ + app_crypto::{app_crypto, sr25519}, + traits::IdentifyAccount, + }; + + app_crypto!(sr25519, KEY_TYPE); + + pub struct TestAuthId; + + impl frame_system::offchain::AppCrypto for TestAuthId { + type RuntimeAppPublic = Public; + type GenericSignature = Sr25519Signature; + type GenericPublic = Sr25519Public; + } + + impl IdentifyAccount for Public { + type AccountId = U256; + + fn into_account(self) -> U256 { + let mut bytes = [0u8; 32]; + bytes.copy_from_slice(self.as_ref()); + U256::from_big_endian(&bytes) + } + } +} + +impl frame_system::offchain::CreateTransactionBase for Test +where + RuntimeCall: From, +{ + type Extrinsic = UncheckedExtrinsic; + type RuntimeCall = RuntimeCall; +} + +impl frame_system::offchain::CreateInherent for Test +where + RuntimeCall: From, +{ + fn create_inherent(call: Self::RuntimeCall) -> Self::Extrinsic { + UncheckedExtrinsic::new_inherent(call) + } +} + +impl frame_system::offchain::CreateSignedTransaction for Test +where + RuntimeCall: From, +{ + fn create_signed_transaction< + C: frame_system::offchain::AppCrypto, + >( + call: >::RuntimeCall, + _public: Self::Public, + _account: Self::AccountId, + nonce: Self::Nonce, + ) -> Option { + let extra: TransactionExtensions = ( + frame_system::CheckNonZeroSender::::new(), + frame_system::CheckWeight::::new(), + pallet_transaction_payment::ChargeTransactionPayment::::from(0), + ); + + Some(UncheckedExtrinsic::new_signed(call, nonce, (), extra)) + } +} + +// Build genesis storage according to the mock runtime. +pub fn new_test_ext() -> sp_io::TestExternalities { + sp_tracing::try_init_simple(); + let t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +#[allow(dead_code)] +pub(crate) fn run_to_block(n: u64) { + while System::block_number() < n { + SubtensorModule::on_finalize(System::block_number()); + System::on_finalize(System::block_number()); + System::reset_events(); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + SubtensorModule::on_initialize(System::block_number()); + } +} + +#[allow(dead_code)] +pub fn register_ok_neuron( + netuid: NetUid, + hotkey_account_id: U256, + coldkey_account_id: U256, + start_nonce: u64, +) { + let block_number: u64 = SubtensorModule::get_current_block_as_u64(); + let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + block_number, + start_nonce, + &hotkey_account_id, + ); + let result = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id), + netuid, + block_number, + nonce, + work, + hotkey_account_id, + coldkey_account_id, + ); + assert_ok!(result); +} + +#[allow(dead_code)] +pub fn add_dynamic_network(hotkey: &U256, coldkey: &U256) -> NetUid { + let netuid = SubtensorModule::get_next_netuid(); + let lock_cost = SubtensorModule::get_network_lock_cost(); + SubtensorModule::add_balance_to_coldkey_account(coldkey, lock_cost.into()); + + assert_ok!(SubtensorModule::register_network( + RawOrigin::Signed(*coldkey).into(), + *hotkey + )); + NetworkRegistrationAllowed::::insert(netuid, true); + NetworkPowRegistrationAllowed::::insert(netuid, true); + FirstEmissionBlockNumber::::insert(netuid, 0); + SubtokenEnabled::::insert(netuid, true); + netuid +} + +pub(crate) fn setup_reserves(netuid: NetUid, tao: TaoCurrency, alpha: AlphaCurrency) { + SubnetTAO::::set(netuid, tao); + SubnetAlphaIn::::set(netuid, alpha); +} + +pub(crate) fn swap_alpha_to_tao_ext( + netuid: NetUid, + alpha: AlphaCurrency, + drop_fees: bool, +) -> (u64, u64) { + if netuid.is_root() { + return (alpha.into(), 0); + } + + let result = ::SwapInterface::swap( + netuid.into(), + OrderType::Sell, + alpha.into(), + ::SwapInterface::min_price(), + drop_fees, + true, + ); + + assert_ok!(&result); + + let result = result.unwrap(); + + // we don't want to have silent 0 comparissons in tests + assert!(result.amount_paid_out > 0); + + (result.amount_paid_out, result.fee_paid) +} + +pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: AlphaCurrency) -> (u64, u64) { + swap_alpha_to_tao_ext(netuid, alpha, false) +} + +#[allow(dead_code)] +pub fn add_network(netuid: NetUid, tempo: u16) { + SubtensorModule::init_new_network(netuid, tempo); + SubtensorModule::set_network_registration_allowed(netuid, true); + SubtensorModule::set_network_pow_registration_allowed(netuid, true); +} + +#[allow(dead_code)] +pub struct TestSubnet { + pub netuid: NetUid, + pub ck_owner: U256, + pub hk_owner: U256, +} + +#[allow(dead_code)] +pub struct TestSetup { + pub subnets: Vec, + pub coldkey: U256, + pub hotkeys: Vec, +} + +#[allow(dead_code)] +pub fn setup_subnets(sncount: u16, neurons: u16) -> TestSetup { + let mut subnets: Vec = Vec::new(); + let owner_ck_start_id = 100; + let owner_hk_start_id = 200; + let coldkey = U256::from(10000); + let neuron_hk_start_id = 20000; + let amount = 1_000_000_000_000; + let mut hotkeys: Vec = Vec::new(); + + for sn in 0..sncount { + let cko = U256::from(owner_ck_start_id + sn); + let hko = U256::from(owner_hk_start_id + sn); + + // Create subnet + let subnet = TestSubnet { + netuid: add_dynamic_network(&cko, &hko), + ck_owner: cko, + hk_owner: hko, + }; + + // Set tempo to 10 blocks + Tempo::::insert(subnet.netuid, 10); + + // Add neurons (all the same for all subnets) + for uid in 1..=neurons { + let hotkey = U256::from(neuron_hk_start_id + uid); + register_ok_neuron(subnet.netuid, hotkey, coldkey, 192213123); + hotkeys.push(hotkey); + } + + // Setup pool reserves + setup_reserves(subnet.netuid, amount.into(), amount.into()); + + // Cause the v3 pool to initialize + SubtensorModule::swap_tao_for_alpha( + subnet.netuid, + 0.into(), + 1_000_000_000_000.into(), + false, + ) + .unwrap(); + + subnets.push(subnet); + } + + TestSetup { + subnets, + coldkey, + hotkeys, + } +} + +pub(crate) fn remove_stake_rate_limit_for_tests(hotkey: &U256, coldkey: &U256, netuid: NetUid) { + StakingOperationRateLimiter::::remove((hotkey, coldkey, netuid)); +} + +#[allow(dead_code)] +pub fn setup_stake(netuid: NetUid, coldkey: &U256, hotkey: &U256, amount: u64) { + // Stake to hotkey account, and check if the result is ok + SubtensorModule::add_balance_to_coldkey_account(coldkey, amount + ExistentialDeposit::get()); + remove_stake_rate_limit_for_tests(hotkey, coldkey, netuid); + assert_ok!(SubtensorModule::add_stake( + RuntimeOrigin::signed(*coldkey), + *hotkey, + netuid, + amount.into() + )); + remove_stake_rate_limit_for_tests(hotkey, coldkey, netuid); +} diff --git a/pallets/transaction-fee/src/tests/mod.rs b/pallets/transaction-fee/src/tests/mod.rs new file mode 100644 index 0000000000..14e138b1d4 --- /dev/null +++ b/pallets/transaction-fee/src/tests/mod.rs @@ -0,0 +1,1196 @@ +#![allow(clippy::indexing_slicing, clippy::unwrap_used)] +use crate::TransactionSource; +use frame_support::assert_ok; +use frame_support::dispatch::GetDispatchInfo; +use pallet_subtensor_swap::AlphaSqrtPrice; +use sp_runtime::{ + traits::{DispatchTransaction, TransactionExtension, TxBaseImplication}, + transaction_validity::{InvalidTransaction, TransactionValidityError}, +}; +use substrate_fixed::types::U64F64; +use subtensor_runtime_common::AlphaCurrency; + +use mock::*; +mod mock; + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_fees_tao --exact --show-output +#[test] +fn test_remove_stake_fees_tao() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + SubtensorModule::add_balance_to_coldkey_account(&sn.coldkey, TAO); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let (expected_unstaked_tao, _swap_fee) = + mock::swap_alpha_to_tao(sn.subnets[0].netuid, unstake_amount); + + // Remove stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before + expected_unstaked_tao - final_balance; + let actual_alpha_fee = alpha_before - alpha_after - unstake_amount; + + // Remove stake extrinsic should pay fees in TAO because ck has sufficient TAO balance + assert!(actual_tao_fee > 0); + assert_eq!(actual_alpha_fee, AlphaCurrency::from(0)); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_fees_alpha --exact --show-output +#[test] +fn test_remove_stake_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let (expected_unstaked_tao, _swap_fee) = + mock::swap_alpha_to_tao(sn.subnets[0].netuid, unstake_amount); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before + expected_unstaked_tao - final_balance; + let actual_alpha_fee = alpha_before - alpha_after - unstake_amount; + + // Remove stake extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// Test that unstaking on root with no free balance results in charging fees from +// staked amount +// +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_root --exact --show-output +#[test] +fn test_remove_stake_root() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = TAO / 10; + let netuid = NetUid::from(0); + let coldkey = U256::from(100000); + let hotkey = U256::from(100001); + + // Root stake + add_network(netuid, 10); + pallet_subtensor::Owner::::insert(hotkey, coldkey); + pallet_subtensor::SubtokenEnabled::::insert(NetUid::from(0), true); + setup_stake(netuid, &coldkey, &hotkey, stake_amount); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake + let balance_before = Balances::free_balance(coldkey); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey, + netuid, + amount_unstaked: unstake_amount.into(), + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(coldkey); + let alpha_after = + SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); + + let actual_tao_fee = balance_before + unstake_amount - final_balance; + let actual_alpha_fee = + AlphaCurrency::from(stake_amount) - alpha_after - unstake_amount.into(); + + // Remove stake extrinsic should pay fees in Alpha (withdrawn from staked TAO) + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// Test that unstaking 100% of stake on root is possible with no free balance +// +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_completely_root --exact --show-output +#[test] +fn test_remove_stake_completely_root() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = TAO; + let netuid = NetUid::from(0); + let coldkey = U256::from(100000); + let hotkey = U256::from(100001); + + // Root stake + add_network(netuid, 10); + pallet_subtensor::Owner::::insert(hotkey, coldkey); + pallet_subtensor::SubtokenEnabled::::insert(NetUid::from(0), true); + setup_stake(netuid, &coldkey, &hotkey, stake_amount); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake + let balance_before = Balances::free_balance(coldkey); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey, + netuid, + amount_unstaked: unstake_amount.into(), + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(coldkey); + let alpha_after = + SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); + + assert_eq!(alpha_after, 0.into()); + assert!(final_balance > balance_before); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_completely_fees_alpha --exact --show-output +#[test] +fn test_remove_stake_completely_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let unstake_amount = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let (expected_unstaked_tao, _swap_fee) = + mock::swap_alpha_to_tao(sn.subnets[0].netuid, unstake_amount); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake + let balance_before = Balances::free_balance(sn.coldkey); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Effectively, the fee is paid in TAO in this case because user receives less TAO, + // and all Alpha is gone, and it is not measurable in Alpha + let actual_fee = balance_before + expected_unstaked_tao - final_balance; + assert_eq!(alpha_after, 0.into()); + assert!(actual_fee > 0); + }); +} + +// Validation should fail if both TAO and Alpha balance are lower than tx fees, +// so that transaction is not included in the block +#[test] +fn test_remove_stake_not_enough_balance_for_fees() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let current_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // For-set Alpha balance to low + let new_current_stake = AlphaCurrency::from(1_000); + SubtensorModule::decrease_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + current_stake - new_current_stake, + ); + + // Remove stake + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: new_current_stake, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + let result = ext.validate( + RuntimeOrigin::signed(sn.coldkey).into(), + &call.clone(), + &info, + 10, + (), + &TxBaseImplication(()), + TransactionSource::External, + ); + + assert_eq!( + result.unwrap_err(), + TransactionValidityError::Invalid(InvalidTransaction::Payment) + ); + }); +} + +// No TAO balance, Alpha fees. If Alpha price is high, it is enough to pay fees, but when Alpha price +// is low, the validation fails +// +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_edge_alpha --exact --show-output +#[test] +fn test_remove_stake_edge_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let current_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // For-set Alpha balance to low, but enough to pay tx fees at the current Alpha price + let new_current_stake = AlphaCurrency::from(1_000_000); + SubtensorModule::decrease_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + current_stake - new_current_stake, + ); + + // Remove stake + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: new_current_stake, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + let result = ext.validate( + RuntimeOrigin::signed(sn.coldkey).into(), + &call.clone(), + &info, + 10, + (), + &TxBaseImplication(()), + TransactionSource::External, + ); + + // Ok - Validation passed + assert_ok!(result); + + // Lower Alpha price to 0.0001 so that there is not enough alpha to cover tx fees + AlphaSqrtPrice::::insert(sn.subnets[0].netuid, U64F64::from_num(0.01)); + let result_low_alpha_price = ext.validate( + RuntimeOrigin::signed(sn.coldkey).into(), + &call.clone(), + &info, + 10, + (), + &TxBaseImplication(()), + TransactionSource::External, + ); + assert_eq!( + result_low_alpha_price.unwrap_err(), + TransactionValidityError::Invalid(InvalidTransaction::Payment) + ); + }); +} + +// Validation passes, but transaction fails => TAO fees are paid +// +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_failing_transaction_tao_fees --exact --show-output +#[test] +fn test_remove_stake_failing_transaction_tao_fees() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + SubtensorModule::add_balance_to_coldkey_account(&sn.coldkey, TAO); + + // Make unstaking fail by reducing liquidity to critical + SubnetTAO::::insert(sn.subnets[0].netuid, TaoCurrency::from(1)); + + // Remove stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before - final_balance; + + // Remove stake extrinsic should pay fees in TAO because ck has sufficient TAO balance + assert!(actual_tao_fee > 0); + assert_eq!(alpha_before, alpha_after); + }); +} + +// Validation passes, but transaction fails => Alpha fees are paid +// +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_failing_transaction_alpha_fees --exact --show-output +#[test] +fn test_remove_stake_failing_transaction_alpha_fees() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Make unstaking fail by reducing liquidity to critical + SubnetTAO::::insert(sn.subnets[0].netuid, TaoCurrency::from(1)); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after; + + // Remove stake extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + assert!(actual_alpha_fee < unstake_amount); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_remove_stake_limit_fees_alpha --exact --show-output +#[test] +fn test_remove_stake_limit_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let (expected_unstaked_tao, _swap_fee) = + mock::swap_alpha_to_tao(sn.subnets[0].netuid, unstake_amount); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Remove stake limit + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::remove_stake_limit { + hotkey: sn.hotkeys[0], + netuid: sn.subnets[0].netuid, + amount_unstaked: unstake_amount, + limit_price: 1_000.into(), + allow_partial: false, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before + expected_unstaked_tao - final_balance; + let actual_alpha_fee = alpha_before - alpha_after - unstake_amount; + + // Remove stake extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_unstake_all_fees_alpha --exact --show-output +#[test] +fn test_unstake_all_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let sn = setup_subnets(10, 1); + let coldkey = U256::from(100000); + for i in 0..10 { + setup_stake(sn.subnets[i].netuid, &coldkey, &sn.hotkeys[0], stake_amount); + } + + // Root stake + add_network(NetUid::from(0), 10); + pallet_subtensor::SubtokenEnabled::::insert(NetUid::from(0), true); + setup_stake(0.into(), &coldkey, &sn.hotkeys[0], stake_amount); + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let mut expected_unstaked_tao = 0; + for i in 0..10 { + let unstake_amount = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &coldkey, + sn.subnets[i].netuid, + ); + + let (tao, _swap_fee) = mock::swap_alpha_to_tao(sn.subnets[i].netuid, unstake_amount); + expected_unstaked_tao += tao; + } + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Unstake all + let balance_before = Balances::free_balance(sn.coldkey); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::unstake_all { + hotkey: sn.hotkeys[0], + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + + // Effectively, the fee is paid in TAO in this case because user receives less TAO, + // and all Alpha is gone, and it is not measurable in Alpha + let actual_fee = balance_before + expected_unstaked_tao - final_balance; + assert!(actual_fee > 0); + + // Check that all subnets got unstaked + for i in 0..10 { + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[i].netuid, + ); + assert_eq!(alpha_after, 0.into()); + } + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_unstake_all_alpha_fees_alpha --exact --show-output +#[test] +fn test_unstake_all_alpha_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let sn = setup_subnets(10, 1); + let coldkey = U256::from(100000); + for i in 0..10 { + setup_stake(sn.subnets[i].netuid, &coldkey, &sn.hotkeys[0], stake_amount); + } + + // Simulate stake removal to get how much TAO should we get for unstaked Alpha + let mut expected_unstaked_tao = 0; + for i in 0..10 { + let unstake_amount = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &coldkey, + sn.subnets[i].netuid, + ); + + let (tao, _swap_fee) = mock::swap_alpha_to_tao(sn.subnets[i].netuid, unstake_amount); + expected_unstaked_tao += tao; + } + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Unstake all + let balance_before = Balances::free_balance(sn.coldkey); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::unstake_all_alpha { + hotkey: sn.hotkeys[0], + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + + // Effectively, the fee is paid in TAO in this case because user receives less TAO, + // and all Alpha is gone, and it is not measurable in Alpha + let actual_fee = balance_before + expected_unstaked_tao - final_balance; + assert!(actual_fee > 0); + + // Check that all subnets got unstaked + for i in 0..10 { + let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[i].netuid, + ); + assert_eq!(alpha_after, 0.into()); + } + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_move_stake_fees_alpha --exact --show-output +#[test] +fn test_move_stake_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(2, 2); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Move stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::move_stake { + origin_hotkey: sn.hotkeys[0], + destination_hotkey: sn.hotkeys[1], + origin_netuid: sn.subnets[0].netuid, + destination_netuid: sn.subnets[1].netuid, + alpha_amount: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Ensure stake was moved + let alpha_after_1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[1], + &sn.coldkey, + sn.subnets[1].netuid, + ); + assert!(alpha_after_1 > 0.into()); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - unstake_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_transfer_stake_fees_alpha --exact --show-output +#[test] +fn test_transfer_stake_fees_alpha() { + new_test_ext().execute_with(|| { + let destination_coldkey = U256::from(100000); + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(2, 2); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Transfer stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::transfer_stake { + destination_coldkey, + hotkey: sn.hotkeys[0], + origin_netuid: sn.subnets[0].netuid, + destination_netuid: sn.subnets[1].netuid, + alpha_amount: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Ensure stake was transferred + let alpha_after_1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &destination_coldkey, + sn.subnets[1].netuid, + ); + assert!(alpha_after_1 > 0.into()); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - unstake_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_swap_stake_fees_alpha --exact --show-output +#[test] +fn test_swap_stake_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(2, 2); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Swap stake + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::swap_stake { + hotkey: sn.hotkeys[0], + origin_netuid: sn.subnets[0].netuid, + destination_netuid: sn.subnets[1].netuid, + alpha_amount: unstake_amount, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Ensure stake was transferred + let alpha_after_1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[1].netuid, + ); + assert!(alpha_after_1 > 0.into()); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - unstake_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_swap_stake_limit_fees_alpha --exact --show-output +#[test] +fn test_swap_stake_limit_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let unstake_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(2, 2); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Swap stake limit + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::swap_stake_limit { + hotkey: sn.hotkeys[0], + origin_netuid: sn.subnets[0].netuid, + destination_netuid: sn.subnets[1].netuid, + alpha_amount: unstake_amount, + limit_price: 1_000.into(), + allow_partial: false, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + // Ensure stake was transferred + let alpha_after_1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[1].netuid, + ); + assert!(alpha_after_1 > 0.into()); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - unstake_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_burn_alpha_fees_alpha --exact --show-output +#[test] +fn test_burn_alpha_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let alpha_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Burn alpha + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::burn_alpha { + hotkey: sn.hotkeys[0], + amount: alpha_amount, + netuid: sn.subnets[0].netuid, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - alpha_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} + +// cargo test --package subtensor-transaction-fee --lib -- tests::test_recycle_alpha_fees_alpha --exact --show-output +#[test] +fn test_recycle_alpha_fees_alpha() { + new_test_ext().execute_with(|| { + let stake_amount = TAO; + let alpha_amount = AlphaCurrency::from(TAO / 50); + let sn = setup_subnets(1, 1); + setup_stake( + sn.subnets[0].netuid, + &sn.coldkey, + &sn.hotkeys[0], + stake_amount, + ); + + // Forse-set signer balance to ED + let current_balance = Balances::free_balance(sn.coldkey); + let _ = SubtensorModule::remove_balance_from_coldkey_account( + &sn.coldkey, + current_balance - ExistentialDeposit::get(), + ); + + // Recycle alpha + let balance_before = Balances::free_balance(sn.coldkey); + let alpha_before = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + let call = RuntimeCall::SubtensorModule(pallet_subtensor::Call::recycle_alpha { + hotkey: sn.hotkeys[0], + amount: alpha_amount, + netuid: sn.subnets[0].netuid, + }); + + // Dispatch the extrinsic with ChargeTransactionPayment extension + let info = call.get_dispatch_info(); + let ext = pallet_transaction_payment::ChargeTransactionPayment::::from(0); + assert_ok!(ext.dispatch_transaction( + RuntimeOrigin::signed(sn.coldkey).into(), + call, + &info, + 0, + 0, + )); + + let final_balance = Balances::free_balance(sn.coldkey); + let alpha_after_0 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( + &sn.hotkeys[0], + &sn.coldkey, + sn.subnets[0].netuid, + ); + + let actual_tao_fee = balance_before - final_balance; + let actual_alpha_fee = alpha_before - alpha_after_0 - alpha_amount; + + // Extrinsic should pay fees in Alpha + assert_eq!(actual_tao_fee, 0); + assert!(actual_alpha_fee > 0.into()); + }); +} diff --git a/pallets/utility/Cargo.toml b/pallets/utility/Cargo.toml index 6d217ebd4b..01ecd42166 100644 --- a/pallets/utility/Cargo.toml +++ b/pallets/utility/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "pallet-utility" version = "38.0.0" -edition = "2021" +edition.workspace = true license = "Apache-2.0" description = "FRAME utilities pallet" readme = "README.md" @@ -13,22 +13,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true } -scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { workspace = true, default-features = false, optional = true } -frame-support = { workspace = true, default-features = false } -frame-system = { workspace = true, default-features = false } -sp-core = { workspace = true, default-features = false } -sp-io = { workspace = true, default-features = false} -sp-runtime = { workspace = true, default-features = false} -subtensor-macros = { workspace = true } +frame-benchmarking = { workspace = true, optional = true } +frame-support.workspace = true +frame-system.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true +codec = { workspace = true, features = ["derive"] } +scale-info = { workspace = true, features = ["derive"] } +subtensor-macros.workspace = true [dev-dependencies] -pallet-balances = { default-features = true, workspace = true } -pallet-collective = { default-features = false, path = "../collective" } -pallet-timestamp = { default-features = true, workspace = true } -sp-core = { default-features = true, workspace = true } -pallet-root-testing = { workspace = true, default-features = false } +pallet-collective.workspace = true +pallet-root-testing.workspace = true +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] @@ -42,7 +42,7 @@ std = [ "sp-io/std", "sp-runtime/std", "pallet-collective/std", - "pallet-root-testing/std" + "pallet-root-testing/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", @@ -51,7 +51,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collective/runtime-benchmarks", - "pallet-timestamp/runtime-benchmarks" + "pallet-timestamp/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", @@ -60,5 +60,5 @@ try-runtime = [ "pallet-balances/try-runtime", "pallet-collective/try-runtime", "pallet-root-testing/try-runtime", - "pallet-timestamp/try-runtime" + "pallet-timestamp/try-runtime", ] diff --git a/pallets/utility/src/lib.rs b/pallets/utility/src/lib.rs index 35f11cbc53..294836677d 100644 --- a/pallets/utility/src/lib.rs +++ b/pallets/utility/src/lib.rs @@ -61,7 +61,7 @@ extern crate alloc; use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ - dispatch::{extract_actual_weight, GetDispatchInfo, PostDispatchInfo}, + dispatch::{GetDispatchInfo, PostDispatchInfo, extract_actual_weight}, traits::{IsSubType, OriginTrait, UnfilteredDispatchable}, }; use sp_core::TypeId; @@ -157,8 +157,7 @@ pub mod pallet { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( core::mem::size_of::<::RuntimeCall>() as u32 <= CALL_ALIGN, - "Call enum size should be smaller than {} bytes.", - CALL_ALIGN, + "Call enum size should be smaller than {CALL_ALIGN} bytes.", ); } } diff --git a/pallets/utility/src/tests.rs b/pallets/utility/src/tests.rs index f0389187a9..a883f1b690 100644 --- a/pallets/utility/src/tests.rs +++ b/pallets/utility/src/tests.rs @@ -32,8 +32,8 @@ use frame_support::{ }; use pallet_collective::{EnsureProportionAtLeast, Instance1}; use sp_runtime::{ - traits::{BadOrigin, BlakeTwo256, Dispatchable, Hash}, BuildStorage, DispatchError, TokenError, + traits::{BadOrigin, BlakeTwo256, Dispatchable, Hash}, }; type BlockNumber = u64; @@ -260,6 +260,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { .expect("Failed to build storage for test"); pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)], + dev_accounts: None, } .assimilate_storage(&mut t) .expect("Failed to build storage for test"); diff --git a/precompiles/Cargo.toml b/precompiles/Cargo.toml index 4159013b85..4045408268 100644 --- a/precompiles/Cargo.toml +++ b/precompiles/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-precompiles" version = "0.1.0" -edition = "2024" +edition.workspace = true authors = ["Opentensor Foundation "] homepage = "https://opentensor.ai/" publish = false @@ -11,32 +11,32 @@ repository = "https://github.com/opentensor/subtensor/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true } -ed25519-dalek = { workspace = true } -fp-evm = { workspace = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -log = { workspace = true } -pallet-balances = { workspace = true } -pallet-evm = { workspace = true } -pallet-evm-precompile-dispatch = { workspace = true } -pallet-evm-precompile-modexp = { workspace = true } -pallet-evm-precompile-sha3fips = { workspace = true } -pallet-evm-precompile-simple = { workspace = true } -pallet-evm-precompile-bn128 = { workspace = true } -pallet-proxy = { workspace = true } -precompile-utils = { workspace = true } -sp-core = { workspace = true } -sp-io = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -subtensor-runtime-common = { workspace = true } -substrate-fixed = { workspace = true } -pallet-subtensor = { workspace = true } -pallet-subtensor-swap = { workspace = true } -pallet-admin-utils = { workspace = true } -subtensor-swap-interface = { workspace = true } -pallet-crowdloan = { workspace = true } +codec = { workspace = true, features = ["derive"] } +ed25519-dalek = { workspace = true, features = ["alloc"] } +fp-evm.workspace = true +frame-support.workspace = true +frame-system.workspace = true +log.workspace = true +pallet-balances.workspace = true +pallet-evm.workspace = true +pallet-evm-precompile-dispatch.workspace = true +pallet-evm-precompile-modexp.workspace = true +pallet-evm-precompile-sha3fips.workspace = true +pallet-evm-precompile-simple.workspace = true +pallet-evm-precompile-bn128.workspace = true +pallet-proxy.workspace = true +precompile-utils.workspace = true +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true +sp-std.workspace = true +subtensor-runtime-common.workspace = true +substrate-fixed.workspace = true +pallet-subtensor.workspace = true +pallet-subtensor-swap.workspace = true +pallet-admin-utils.workspace = true +subtensor-swap-interface.workspace = true +pallet-crowdloan.workspace = true [lints] workspace = true diff --git a/precompiles/src/alpha.rs b/precompiles/src/alpha.rs index 9be98b3b8a..42261674d9 100644 --- a/precompiles/src/alpha.rs +++ b/precompiles/src/alpha.rs @@ -62,7 +62,7 @@ where #[precompile::public("getTaoInPool(uint16)")] #[precompile::view] fn get_tao_in_pool(_handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::SubnetTAO::::get(NetUid::from(netuid))) + Ok(pallet_subtensor::SubnetTAO::::get(NetUid::from(netuid)).to_u64()) } #[precompile::public("getAlphaInPool(uint16)")] @@ -164,9 +164,9 @@ where #[precompile::public("getTaoInEmission(uint16)")] #[precompile::view] fn get_tao_in_emission(_handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(U256::from(pallet_subtensor::SubnetTaoInEmission::::get( - NetUid::from(netuid), - ))) + Ok(U256::from( + pallet_subtensor::SubnetTaoInEmission::::get(NetUid::from(netuid)).to_u64(), + )) } #[precompile::public("getAlphaInEmission(uint16)")] diff --git a/precompiles/src/extensions.rs b/precompiles/src/extensions.rs index ffa8da5778..62c2cef6e6 100644 --- a/precompiles/src/extensions.rs +++ b/precompiles/src/extensions.rs @@ -91,12 +91,12 @@ pub(crate) trait PrecompileHandleExt: PrecompileHandle { ); } - log::debug!("Dispatch succeeded. Post info: {:?}", post_info); + log::debug!("Dispatch succeeded. Post info: {post_info:?}"); Ok(()) } Err(e) => { - log::error!("Dispatch failed. Error: {:?}", e); + log::error!("Dispatch failed. Error: {e:?}"); log::warn!("Returning error PrecompileFailure::Error"); Err(PrecompileFailure::Error { exit_status: ExitError::Other( @@ -141,7 +141,7 @@ pub(crate) trait PrecompileExt>: Precompile { } else { Some(Err(PrecompileFailure::Error { exit_status: ExitError::Other( - format!("Precompile {:?} is disabled", precompile_enum).into(), + format!("Precompile {precompile_enum:?} is disabled").into(), ), })) } diff --git a/precompiles/src/metagraph.rs b/precompiles/src/metagraph.rs index a508dd7c02..cc9652a74b 100644 --- a/precompiles/src/metagraph.rs +++ b/precompiles/src/metagraph.rs @@ -5,7 +5,7 @@ use fp_evm::{ExitError, PrecompileFailure, PrecompileHandle}; use pallet_subtensor::AxonInfo as SubtensorModuleAxonInfo; use precompile_utils::{EvmResult, solidity::Codec}; use sp_core::{ByteArray, H256}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Currency, NetUid}; use crate::PrecompileExt; @@ -41,9 +41,7 @@ where exit_status: ExitError::InvalidRange, })?; - Ok(pallet_subtensor::Pallet::::get_total_stake_for_hotkey( - &hotkey, - )) + Ok(pallet_subtensor::Pallet::::get_total_stake_for_hotkey(&hotkey).to_u64()) } #[precompile::public("getRank(uint16,uint16)")] diff --git a/precompiles/src/staking.rs b/precompiles/src/staking.rs index 22756c2a9a..5f927d62ae 100644 --- a/precompiles/src/staking.rs +++ b/precompiles/src/staking.rs @@ -37,7 +37,7 @@ use precompile_utils::EvmResult; use sp_core::{H256, U256}; use sp_runtime::traits::{Dispatchable, StaticLookup, UniqueSaturatedInto}; use sp_std::vec; -use subtensor_runtime_common::{NetUid, ProxyType}; +use subtensor_runtime_common::{Currency, NetUid, ProxyType}; use crate::{PrecompileExt, PrecompileHandleExt}; @@ -89,13 +89,13 @@ where netuid: U256, ) -> EvmResult<()> { let account_id = handle.caller_account_id::(); - let amount_staked = amount_rao.unique_saturated_into(); + let amount_staked: u64 = amount_rao.unique_saturated_into(); let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; let call = pallet_subtensor::Call::::add_stake { hotkey, netuid: netuid.into(), - amount_staked, + amount_staked: amount_staked.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -133,7 +133,7 @@ where let call = pallet_subtensor::Call::::remove_stake_full_limit { hotkey, netuid: netuid.into(), - limit_price, + limit_price: limit_price.map(Into::into), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -220,7 +220,7 @@ where let coldkey = R::AccountId::from(coldkey.0); let stake = pallet_subtensor::Pallet::::get_total_stake_for_coldkey(&coldkey); - Ok(stake.into()) + Ok(stake.to_u64().into()) } #[precompile::public("getTotalHotkeyStake(bytes32)")] @@ -232,7 +232,7 @@ where let hotkey = R::AccountId::from(hotkey.0); let stake = pallet_subtensor::Pallet::::get_total_stake_for_hotkey(&hotkey); - Ok(stake.into()) + Ok(stake.to_u64().into()) } #[precompile::public("getStake(bytes32,bytes32,uint256)")] @@ -337,15 +337,15 @@ where netuid: U256, ) -> EvmResult<()> { let account_id = handle.caller_account_id::(); - let amount_staked = amount_rao.unique_saturated_into(); - let limit_price = limit_price_rao.unique_saturated_into(); + let amount_staked: u64 = amount_rao.unique_saturated_into(); + let limit_price: u64 = limit_price_rao.unique_saturated_into(); let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; let call = pallet_subtensor::Call::::add_stake_limit { hotkey, netuid: netuid.into(), - amount_staked, - limit_price, + amount_staked: amount_staked.into(), + limit_price: limit_price.into(), allow_partial, }; @@ -365,12 +365,12 @@ where let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; let amount_unstaked: u64 = amount_alpha.unique_saturated_into(); - let limit_price = limit_price_rao.unique_saturated_into(); + let limit_price: u64 = limit_price_rao.unique_saturated_into(); let call = pallet_subtensor::Call::::remove_stake_limit { hotkey, netuid: netuid.into(), amount_unstaked: amount_unstaked.into(), - limit_price, + limit_price: limit_price.into(), allow_partial, }; @@ -432,10 +432,11 @@ where let amount_sub = handle.try_convert_apparent_value::()?; let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; + let amount_staked: u64 = amount_sub.unique_saturated_into(); let call = pallet_subtensor::Call::::add_stake { hotkey, netuid: netuid.into(), - amount_staked: amount_sub.unique_saturated_into(), + amount_staked: amount_staked.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -474,7 +475,8 @@ where let coldkey = R::AccountId::from(coldkey.0); // get total stake of coldkey - let total_stake = pallet_subtensor::Pallet::::get_total_stake_for_coldkey(&coldkey); + let total_stake = + pallet_subtensor::Pallet::::get_total_stake_for_coldkey(&coldkey).to_u64(); // Convert to EVM decimals let stake_u256: SubstrateBalance = total_stake.into(); let stake_eth = ::BalanceConverter::into_evm_balance(stake_u256) @@ -493,7 +495,8 @@ where let hotkey = R::AccountId::from(hotkey.0); // get total stake of hotkey - let total_stake = pallet_subtensor::Pallet::::get_total_stake_for_hotkey(&hotkey); + let total_stake = + pallet_subtensor::Pallet::::get_total_stake_for_hotkey(&hotkey).to_u64(); // Convert to EVM decimals let stake_u256: SubstrateBalance = total_stake.into(); let stake_eth = ::BalanceConverter::into_evm_balance(stake_u256) @@ -580,10 +583,7 @@ where let transfer_result = transfer_call.dispatch(RawOrigin::Signed(Self::account_id()).into()); if let Err(dispatch_error) = transfer_result { - log::error!( - "Transfer back to caller failed. Error: {:?}", - dispatch_error - ); + log::error!("Transfer back to caller failed. Error: {dispatch_error:?}"); return Err(PrecompileFailure::Error { exit_status: ExitError::Other("Transfer back to caller failed".into()), }); diff --git a/precompiles/src/subnet.rs b/precompiles/src/subnet.rs index 3a598db61c..8b4d0eff88 100644 --- a/precompiles/src/subnet.rs +++ b/precompiles/src/subnet.rs @@ -8,7 +8,7 @@ use precompile_utils::{EvmResult, prelude::BoundedString}; use sp_core::H256; use sp_runtime::traits::Dispatchable; use sp_std::vec; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Currency, NetUid}; use crate::{PrecompileExt, PrecompileHandleExt}; @@ -516,7 +516,7 @@ where #[precompile::public("getMinBurn(uint16)")] #[precompile::view] fn get_min_burn(_: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::MinBurn::::get(NetUid::from(netuid))) + Ok(pallet_subtensor::MinBurn::::get(NetUid::from(netuid)).to_u64()) } #[precompile::public("setMinBurn(uint16,uint64)")] @@ -533,7 +533,7 @@ where #[precompile::public("getMaxBurn(uint16)")] #[precompile::view] fn get_max_burn(_: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::MaxBurn::::get(NetUid::from(netuid))) + Ok(pallet_subtensor::MaxBurn::::get(NetUid::from(netuid)).to_u64()) } #[precompile::public("setMaxBurn(uint16,uint64)")] diff --git a/primitives/safe-math/Cargo.toml b/primitives/safe-math/Cargo.toml index eb39f35807..eae2551a84 100644 --- a/primitives/safe-math/Cargo.toml +++ b/primitives/safe-math/Cargo.toml @@ -1,15 +1,13 @@ [package] name = "safe-math" version = "0.1.0" -edition = { workspace = true } +edition.workspace = true [dependencies] -substrate-fixed = { workspace = true } -sp-arithmetic = { workspace = true } -sp-std = { workspace = true } -num-traits = { version = "0.2.19", default-features = false, features = [ - "libm", -] } +substrate-fixed.workspace = true +sp-arithmetic.workspace = true +sp-std.workspace = true +num-traits = { workspace = true, features = ["libm"] } [lints] workspace = true diff --git a/primitives/share-pool/Cargo.toml b/primitives/share-pool/Cargo.toml index 79b7a232a4..ba42b0d77d 100644 --- a/primitives/share-pool/Cargo.toml +++ b/primitives/share-pool/Cargo.toml @@ -1,20 +1,16 @@ [package] name = "share-pool" version = "0.1.0" -edition = "2024" +edition.workspace = true [dependencies] -substrate-fixed = { workspace = true } -sp-std = { workspace = true } -safe-math = { default-features = false, path = "../safe-math" } +substrate-fixed.workspace = true +sp-std.workspace = true +safe-math.workspace = true [lints] workspace = true [features] default = ["std"] -std = [ - "substrate-fixed/std", - "sp-std/std", - "safe-math/std", -] +std = ["substrate-fixed/std", "sp-std/std", "safe-math/std"] diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index 2fa522b6bc..598dab5edf 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -4,7 +4,7 @@ version = "4.0.0-dev" description = "Subtensor network" authors = ["Opentensor Foundation "] homepage = "https://opentensor.ai/" -edition = "2024" +edition.workspace = true license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor/" @@ -15,18 +15,12 @@ workspace = true [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] -[[bin]] -name = "spec_version" -path = "src/spec_version.rs" - [dependencies] subtensor-macros.workspace = true -subtensor-custom-rpc-runtime-api = { workspace = true } -smallvec = { workspace = true } -log = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ - "derive", -] } +subtensor-custom-rpc-runtime-api.workspace = true +smallvec.workspace = true +log.workspace = true +codec = { workspace = true, features = ["derive"] } scale-info = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["alloc"] } pallet-aura = { workspace = true } @@ -36,103 +30,103 @@ pallet-subtensor-swap = { workspace = true } pallet-subtensor-swap-runtime-api = { workspace = true } substrate-fixed = { workspace = true } subtensor-swap-interface = { workspace = true } +subtensor-transaction-fee = { workspace = true } frame-support = { workspace = true } pallet-grandpa = { workspace = true } pallet-insecure-randomness-collective-flip = { workspace = true } frame-system = { workspace = true } frame-try-runtime = { workspace = true, optional = true } -pallet-timestamp = { workspace = true } -pallet-transaction-payment = { workspace = true } -pallet-utility = { workspace = true } -frame-executive = { workspace = true } -frame-metadata-hash-extension = { workspace = true } -sp-api = { workspace = true } -sp-block-builder = { workspace = true } -sp-consensus-aura = { workspace = true } -sp-core = { workspace = true } -sp-storage = { workspace = true } -sp-genesis-builder = { workspace = true } -sp-inherents = { workspace = true } -sp-offchain = { workspace = true } -sp-runtime = { workspace = true } -sp-session = { workspace = true } -sp-std = { workspace = true } -sp-transaction-pool = { workspace = true } -sp-version = { workspace = true } -subtensor-runtime-common = { workspace = true } -subtensor-precompiles = { workspace = true } +pallet-timestamp.workspace = true +pallet-transaction-payment.workspace = true +pallet-utility.workspace = true +frame-executive.workspace = true +frame-metadata-hash-extension.workspace = true +sp-api.workspace = true +sp-block-builder.workspace = true +sp-consensus-aura.workspace = true +sp-core.workspace = true +sp-storage.workspace = true +sp-genesis-builder.workspace = true +sp-inherents.workspace = true +sp-offchain.workspace = true +sp-runtime.workspace = true +sp-session.workspace = true +sp-std.workspace = true +sp-transaction-pool.workspace = true +sp-version.workspace = true +subtensor-runtime-common.workspace = true +subtensor-precompiles.workspace = true # Temporary sudo -pallet-sudo = { workspace = true } +pallet-sudo.workspace = true -pallet-admin-utils = { workspace = true } +pallet-admin-utils.workspace = true # Used for sudo decentralization -pallet-collective = { workspace = true } -pallet-membership = { workspace = true } +pallet-collective.workspace = true +pallet-membership.workspace = true # Multisig -pallet-multisig = { workspace = true } +pallet-multisig.workspace = true # Proxy Pallet -pallet-proxy = { workspace = true } +pallet-proxy.workspace = true # Scheduler pallet -pallet-scheduler = { workspace = true } -pallet-preimage = { workspace = true } +pallet-scheduler.workspace = true +pallet-preimage.workspace = true # Safe mode pallet - -pallet-safe-mode = { workspace = true } +pallet-safe-mode.workspace = true # Used for the node subtensor's RPCs -frame-system-rpc-runtime-api = { workspace = true } -pallet-transaction-payment-rpc-runtime-api = { workspace = true } +frame-system-rpc-runtime-api.workspace = true +pallet-transaction-payment-rpc-runtime-api.workspace = true # Used for runtime benchmarking frame-benchmarking = { workspace = true, optional = true } frame-system-benchmarking = { workspace = true, optional = true } # Identity registry pallet for registering project info -pallet-registry = { workspace = true } +pallet-registry.workspace = true # Metadata commitment pallet -pallet-commitments = { workspace = true } +pallet-commitments.workspace = true # Frontier -fp-evm = { workspace = true } -fp-rpc = { workspace = true } -fp-self-contained = { workspace = true } -precompile-utils = { workspace = true } +fp-evm.workspace = true +fp-rpc.workspace = true +fp-self-contained = { workspace = true, features = ["serde"] } +precompile-utils.workspace = true # Frontier FRAME -pallet-base-fee = { workspace = true } -pallet-ethereum = { workspace = true } -pallet-evm = { workspace = true } -pallet-evm-chain-id = { workspace = true } -pallet-evm-precompile-modexp = { workspace = true } -pallet-evm-precompile-sha3fips = { workspace = true } -pallet-evm-precompile-simple = { workspace = true } -pallet-hotfix-sufficients = { workspace = true } -fp-account = { workspace = true } +pallet-base-fee.workspace = true +pallet-ethereum.workspace = true +pallet-evm.workspace = true +pallet-evm-chain-id.workspace = true +pallet-evm-precompile-modexp.workspace = true +pallet-evm-precompile-sha3fips.workspace = true +pallet-evm-precompile-simple.workspace = true +pallet-hotfix-sufficients.workspace = true +fp-account.workspace = true #drand -pallet-drand = { workspace = true, default-features = false } -getrandom = { workspace = true, default-features = false } -tle = { workspace = true } -hex = { workspace = true } -rand_chacha = { workspace = true } -w3f-bls = { workspace = true } -sha2 = { workspace = true } -ark-serialize = { workspace = true } +pallet-drand.workspace = true +getrandom.workspace = true +tle.workspace = true +hex.workspace = true +rand_chacha.workspace = true +w3f-bls.workspace = true +sha2.workspace = true +ark-serialize = { workspace = true, features = ["derive"] } # Crowdloan -pallet-crowdloan = { workspace = true } +pallet-crowdloan.workspace = true [dev-dependencies] -frame-metadata = { workspace = true } -sp-io = { workspace = true } -sp-tracing = { workspace = true } +frame-metadata.workspace = true +sp-io.workspace = true +sp-tracing.workspace = true [build-dependencies] substrate-wasm-builder = { workspace = true, optional = true } @@ -151,6 +145,7 @@ std = [ "codec/std", "scale-info/std", "frame-executive/std", + "frame-metadata/std", "frame-metadata-hash-extension/std", "frame-support/std", "frame-system-rpc-runtime-api/std", @@ -194,6 +189,7 @@ std = [ "pallet-registry/std", "pallet-admin-utils/std", "subtensor-custom-rpc-runtime-api/std", + "subtensor-transaction-fee/std", "serde_json/std", "sp-io/std", "sp-tracing/std", @@ -257,6 +253,9 @@ runtime-benchmarks = [ "pallet-evm/runtime-benchmarks", "pallet-hotfix-sufficients/runtime-benchmarks", "pallet-drand/runtime-benchmarks", + + # Smart Tx fees pallet + "subtensor-transaction-fee/runtime-benchmarks", ] try-runtime = [ "frame-try-runtime/try-runtime", diff --git a/runtime/src/check_nonce.rs b/runtime/src/check_nonce.rs index 2e05c63867..0d28d33252 100644 --- a/runtime/src/check_nonce.rs +++ b/runtime/src/check_nonce.rs @@ -1,7 +1,7 @@ // Customized from the original implementation in the Polkadot SDK. // https://github.com/paritytech/polkadot-sdk/blob/b600af050d6b6c8da59ae2a2a793ee2d8827ab1e/substrate/frame/system/src/extensions/check_nonce.rs -use codec::{Decode, Encode}; +use codec::{Decode, DecodeWithMemTracking, Encode}; use frame_support::{ RuntimeDebugNoBound, dispatch::{DispatchInfo, Pays}, @@ -34,8 +34,8 @@ use subtensor_macros::freeze_struct; /// step. This means that other extensions ahead of `CheckNonce` in the pipeline must not alter the /// nonce during their own preparation step, or else the transaction may be rejected during dispatch /// or lead to an inconsistent account state.. -#[freeze_struct("feac7c9db94d39ac")] -#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] +#[freeze_struct("cc77e8303313108b")] +#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct CheckNonce(#[codec(compact)] pub T::Nonce); diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 52b8d63e1a..8b8b6b7349 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -16,19 +16,12 @@ mod migrations; extern crate alloc; use codec::{Compact, Decode, Encode}; -use frame_support::dispatch::DispatchResult; -use frame_support::traits::{Imbalance, InsideBoth}; use frame_support::{ PalletId, - dispatch::DispatchResultWithPostInfo, + dispatch::{DispatchResult, DispatchResultWithPostInfo}, genesis_builder_helper::{build_state, get_preset}, pallet_prelude::Get, - traits::{ - Contains, LinearStoragePrice, OnUnbalanced, - fungible::{ - DecreaseIssuance, HoldConsideration, Imbalance as FungibleImbalance, IncreaseIssuance, - }, - }, + traits::{Contains, InsideBoth, LinearStoragePrice, fungible::HoldConsideration}, }; use frame_system::{EnsureNever, EnsureRoot, EnsureRootWithSuccess, RawOrigin}; use pallet_commitments::{CanCommit, OnMetadataCommitment}; @@ -45,7 +38,6 @@ use pallet_subtensor::rpc_info::{ stake_info::StakeInfo, subnet_info::{SubnetHyperparams, SubnetHyperparamsV2, SubnetInfo, SubnetInfov2}, }; -use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{ @@ -68,7 +60,7 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; use subtensor_precompiles::Precompiles; -use subtensor_runtime_common::{AlphaCurrency, time::*, *}; +use subtensor_runtime_common::{AlphaCurrency, TaoCurrency, time::*, *}; // A few exports that help ease life for downstream crates. pub use frame_support::{ @@ -88,7 +80,9 @@ pub use frame_support::{ pub use frame_system::Call as SystemCall; pub use pallet_balances::Call as BalancesCall; pub use pallet_timestamp::Call as TimestampCall; -use pallet_transaction_payment::{ConstFeeMultiplier, FungibleAdapter, Multiplier}; +use pallet_transaction_payment::{ConstFeeMultiplier, Multiplier}; +use subtensor_transaction_fee::{SubtensorTxFeeHandler, TransactionFeeHandler}; + #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Perbill, Permill}; @@ -218,7 +212,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // `spec_version`, and `authoring_version` are the same between Wasm and native. // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use // the compatible custom types. - spec_version: 299, + spec_version: 301, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -445,58 +439,16 @@ impl pallet_balances::Config for Runtime { type DoneSlashHandler = (); } -pub struct LinearWeightToFee; - -impl WeightToFeePolynomial for LinearWeightToFee { - type Balance = Balance; - - fn polynomial() -> WeightToFeeCoefficients { - let coefficient = WeightToFeeCoefficient { - coeff_integer: 0, - coeff_frac: Perbill::from_parts(500_000), - negative: false, - degree: 1, - }; - - smallvec!(coefficient) - } -} - parameter_types! { pub const OperationalFeeMultiplier: u8 = 5; pub FeeMultiplier: Multiplier = Multiplier::one(); } -/// Deduct the transaction fee from the Subtensor Pallet TotalIssuance when dropping the transaction -/// fee. -pub struct TransactionFeeHandler; -impl - OnUnbalanced< - FungibleImbalance< - u64, - DecreaseIssuance>, - IncreaseIssuance>, - >, - > for TransactionFeeHandler -{ - fn on_nonzero_unbalanced( - credit: FungibleImbalance< - u64, - DecreaseIssuance>, - IncreaseIssuance>, - >, - ) { - let ti_before = pallet_subtensor::TotalIssuance::::get(); - pallet_subtensor::TotalIssuance::::put(ti_before.saturating_sub(credit.peek())); - drop(credit); - } -} - impl pallet_transaction_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type OnChargeTransaction = FungibleAdapter; + type OnChargeTransaction = SubtensorTxFeeHandler>; // Convert dispatch weight to a chargeable fee. - type WeightToFee = LinearWeightToFee; + type WeightToFee = subtensor_transaction_fee::LinearWeightToFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; type LengthToFee = IdentityFee; type FeeMultiplierUpdate = ConstFeeMultiplier; @@ -671,6 +623,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = pallet_multisig::weights::SubstrateWeight; + type BlockNumberProvider = System; } // Proxy Pallet config @@ -1005,6 +958,7 @@ impl pallet_scheduler::Config for Runtime { type WeightInfo = pallet_scheduler::weights::SubstrateWeight; type OriginPrivilegeCmp = OriginPrivilegeCmp; type Preimages = Preimage; + type BlockNumberProvider = System; } parameter_types! { @@ -1408,17 +1362,13 @@ impl BalanceConverter for SubtensorEvmBalanceConverter { } else { // Log value too large log::debug!( - "SubtensorEvmBalanceConverter::into_evm_balance( {:?} ) larger than U256::MAX", - value + "SubtensorEvmBalanceConverter::into_evm_balance( {value:?} ) larger than U256::MAX" ); None } } else { // Log overflow - log::debug!( - "SubtensorEvmBalanceConverter::into_evm_balance( {:?} ) overflow", - value - ); + log::debug!("SubtensorEvmBalanceConverter::into_evm_balance( {value:?} ) overflow"); None } } @@ -1433,16 +1383,14 @@ impl BalanceConverter for SubtensorEvmBalanceConverter { } else { // Log value too large log::debug!( - "SubtensorEvmBalanceConverter::into_substrate_balance( {:?} ) larger than u64::MAX", - value + "SubtensorEvmBalanceConverter::into_substrate_balance( {value:?} ) larger than u64::MAX" ); None } } else { // Log overflow log::debug!( - "SubtensorEvmBalanceConverter::into_substrate_balance( {:?} ) overflow", - value + "SubtensorEvmBalanceConverter::into_substrate_balance( {value:?} ) overflow" ); None } @@ -1473,6 +1421,8 @@ impl pallet_evm::Config for Runtime { type BalanceConverter = SubtensorEvmBalanceConverter; type AccountProvider = pallet_evm::FrameSystemAccountProvider; type GasLimitStorageGrowthRatio = (); + type CreateOriginFilter = (); + type CreateInnerOriginFilter = (); } parameter_types! { @@ -2243,7 +2193,7 @@ impl_runtime_apis! { Vec, Vec, ) { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkList}; + use frame_benchmarking::{baseline, BenchmarkList}; use frame_support::traits::StorageInfoTrait; use frame_system_benchmarking::Pallet as SystemBench; use baseline::Pallet as BaselineBench; @@ -2259,7 +2209,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, alloc::string::String> { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch}; + use frame_benchmarking::{baseline, BenchmarkBatch}; use sp_storage::TrackedStorageKey; use frame_system_benchmarking::Pallet as SystemBench; @@ -2407,7 +2357,7 @@ impl_runtime_apis! { } impl subtensor_custom_rpc_runtime_api::SubnetRegistrationRuntimeApi for Runtime { - fn get_network_registration_cost() -> u64 { + fn get_network_registration_cost() -> TaoCurrency { SubtensorModule::get_network_lock_cost() } } diff --git a/runtime/tests/pallet_proxy.rs b/runtime/tests/pallet_proxy.rs index 5c6c9cd821..b81c34e1dc 100644 --- a/runtime/tests/pallet_proxy.rs +++ b/runtime/tests/pallet_proxy.rs @@ -24,6 +24,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { (AccountId::from(DELEGATE), amount), (AccountId::from(OTHER_ACCOUNT), amount), ], + dev_accounts: None, }, triumvirate: pallet_collective::GenesisConfig { @@ -142,7 +143,7 @@ fn call_add_stake() -> RuntimeCall { RuntimeCall::SubtensorModule(pallet_subtensor::Call::add_stake { hotkey: AccountId::from(DELEGATE), netuid, - amount_staked, + amount_staked: amount_staked.into(), }) } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 8b497b3762..bfb378c468 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "1.87" +channel = "1.88" # rustc 1.88.0 (6b00bc388 2025-06-23) components = [ "cargo", "clippy", @@ -10,5 +10,5 @@ components = [ "rustc-dev", "rustfmt", ] -targets = ["wasm32-unknown-unknown"] +targets = ["wasm32v1-none"] profile = "minimal" diff --git a/support/linting/Cargo.toml b/support/linting/Cargo.toml index a74f77be2a..1b7528cb17 100644 --- a/support/linting/Cargo.toml +++ b/support/linting/Cargo.toml @@ -1,13 +1,19 @@ [package] name = "subtensor-linting" version = "0.1.0" -edition = "2024" +edition.workspace = true [dependencies] -syn.workspace = true +syn = { workspace = true, features = [ + "full", + "visit-mut", + "visit", + "extra-traits", + "parsing", +] } quote.workspace = true proc-macro2.workspace = true -procedural-fork = { version = "1.10.0-rc3", path = "../procedural-fork" } +procedural-fork.workspace = true [lints] workspace = true diff --git a/support/macros/Cargo.toml b/support/macros/Cargo.toml index e9acb21ab7..3f9a9c2c33 100644 --- a/support/macros/Cargo.toml +++ b/support/macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-macros" version = "0.1.0" -edition = "2024" +edition.workspace = true license = "MIT" description = "support macros for Subtensor" @@ -12,10 +12,16 @@ homepage = "https://bittensor.com/" proc-macro = true [dependencies] -syn.workspace = true +syn = { workspace = true, features = [ + "full", + "visit-mut", + "visit", + "extra-traits", + "parsing", +] } proc-macro2.workspace = true quote.workspace = true -ahash = "0.8" +ahash.workspace = true [lints] workspace = true diff --git a/support/macros/src/lib.rs b/support/macros/src/lib.rs index 91b5ed2a78..ccd3274148 100644 --- a/support/macros/src/lib.rs +++ b/support/macros/src/lib.rs @@ -41,7 +41,7 @@ fn freeze_struct_impl( visit_item_struct_mut(&mut visitor, &mut item_clone); let calculated_hash = generate_hash(&item_clone); - let calculated_hash_hex = format!("{:x}", calculated_hash); + let calculated_hash_hex = format!("{calculated_hash:x}"); if attr.is_empty() { return Err(Error::new_spanned( @@ -60,11 +60,10 @@ fn freeze_struct_impl( return Err(Error::new_spanned( item, format!( - "You have made a non-trivial change to this struct and the provided hashcode no longer matches:\n{} != {}\n\n\ + "You have made a non-trivial change to this struct and the provided hashcode no longer matches:\n{provided_hash_hex} != {calculated_hash_hex}\n\n\ If this was intentional, please update the hashcode in the `freeze_struct` attribute to:\n\ - {}\n\nNote that if you are changing a storage struct in any way, including simply re-ordering fields, \ - you will need a migration to prevent data corruption.", - provided_hash_hex, calculated_hash_hex, calculated_hash_hex + {calculated_hash_hex}\n\nNote that if you are changing a storage struct in any way, including simply re-ordering fields, \ + you will need a migration to prevent data corruption." ), )); } diff --git a/support/procedural-fork/Cargo.toml b/support/procedural-fork/Cargo.toml index 503c81f1fd..fdc280ec14 100644 --- a/support/procedural-fork/Cargo.toml +++ b/support/procedural-fork/Cargo.toml @@ -1,31 +1,37 @@ [package] name = "procedural-fork" version = "1.10.0-rc3" -edition = "2021" +edition.workspace = true [lints.clippy] all = "allow" [dependencies] -derive-syn-parse = "0.2" -Inflector = "0.11" -cfg-expr = "0.15" -itertools = "0.10" +derive-syn-parse.workspace = true +Inflector.workspace = true +cfg-expr.workspace = true +itertools.workspace = true proc-macro2.workspace = true quote.workspace = true -syn.workspace = true -macro_magic = { version = "0.5", features = ["proc_support"] } -frame-support-procedural-tools = { version = "10.0.0" } -proc-macro-warning = { version = "1", default-features = false } -expander = "2" -sp-crypto-hashing = { default-features = false, version = "0.1.0" } +syn = { workspace = true, features = [ + "full", + "visit-mut", + "visit", + "extra-traits", + "parsing", +] } +macro_magic = { workspace = true, features = ["proc_support"] } +frame-support-procedural-tools.workspace = true +proc-macro-warning.workspace = true +expander.workspace = true +sp-crypto-hashing.workspace = true [dev-dependencies] -regex = "1" +regex.workspace = true [features] default = ["std"] -std = ["sp-crypto-hashing/std"] +std = ["sp-crypto-hashing/std", "regex/std"] no-metadata-docs = [] experimental = [] # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of diff --git a/support/procedural-fork/src/benchmark.rs b/support/procedural-fork/src/benchmark.rs index 0eb3c330a1..61cda35c66 100644 --- a/support/procedural-fork/src/benchmark.rs +++ b/support/procedural-fork/src/benchmark.rs @@ -21,16 +21,16 @@ use derive_syn_parse::Parse; use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro::TokenStream; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::{ + Attribute, Error, Expr, ExprBlock, ExprCall, ExprPath, FnArg, Item, ItemFn, ItemMod, Pat, Path, + PathArguments, PathSegment, Result, ReturnType, Signature, Stmt, Token, Type, TypePath, + Visibility, WhereClause, parse::{Nothing, ParseStream}, parse_quote, punctuated::Punctuated, spanned::Spanned, token::{Comma, Gt, Lt, PathSep}, - Attribute, Error, Expr, ExprBlock, ExprCall, ExprPath, FnArg, Item, ItemFn, ItemMod, Pat, Path, - PathArguments, PathSegment, Result, ReturnType, Signature, Stmt, Token, Type, TypePath, - Visibility, WhereClause, }; mod keywords { @@ -297,9 +297,9 @@ fn ensure_valid_return_type(item_fn: &ItemFn) -> Result<()> { let non_unit = |span| return Err(Error::new(span, "expected `()`")); let Type::Path(TypePath { path, qself: _ }) = &**typ else { return Err(Error::new( - typ.span(), - "Only `Result<(), BenchmarkError>` or a blank return type is allowed on benchmark function definitions", - )); + typ.span(), + "Only `Result<(), BenchmarkError>` or a blank return type is allowed on benchmark function definitions", + )); }; let seg = path .segments @@ -363,9 +363,9 @@ fn parse_params(item_fn: &ItemFn) -> Result> { let var_span = ident.span(); let invalid_param_name = || { return Err(Error::new( - var_span, - "Benchmark parameter names must consist of a single lowercase letter (a-z) and no other characters.", - )); + var_span, + "Benchmark parameter names must consist of a single lowercase letter (a-z) and no other characters.", + )); }; let name = ident.ident.to_token_stream().to_string(); if name.len() > 1 { @@ -404,9 +404,9 @@ fn parse_params(item_fn: &ItemFn) -> Result> { /// Used in several places where the `#[extrinsic_call]` or `#[body]` annotation is missing fn missing_call(item_fn: &ItemFn) -> Result { return Err(Error::new( - item_fn.block.brace_token.span.join(), - "No valid #[extrinsic_call] or #[block] annotation could be found in benchmark function body." - )); + item_fn.block.brace_token.span.join(), + "No valid #[extrinsic_call] or #[block] annotation could be found in benchmark function body.", + )); } /// Finds the `BenchmarkCallDef` and its index (within the list of stmts for the fn) and @@ -455,7 +455,7 @@ fn parse_call_def(item_fn: &ItemFn) -> Result<(usize, BenchmarkCallDef)> { return Err(Error::new( call_defs[1].1.attr_span(), "Only one #[extrinsic_call] or #[block] attribute is allowed per benchmark.", - )) + )); } }) } diff --git a/support/procedural-fork/src/construct_runtime/expand/config.rs b/support/procedural-fork/src/construct_runtime/expand/config.rs index ff715e5846..1fbcd107f6 100644 --- a/support/procedural-fork/src/construct_runtime/expand/config.rs +++ b/support/procedural-fork/src/construct_runtime/expand/config.rs @@ -18,7 +18,7 @@ use crate::construct_runtime::Pallet; use inflector::Inflector; use proc_macro2::TokenStream; -use quote::{format_ident, quote, ToTokens}; +use quote::{ToTokens, format_ident, quote}; use std::str::FromStr; use syn::Ident; diff --git a/support/procedural-fork/src/construct_runtime/expand/metadata.rs b/support/procedural-fork/src/construct_runtime/expand/metadata.rs index 9f3d9cd4a3..4d338d7977 100644 --- a/support/procedural-fork/src/construct_runtime/expand/metadata.rs +++ b/support/procedural-fork/src/construct_runtime/expand/metadata.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License -use crate::construct_runtime::{parse::PalletPath, Pallet}; +use crate::construct_runtime::{Pallet, parse::PalletPath}; use proc_macro2::TokenStream; use quote::quote; use std::str::FromStr; diff --git a/support/procedural-fork/src/construct_runtime/expand/mod.rs b/support/procedural-fork/src/construct_runtime/expand/mod.rs index 88f9a3c6e3..2d3538fcff 100644 --- a/support/procedural-fork/src/construct_runtime/expand/mod.rs +++ b/support/procedural-fork/src/construct_runtime/expand/mod.rs @@ -37,7 +37,7 @@ pub use inherent::expand_outer_inherent; pub use lock_id::expand_outer_lock_id; pub use metadata::expand_runtime_metadata; pub use origin::expand_outer_origin; -pub use outer_enums::{expand_outer_enum, OuterEnumType}; +pub use outer_enums::{OuterEnumType, expand_outer_enum}; pub use slash_reason::expand_outer_slash_reason; pub use task::expand_outer_task; pub use unsigned::expand_outer_validate_unsigned; diff --git a/support/procedural-fork/src/construct_runtime/expand/outer_enums.rs b/support/procedural-fork/src/construct_runtime/expand/outer_enums.rs index 28e39c7a21..3747cedea2 100644 --- a/support/procedural-fork/src/construct_runtime/expand/outer_enums.rs +++ b/support/procedural-fork/src/construct_runtime/expand/outer_enums.rs @@ -17,7 +17,7 @@ use crate::construct_runtime::Pallet; use proc_macro2::{Span, TokenStream}; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use std::str::FromStr; use syn::{Generics, Ident}; diff --git a/support/procedural-fork/src/construct_runtime/mod.rs b/support/procedural-fork/src/construct_runtime/mod.rs index 9bc271fdc8..cf39972461 100644 --- a/support/procedural-fork/src/construct_runtime/mod.rs +++ b/support/procedural-fork/src/construct_runtime/mod.rs @@ -222,7 +222,7 @@ use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use std::{collections::HashSet, str::FromStr}; -use syn::{spanned::Spanned, Ident, Result}; +use syn::{Ident, Result, spanned::Spanned}; /// The fixed name of the system pallet. const SYSTEM_PALLET_NAME: &str = "System"; diff --git a/support/procedural-fork/src/construct_runtime/parse.rs b/support/procedural-fork/src/construct_runtime/parse.rs index e5e60b3ff9..d2b2a4e4f6 100644 --- a/support/procedural-fork/src/construct_runtime/parse.rs +++ b/support/procedural-fork/src/construct_runtime/parse.rs @@ -20,11 +20,12 @@ use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use std::collections::{HashMap, HashSet}; use syn::{ + Attribute, Error, Ident, Path, Result, Token, ext::IdentExt, parse::{Parse, ParseStream}, punctuated::Punctuated, spanned::Spanned, - token, Attribute, Error, Ident, Path, Result, Token, + token, }; mod keyword { @@ -149,9 +150,7 @@ impl Parse for WhereSection { remove_kind(input, WhereKind::NodeBlock, &mut definitions)?; remove_kind(input, WhereKind::UncheckedExtrinsic, &mut definitions)?; if let Some(WhereDefinition { - ref kind_span, - ref kind, - .. + kind_span, kind, .. }) = definitions.first() { let msg = format!( diff --git a/support/procedural-fork/src/derive_impl.rs b/support/procedural-fork/src/derive_impl.rs index e91f9c534a..4320a8bf86 100644 --- a/support/procedural-fork/src/derive_impl.rs +++ b/support/procedural-fork/src/derive_impl.rs @@ -20,10 +20,10 @@ use derive_syn_parse::Parse; use macro_magic::mm_core::ForeignPath; use proc_macro2::TokenStream as TokenStream2; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use std::collections::HashSet; use syn::{ - parse2, parse_quote, spanned::Spanned, token, Ident, ImplItem, ItemImpl, Path, Result, Token, + Ident, ImplItem, ItemImpl, Path, Result, Token, parse_quote, parse2, spanned::Spanned, token, }; mod keyword { diff --git a/support/procedural-fork/src/dynamic_params.rs b/support/procedural-fork/src/dynamic_params.rs index e1f9f626ce..eeb7720798 100644 --- a/support/procedural-fork/src/dynamic_params.rs +++ b/support/procedural-fork/src/dynamic_params.rs @@ -21,8 +21,8 @@ use frame_support_procedural_tools::generate_access_from_frame_or_crate; use inflector::Inflector; use proc_macro2::{Span, TokenStream}; -use quote::{format_ident, quote, ToTokens}; -use syn::{parse2, spanned::Spanned, visit_mut, visit_mut::VisitMut, Result, Token}; +use quote::{ToTokens, format_ident, quote}; +use syn::{Result, Token, parse2, spanned::Spanned, visit_mut, visit_mut::VisitMut}; /// Parse and expand a `#[dynamic_params(..)]` module. pub fn dynamic_params(attr: TokenStream, item: TokenStream) -> Result { diff --git a/support/procedural-fork/src/key_prefix.rs b/support/procedural-fork/src/key_prefix.rs index aea60ce3ba..6202d227a9 100644 --- a/support/procedural-fork/src/key_prefix.rs +++ b/support/procedural-fork/src/key_prefix.rs @@ -17,7 +17,7 @@ use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::{Span, TokenStream}; -use quote::{format_ident, quote, ToTokens}; +use quote::{ToTokens, format_ident, quote}; use syn::{Ident, Result}; const MAX_IDENTS: usize = 18; diff --git a/support/procedural-fork/src/no_bound/default.rs b/support/procedural-fork/src/no_bound/default.rs index 3f896da352..615268d7bd 100644 --- a/support/procedural-fork/src/no_bound/default.rs +++ b/support/procedural-fork/src/no_bound/default.rs @@ -17,7 +17,7 @@ use proc_macro2::Span; use quote::{quote, quote_spanned}; -use syn::{spanned::Spanned, Data, DeriveInput, Fields}; +use syn::{Data, DeriveInput, Fields, spanned::Spanned}; /// Derive Default but do not bound any generic. pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -152,7 +152,7 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To "Union type not supported by `derive(DefaultNoBound)`", ) .to_compile_error() - .into() + .into(); } }; diff --git a/support/procedural-fork/src/pallet/expand/call.rs b/support/procedural-fork/src/pallet/expand/call.rs index a39e81fd1f..189eabe4cd 100644 --- a/support/procedural-fork/src/pallet/expand/call.rs +++ b/support/procedural-fork/src/pallet/expand/call.rs @@ -16,16 +16,16 @@ // limitations under the License. use crate::{ + COUNTER, pallet::{ + Def, expand::warnings::{weight_constant_warning, weight_witness_warning}, parse::call::CallWeightDef, - Def, }, - COUNTER, }; -use proc_macro2::TokenStream as TokenStream2; use proc_macro_warning::Warning; -use quote::{quote, ToTokens}; +use proc_macro2::TokenStream as TokenStream2; +use quote::{ToTokens, quote}; use syn::spanned::Spanned; /// diff --git a/support/procedural-fork/src/pallet/expand/config.rs b/support/procedural-fork/src/pallet/expand/config.rs index 836c74ae7c..dbaf709e88 100644 --- a/support/procedural-fork/src/pallet/expand/config.rs +++ b/support/procedural-fork/src/pallet/expand/config.rs @@ -18,7 +18,7 @@ use crate::pallet::Def; use proc_macro2::TokenStream; use quote::quote; -use syn::{parse_quote, Item}; +use syn::{Item, parse_quote}; /// /// * Generate default rust doc diff --git a/support/procedural-fork/src/pallet/expand/documentation.rs b/support/procedural-fork/src/pallet/expand/documentation.rs index 62b2e8b8b3..f1b91c5f2a 100644 --- a/support/procedural-fork/src/pallet/expand/documentation.rs +++ b/support/procedural-fork/src/pallet/expand/documentation.rs @@ -18,7 +18,7 @@ use crate::pallet::Def; use proc_macro2::TokenStream; use quote::ToTokens; -use syn::{spanned::Spanned, Attribute, Lit, LitStr}; +use syn::{Attribute, Lit, LitStr, spanned::Spanned}; const DOC: &'static str = "doc"; const PALLET_DOC: &'static str = "pallet_doc"; diff --git a/support/procedural-fork/src/pallet/expand/error.rs b/support/procedural-fork/src/pallet/expand/error.rs index 1b76034efa..e68b8663f6 100644 --- a/support/procedural-fork/src/pallet/expand/error.rs +++ b/support/procedural-fork/src/pallet/expand/error.rs @@ -16,11 +16,11 @@ // limitations under the License. use crate::{ + COUNTER, pallet::{ - parse::error::{VariantDef, VariantField}, Def, + parse::error::{VariantDef, VariantField}, }, - COUNTER, }; use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; diff --git a/support/procedural-fork/src/pallet/expand/event.rs b/support/procedural-fork/src/pallet/expand/event.rs index 931dcd95a6..8b75f2d45a 100644 --- a/support/procedural-fork/src/pallet/expand/event.rs +++ b/support/procedural-fork/src/pallet/expand/event.rs @@ -16,11 +16,11 @@ // limitations under the License. use crate::{ - pallet::{parse::event::PalletEventDepositAttr, Def}, COUNTER, + pallet::{Def, parse::event::PalletEventDepositAttr}, }; use frame_support_procedural_tools::get_doc_literals; -use syn::{spanned::Spanned, Ident}; +use syn::{Ident, spanned::Spanned}; /// /// * Add __Ignore variant on Event diff --git a/support/procedural-fork/src/pallet/expand/genesis_config.rs b/support/procedural-fork/src/pallet/expand/genesis_config.rs index e171e2468d..e98b410d02 100644 --- a/support/procedural-fork/src/pallet/expand/genesis_config.rs +++ b/support/procedural-fork/src/pallet/expand/genesis_config.rs @@ -15,10 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{pallet::Def, COUNTER}; +use crate::{COUNTER, pallet::Def}; use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; -use syn::{spanned::Spanned, Ident}; +use syn::{Ident, spanned::Spanned}; /// /// * add various derive trait on GenesisConfig struct. diff --git a/support/procedural-fork/src/pallet/expand/inherent.rs b/support/procedural-fork/src/pallet/expand/inherent.rs index 0a80d672ab..832a755145 100644 --- a/support/procedural-fork/src/pallet/expand/inherent.rs +++ b/support/procedural-fork/src/pallet/expand/inherent.rs @@ -15,10 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{pallet::Def, COUNTER}; +use crate::{COUNTER, pallet::Def}; use proc_macro2::TokenStream; use quote::quote; -use syn::{spanned::Spanned, Ident}; +use syn::{Ident, spanned::Spanned}; pub fn expand_inherents(def: &mut Def) -> TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/support/procedural-fork/src/pallet/expand/instances.rs b/support/procedural-fork/src/pallet/expand/instances.rs index 12423409cf..d6d80854ae 100644 --- a/support/procedural-fork/src/pallet/expand/instances.rs +++ b/support/procedural-fork/src/pallet/expand/instances.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{pallet::Def, NUMBER_OF_INSTANCE}; +use crate::{NUMBER_OF_INSTANCE, pallet::Def}; use proc_macro2::Span; /// diff --git a/support/procedural-fork/src/pallet/expand/origin.rs b/support/procedural-fork/src/pallet/expand/origin.rs index 167445ad64..3399143f04 100644 --- a/support/procedural-fork/src/pallet/expand/origin.rs +++ b/support/procedural-fork/src/pallet/expand/origin.rs @@ -15,10 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{pallet::Def, COUNTER}; +use crate::{COUNTER, pallet::Def}; use proc_macro2::TokenStream; use quote::quote; -use syn::{spanned::Spanned, Ident}; +use syn::{Ident, spanned::Spanned}; pub fn expand_origins(def: &mut Def) -> TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/support/procedural-fork/src/pallet/expand/pallet_struct.rs b/support/procedural-fork/src/pallet/expand/pallet_struct.rs index 64e5d533cd..8d2e198bc5 100644 --- a/support/procedural-fork/src/pallet/expand/pallet_struct.rs +++ b/support/procedural-fork/src/pallet/expand/pallet_struct.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::pallet::{expand::merge_where_clauses, Def}; +use crate::pallet::{Def, expand::merge_where_clauses}; use frame_support_procedural_tools::get_doc_literals; /// diff --git a/support/procedural-fork/src/pallet/expand/storage.rs b/support/procedural-fork/src/pallet/expand/storage.rs index 95b0466707..51c9e8eb12 100644 --- a/support/procedural-fork/src/pallet/expand/storage.rs +++ b/support/procedural-fork/src/pallet/expand/storage.rs @@ -18,11 +18,11 @@ use crate::{ counter_prefix, pallet::{ + Def, parse::{ helper::two128_str, storage::{Metadata, QueryKind, StorageDef, StorageGenerics}, }, - Def, }, }; use quote::ToTokens; @@ -445,8 +445,8 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { let docs = if cfg!(feature = "no-metadata-docs") { &no_docs } else { &storage.docs }; let ident = &storage.ident; - let gen = &def.type_use_generics(storage.attr_span); - let full_ident = quote::quote_spanned!(storage.attr_span => #ident<#gen> ); + let generics = &def.type_use_generics(storage.attr_span); + let full_ident = quote::quote_spanned!(storage.attr_span => #ident<#generics> ); let cfg_attrs = &storage.cfg_attrs; @@ -469,10 +469,10 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { super::merge_where_clauses(&[&storage.where_clause, &def.config.where_clause]); let ident = &storage.ident; - let gen = &def.type_use_generics(storage.attr_span); + let generics = &def.type_use_generics(storage.attr_span); let type_impl_gen = &def.type_impl_generics(storage.attr_span); let type_use_gen = &def.type_use_generics(storage.attr_span); - let full_ident = quote::quote_spanned!(storage.attr_span => #ident<#gen> ); + let full_ident = quote::quote_spanned!(storage.attr_span => #ident<#generics> ); let cfg_attrs = &storage.cfg_attrs; @@ -876,8 +876,8 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { // crate. if storage.try_decode && storage.cfg_attrs.is_empty() { let ident = &storage.ident; - let gen = &def.type_use_generics(storage.attr_span); - Some(quote::quote_spanned!(storage.attr_span => #ident<#gen> )) + let generics = &def.type_use_generics(storage.attr_span); + Some(quote::quote_spanned!(storage.attr_span => #ident<#generics> )) } else { None } diff --git a/support/procedural-fork/src/pallet/expand/tasks.rs b/support/procedural-fork/src/pallet/expand/tasks.rs index 8a0bd22528..98496009b3 100644 --- a/support/procedural-fork/src/pallet/expand/tasks.rs +++ b/support/procedural-fork/src/pallet/expand/tasks.rs @@ -19,12 +19,12 @@ //! Home of the expansion code for the Tasks API -use crate::pallet::{parse::tasks::*, Def}; +use crate::pallet::{Def, parse::tasks::*}; use derive_syn_parse::Parse; use inflector::Inflector; use proc_macro2::TokenStream as TokenStream2; -use quote::{format_ident, quote, ToTokens}; -use syn::{parse_quote, spanned::Spanned, ItemEnum, ItemImpl}; +use quote::{ToTokens, format_ident, quote}; +use syn::{ItemEnum, ItemImpl, parse_quote, spanned::Spanned}; impl TaskEnumDef { /// Since we optionally allow users to manually specify a `#[pallet::task_enum]`, in the diff --git a/support/procedural-fork/src/pallet/expand/tt_default_parts.rs b/support/procedural-fork/src/pallet/expand/tt_default_parts.rs index 8e7dc39d86..abd48aa21d 100644 --- a/support/procedural-fork/src/pallet/expand/tt_default_parts.rs +++ b/support/procedural-fork/src/pallet/expand/tt_default_parts.rs @@ -16,8 +16,8 @@ // limitations under the License. use crate::{ - pallet::{CompositeKeyword, Def}, COUNTER, + pallet::{CompositeKeyword, Def}, }; use syn::spanned::Spanned; @@ -38,23 +38,23 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { let storage_part = (!def.storages.is_empty()).then(|| quote::quote!(Storage,)); let event_part = def.event.as_ref().map(|event| { - let gen = event.gen_kind.is_generic().then(|| quote::quote!( )); - quote::quote!( Event #gen , ) + let generics = event.gen_kind.is_generic().then(|| quote::quote!( )); + quote::quote!( Event #generics , ) }); let error_part = def.error.as_ref().map(|_| quote::quote!(Error,)); let origin_part = def.origin.as_ref().map(|origin| { - let gen = origin.is_generic.then(|| quote::quote!( )); - quote::quote!( Origin #gen , ) + let generics = origin.is_generic.then(|| quote::quote!( )); + quote::quote!( Origin #generics , ) }); let config_part = def.genesis_config.as_ref().map(|genesis_config| { - let gen = genesis_config + let generic = genesis_config .gen_kind .is_generic() .then(|| quote::quote!( )); - quote::quote!( Config #gen , ) + quote::quote!( Config #generic , ) }); let inherent_part = def.inherent.as_ref().map(|_| quote::quote!(Inherent,)); @@ -95,23 +95,23 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { let storage_part_v2 = (!def.storages.is_empty()).then(|| quote::quote!(+ Storage)); let event_part_v2 = def.event.as_ref().map(|event| { - let gen = event.gen_kind.is_generic().then(|| quote::quote!()); - quote::quote!(+ Event #gen) + let generic = event.gen_kind.is_generic().then(|| quote::quote!()); + quote::quote!(+ Event #generic) }); let error_part_v2 = def.error.as_ref().map(|_| quote::quote!(+ Error)); let origin_part_v2 = def.origin.as_ref().map(|origin| { - let gen = origin.is_generic.then(|| quote::quote!()); - quote::quote!(+ Origin #gen) + let generic = origin.is_generic.then(|| quote::quote!()); + quote::quote!(+ Origin #generic) }); let config_part_v2 = def.genesis_config.as_ref().map(|genesis_config| { - let gen = genesis_config + let generic = genesis_config .gen_kind .is_generic() .then(|| quote::quote!()); - quote::quote!(+ Config #gen) + quote::quote!(+ Config #generic) }); let inherent_part_v2 = def.inherent.as_ref().map(|_| quote::quote!(+ Inherent)); diff --git a/support/procedural-fork/src/pallet/expand/validate_unsigned.rs b/support/procedural-fork/src/pallet/expand/validate_unsigned.rs index 28c78a1c66..a3a849704d 100644 --- a/support/procedural-fork/src/pallet/expand/validate_unsigned.rs +++ b/support/procedural-fork/src/pallet/expand/validate_unsigned.rs @@ -15,10 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{pallet::Def, COUNTER}; +use crate::{COUNTER, pallet::Def}; use proc_macro2::TokenStream; use quote::quote; -use syn::{spanned::Spanned, Ident}; +use syn::{Ident, spanned::Spanned}; pub fn expand_validate_unsigned(def: &mut Def) -> TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/support/procedural-fork/src/pallet/mod.rs b/support/procedural-fork/src/pallet/mod.rs index d3796662f1..3636cc611b 100644 --- a/support/procedural-fork/src/pallet/mod.rs +++ b/support/procedural-fork/src/pallet/mod.rs @@ -28,7 +28,7 @@ mod expand; pub(crate) mod parse; -pub use parse::{composite::keyword::CompositeKeyword, Def}; +pub use parse::{Def, composite::keyword::CompositeKeyword}; use syn::spanned::Spanned; mod keyword { diff --git a/support/procedural-fork/src/pallet/parse/call.rs b/support/procedural-fork/src/pallet/parse/call.rs index 865c634732..5555bfdc16 100644 --- a/support/procedural-fork/src/pallet/parse/call.rs +++ b/support/procedural-fork/src/pallet/parse/call.rs @@ -15,12 +15,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{helper, InheritedCallWeightAttr}; +use super::{InheritedCallWeightAttr, helper}; use frame_support_procedural_tools::get_doc_literals; use proc_macro2::Span; use quote::ToTokens; use std::collections::HashMap; -use syn::{spanned::Spanned, ExprClosure}; +use syn::{ExprClosure, spanned::Spanned}; /// List of additional token to be used for parsing. mod keyword { @@ -422,8 +422,7 @@ impl CallDef { }; if feeless_arg_type != arg.2 { - let msg = - "Invalid pallet::call, feeless_if closure argument must have \ + let msg = "Invalid pallet::call, feeless_if closure argument must have \ a reference to the same type as the dispatchable function argument"; return Err(syn::Error::new(feeless_arg.span(), msg)); } diff --git a/support/procedural-fork/src/pallet/parse/composite.rs b/support/procedural-fork/src/pallet/parse/composite.rs index 239b4fd4bc..f679710b9a 100644 --- a/support/procedural-fork/src/pallet/parse/composite.rs +++ b/support/procedural-fork/src/pallet/parse/composite.rs @@ -115,7 +115,7 @@ impl CompositeDef { return Err(syn::Error::new( variant.ident.span(), "The composite enum does not support variants with fields!", - )) + )); } syn::Fields::Unit => (), } diff --git a/support/procedural-fork/src/pallet/parse/config.rs b/support/procedural-fork/src/pallet/parse/config.rs index 95b4143b65..a7b1f043b6 100644 --- a/support/procedural-fork/src/pallet/parse/config.rs +++ b/support/procedural-fork/src/pallet/parse/config.rs @@ -18,7 +18,7 @@ use super::helper; use frame_support_procedural_tools::{get_doc_literals, is_using_frame_crate}; use quote::ToTokens; -use syn::{spanned::Spanned, token, Token}; +use syn::{Token, spanned::Spanned, token}; /// List of additional token to be used for parsing. mod keyword { @@ -239,8 +239,7 @@ fn check_event_type( // Check event has no generics if !type_.generics.params.is_empty() || type_.generics.where_clause.is_some() { - let msg = - "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must have\ + let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must have\ no generics nor where_clause"; return Err(syn::Error::new(trait_item.span(), msg)); } @@ -265,15 +264,13 @@ fn check_event_type( .find_map(|s| syn::parse2::(s.to_token_stream()).ok()); let Some(from_event_bound) = from_event_bound else { - let msg = - "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ + let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ bound: `From` or `From>` or `From>`"; return Err(syn::Error::new(type_.span(), msg)); }; if from_event_bound.is_generic && (from_event_bound.has_instance != trait_has_instance) { - let msg = - "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` bounds inconsistent \ + let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` bounds inconsistent \ `From`. Config and generic Event must be both with instance or \ without instance"; return Err(syn::Error::new(type_.span(), msg)); @@ -299,7 +296,7 @@ fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool // We can't use the path to `frame_system` from `frame` if `frame_system` is not being // in scope through `frame`. { - return false + return false; } (false, true) => // We know that the only valid frame_system path is one that is `frame_system`, as @@ -417,7 +414,7 @@ impl ConfigDef { helper::take_first_item_pallet_attr::(trait_item) { match (pallet_attr.typ, &trait_item) { - (PalletAttrType::Constant(_), syn::TraitItem::Type(ref typ)) => { + (PalletAttrType::Constant(_), syn::TraitItem::Type(typ)) => { if already_constant { return Err(syn::Error::new( pallet_attr._bracket.span.join(), @@ -431,15 +428,15 @@ impl ConfigDef { return Err(syn::Error::new( trait_item.span(), "Invalid #[pallet::constant] in #[pallet::config], expected type item", - )) + )); } (PalletAttrType::NoDefault(_), _) => { if !enable_default { return Err(syn::Error::new( - pallet_attr._bracket.span.join(), - "`#[pallet:no_default]` can only be used if `#[pallet::config(with_default)]` \ - has been specified" - )); + pallet_attr._bracket.span.join(), + "`#[pallet:no_default]` can only be used if `#[pallet::config(with_default)]` \ + has been specified", + )); } if already_no_default { return Err(syn::Error::new( @@ -453,10 +450,10 @@ impl ConfigDef { (PalletAttrType::NoBounds(_), _) => { if !enable_default { return Err(syn::Error::new( - pallet_attr._bracket.span.join(), - "`#[pallet:no_default_bounds]` can only be used if `#[pallet::config(with_default)]` \ - has been specified" - )); + pallet_attr._bracket.span.join(), + "`#[pallet:no_default_bounds]` can only be used if `#[pallet::config(with_default)]` \ + has been specified", + )); } if already_no_default_bounds { return Err(syn::Error::new( diff --git a/support/procedural-fork/src/pallet/parse/error.rs b/support/procedural-fork/src/pallet/parse/error.rs index 7aab5732b7..8bd2f438bd 100644 --- a/support/procedural-fork/src/pallet/parse/error.rs +++ b/support/procedural-fork/src/pallet/parse/error.rs @@ -17,7 +17,7 @@ use super::helper; use quote::ToTokens; -use syn::{spanned::Spanned, Fields}; +use syn::{Fields, spanned::Spanned}; /// List of additional token to be used for parsing. mod keyword { diff --git a/support/procedural-fork/src/pallet/parse/helper.rs b/support/procedural-fork/src/pallet/parse/helper.rs index 1105046c2b..e243dcbbfb 100644 --- a/support/procedural-fork/src/pallet/parse/helper.rs +++ b/support/procedural-fork/src/pallet/parse/helper.rs @@ -16,7 +16,7 @@ // limitations under the License. use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::spanned::Spanned; /// List of additional token to be used for parsing. @@ -196,7 +196,7 @@ impl syn::parse::Parse for StaticLifetime { /// `span` is used in case generics is empty (empty generics has span == call_site). /// /// return the instance if found. -pub fn check_config_def_gen(gen: &syn::Generics, span: proc_macro2::Span) -> syn::Result<()> { +pub fn check_config_def_gen(r#gen: &syn::Generics, span: proc_macro2::Span) -> syn::Result<()> { let expected = "expected `I: 'static = ()`"; pub struct CheckTraitDefGenerics; impl syn::parse::Parse for CheckTraitDefGenerics { @@ -211,7 +211,7 @@ pub fn check_config_def_gen(gen: &syn::Generics, span: proc_macro2::Span) -> syn } } - syn::parse2::(gen.params.to_token_stream()).map_err(|e| { + syn::parse2::(r#gen.params.to_token_stream()).map_err(|e| { let msg = format!("Invalid generics: {}", expected); let mut err = syn::Error::new(span, msg); err.combine(e); @@ -229,7 +229,7 @@ pub fn check_config_def_gen(gen: &syn::Generics, span: proc_macro2::Span) -> syn /// /// return the instance if found. pub fn check_type_def_gen_no_bounds( - gen: &syn::Generics, + r#gen: &syn::Generics, span: proc_macro2::Span, ) -> syn::Result { let expected = "expected `T` or `T, I = ()`"; @@ -254,7 +254,7 @@ pub fn check_type_def_gen_no_bounds( } } - let i = syn::parse2::(gen.params.to_token_stream()) + let i = syn::parse2::(r#gen.params.to_token_stream()) .map_err(|e| { let msg = format!("Invalid type def generics: {}", expected); let mut err = syn::Error::new(span, msg); @@ -277,7 +277,7 @@ pub fn check_type_def_gen_no_bounds( /// /// return some instance usage if there is some generic, or none otherwise. pub fn check_type_def_optional_gen( - gen: &syn::Generics, + r#gen: &syn::Generics, span: proc_macro2::Span, ) -> syn::Result> { let expected = "expected `` or `T` or `T: Config` or `T, I = ()` or \ @@ -335,7 +335,7 @@ pub fn check_type_def_optional_gen( } } - let i = syn::parse2::(gen.params.to_token_stream()) + let i = syn::parse2::(r#gen.params.to_token_stream()) .map_err(|e| { let msg = format!("Invalid type def generics: {}", expected); let mut err = syn::Error::new(span, msg); @@ -400,7 +400,10 @@ pub fn check_pallet_struct_usage(type_: &Box) -> syn::Result syn::Result { +pub fn check_impl_gen( + r#gen: &syn::Generics, + span: proc_macro2::Span, +) -> syn::Result { let expected = "expected `impl` or `impl, I: 'static>`"; pub struct Checker(InstanceUsage); impl syn::parse::Parse for Checker { @@ -428,7 +431,7 @@ pub fn check_impl_gen(gen: &syn::Generics, span: proc_macro2::Span) -> syn::Resu } } - let i = syn::parse2::(gen.params.to_token_stream()) + let i = syn::parse2::(r#gen.params.to_token_stream()) .map_err(|e| { let mut err = syn::Error::new(span, format!("Invalid generics: {}", expected)); err.combine(e); @@ -449,7 +452,7 @@ pub fn check_impl_gen(gen: &syn::Generics, span: proc_macro2::Span) -> syn::Resu /// /// return the instance if found. pub fn check_type_def_gen( - gen: &syn::Generics, + r#gen: &syn::Generics, span: proc_macro2::Span, ) -> syn::Result { let expected = "expected `T` or `T: Config` or `T, I = ()` or \ @@ -503,7 +506,7 @@ pub fn check_type_def_gen( } } - let mut i = syn::parse2::(gen.params.to_token_stream()) + let mut i = syn::parse2::(r#gen.params.to_token_stream()) .map_err(|e| { let msg = format!("Invalid type def generics: {}", expected); let mut err = syn::Error::new(span, msg); @@ -574,7 +577,7 @@ pub fn check_genesis_builder_usage(type_: &syn::Path) -> syn::Result syn::Result> { let expected = "expected `` or `T: Config` or `T: Config, I: 'static`"; @@ -611,7 +614,7 @@ pub fn check_type_value_gen( } } - let i = syn::parse2::(gen.params.to_token_stream()) + let i = syn::parse2::(r#gen.params.to_token_stream()) .map_err(|e| { let msg = format!("Invalid type def generics: {}", expected); let mut err = syn::Error::new(span, msg); diff --git a/support/procedural-fork/src/pallet/parse/mod.rs b/support/procedural-fork/src/pallet/parse/mod.rs index 69f9217333..05eacd1449 100644 --- a/support/procedural-fork/src/pallet/parse/mod.rs +++ b/support/procedural-fork/src/pallet/parse/mod.rs @@ -40,7 +40,7 @@ pub mod validate_unsigned; #[cfg(test)] pub mod tests; -use composite::{keyword::CompositeKeyword, CompositeDef}; +use composite::{CompositeDef, keyword::CompositeKeyword}; use frame_support_procedural_tools::generate_access_from_frame_or_crate; use quote::ToTokens; use syn::spanned::Spanned; @@ -109,108 +109,122 @@ impl Def { let pallet_attr: Option = helper::take_first_item_pallet_attr(item)?; match pallet_attr { - Some(PalletAttr::Config(_, with_default)) if config.is_none() => - config = Some(config::ConfigDef::try_from( - &frame_system, - index, - item, - with_default, - )?), - Some(PalletAttr::Pallet(span)) if pallet_struct.is_none() => { - let p = pallet_struct::PalletStructDef::try_from(span, index, item)?; - pallet_struct = Some(p); - }, - Some(PalletAttr::Hooks(span)) if hooks.is_none() => { - let m = hooks::HooksDef::try_from(span, item)?; - hooks = Some(m); - }, - Some(PalletAttr::RuntimeCall(cw, span)) if call.is_none() => - call = Some(call::CallDef::try_from(span, index, item, dev_mode, cw)?), - Some(PalletAttr::Tasks(_)) if tasks.is_none() => { - let item_tokens = item.to_token_stream(); - // `TasksDef::parse` needs to know if attr was provided so we artificially - // re-insert it here - tasks = Some(syn::parse2::(quote::quote! { - #[pallet::tasks_experimental] - #item_tokens - })?); - - // replace item with a no-op because it will be handled by the expansion of tasks - *item = syn::Item::Verbatim(quote::quote!()); - } - Some(PalletAttr::TaskCondition(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_condition]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::TaskIndex(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_index]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::TaskList(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_list]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::RuntimeTask(_)) if task_enum.is_none() => - task_enum = Some(syn::parse2::(item.to_token_stream())?), - Some(PalletAttr::Error(span)) if error.is_none() => - error = Some(error::ErrorDef::try_from(span, index, item)?), - Some(PalletAttr::RuntimeEvent(span)) if event.is_none() => - event = Some(event::EventDef::try_from(span, index, item)?), - Some(PalletAttr::GenesisConfig(_)) if genesis_config.is_none() => { - let g = genesis_config::GenesisConfigDef::try_from(index, item)?; - genesis_config = Some(g); - }, - Some(PalletAttr::GenesisBuild(span)) if genesis_build.is_none() => { - let g = genesis_build::GenesisBuildDef::try_from(span, item)?; - genesis_build = Some(g); - }, - Some(PalletAttr::RuntimeOrigin(_)) if origin.is_none() => - origin = Some(origin::OriginDef::try_from(item)?), - Some(PalletAttr::Inherent(_)) if inherent.is_none() => - inherent = Some(inherent::InherentDef::try_from(item)?), - Some(PalletAttr::Storage(span)) => - storages.push(storage::StorageDef::try_from(span, index, item, dev_mode)?), - Some(PalletAttr::ValidateUnsigned(_)) if validate_unsigned.is_none() => { - let v = validate_unsigned::ValidateUnsignedDef::try_from(item)?; - validate_unsigned = Some(v); - }, - Some(PalletAttr::TypeValue(span)) => - type_values.push(type_value::TypeValueDef::try_from(span, index, item)?), - Some(PalletAttr::ExtraConstants(_)) => - extra_constants = - Some(extra_constants::ExtraConstantsDef::try_from(item)?), - Some(PalletAttr::Composite(span)) => { - let composite = - composite::CompositeDef::try_from(span, &frame_support, item)?; - if composites.iter().any(|def| { - match (&def.composite_keyword, &composite.composite_keyword) { - ( - CompositeKeyword::FreezeReason(_), - CompositeKeyword::FreezeReason(_), - ) | - (CompositeKeyword::HoldReason(_), CompositeKeyword::HoldReason(_)) | - (CompositeKeyword::LockId(_), CompositeKeyword::LockId(_)) | - ( - CompositeKeyword::SlashReason(_), - CompositeKeyword::SlashReason(_), - ) => true, - _ => false, - } - }) { - let msg = format!( - "Invalid duplicated `{}` definition", - composite.composite_keyword - ); - return Err(syn::Error::new(composite.composite_keyword.span(), &msg)) - } - composites.push(composite); - }, - Some(attr) => { - let msg = "Invalid duplicated attribute"; - return Err(syn::Error::new(attr.span(), msg)) - }, - None => (), - } + Some(PalletAttr::Config(_, with_default)) if config.is_none() => { + config = Some(config::ConfigDef::try_from( + &frame_system, + index, + item, + with_default, + )?) + } + Some(PalletAttr::Pallet(span)) if pallet_struct.is_none() => { + let p = pallet_struct::PalletStructDef::try_from(span, index, item)?; + pallet_struct = Some(p); + } + Some(PalletAttr::Hooks(span)) if hooks.is_none() => { + let m = hooks::HooksDef::try_from(span, item)?; + hooks = Some(m); + } + Some(PalletAttr::RuntimeCall(cw, span)) if call.is_none() => { + call = Some(call::CallDef::try_from(span, index, item, dev_mode, cw)?) + } + Some(PalletAttr::Tasks(_)) if tasks.is_none() => { + let item_tokens = item.to_token_stream(); + // `TasksDef::parse` needs to know if attr was provided so we artificially + // re-insert it here + tasks = Some(syn::parse2::(quote::quote! { + #[pallet::tasks_experimental] + #item_tokens + })?); + + // replace item with a no-op because it will be handled by the expansion of tasks + *item = syn::Item::Verbatim(quote::quote!()); + } + Some(PalletAttr::TaskCondition(span)) => { + return Err(syn::Error::new( + span, + "`#[pallet::task_condition]` can only be used on items within an `impl` statement.", + )); + } + Some(PalletAttr::TaskIndex(span)) => { + return Err(syn::Error::new( + span, + "`#[pallet::task_index]` can only be used on items within an `impl` statement.", + )); + } + Some(PalletAttr::TaskList(span)) => { + return Err(syn::Error::new( + span, + "`#[pallet::task_list]` can only be used on items within an `impl` statement.", + )); + } + Some(PalletAttr::RuntimeTask(_)) if task_enum.is_none() => { + task_enum = Some(syn::parse2::(item.to_token_stream())?) + } + Some(PalletAttr::Error(span)) if error.is_none() => { + error = Some(error::ErrorDef::try_from(span, index, item)?) + } + Some(PalletAttr::RuntimeEvent(span)) if event.is_none() => { + event = Some(event::EventDef::try_from(span, index, item)?) + } + Some(PalletAttr::GenesisConfig(_)) if genesis_config.is_none() => { + let g = genesis_config::GenesisConfigDef::try_from(index, item)?; + genesis_config = Some(g); + } + Some(PalletAttr::GenesisBuild(span)) if genesis_build.is_none() => { + let g = genesis_build::GenesisBuildDef::try_from(span, item)?; + genesis_build = Some(g); + } + Some(PalletAttr::RuntimeOrigin(_)) if origin.is_none() => { + origin = Some(origin::OriginDef::try_from(item)?) + } + Some(PalletAttr::Inherent(_)) if inherent.is_none() => { + inherent = Some(inherent::InherentDef::try_from(item)?) + } + Some(PalletAttr::Storage(span)) => { + storages.push(storage::StorageDef::try_from(span, index, item, dev_mode)?) + } + Some(PalletAttr::ValidateUnsigned(_)) if validate_unsigned.is_none() => { + let v = validate_unsigned::ValidateUnsignedDef::try_from(item)?; + validate_unsigned = Some(v); + } + Some(PalletAttr::TypeValue(span)) => { + type_values.push(type_value::TypeValueDef::try_from(span, index, item)?) + } + Some(PalletAttr::ExtraConstants(_)) => { + extra_constants = Some(extra_constants::ExtraConstantsDef::try_from(item)?) + } + Some(PalletAttr::Composite(span)) => { + let composite = composite::CompositeDef::try_from(span, &frame_support, item)?; + if composites.iter().any(|def| { + match (&def.composite_keyword, &composite.composite_keyword) { + ( + CompositeKeyword::FreezeReason(_), + CompositeKeyword::FreezeReason(_), + ) + | (CompositeKeyword::HoldReason(_), CompositeKeyword::HoldReason(_)) + | (CompositeKeyword::LockId(_), CompositeKeyword::LockId(_)) + | ( + CompositeKeyword::SlashReason(_), + CompositeKeyword::SlashReason(_), + ) => true, + _ => false, + } + }) { + let msg = format!( + "Invalid duplicated `{}` definition", + composite.composite_keyword + ); + return Err(syn::Error::new(composite.composite_keyword.span(), &msg)); + } + composites.push(composite); + } + Some(attr) => { + let msg = "Invalid duplicated attribute"; + return Err(syn::Error::new(attr.span(), msg)); + } + None => (), + } } if genesis_config.is_some() != genesis_build.is_some() { @@ -277,15 +291,15 @@ impl Def { return Err(syn::Error::new( *item_span, "Missing `#[pallet::tasks_experimental]` impl", - )) + )); } (None, Some(tasks)) => { if tasks.tasks_attr.is_none() { return Err(syn::Error::new( - tasks.item_impl.impl_token.span(), - "A `#[pallet::tasks_experimental]` attribute must be attached to your `Task` impl if the \ + tasks.item_impl.impl_token.span(), + "A `#[pallet::tasks_experimental]` attribute must be attached to your `Task` impl if the \ task enum has been omitted", - )); + )); } else { } } diff --git a/support/procedural-fork/src/pallet/parse/storage.rs b/support/procedural-fork/src/pallet/parse/storage.rs index 64a5e685bd..00f0f6e141 100644 --- a/support/procedural-fork/src/pallet/parse/storage.rs +++ b/support/procedural-fork/src/pallet/parse/storage.rs @@ -139,7 +139,7 @@ impl PalletStorageAttrInfo { return Err(syn::Error::new( attr.attr_span(), "Invalid attribute: Duplicate attribute", - )) + )); } } } @@ -741,13 +741,13 @@ fn process_generics( if args .args .iter() - .all(|gen| matches!(gen, syn::GenericArgument::Type(_))) + .all(|r#gen| matches!(r#gen, syn::GenericArgument::Type(_))) { let args = args .args .iter() - .map(|gen| match gen { - syn::GenericArgument::Type(gen) => gen.clone(), + .map(|r#gen| match r#gen { + syn::GenericArgument::Type(r#gen) => r#gen.clone(), _ => unreachable!("It is asserted above that all generics are types"), }) .collect::>(); @@ -755,13 +755,13 @@ fn process_generics( } else if args .args .iter() - .all(|gen| matches!(gen, syn::GenericArgument::AssocType(_))) + .all(|r#gen| matches!(r#gen, syn::GenericArgument::AssocType(_))) { let args = args .args .iter() - .map(|gen| match gen { - syn::GenericArgument::AssocType(gen) => gen.clone(), + .map(|r#gen| match r#gen { + syn::GenericArgument::AssocType(r#gen) => r#gen.clone(), _ => unreachable!("It is asserted above that all generics are bindings"), }) .collect::>(); @@ -915,7 +915,7 @@ impl StorageDef { .last() .map_or(false, |s| s.ident == "OptionQuery") => { - return Ok(Some(QueryKind::OptionQuery)) + return Ok(Some(QueryKind::OptionQuery)); } Type::Path(TypePath { path: Path { segments, .. }, @@ -931,7 +931,7 @@ impl StorageDef { .last() .map_or(false, |s| s.ident == "ValueQuery") => { - return Ok(Some(QueryKind::ValueQuery)) + return Ok(Some(QueryKind::ValueQuery)); } _ => return Ok(None), }; @@ -1003,10 +1003,10 @@ impl StorageDef { } gen_arg => { let msg = format!( - "Invalid pallet::storage, unexpected generic argument kind, expected a \ + "Invalid pallet::storage, unexpected generic argument kind, expected a \ type path to a `PalletError` enum variant, found `{}`", - gen_arg.to_token_stream().to_string(), - ); + gen_arg.to_token_stream().to_string(), + ); Err(syn::Error::new(gen_arg.span(), msg)) } } diff --git a/support/procedural-fork/src/pallet/parse/tasks.rs b/support/procedural-fork/src/pallet/parse/tasks.rs index 2a8d148267..8da1fa8823 100644 --- a/support/procedural-fork/src/pallet/parse/tasks.rs +++ b/support/procedural-fork/src/pallet/parse/tasks.rs @@ -28,14 +28,14 @@ use crate::pallet::parse::tests::simulate_manifest_dir; use derive_syn_parse::Parse; use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::TokenStream as TokenStream2; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::{ + Error, Expr, Ident, ImplItem, ImplItemFn, ItemEnum, ItemImpl, LitInt, Path, PathArguments, + Result, TypePath, parse::ParseStream, parse2, spanned::Spanned, token::{Bracket, Paren, PathSep, Pound}, - Error, Expr, Ident, ImplItem, ImplItemFn, ItemEnum, ItemImpl, LitInt, Path, PathArguments, - Result, TypePath, }; pub mod keywords { @@ -299,7 +299,7 @@ impl syn::parse::Parse for TaskDef { return Err(Error::new( input.span(), "unexpected function argument type", - )) + )); } } } @@ -460,7 +460,7 @@ impl TryFrom> for TaskIndexAttr { "`{:?}` cannot be converted to a `TaskIndexAttr`", value.meta ), - )) + )); } } } @@ -482,7 +482,7 @@ impl TryFrom> for TaskConditionAttr { "`{:?}` cannot be converted to a `TaskConditionAttr`", value.meta ), - )) + )); } } } @@ -504,7 +504,7 @@ impl TryFrom> for TaskWeightAttr { "`{:?}` cannot be converted to a `TaskWeightAttr`", value.meta ), - )) + )); } } } @@ -523,7 +523,7 @@ impl TryFrom> for TaskListAttr { return Err(Error::new( value.span(), format!("`{:?}` cannot be converted to a `TaskListAttr`", value.meta), - )) + )); } } } diff --git a/support/procedural-fork/src/runtime/expand/mod.rs b/support/procedural-fork/src/runtime/expand/mod.rs index a1a6d4d071..b51012541b 100644 --- a/support/procedural-fork/src/runtime/expand/mod.rs +++ b/support/procedural-fork/src/runtime/expand/mod.rs @@ -22,10 +22,10 @@ use crate::{ decl_static_assertions, expand, }, runtime::{ + Def, parse::{ AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, }, - Def, }, }; use cfg_expr::Predicate; diff --git a/support/procedural-fork/src/runtime/parse/mod.rs b/support/procedural-fork/src/runtime/parse/mod.rs index 494ab2c53e..67fc03c59f 100644 --- a/support/procedural-fork/src/runtime/parse/mod.rs +++ b/support/procedural-fork/src/runtime/parse/mod.rs @@ -26,7 +26,7 @@ use pallet_decl::PalletDeclaration; use proc_macro2::TokenStream as TokenStream2; use quote::ToTokens; use std::collections::HashMap; -use syn::{spanned::Spanned, Ident, Token}; +use syn::{Ident, Token, spanned::Spanned}; use frame_support_procedural_tools::syn_ext as ext; use runtime_types::RuntimeType; @@ -223,9 +223,9 @@ impl Def { if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { let msg = format!( - "Pallet indices are conflicting: Both pallets {} and {} are at index {}", - used_pallet, pallet.name, pallet.index, - ); + "Pallet indices are conflicting: Both pallets {} and {} are at index {}", + used_pallet, pallet.name, pallet.index, + ); let mut err = syn::Error::new(used_pallet.span(), &msg); err.combine(syn::Error::new(pallet.name.span(), msg)); return Err(err); diff --git a/support/procedural-fork/src/runtime/parse/pallet.rs b/support/procedural-fork/src/runtime/parse/pallet.rs index 591c059307..460818e4d5 100644 --- a/support/procedural-fork/src/runtime/parse/pallet.rs +++ b/support/procedural-fork/src/runtime/parse/pallet.rs @@ -21,7 +21,7 @@ use crate::{ }; use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; -use syn::{punctuated::Punctuated, token, Error}; +use syn::{Error, punctuated::Punctuated, token}; impl Pallet { pub fn try_from( @@ -102,7 +102,7 @@ impl Pallet { #[test] fn pallet_parsing_works() { - use syn::{parse_quote, ItemType}; + use syn::{ItemType, parse_quote}; let item: ItemType = parse_quote! { pub type System = frame_system + Call; @@ -131,7 +131,7 @@ fn pallet_parsing_works() { #[test] fn pallet_parsing_works_with_instance() { - use syn::{parse_quote, ItemType}; + use syn::{ItemType, parse_quote}; let item: ItemType = parse_quote! { pub type System = frame_system + Call; @@ -160,7 +160,7 @@ fn pallet_parsing_works_with_instance() { #[test] fn pallet_parsing_works_with_pallet() { - use syn::{parse_quote, ItemType}; + use syn::{ItemType, parse_quote}; let item: ItemType = parse_quote! { pub type System = frame_system::Pallet + Call; @@ -189,7 +189,7 @@ fn pallet_parsing_works_with_pallet() { #[test] fn pallet_parsing_works_with_instance_and_pallet() { - use syn::{parse_quote, ItemType}; + use syn::{ItemType, parse_quote}; let item: ItemType = parse_quote! { pub type System = frame_system::Pallet + Call; diff --git a/support/procedural-fork/src/runtime/parse/runtime_types.rs b/support/procedural-fork/src/runtime/parse/runtime_types.rs index 4d8c8358c6..56c765d04e 100644 --- a/support/procedural-fork/src/runtime/parse/runtime_types.rs +++ b/support/procedural-fork/src/runtime/parse/runtime_types.rs @@ -16,8 +16,8 @@ // limitations under the License. use syn::{ - parse::{Parse, ParseStream}, Result, + parse::{Parse, ParseStream}, }; mod keyword { diff --git a/support/procedural-fork/src/storage_alias.rs b/support/procedural-fork/src/storage_alias.rs index 7099239f9d..018105053e 100644 --- a/support/procedural-fork/src/storage_alias.rs +++ b/support/procedural-fork/src/storage_alias.rs @@ -20,15 +20,15 @@ use crate::{counter_prefix, pallet::parse::helper}; use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::{Span, TokenStream}; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::{ + Attribute, Error, Ident, Result, Token, Type, TypeParam, Visibility, WhereClause, parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, spanned::Spanned, token, visit::Visit, - Attribute, Error, Ident, Result, Token, Type, TypeParam, Visibility, WhereClause, }; /// Extension trait for [`Type`]. @@ -607,7 +607,7 @@ fn generate_storage_instance( return Err(Error::new_spanned( prefix, "Prefix type `verbatim` requires that the prefix is an ident.", - )) + )); } }; diff --git a/support/tools/Cargo.toml b/support/tools/Cargo.toml index ab8506ffa0..065b3532d1 100644 --- a/support/tools/Cargo.toml +++ b/support/tools/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subtensor-tools" version = "0.1.0" -edition = "2024" +edition.workspace = true license = "MIT" description = "support tools for Subtensor" @@ -12,8 +12,13 @@ homepage = "https://bittensor.com" name = "bump-version" path = "src/bump_version.rs" +[[bin]] +name = "spec-version" +path = "src/spec_version.rs" + [dependencies] -anyhow = { workspace = true } -clap = { version = "4.5", features = ["derive"] } -semver = "1.0" -toml_edit = "0.22" +anyhow.workspace = true +clap = { workspace = true, features = ["derive"] } +semver.workspace = true +toml_edit.workspace = true +node-subtensor-runtime = { workspace = true, default-features = true } diff --git a/runtime/src/spec_version.rs b/support/tools/src/spec_version.rs similarity index 100% rename from runtime/src/spec_version.rs rename to support/tools/src/spec_version.rs