diff --git a/.github/workflows/frontier-rpc-tests.yml b/.github/workflows/frontier-rpc-tests.yml index 231ad7e93d..1ccf2c1dea 100644 --- a/.github/workflows/frontier-rpc-tests.yml +++ b/.github/workflows/frontier-rpc-tests.yml @@ -2,7 +2,7 @@ name: Frontier RPC Tests on: workflow_dispatch: push: - branches: [ master ] + branches: [master] concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -25,7 +25,7 @@ jobs: run: rustup target list --installed - name: Build astar-collator - run: cargo build --release --locked --features manual-seal,evm-tracing --bin astar-collator + run: cargo build --release --locked --features manual-seal --bin astar-collator - name: Clone frontier tests run: git clone https://github.com/AstarNetwork/frontier-tests.git --depth 1 @@ -34,7 +34,7 @@ jobs: uses: actions/setup-node@v4 with: node-version: 18.x - cache: 'npm' + cache: "npm" cache-dependency-path: frontier-tests/package-lock.json - name: Install dependencies diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3a20c67eb6..5476a68ab1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,7 +2,7 @@ name: Release Build on: push: tags: - - v[0-9]+.[0-9]+.[0-9]+* + - v[0-9]+.[0-9]+.[0-9]+* workflow_dispatch: env: SUBWASM_VERSION: 0.16.1 @@ -10,37 +10,37 @@ jobs: checks-and-tests: runs-on: [self-hosted, Linux, X64] steps: - - name: Free disk space - run: | - sudo rm -rf /usr/share/dotnet - sudo rm -rf /usr/local/lib/android - sudo rm -rf /opt/ghc - sudo rm -rf "/usr/local/share/boost" - sudo rm -rf "$AGENT_TOOLSDIRECTORY" - df -h + - name: Free disk space + run: | + sudo rm -rf /usr/share/dotnet + sudo rm -rf /usr/local/lib/android + sudo rm -rf /opt/ghc + sudo rm -rf "/usr/local/share/boost" + sudo rm -rf "$AGENT_TOOLSDIRECTORY" + df -h - - name: Checkout the source code - uses: actions/checkout@v4 - with: - submodules: true + - name: Checkout the source code + uses: actions/checkout@v4 + with: + submodules: true - - name: Install deps - run: sudo apt -y install protobuf-compiler + - name: Install deps + run: sudo apt -y install protobuf-compiler - - name: Install & display rust toolchain - run: rustup show + - name: Install & display rust toolchain + run: rustup show - - name: Check targets are installed correctly - run: rustup target list --installed + - name: Check targets are installed correctly + run: rustup target list --installed - - name: Install cargo-nextest - run: curl -LsSf https://get.nexte.st/latest/linux | tar zxf - -C ${CARGO_HOME:-~/.cargo}/bin + - name: Install cargo-nextest + run: curl -LsSf https://get.nexte.st/latest/linux | tar zxf - -C ${CARGO_HOME:-~/.cargo}/bin - - name: Check all features compilation - run: cargo check --verbose --features try-runtime,runtime-benchmarks --locked + - name: Check all features compilation + run: cargo check --features try-runtime,runtime-benchmarks --locked - - name: Run all tests - run: make test-all + - name: Run all tests + run: make test-all native-linux: needs: checks-and-tests @@ -48,114 +48,102 @@ jobs: strategy: matrix: target: - - x86_64-unknown-linux-gnu - - aarch64-unknown-linux-gnu + - x86_64-unknown-linux-gnu + - aarch64-unknown-linux-gnu steps: - - name: Checkout the source code - uses: actions/checkout@v4 - with: - submodules: true - - - name: Install deps - run: sudo apt -y install protobuf-compiler - - - name: aarch64 setup - if: contains(matrix.target, 'aarch64') - shell: bash - run: | - sudo apt update - sudo apt install -y gcc-multilib g++-multilib - sudo apt install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu - - mkdir -p .cargo - touch .cargo/config - printf '[target.aarch64-unknown-linux-gnu]\nlinker = "aarch64-linux-gnu-gcc"' >> .cargo/config - - - name: x86_64 setup - if: contains(matrix.target, 'x86_64') - run: | - mkdir -p .cargo - touch .cargo/config - printf '[target.x86_64-unknown-linux-gnu]\nrustflags = ["-Clink-arg=-fuse-ld=lld"]' >> .cargo/config - - - name: Install & display rust toolchain - run: rustup show - - - name: Add aarch64 target - if: contains(matrix.target, 'aarch64') - run: rustup target add ${{ matrix.target }} - - - name: Check targets are installed correctly - run: rustup target list --installed - - - name: Build optimized binary - run: CARGO_PROFILE_RELEASE_LTO=true RUSTFLAGS="-C codegen-units=1" cargo build --release --target ${{ matrix.target }} --verbose --locked - - - name: Set artifact name - env: - TARGET: ${{ matrix.target }} - id: artifact-name - run: echo "::set-output name=name::astar-ubuntu-latest-${TARGET%%-*}" - - - uses: actions/upload-artifact@v3 - with: - name: ${{ steps.artifact-name.outputs.name }} - path: target/${{ matrix.target }}/release/astar-collator - - evm-tracing-native-linux: - needs: checks-and-tests - runs-on: [self-hosted, Linux, X64] - steps: + - name: Checkout the source code + uses: actions/checkout@v4 + with: + submodules: true - - name: Checkout the source code - uses: actions/checkout@v4 - with: - submodules: true + - name: Install deps + run: sudo apt -y install protobuf-compiler - - name: Install deps - run: sudo apt -y install protobuf-compiler + - name: aarch64 setup + if: contains(matrix.target, 'aarch64') + shell: bash + run: | + sudo apt update + sudo apt install -y gcc-multilib g++-multilib + sudo apt install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu - - name: x86_64 setup - run: | - mkdir -p .cargo - touch .cargo/config - printf '[target.x86_64-unknown-linux-gnu]\nrustflags = ["-Clink-arg=-fuse-ld=lld"]' >> .cargo/config + mkdir -p .cargo + touch .cargo/config + printf '[target.aarch64-unknown-linux-gnu]\nlinker = "aarch64-linux-gnu-gcc"' >> .cargo/config - - name: Install & display rust toolchain - run: rustup show + - name: x86_64 setup + if: contains(matrix.target, 'x86_64') + run: | + mkdir -p .cargo + touch .cargo/config + printf '[target.x86_64-unknown-linux-gnu]\nrustflags = ["-Clink-arg=-fuse-ld=lld"]' >> .cargo/config - - name: Check targets are installed correctly - run: rustup target list --installed + - name: Install & display rust toolchain + run: rustup show - - name: Build optimized binary with evm tracing - run: CARGO_PROFILE_RELEASE_LTO=true RUSTFLAGS="-C codegen-units=1" cargo build --release --target x86_64-unknown-linux-gnu --features on-chain-release-build,evm-tracing --verbose --locked + - name: Add aarch64 target + if: contains(matrix.target, 'aarch64') + run: rustup target add ${{ matrix.target }} - - uses: actions/upload-artifact@v3 - with: - name: astar-evm-tracing-ubuntu-latest-x86_64-unknown-linux-gnu - path: target/x86_64-unknown-linux-gnu/release/astar-collator + - name: Check targets are installed correctly + run: rustup target list --installed - - name: rename evm tracing runtimes - run: | - mv target/x86_64-unknown-linux-gnu/release/wbuild/astar-runtime/astar_runtime.compact.compressed.wasm target/x86_64-unknown-linux-gnu/release/wbuild/astar-runtime/astar_evm_tracing_runtime.compact.compressed.wasm - mv target/x86_64-unknown-linux-gnu/release/wbuild/shiden-runtime/shiden_runtime.compact.compressed.wasm target/x86_64-unknown-linux-gnu/release/wbuild/shiden-runtime/shiden_evm_tracing_runtime.compact.compressed.wasm - mv target/x86_64-unknown-linux-gnu/release/wbuild/shibuya-runtime/shibuya_runtime.compact.compressed.wasm target/x86_64-unknown-linux-gnu/release/wbuild/shibuya-runtime/shibuya_evm_tracing_runtime.compact.compressed.wasm + - name: Build optimized binary + run: cargo build --profile production --target ${{ matrix.target }} --locked - - uses: actions/upload-artifact@v3 - with: - name: astar-evm-tracing-runtime - path: target/x86_64-unknown-linux-gnu/release/wbuild/astar-runtime/astar_evm_tracing_runtime.compact.compressed.wasm + - name: Set artifact name + env: + TARGET: ${{ matrix.target }} + id: artifact-name + run: echo "::set-output name=name::astar-ubuntu-latest-${TARGET%%-*}" - - uses: actions/upload-artifact@v3 - with: - name: shiden-evm-tracing-runtime - path: target/x86_64-unknown-linux-gnu/release/wbuild/shiden-runtime/shiden_evm_tracing_runtime.compact.compressed.wasm + - uses: actions/upload-artifact@v3 + with: + name: ${{ steps.artifact-name.outputs.name }} + path: target/${{ matrix.target }}/production/astar-collator - - uses: actions/upload-artifact@v3 - with: - name: shibuya-evm-tracing-runtime - path: target/x86_64-unknown-linux-gnu/release/wbuild/shibuya-runtime/shibuya_evm_tracing_runtime.compact.compressed.wasm + evm-tracing-runtimes: + needs: checks-and-tests + runs-on: [self-hosted, Linux, X64] + steps: + - name: Checkout the source code + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install deps + run: sudo apt -y install protobuf-compiler + + - name: Install & display rust toolchain + run: rustup show + + - name: Check targets are installed correctly + run: rustup target list --installed + + - name: Build optimized runtimes with evm tracing + run: cargo build --profile production --locked --features on-chain-release-build,evm-tracing -p astar-runtime -p shiden-runtime -p shibuya-runtime + + - name: rename evm tracing runtimes + run: | + mv target/production/wbuild/astar-runtime/astar_runtime.compact.compressed.wasm target/production/wbuild/astar-runtime/astar_evm_tracing_runtime.compact.compressed.wasm + mv target/production/wbuild/shiden-runtime/shiden_runtime.compact.compressed.wasm target/production/wbuild/shiden-runtime/shiden_evm_tracing_runtime.compact.compressed.wasm + mv target/production/wbuild/shibuya-runtime/shibuya_runtime.compact.compressed.wasm target/production/wbuild/shibuya-runtime/shibuya_evm_tracing_runtime.compact.compressed.wasm + + - uses: actions/upload-artifact@v3 + with: + name: astar-evm-tracing-runtime + path: target/production/wbuild/astar-runtime/astar_evm_tracing_runtime.compact.compressed.wasm + + - uses: actions/upload-artifact@v3 + with: + name: shiden-evm-tracing-runtime + path: target/production/wbuild/shiden-runtime/shiden_evm_tracing_runtime.compact.compressed.wasm + + - uses: actions/upload-artifact@v3 + with: + name: shibuya-evm-tracing-runtime + path: target/production/wbuild/shibuya-runtime/shibuya_evm_tracing_runtime.compact.compressed.wasm native-macos: needs: checks-and-tests @@ -169,80 +157,80 @@ jobs: id-token: write contents: read steps: - - name: Checkout the source code - uses: actions/checkout@v4 - with: - submodules: true + - name: Checkout the source code + uses: actions/checkout@v4 + with: + submodules: true - - name: configure aws credentials - uses: aws-actions/configure-aws-credentials@v4 - with: - role-to-assume: ${{ secrets.SCCACHE_ROLE }} - role-session-name: github_astar_mac - aws-region: ${{ secrets.SCCACHE_REGION }} + - name: configure aws credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.SCCACHE_ROLE }} + role-session-name: github_astar_mac + aws-region: ${{ secrets.SCCACHE_REGION }} - - name: Install deps - run: brew install protobuf sccache + - name: Install deps + run: brew install protobuf sccache - - name: Install & display rust toolchain - run: rustup show + - name: Install & display rust toolchain + run: rustup show - - name: Check targets are installed correctly - run: rustup target list --installed + - name: Check targets are installed correctly + run: rustup target list --installed - - name: Build optimized binary - run: cargo build --release --verbose --locked + - name: Build optimized binary + run: cargo build --locked --profile production - - name: Show sccache stats - run: sccache --show-stats + - name: Show sccache stats + run: sccache --show-stats - - uses: actions/upload-artifact@v3 - with: - name: astar-macOS-latest-x86_64 - path: target/release/astar-collator + - uses: actions/upload-artifact@v3 + with: + name: astar-macOS-latest-x86_64 + path: target/production/astar-collator docker: needs: native-linux runs-on: ubuntu-latest steps: - - name: Checkout the source code - uses: actions/checkout@v4 - with: - submodules: true - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - - - name: Docker meta - id: docker_meta - uses: crazy-max/ghaction-docker-meta@v1 - with: - images: staketechnologies/astar-collator - tag-custom: shiden - tag-sha: true # add git short SHA as Docker tag - - - name: Download pre-built linux collator binary - uses: actions/download-artifact@v3 - with: - name: astar-ubuntu-latest-x86_64 - - - name: Make binary executable and copy it to docker folder - run: chmod +x astar-collator && cp astar-collator third-party/docker - - - name: Build & Push docker image - uses: docker/build-push-action@v2 - with: - context: third-party/docker - platforms: linux/amd64 - labels: ${{ steps.docker_meta.outputs.labels }} - tags: ${{ steps.docker_meta.outputs.tags }} - push: true + - name: Checkout the source code + uses: actions/checkout@v4 + with: + submodules: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Docker meta + id: docker_meta + uses: crazy-max/ghaction-docker-meta@v1 + with: + images: staketechnologies/astar-collator + tag-custom: shiden + tag-sha: true # add git short SHA as Docker tag + + - name: Download pre-built linux collator binary + uses: actions/download-artifact@v3 + with: + name: astar-ubuntu-latest-x86_64 + + - name: Make binary executable and copy it to docker folder + run: chmod +x astar-collator && cp astar-collator third-party/docker + + - name: Build & Push docker image + uses: docker/build-push-action@v2 + with: + context: third-party/docker + platforms: linux/amd64 + labels: ${{ steps.docker_meta.outputs.labels }} + tags: ${{ steps.docker_meta.outputs.tags }} + push: true srtool: needs: checks-and-tests @@ -251,138 +239,139 @@ jobs: matrix: chain: ["astar", "shiden", "shibuya"] steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Srtool build - id: srtool_build - uses: chevdor/srtool-actions@v0.8.0 - env: - # needed to enable metadata hash generation - BUILD_OPTS: "--features on-chain-release-build" - with: - chain: ${{ matrix.chain }} - runtime_dir: runtime/${{ matrix.chain }} - - - name: Summary - run: | - echo '${{ steps.srtool_build.outputs.json }}' | jq > ${{ matrix.chain }}-srtool-digest.json - cat ${{ matrix.chain }}-srtool-digest.json - echo "Compact Runtime: ${{ steps.srtool_build.outputs.wasm }}" - echo "Compressed Runtime: ${{ steps.srtool_build.outputs.wasm_compressed }}" - cp ${{ steps.srtool_build.outputs.wasm }} ${{ matrix.chain }}_runtime.compact.wasm - cp ${{ steps.srtool_build.outputs.wasm_compressed }} ${{ matrix.chain }}_runtime.compact.compressed.wasm - - # it takes a while to build the runtime, so let's save the artifact as soon as we have it - - name: Archive Artifacts for ${{ matrix.chain }} - uses: actions/upload-artifact@v3 - with: - name: ${{ matrix.chain }}-runtime - path: | - ${{ matrix.chain }}_runtime.compact.wasm - ${{ matrix.chain }}_runtime.compact.compressed.wasm - ${{ matrix.chain }}-srtool-digest.json - - # We now get extra information thanks to subwasm - - name: Install subwasm - run: | - wget https://github.com/chevdor/subwasm/releases/download/v${{ env.SUBWASM_VERSION }}/subwasm_linux_amd64_v${{ env.SUBWASM_VERSION }}.deb - sudo dpkg -i subwasm_linux_amd64_v${{ env.SUBWASM_VERSION }}.deb - subwasm --version - - - name: Show Runtime information - shell: bash - run: | - subwasm info ${{ steps.srtool_build.outputs.wasm }} - subwasm info ${{ steps.srtool_build.outputs.wasm_compressed }} - subwasm --json info ${{ steps.srtool_build.outputs.wasm }} > ${{ matrix.chain }}-info.json - subwasm --json info ${{ steps.srtool_build.outputs.wasm_compressed }} > ${{ matrix.chain }}-compressed-info.json - - - name: Extract the metadata - shell: bash - run: | - subwasm meta ${{ steps.srtool_build.outputs.wasm }} - subwasm --json meta ${{ steps.srtool_build.outputs.wasm }} > ${{ matrix.chain }}-metadata.json - - - name: Check the metadata diff - shell: bash - # the following subwasm call will error for chains that are not known and/or live, that includes shell for instance - run: | - subwasm diff ${{ steps.srtool_build.outputs.wasm }} --chain-b ${{ matrix.chain }} || \ - echo "Subwasm call failed, check the logs. This is likely because ${{ matrix.chain }} is not known by subwasm" | \ - tee ${{ matrix.chain }}-diff.txt - - - name: Archive Subwasm results - uses: actions/upload-artifact@v3 - with: - name: ${{ matrix.chain }}-runtime - path: | - ${{ matrix.chain }}-info.json - ${{ matrix.chain }}-compressed-info.json - ${{ matrix.chain }}-metadata.json - ${{ matrix.chain }}-diff.txt + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Srtool build + id: srtool_build + uses: chevdor/srtool-actions@v0.8.0 + env: + # needed to enable metadata hash generation + BUILD_OPTS: "--features on-chain-release-build" + with: + profile: production + chain: ${{ matrix.chain }} + runtime_dir: runtime/${{ matrix.chain }} + + - name: Summary + run: | + echo '${{ steps.srtool_build.outputs.json }}' | jq > ${{ matrix.chain }}-srtool-digest.json + cat ${{ matrix.chain }}-srtool-digest.json + echo "Compact Runtime: ${{ steps.srtool_build.outputs.wasm }}" + echo "Compressed Runtime: ${{ steps.srtool_build.outputs.wasm_compressed }}" + cp ${{ steps.srtool_build.outputs.wasm }} ${{ matrix.chain }}_runtime.compact.wasm + cp ${{ steps.srtool_build.outputs.wasm_compressed }} ${{ matrix.chain }}_runtime.compact.compressed.wasm + + # it takes a while to build the runtime, so let's save the artifact as soon as we have it + - name: Archive Artifacts for ${{ matrix.chain }} + uses: actions/upload-artifact@v3 + with: + name: ${{ matrix.chain }}-runtime + path: | + ${{ matrix.chain }}_runtime.compact.wasm + ${{ matrix.chain }}_runtime.compact.compressed.wasm + ${{ matrix.chain }}-srtool-digest.json + + # We now get extra information thanks to subwasm + - name: Install subwasm + run: | + wget https://github.com/chevdor/subwasm/releases/download/v${{ env.SUBWASM_VERSION }}/subwasm_linux_amd64_v${{ env.SUBWASM_VERSION }}.deb + sudo dpkg -i subwasm_linux_amd64_v${{ env.SUBWASM_VERSION }}.deb + subwasm --version + + - name: Show Runtime information + shell: bash + run: | + subwasm info ${{ steps.srtool_build.outputs.wasm }} + subwasm info ${{ steps.srtool_build.outputs.wasm_compressed }} + subwasm --json info ${{ steps.srtool_build.outputs.wasm }} > ${{ matrix.chain }}-info.json + subwasm --json info ${{ steps.srtool_build.outputs.wasm_compressed }} > ${{ matrix.chain }}-compressed-info.json + + - name: Extract the metadata + shell: bash + run: | + subwasm meta ${{ steps.srtool_build.outputs.wasm }} + subwasm --json meta ${{ steps.srtool_build.outputs.wasm }} > ${{ matrix.chain }}-metadata.json + + - name: Check the metadata diff + shell: bash + # the following subwasm call will error for chains that are not known and/or live, that includes shell for instance + run: | + subwasm diff ${{ steps.srtool_build.outputs.wasm }} --chain-b ${{ matrix.chain }} || \ + echo "Subwasm call failed, check the logs. This is likely because ${{ matrix.chain }} is not known by subwasm" | \ + tee ${{ matrix.chain }}-diff.txt + + - name: Archive Subwasm results + uses: actions/upload-artifact@v3 + with: + name: ${{ matrix.chain }}-runtime + path: | + ${{ matrix.chain }}-info.json + ${{ matrix.chain }}-compressed-info.json + ${{ matrix.chain }}-metadata.json + ${{ matrix.chain }}-diff.txt publish-release-draft: - needs: [native-linux, evm-tracing-native-linux, native-macOS, docker, srtool] + needs: [native-linux, evm-tracing-runtimes, native-macOS, docker, srtool] runs-on: ubuntu-latest outputs: release_url: ${{ steps.create-release.outputs.html_url }} upload_url: ${{ steps.create-release.outputs.upload_url }} steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Download astar runtime - uses: actions/download-artifact@v3 - with: - name: astar-runtime - path: runtime-artifacts - - - name: Download shiden runtime - uses: actions/download-artifact@v3 - with: - name: shiden-runtime - path: runtime-artifacts - - - name: Download shibuya runtime - uses: actions/download-artifact@v3 - with: - name: shibuya-runtime - path: runtime-artifacts - - - name: Use Node.js 18.x - uses: actions/setup-node@v2 - with: - node-version: 18.x - - - name: Get the latest release - id: latest-release - uses: pozetroninc/github-action-get-latest-release@v0.5.0 - with: - repository: AstarNetwork/Astar - excludes: "prerelease, draft" - - - name: Generate Release Body - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - id: generate-release-body - run: | - cd .github/scripts - yarn - yarn -s run ts-node generate-release-body.ts generate --owner "${{ github.repository_owner }}" --repo "$(basename ${{ github.repository }})" --from "${{ steps.latest-release.outputs.release }}" --to "${{ github.ref_name }}" --srtool-report-folder '../../runtime-artifacts/' > ../../body.md - - - name: Create Release Draft - id: create-release - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ github.ref_name }} - release_name: ${{ github.ref_name }} - body_path: body.md - draft: true + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Download astar runtime + uses: actions/download-artifact@v3 + with: + name: astar-runtime + path: runtime-artifacts + + - name: Download shiden runtime + uses: actions/download-artifact@v3 + with: + name: shiden-runtime + path: runtime-artifacts + + - name: Download shibuya runtime + uses: actions/download-artifact@v3 + with: + name: shibuya-runtime + path: runtime-artifacts + + - name: Use Node.js 18.x + uses: actions/setup-node@v2 + with: + node-version: 18.x + + - name: Get the latest release + id: latest-release + uses: pozetroninc/github-action-get-latest-release@v0.5.0 + with: + repository: AstarNetwork/Astar + excludes: "prerelease, draft" + + - name: Generate Release Body + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + id: generate-release-body + run: | + cd .github/scripts + yarn + yarn -s run ts-node generate-release-body.ts generate --owner "${{ github.repository_owner }}" --repo "$(basename ${{ github.repository }})" --from "${{ steps.latest-release.outputs.release }}" --to "${{ github.ref_name }}" --srtool-report-folder '../../runtime-artifacts/' > ../../body.md + + - name: Create Release Draft + id: create-release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref_name }} + release_name: ${{ github.ref_name }} + body_path: body.md + draft: true upload-binaries: needs: publish-release-draft @@ -392,35 +381,35 @@ jobs: os: ["ubuntu", "macOS"] arch: ["x86_64", "aarch64"] exclude: - - os: macOS - arch: aarch64 + - os: macOS + arch: aarch64 steps: - - name: Create download folder - run: | - mkdir -p ${{ matrix.os }}-${{ matrix.arch }}-bin - mkdir -p ubuntu-tracing-bin - - - name: Download pre-built collator binary - uses: actions/download-artifact@v3 - with: - name: astar-${{ matrix.os }}-latest-${{ matrix.arch }} - path: ${{ matrix.os }}-${{ matrix.arch }}-bin - - - name: Make binary executable and tar gzip - run: | - cd ${{ matrix.os }}-${{ matrix.arch }}-bin - chmod +x astar-collator - tar zcvf astar-collator.tar.gz astar-collator - - - name: Upload binary artifact - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: ${{ matrix.os }}-${{ matrix.arch }}-bin/astar-collator.tar.gz - asset_name: astar-collator-${{ github.ref_name }}-${{ matrix.os }}-${{ matrix.arch }}.tar.gz - asset_content_type: application/gzip + - name: Create download folder + run: | + mkdir -p ${{ matrix.os }}-${{ matrix.arch }}-bin + mkdir -p ubuntu-tracing-bin + + - name: Download pre-built collator binary + uses: actions/download-artifact@v3 + with: + name: astar-${{ matrix.os }}-latest-${{ matrix.arch }} + path: ${{ matrix.os }}-${{ matrix.arch }}-bin + + - name: Make binary executable and tar gzip + run: | + cd ${{ matrix.os }}-${{ matrix.arch }}-bin + chmod +x astar-collator + tar zcvf astar-collator.tar.gz astar-collator + + - name: Upload binary artifact + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: ${{ matrix.os }}-${{ matrix.arch }}-bin/astar-collator.tar.gz + asset_name: astar-collator-${{ github.ref_name }}-${{ matrix.os }}-${{ matrix.arch }}.tar.gz + asset_content_type: application/gzip upload-runtimes: needs: publish-release-draft @@ -429,60 +418,60 @@ jobs: matrix: chain: ["astar", "shiden", "shibuya"] steps: - - name: Download runtime - uses: actions/download-artifact@v3 - with: - name: ${{ matrix.chain }}-runtime - - - name: Get runtime version - id: get-runtime-version - run: | - ls -R - chain=${{ matrix.chain }} - runtime_version=$(cat $chain-compressed-info.json | jq '.core_version' | tr -d '"' | cut -d ' ' -f 1) - echo $runtime_version - echo "runtime=$(echo $runtime_version)" >> $GITHUB_ENV - echo "${{ matrix.chain }}=$(echo $runtime_version)" >> $GITHUB_OUTPUT - - - name: Upload ${{ matrix.chain }} Wasm - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: ${{ matrix.chain }}_runtime.compact.compressed.wasm - asset_name: ${{ env.runtime }}.wasm - asset_content_type: application/wasm - - - name: Upload ${{ matrix.chain }} Metadata - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: ${{ matrix.chain }}-metadata.json - asset_name: ${{ matrix.chain }}-metadata.json - asset_content_type: application/json - - - name: Upload ${{ matrix.chain }} Compressed Info - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: ${{ matrix.chain }}-compressed-info.json - asset_name: ${{ matrix.chain }}-compressed-info.json - asset_content_type: application/json - - - name: Upload ${{ matrix.chain }} Srtool Digest - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: ${{ matrix.chain }}-srtool-digest.json - asset_name: ${{ matrix.chain }}-srtool-digest.json - asset_content_type: application/json + - name: Download runtime + uses: actions/download-artifact@v3 + with: + name: ${{ matrix.chain }}-runtime + + - name: Get runtime version + id: get-runtime-version + run: | + ls -R + chain=${{ matrix.chain }} + runtime_version=$(cat $chain-compressed-info.json | jq '.core_version' | tr -d '"' | cut -d ' ' -f 1) + echo $runtime_version + echo "runtime=$(echo $runtime_version)" >> $GITHUB_ENV + echo "${{ matrix.chain }}=$(echo $runtime_version)" >> $GITHUB_OUTPUT + + - name: Upload ${{ matrix.chain }} Wasm + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: ${{ matrix.chain }}_runtime.compact.compressed.wasm + asset_name: ${{ env.runtime }}.wasm + asset_content_type: application/wasm + + - name: Upload ${{ matrix.chain }} Metadata + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: ${{ matrix.chain }}-metadata.json + asset_name: ${{ matrix.chain }}-metadata.json + asset_content_type: application/json + + - name: Upload ${{ matrix.chain }} Compressed Info + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: ${{ matrix.chain }}-compressed-info.json + asset_name: ${{ matrix.chain }}-compressed-info.json + asset_content_type: application/json + + - name: Upload ${{ matrix.chain }} Srtool Digest + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: ${{ matrix.chain }}-srtool-digest.json + asset_name: ${{ matrix.chain }}-srtool-digest.json + asset_content_type: application/json outputs: astar_runtime_version: ${{ steps.get-runtime-version.outputs.astar }} @@ -490,61 +479,54 @@ jobs: shibuya_runtime_version: ${{ steps.get-runtime-version.outputs.shibuya }} upload-evm-tracing-artifacts: - needs: [publish-release-draft,upload-runtimes] + needs: [publish-release-draft, upload-runtimes] runs-on: ubuntu-latest steps: - - name: Download pre-built collator binary for evm tracing - uses: actions/download-artifact@v3 - with: - name: astar-evm-tracing-ubuntu-latest-x86_64-unknown-linux-gnu - path: evm-tracing-artifacts - - - name: Download evm tracing runtime - uses: actions/download-artifact@v3 - with: - name: astar-evm-tracing-runtime - path: evm-tracing-artifacts - - - name: Download evm tracing runtime - uses: actions/download-artifact@v3 - with: - name: shiden-evm-tracing-runtime - path: evm-tracing-artifacts - - - name: Download evm tracing runtime - uses: actions/download-artifact@v3 - with: - name: shibuya-evm-tracing-runtime - path: evm-tracing-artifacts - - - name: Make evm tracing binary executable and rename - run: | - cd evm-tracing-artifacts - chmod +x astar-collator - mv astar_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.astar_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm - mv shiden_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.shiden_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm - mv shibuya_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.shibuya_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm - - - name: Compress folder - run: | - tar zcvf evm-tracing-artifacts.tar.gz evm-tracing-artifacts - - - name: Upload evm tracing binary artifact - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} - asset_path: evm-tracing-artifacts.tar.gz - asset_name: evm-tracing-artifacts-${{ github.ref_name }}.tar.gz - asset_content_type: application/gzip + - name: Download evm tracing runtime + uses: actions/download-artifact@v3 + with: + name: astar-evm-tracing-runtime + path: evm-tracing-artifacts + + - name: Download evm tracing runtime + uses: actions/download-artifact@v3 + with: + name: shiden-evm-tracing-runtime + path: evm-tracing-artifacts + + - name: Download evm tracing runtime + uses: actions/download-artifact@v3 + with: + name: shibuya-evm-tracing-runtime + path: evm-tracing-artifacts + + - name: Rename evm tracing + run: | + cd evm-tracing-artifacts + mv astar_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.astar_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm + mv shiden_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.shiden_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm + mv shibuya_evm_tracing_runtime.compact.compressed.wasm ${{needs.upload-runtimes.outputs.shibuya_runtime_version}}_evm_tracing_runtime.compact.compressed.wasm + + - name: Compress folder + run: | + tar zcvf evm-tracing-artifacts.tar.gz evm-tracing-artifacts + + - name: Upload evm tracing binary artifact + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.publish-release-draft.outputs.upload_url }} + asset_path: evm-tracing-artifacts.tar.gz + asset_name: evm-tracing-artifacts-${{ github.ref_name }}.tar.gz + asset_content_type: application/gzip chain-sync-smoke: needs: native-linux runs-on: ubuntu-latest strategy: matrix: - chain: [ "astar", "shiden", "shibuya" ] + chain: ["astar", "shiden", "shibuya"] steps: - name: Checkout the source code @@ -566,7 +548,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - chain: [ "astar-dev", "shiden-dev", "shibuya-dev" ] + chain: ["astar-dev", "shiden-dev", "shibuya-dev"] steps: - name: Checkout the source code @@ -576,12 +558,10 @@ jobs: uses: actions/download-artifact@v3 with: name: astar-ubuntu-latest-x86_64 - path: target/release + path: third-party/zombienet - name: Setup - run: | - chmod +x target/release/astar-collator - mv target/release/astar-collator third-party/zombienet + run: chmod +x third-party/zombienet/astar-collator - name: Setup zombienet working-directory: third-party/zombienet diff --git a/Cargo.lock b/Cargo.lock index 2a774b07b4..3e7d03b64d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -645,7 +645,9 @@ dependencies = [ "frame-benchmarking", "frame-benchmarking-cli", "frame-metadata-hash-extension", + "frame-support", "frame-system", + "frame-system-rpc-runtime-api", "frame-try-runtime", "futures 0.3.30", "jsonrpsee", @@ -661,6 +663,7 @@ dependencies = [ "pallet-evm", "pallet-transaction-payment", "pallet-transaction-payment-rpc", + "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "polkadot-cli", "polkadot-core-primitives", @@ -699,6 +702,7 @@ dependencies = [ "sp-consensus", "sp-consensus-aura", "sp-core", + "sp-genesis-builder", "sp-inherents", "sp-io", "sp-keyring", @@ -706,9 +710,11 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", + "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.11.0)", "sp-timestamp", "sp-transaction-pool", "sp-trie", + "sp-version", "substrate-build-script-utils", "substrate-frame-rpc-system", "substrate-prometheus-endpoint", @@ -765,7 +771,8 @@ dependencies = [ "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-primitives-utility", - "dapp-staking-v3-runtime-api", + "dapp-staking-runtime-api", + "fp-evm", "fp-rpc", "fp-self-contained", "frame-benchmarking", @@ -792,14 +799,14 @@ dependencies = [ "pallet-chain-extension-assets", "pallet-collator-selection 3.3.2", "pallet-contracts", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-dynamic-evm-base-fee", "pallet-ethereum", "pallet-evm", "pallet-evm-precompile-assets-erc20", "pallet-evm-precompile-blake2", "pallet-evm-precompile-bn128", - "pallet-evm-precompile-dapp-staking-v3", + "pallet-evm-precompile-dapp-staking", "pallet-evm-precompile-dispatch", "pallet-evm-precompile-dispatch-lockdrop", "pallet-evm-precompile-ed25519", @@ -834,6 +841,7 @@ dependencies = [ "polkadot-runtime-common", "precompile-utils", "scale-info", + "serde_json", "smallvec", "sp-api", "sp-arithmetic", @@ -2936,7 +2944,7 @@ dependencies = [ ] [[package]] -name = "dapp-staking-v3-runtime-api" +name = "dapp-staking-runtime-api" version = "0.1.0" dependencies = [ "astar-primitives", @@ -5560,7 +5568,7 @@ dependencies = [ "pallet-collective-proxy", "pallet-contracts", "pallet-contracts-uapi", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-democracy", "pallet-ethereum", "pallet-ethereum-checked", @@ -6541,7 +6549,8 @@ version = "5.43.1" dependencies = [ "array-bytes 6.2.3", "astar-primitives", - "dapp-staking-v3-runtime-api", + "dapp-staking-runtime-api", + "fp-evm", "fp-rpc", "fp-self-contained", "frame-benchmarking", @@ -6565,7 +6574,7 @@ dependencies = [ "pallet-collective", "pallet-collective-proxy", "pallet-contracts", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-democracy", "pallet-dynamic-evm-base-fee", "pallet-ethereum", @@ -6574,7 +6583,7 @@ dependencies = [ "pallet-evm-precompile-assets-erc20", "pallet-evm-precompile-blake2", "pallet-evm-precompile-bn128", - "pallet-evm-precompile-dapp-staking-v3", + "pallet-evm-precompile-dapp-staking", "pallet-evm-precompile-dispatch", "pallet-evm-precompile-dispatch-lockdrop", "pallet-evm-precompile-ed25519", @@ -6603,6 +6612,7 @@ dependencies = [ "parity-scale-codec", "precompile-utils", "scale-info", + "serde_json", "smallvec", "sp-api", "sp-arithmetic", @@ -8464,7 +8474,7 @@ dependencies = [ ] [[package]] -name = "pallet-dapp-staking-v3" +name = "pallet-dapp-staking" version = "0.1.0" dependencies = [ "assert_matches", @@ -8707,7 +8717,7 @@ dependencies = [ ] [[package]] -name = "pallet-evm-precompile-dapp-staking-v3" +name = "pallet-evm-precompile-dapp-staking" version = "0.1.0" dependencies = [ "assert_matches", @@ -8719,7 +8729,7 @@ dependencies = [ "log", "num_enum 0.5.11", "pallet-balances", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-evm", "pallet-timestamp", "parity-scale-codec", @@ -14367,7 +14377,8 @@ dependencies = [ "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-primitives-utility", - "dapp-staking-v3-runtime-api", + "dapp-staking-runtime-api", + "fp-evm", "fp-rpc", "fp-self-contained", "frame-benchmarking", @@ -14397,7 +14408,7 @@ dependencies = [ "pallet-collective", "pallet-collective-proxy", "pallet-contracts", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-democracy", "pallet-dynamic-evm-base-fee", "pallet-ethereum", @@ -14407,7 +14418,7 @@ dependencies = [ "pallet-evm-precompile-assets-erc20", "pallet-evm-precompile-blake2", "pallet-evm-precompile-bn128", - "pallet-evm-precompile-dapp-staking-v3", + "pallet-evm-precompile-dapp-staking", "pallet-evm-precompile-dispatch", "pallet-evm-precompile-dispatch-lockdrop", "pallet-evm-precompile-ed25519", @@ -14448,6 +14459,7 @@ dependencies = [ "polkadot-runtime-common", "precompile-utils", "scale-info", + "serde_json", "smallvec", "sp-api", "sp-arithmetic", @@ -14487,7 +14499,8 @@ dependencies = [ "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-primitives-utility", - "dapp-staking-v3-runtime-api", + "dapp-staking-runtime-api", + "fp-evm", "fp-rpc", "fp-self-contained", "frame-benchmarking", @@ -14514,14 +14527,14 @@ dependencies = [ "pallet-chain-extension-assets", "pallet-collator-selection 3.3.2", "pallet-contracts", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-dynamic-evm-base-fee", "pallet-ethereum", "pallet-evm", "pallet-evm-precompile-assets-erc20", "pallet-evm-precompile-blake2", "pallet-evm-precompile-bn128", - "pallet-evm-precompile-dapp-staking-v3", + "pallet-evm-precompile-dapp-staking", "pallet-evm-precompile-dispatch", "pallet-evm-precompile-dispatch-lockdrop", "pallet-evm-precompile-ed25519", @@ -14557,6 +14570,7 @@ dependencies = [ "polkadot-runtime-common", "precompile-utils", "scale-info", + "serde_json", "smallvec", "sp-api", "sp-arithmetic", @@ -18123,7 +18137,7 @@ dependencies = [ "pallet-assets", "pallet-balances", "pallet-contracts", - "pallet-dapp-staking-v3", + "pallet-dapp-staking", "pallet-insecure-randomness-collective-flip", "pallet-message-queue", "pallet-proxy", diff --git a/Cargo.toml b/Cargo.toml index bbf3a5a709..2109c7d423 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,11 @@ exclude = ["vendor"] # Astar runtime requires unwinding. panic = "unwind" +[profile.production] +inherits = "release" +lto = true +codegen-units = 1 + [workspace.package] authors = ["Stake Technologies "] edition = "2021" @@ -72,7 +77,7 @@ clap = { version = "4.2.5", features = ["derive"] } env_logger = "0.10.0" futures = { version = "0.3.30" } serde = { version = "1.0.151", default-features = false, features = ["derive", "alloc"] } -serde_json = "1.0.92" +serde_json = { version = "1.0.92", default-features = false } tokio = { version = "1.24.2", features = ["macros", "sync"] } url = "2.2.2" jsonrpsee = { version = "0.22.5", features = ["server"] } @@ -282,7 +287,7 @@ orml-oracle = { git = "https://github.com/AstarNetwork/open-runtime-module-libra # Astar pallets & modules # (wasm) pallet-collator-selection = { path = "./pallets/collator-selection", default-features = false } -pallet-dapp-staking-v3 = { path = "./pallets/dapp-staking-v3", default-features = false } +pallet-dapp-staking = { path = "./pallets/dapp-staking", default-features = false } pallet-xc-asset-config = { path = "./pallets/xc-asset-config", default-features = false } pallet-ethereum-checked = { path = "./pallets/ethereum-checked", default-features = false } pallet-inflation = { path = "./pallets/inflation", default-features = false } @@ -294,7 +299,7 @@ pallet-price-aggregator = { path = "./pallets/price-aggregator", default-feature pallet-collective-proxy = { path = "./pallets/collective-proxy", default-features = false } vesting-mbm = { path = "./pallets/vesting-mbm", default-features = false } -dapp-staking-v3-runtime-api = { path = "./pallets/dapp-staking-v3/rpc/runtime-api", default-features = false } +dapp-staking-runtime-api = { path = "./pallets/dapp-staking/rpc/runtime-api", default-features = false } astar-primitives = { path = "./primitives", default-features = false } astar-test-utils = { path = "./tests/utils", default-features = false } @@ -303,7 +308,7 @@ pallet-evm-precompile-assets-erc20 = { path = "./precompiles/assets-erc20", defa pallet-evm-precompile-sr25519 = { path = "./precompiles/sr25519", default-features = false } pallet-evm-precompile-substrate-ecdsa = { path = "./precompiles/substrate-ecdsa", default-features = false } pallet-evm-precompile-xcm = { path = "./precompiles/xcm", default-features = false } -pallet-evm-precompile-dapp-staking-v3 = { path = "./precompiles/dapp-staking-v3", default-features = false } +pallet-evm-precompile-dapp-staking = { path = "./precompiles/dapp-staking", default-features = false } pallet-evm-precompile-unified-accounts = { path = "./precompiles/unified-accounts", default-features = false } pallet-evm-precompile-dispatch-lockdrop = { path = "./precompiles/dispatch-lockdrop", default-features = false } diff --git a/bin/collator/Cargo.toml b/bin/collator/Cargo.toml index 1af68ec9d9..a784f981bb 100644 --- a/bin/collator/Cargo.toml +++ b/bin/collator/Cargo.toml @@ -33,6 +33,7 @@ sp-api = { workspace = true, features = ["std"] } sp-block-builder = { workspace = true, features = ["std"] } sp-consensus-aura = { workspace = true, features = ["std"] } sp-core = { workspace = true, features = ["std"] } +sp-genesis-builder = { workspace = true, features = ["std"] } sp-inherents = { workspace = true, features = ["std"] } sp-io = { workspace = true, features = ["std"] } sp-offchain = { workspace = true, features = ["std"] } @@ -40,12 +41,15 @@ sp-runtime = { workspace = true, features = ["std"] } sp-session = { workspace = true, features = ["std"] } sp-transaction-pool = { workspace = true, features = ["std"] } +frame-support = { workspace = true } sp-blockchain = { workspace = true } sp-consensus = { workspace = true } sp-keyring = { workspace = true, optional = true } sp-keystore = { workspace = true } +sp-std = { workspace = true } sp-timestamp = { workspace = true } sp-trie = { workspace = true } +sp-version = { workspace = true } # client dependencies sc-basic-authorship = { workspace = true } @@ -88,6 +92,7 @@ fc-storage = { workspace = true } fp-consensus = { workspace = true } fp-evm = { workspace = true, features = ["std"] } fp-storage = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } # astar-specific dependencies astar-runtime = { workspace = true, features = ["std"] } @@ -101,8 +106,9 @@ astar-primitives = { workspace = true } # frame dependencies frame-metadata-hash-extension = { workspace = true } frame-system = { workspace = true, features = ["std"] } -pallet-transaction-payment = { workspace = true, features = ["std"] } +pallet-transaction-payment = { workspace = true } pallet-transaction-payment-rpc = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } substrate-frame-rpc-system = { workspace = true } # CLI-specific dependencies @@ -142,13 +148,13 @@ polkadot-runtime-common = { workspace = true, features = ["std"], optional = tru frame-try-runtime = { workspace = true, features = ["std"], optional = true } # evm-tracing -moonbeam-rpc-primitives-debug = { workspace = true, features = ["std"], optional = true } -moonbeam-rpc-primitives-txpool = { workspace = true, features = ["std"], optional = true } +moonbeam-rpc-primitives-debug = { workspace = true } +moonbeam-rpc-primitives-txpool = { workspace = true } moonbeam-primitives-ext = { workspace = true } -moonbeam-rpc-debug = { workspace = true, optional = true } -moonbeam-rpc-trace = { workspace = true, optional = true } -moonbeam-rpc-txpool = { workspace = true, optional = true } +moonbeam-rpc-debug = { workspace = true } +moonbeam-rpc-trace = { workspace = true } +moonbeam-rpc-txpool = { workspace = true } [build-dependencies] polkadot-cli = { workspace = true, optional = true } @@ -181,6 +187,7 @@ runtime-benchmarks = [ "sc-service/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "cumulus-primitives-core/runtime-benchmarks", + "frame-support/runtime-benchmarks", ] try-runtime = [ "local-runtime/try-runtime", @@ -197,16 +204,6 @@ try-runtime = [ "shibuya-runtime/try-runtime", "shiden-runtime/try-runtime", "sp-runtime/try-runtime", -] -evm-tracing = [ - "moonbeam-rpc-debug", - "moonbeam-rpc-primitives-debug", - "moonbeam-rpc-primitives-txpool", - "moonbeam-rpc-trace", - "moonbeam-rpc-txpool", - "shibuya-runtime/evm-tracing", - "shiden-runtime/evm-tracing", - "astar-runtime/evm-tracing", - "local-runtime/evm-tracing", + "frame-support/try-runtime", ] manual-seal = ["sc-consensus-manual-seal"] diff --git a/bin/collator/src/cli.rs b/bin/collator/src/cli.rs index f0c03f2d70..ec709637cf 100644 --- a/bin/collator/src/cli.rs +++ b/bin/collator/src/cli.rs @@ -19,7 +19,6 @@ use clap::Parser; use std::path::PathBuf; -#[cfg(feature = "evm-tracing")] use crate::evm_tracing_types::EthApiOptions; /// An overarching CLI command definition. @@ -34,7 +33,6 @@ pub struct Cli { pub run: cumulus_client_cli::RunCmd, #[allow(missing_docs)] - #[cfg(feature = "evm-tracing")] #[clap(flatten)] pub eth_api_options: EthApiOptions, diff --git a/bin/collator/src/command.rs b/bin/collator/src/command.rs index 13f7ff2d3a..a2073426b8 100644 --- a/bin/collator/src/command.rs +++ b/bin/collator/src/command.rs @@ -19,14 +19,12 @@ //! Astar collator CLI handlers. use crate::{ cli::{Cli, RelayChainCli, Subcommand}, + evm_tracing_types::EvmTracingConfig, local::{self, development_config}, - parachain::{ - self, chain_spec, service::AdditionalConfig, start_astar_node, start_shibuya_node, - start_shiden_node, - }, + parachain::{self, chain_spec, service::AdditionalConfig}, }; use cumulus_primitives_core::ParaId; -use log::{error, info}; +use log::info; use sc_cli::{ ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, Result, SharedParams, SubstrateCli, @@ -198,169 +196,49 @@ pub fn run() -> Result<()> { } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } else { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + import_queue, + .. + } = parachain::new_partial(&config)?; + Ok((cmd.run(client, import_queue), task_manager)) + }) } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, config.database), task_manager)) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - Ok((cmd.run(client, config.database), task_manager)) - }) - } else { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, config.database), task_manager)) - }) - } + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + .. + } = parachain::new_partial(&config)?; + Ok((cmd.run(client, config.database), task_manager)) + }) } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, config.chain_spec), task_manager)) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - Ok((cmd.run(client, config.chain_spec), task_manager)) - }) - } else { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, config.chain_spec), task_manager)) - }) - } + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + .. + } = parachain::new_partial(&config)?; + Ok((cmd.run(client, config.chain_spec), task_manager)) + }) } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } else { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - import_queue, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - } + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + import_queue, + .. + } = parachain::new_partial(&config)?; + Ok((cmd.run(client, import_queue), task_manager)) + }) } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; @@ -383,89 +261,26 @@ pub fn run() -> Result<()> { } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - backend, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - backend, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) - }) - } else { - runner.async_run(|config| { - let PartialComponents { - client, - task_manager, - backend, - .. - } = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) - }) - } + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + backend, + .. + } = parachain::new_partial(&config)?; + let aux_revert = Box::new(|client, _, blocks| { + sc_consensus_grandpa::revert(client, blocks)?; + Ok(()) + }); + Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) + }) } Some(Subcommand::ExportGenesisState(cmd)) => { let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_astar() { - runner.sync_run(|config| { - let PartialComponents { client, .. } = - parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - cmd.run(client) - }) - } else if runner.config().chain_spec.is_shiden() { - runner.sync_run(|config| { - let PartialComponents { client, .. } = - parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - cmd.run(client) - }) - } else { - runner.sync_run(|config| { - let PartialComponents { client, .. } = - parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - cmd.run(client) - }) - } + runner.sync_run(|config| { + let PartialComponents { client, .. } = parachain::new_partial(&config)?; + cmd.run(client) + }) } Some(Subcommand::ExportGenesisWasm(cmd)) => { let runner = cli.create_runner(cmd)?; @@ -517,66 +332,22 @@ pub fn run() -> Result<()> { } } BenchmarkCmd::Block(cmd) => { - if chain_spec.is_astar() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - cmd.run(params.client) - }) - } else if chain_spec.is_shiden() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - cmd.run(params.client) - }) - } else if chain_spec.is_shibuya() { + if chain_spec.is_dev() { runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; + let params = local::new_partial(&config)?; cmd.run(params.client) }) } else { runner.sync_run(|config| { - let params = local::new_partial(&config)?; + let params = parachain::new_partial(&config)?; cmd.run(params.client) }) } } BenchmarkCmd::Storage(cmd) => { - if chain_spec.is_astar() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - let db = params.backend.expose_db(); - let storage = params.backend.expose_storage(); - - cmd.run(config, params.client, db, storage) - }) - } else if chain_spec.is_shiden() { + if chain_spec.is_dev() { runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - let db = params.backend.expose_db(); - let storage = params.backend.expose_storage(); - - cmd.run(config, params.client, db, storage) - }) - } else if chain_spec.is_shibuya() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; + let params = local::new_partial(&config)?; let db = params.backend.expose_db(); let storage = params.backend.expose_storage(); @@ -584,7 +355,7 @@ pub fn run() -> Result<()> { }) } else { runner.sync_run(|config| { - let params = local::new_partial(&config)?; + let params = parachain::new_partial(&config)?; let db = params.backend.expose_db(); let storage = params.backend.expose_storage(); @@ -593,33 +364,11 @@ pub fn run() -> Result<()> { } } BenchmarkCmd::Overhead(cmd) => { - if chain_spec.is_astar() { + if chain_spec.is_dev() { runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - let ext_builder = RemarkBuilder::new(params.client.clone()); - let inherent_data = para_benchmark_inherent_data() - .map_err(|e| format!("generating inherent data: {:?}", e))?; - - cmd.run( - config, - params.client, - inherent_data, - Vec::new(), - &ext_builder, - ) - }) - } else if chain_spec.is_shiden() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - + let params = local::new_partial(&config)?; let ext_builder = RemarkBuilder::new(params.client.clone()); - let inherent_data = para_benchmark_inherent_data() + let inherent_data = local_benchmark_inherent_data() .map_err(|e| format!("generating inherent data: {:?}", e))?; cmd.run( @@ -630,32 +379,14 @@ pub fn run() -> Result<()> { &ext_builder, ) }) - } else if chain_spec.is_shibuya() { + } else { runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; + let params = parachain::new_partial(&config)?; let ext_builder = RemarkBuilder::new(params.client.clone()); let inherent_data = para_benchmark_inherent_data() .map_err(|e| format!("generating inherent data: {:?}", e))?; - cmd.run( - config, - params.client, - inherent_data, - Vec::new(), - &ext_builder, - ) - }) - } else { - runner.sync_run(|config| { - let params = local::new_partial(&config)?; - let ext_builder = RemarkBuilder::new(params.client.clone()); - let inherent_data = local_benchmark_inherent_data() - .map_err(|e| format!("generating inherent data: {:?}", e))?; - cmd.run( config, params.client, @@ -667,54 +398,9 @@ pub fn run() -> Result<()> { } } BenchmarkCmd::Extrinsic(cmd) => { - if chain_spec.is_astar() { + if chain_spec.is_dev() { runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; - let remark_builder = RemarkBuilder::new(params.client.clone()); - let tka_builder = TransferKeepAliveBuilder::new( - params.client.clone(), - Sr25519Keyring::Alice.to_account_id(), - params.client.existential_deposit(), - ); - let ext_factory = ExtrinsicFactory(vec![ - Box::new(remark_builder), - Box::new(tka_builder), - ]); - let inherent_data = para_benchmark_inherent_data() - .map_err(|e| format!("generating inherent data: {:?}", e))?; - - cmd.run(params.client, inherent_data, Vec::new(), &ext_factory) - }) - } else if chain_spec.is_shiden() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue_fallback, - )?; - let remark_builder = RemarkBuilder::new(params.client.clone()); - let tka_builder = TransferKeepAliveBuilder::new( - params.client.clone(), - Sr25519Keyring::Alice.to_account_id(), - params.client.existential_deposit(), - ); - let ext_factory = ExtrinsicFactory(vec![ - Box::new(remark_builder), - Box::new(tka_builder), - ]); - let inherent_data = para_benchmark_inherent_data() - .map_err(|e| format!("generating inherent data: {:?}", e))?; - - cmd.run(params.client, inherent_data, Vec::new(), &ext_factory) - }) - } else if chain_spec.is_shibuya() { - runner.sync_run(|config| { - let params = parachain::new_partial::( - &config, - parachain::build_import_queue, - )?; + let params = local::new_partial(&config)?; let remark_builder = RemarkBuilder::new(params.client.clone()); let tka_builder = TransferKeepAliveBuilder::new( params.client.clone(), @@ -725,14 +411,14 @@ pub fn run() -> Result<()> { Box::new(remark_builder), Box::new(tka_builder), ]); - let inherent_data = para_benchmark_inherent_data() + let inherent_data = local_benchmark_inherent_data() .map_err(|e| format!("generating inherent data: {:?}", e))?; cmd.run(params.client, inherent_data, Vec::new(), &ext_factory) }) } else { runner.sync_run(|config| { - let params = local::new_partial(&config)?; + let params = parachain::new_partial(&config)?; let remark_builder = RemarkBuilder::new(params.client.clone()); let tka_builder = TransferKeepAliveBuilder::new( params.client.clone(), @@ -743,7 +429,7 @@ pub fn run() -> Result<()> { Box::new(remark_builder), Box::new(tka_builder), ]); - let inherent_data = local_benchmark_inherent_data() + let inherent_data = para_benchmark_inherent_data() .map_err(|e| format!("generating inherent data: {:?}", e))?; cmd.run(params.client, inherent_data, Vec::new(), &ext_factory) @@ -759,8 +445,7 @@ pub fn run() -> Result<()> { let runner = cli.create_runner(&cli.run.normalize())?; let collator_options = cli.run.collator_options(); - #[cfg(feature = "evm-tracing")] - let evm_tracing_config = crate::evm_tracing_types::EvmTracingConfig { + let evm_tracing_config = EvmTracingConfig { ethapi: cli.eth_api_options.ethapi, ethapi_max_permits: cli.eth_api_options.ethapi_max_permits, ethapi_trace_max_count: cli.eth_api_options.ethapi_trace_max_count, @@ -773,7 +458,11 @@ pub fn run() -> Result<()> { runner.run_node_until_exit(|config| async move { if config.chain_spec.is_dev() { - return local::start_node::>(config, #[cfg(feature = "evm-tracing")] evm_tracing_config).map_err(Into::into); + return local::start_node::>( + config, + evm_tracing_config, + ) + .map_err(Into::into); } let polkadot_cli = RelayChainCli::new( @@ -786,11 +475,13 @@ pub fn run() -> Result<()> { let para_id = ParaId::from( chain_spec::Extensions::try_get(&*config.chain_spec) .map(|e| e.para_id) - .ok_or("ParaId not found in chain spec extension")? + .ok_or("ParaId not found in chain spec extension")?, ); let parachain_account = - AccountIdConversion::::into_account_truncating(¶_id); + AccountIdConversion::::into_account_truncating( + ¶_id, + ); let polkadot_config = SubstrateCli::create_configuration( &polkadot_cli, @@ -818,49 +509,23 @@ pub fn run() -> Result<()> { .flatten(); let additional_config = AdditionalConfig { - #[cfg(feature = "evm-tracing")] - evm_tracing_config: evm_tracing_config, + evm_tracing_config, enable_evm_rpc: cli.enable_evm_rpc, proposer_block_size_limit: cli.proposer_block_size_limit, proposer_soft_deadline_percent: cli.proposer_soft_deadline_percent, hwbench, }; - if config.chain_spec.is_astar() { - start_astar_node( - config, - polkadot_config, - collator_options, - para_id, - additional_config - ) - .await - .map(|r| r.0) - .map_err(Into::into) - } else if config.chain_spec.is_shiden() { - start_shiden_node( config, - polkadot_config, - collator_options, - para_id, - additional_config - ) - .await - .map(|r| r.0) - .map_err(Into::into) - } else if config.chain_spec.is_shibuya() { - start_shibuya_node( config, - polkadot_config, - collator_options, - para_id, - additional_config) - .await - .map(|r| r.0) - .map_err(Into::into) - } else { - let err_msg = "Unrecognized chain spec - name should start with one of: astar or shiden or shibuya"; - error!("{}", err_msg); - Err(err_msg.into()) - } + parachain::start_node( + config, + polkadot_config, + collator_options, + para_id, + additional_config, + ) + .await + .map(|r| r.0) + .map_err(Into::into) }) } } diff --git a/bin/collator/src/local/chain_spec.rs b/bin/collator/src/local/chain_spec.rs index e545408bc8..af35be4a52 100644 --- a/bin/collator/src/local/chain_spec.rs +++ b/bin/collator/src/local/chain_spec.rs @@ -16,208 +16,27 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -//! Chain specifications. - -use local_runtime::{ - wasm_binary_unwrap, AccountId, AuraConfig, AuraId, BalancesConfig, - CommunityCouncilMembershipConfig, CommunityTreasuryPalletId, CouncilMembershipConfig, - DappStakingConfig, EVMConfig, GrandpaConfig, GrandpaId, InflationConfig, InflationParameters, - Precompiles, RuntimeGenesisConfig, Signature, SudoConfig, TechnicalCommitteeMembershipConfig, - TierThreshold, TreasuryPalletId, VestingConfig, AST, -}; +use local_runtime::wasm_binary_unwrap; use sc_service::ChainType; -use sp_core::{crypto::Ss58Codec, sr25519, Pair, Public}; -use sp_runtime::{ - traits::{AccountIdConversion, IdentifyAccount, Verify}, - Perbill, Permill, -}; - -type AccountPublic = ::Signer; -/// Specialized `ChainSpec` for Shiden Network. +/// Specialized `ChainSpec` for local network. pub type ChainSpec = sc_service::GenericChainSpec; -/// Helper function to generate a crypto pair from seed -fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -/// Helper function to generate an account ID from seed -fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -/// Generate an Aura authority key. -pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { - (get_from_seed::(s), get_from_seed::(s)) -} - -/// Development config (single validator Alice) +/// Development config. pub fn development_config() -> ChainSpec { let mut properties = serde_json::map::Map::new(); properties.insert("tokenSymbol".into(), "LOC".into()); properties.insert("tokenDecimals".into(), 18.into()); + ChainSpec::builder(wasm_binary_unwrap(), None) .with_name("Development") .with_id("dev") .with_chain_type(ChainType::Development) .with_properties(properties) - .with_genesis_config(testnet_genesis( - vec![authority_keys_from_seed("Alice")], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - TreasuryPalletId::get().into_account_truncating(), - CommunityTreasuryPalletId::get().into_account_truncating(), - // Arrakis.TEST account in MetaMask - // Import known test account with private key - // 0x01ab6e801c06e59ca97a14fc0a1978b27fa366fc87450e0b65459dd3515b7391 - // H160 address: 0xaaafB3972B05630fCceE866eC69CdADd9baC2771 - AccountId::from_ss58check("5FQedkNQcF2fJPwkB6Z1ZcMgGti4vcJQNs6x85YPv3VhjBBT") - .unwrap(), - ], - )) + .with_genesis_config(local_runtime::genesis_config::default_config()) .build() } -fn testnet_genesis( - initial_authorities: Vec<(AuraId, GrandpaId)>, - root_key: AccountId, - endowed_accounts: Vec, -) -> serde_json::Value { - let accounts: Vec = vec!["Alice", "Bob", "Charlie", "Dave", "Eve"] - .iter() - .map(|s| get_account_id_from_seed::(s)) - .collect(); - - // This is supposed the be the simplest bytecode to revert without returning any data. - // We will pre-deploy it under all of our precompiles to ensure they can be called from - // within contracts. - // (PUSH1 0x00 PUSH1 0x00 REVERT) - let revert_bytecode = vec![0x60, 0x00, 0x60, 0x00, 0xFD]; - let config = RuntimeGenesisConfig { - system: Default::default(), - balances: BalancesConfig { - balances: endowed_accounts - .iter() - .cloned() - .map(|k| (k, 1_000_000_000 * AST)) - .collect(), - }, - vesting: VestingConfig { vesting: vec![] }, - aura: AuraConfig { - authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), - }, - grandpa: GrandpaConfig { - authorities: initial_authorities - .iter() - .map(|x| (x.1.clone(), 1)) - .collect(), - ..Default::default() - }, - evm: EVMConfig { - // We need _some_ code inserted at the precompile address so that - // the evm will actually call the address. - accounts: Precompiles::used_addresses_h160() - .map(|addr| { - ( - addr, - fp_evm::GenesisAccount { - nonce: Default::default(), - balance: Default::default(), - storage: Default::default(), - code: revert_bytecode.clone(), - }, - ) - }) - .collect(), - ..Default::default() - }, - ethereum: Default::default(), - sudo: SudoConfig { - key: Some(root_key), - }, - assets: Default::default(), - transaction_payment: Default::default(), - dapp_staking: DappStakingConfig { - reward_portion: vec![ - Permill::from_percent(40), - Permill::from_percent(30), - Permill::from_percent(20), - Permill::from_percent(10), - ], - slot_distribution: vec![ - Permill::from_percent(10), - Permill::from_percent(20), - Permill::from_percent(30), - Permill::from_percent(40), - ], - tier_thresholds: vec![ - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(35_700_000), // 3.57% - minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(8_900_000), // 0.89% - minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(23_800_000), // 2.38% - minimum_required_percentage: Perbill::from_parts(17_900_000), // 1.79% - }, - TierThreshold::FixedPercentage { - required_percentage: Perbill::from_parts(600_000), // 0.06% - }, - ], - slots_per_tier: vec![10, 20, 30, 40], - safeguard: Some(false), - ..Default::default() - }, - inflation: InflationConfig { - params: InflationParameters::default(), - ..Default::default() - }, - council_membership: CouncilMembershipConfig { - members: accounts - .clone() - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - technical_committee_membership: TechnicalCommitteeMembershipConfig { - members: accounts[..3] - .to_vec() - .try_into() - .expect("Should support at least 3 members."), - phantom: Default::default(), - }, - community_council_membership: CommunityCouncilMembershipConfig { - members: accounts - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - council: Default::default(), - technical_committee: Default::default(), - community_council: Default::default(), - democracy: Default::default(), - treasury: Default::default(), - community_treasury: Default::default(), - }; - - serde_json::to_value(&config).expect("Could not build genesis config.") -} - #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/bin/collator/src/local/service.rs b/bin/collator/src/local/service.rs index e444eb7f9c..7c3c210441 100644 --- a/bin/collator/src/local/service.rs +++ b/bin/collator/src/local/service.rs @@ -18,6 +18,10 @@ //! Local Service and ServiceFactory implementation. Specialized wrapper over substrate service. +use crate::{ + evm_tracing_types::{EthApi as EthApiCmd, EvmTracingConfig}, + rpc::tracing, +}; use fc_consensus::FrontierBlockImport; use fc_rpc_core::types::{FeeHistoryCache, FilterPool}; use fc_storage::StorageOverrideHandler; @@ -29,14 +33,10 @@ use sc_network::NetworkBackend; use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sp_runtime::traits::Block as BlockT; -use std::{collections::BTreeMap, sync::Arc, time::Duration}; - #[cfg(not(feature = "manual-seal"))] use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; - -#[cfg(feature = "evm-tracing")] -use crate::{evm_tracing_types::EthApi as EthApiCmd, rpc::tracing}; +use sp_runtime::traits::Block as BlockT; +use std::{collections::BTreeMap, sync::Arc, time::Duration}; pub use local_runtime::RuntimeApi; @@ -47,16 +47,11 @@ use astar_primitives::*; const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512; /// Parachain host functions -#[cfg(feature = "evm-tracing")] pub type HostFunctions = ( cumulus_client_service::ParachainHostFunctions, moonbeam_primitives_ext::moonbeam_ext::HostFunctions, ); -/// Parachain host functions -#[cfg(not(feature = "evm-tracing"))] -pub type HostFunctions = (cumulus_client_service::ParachainHostFunctions,); - type ParachainExecutor = WasmExecutor; type FullClient = sc_service::TFullClient; @@ -202,7 +197,7 @@ pub fn new_partial( /// Builds a new service. pub fn start_node( config: Configuration, - #[cfg(feature = "evm-tracing")] evm_tracing_config: crate::evm_tracing_types::EvmTracingConfig, + evm_tracing_config: EvmTracingConfig, ) -> Result where N: NetworkBackend::Hash>, @@ -290,10 +285,8 @@ where > = Default::default(); let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks); - #[cfg(feature = "evm-tracing")] let ethapi_cmd = evm_tracing_config.ethapi.clone(); - #[cfg(feature = "evm-tracing")] let tracing_requesters = if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) { tracing::spawn_tracing_tasks( @@ -415,7 +408,6 @@ where deps, subscription, pubsub_notification_sinks.clone(), - #[cfg(feature = "evm-tracing")] crate::rpc::EvmTracingConfig { tracing_requesters: tracing_requesters.clone(), trace_filter_max_count: evm_tracing_config.ethapi_trace_max_count, diff --git a/bin/collator/src/parachain/chain_spec/astar.rs b/bin/collator/src/parachain/chain_spec/astar.rs index f5e0ec3491..47819db0c7 100644 --- a/bin/collator/src/parachain/chain_spec/astar.rs +++ b/bin/collator/src/parachain/chain_spec/astar.rs @@ -18,42 +18,17 @@ //! Astar chain specifications. -use super::{get_from_seed, Extensions}; -use astar_primitives::oracle::CurrencyAmount; -use astar_runtime::{ - wasm_binary_unwrap, AccountId, AuraId, Balance, DappStakingConfig, EVMConfig, InflationConfig, - InflationParameters, OracleMembershipConfig, ParachainInfoConfig, Precompiles, - PriceAggregatorConfig, Signature, TierThreshold, ASTR, -}; -use cumulus_primitives_core::ParaId; +use super::Extensions; +use astar_primitives::parachain::ASTAR_ID; +use astar_runtime::wasm_binary_unwrap; use sc_service::ChainType; -use sp_core::{sr25519, Pair, Public}; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - Perbill, Permill, -}; - -const PARA_ID: u32 = 2006; /// Specialized `ChainSpec` for Astar Network. pub type AstarChainSpec = sc_service::GenericChainSpec; -/// Gen Astar chain specification for given parachain id. +/// Get Astar chain specification. pub fn get_chain_spec() -> AstarChainSpec { - // Alice as default - let sudo_key = get_account_id_from_seed::("Alice"); - let endowned = vec![ - ( - get_account_id_from_seed::("Alice"), - 1_000_000_000 * ASTR, - ), - ( - get_account_id_from_seed::("Bob"), - 1_000_000_000 * ASTR, - ), - ]; - let mut properties = serde_json::map::Map::new(); properties.insert("tokenSymbol".into(), "ASTR".into()); properties.insert("tokenDecimals".into(), 18.into()); @@ -63,161 +38,13 @@ pub fn get_chain_spec() -> AstarChainSpec { Extensions { bad_blocks: Default::default(), relay_chain: "tokyo".into(), - para_id: PARA_ID, + para_id: ASTAR_ID, }, ) .with_name("Astar Testnet") .with_id("astar") .with_chain_type(ChainType::Development) .with_properties(properties) - .with_genesis_config(make_genesis( - endowned.clone(), - sudo_key.clone(), - PARA_ID.into(), - )) + .with_genesis_config(astar_runtime::genesis_config::default_config(ASTAR_ID)) .build() } - -fn session_keys(aura: AuraId) -> astar_runtime::SessionKeys { - astar_runtime::SessionKeys { aura } -} - -/// Helper function to create RuntimeGenesisConfig. -fn make_genesis( - balances: Vec<(AccountId, Balance)>, - root_key: AccountId, - parachain_id: ParaId, -) -> serde_json::Value { - let authorities = vec![ - ( - get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), - ), - ]; - - // This is supposed the be the simplest bytecode to revert without returning any data. - // We will pre-deploy it under all of our precompiles to ensure they can be called from - // within contracts. - // (PUSH1 0x00 PUSH1 0x00 REVERT) - let revert_bytecode = vec![0x60, 0x00, 0x60, 0x00, 0xFD]; - - let config = astar_runtime::RuntimeGenesisConfig { - system: Default::default(), - sudo: astar_runtime::SudoConfig { - key: Some(root_key), - }, - parachain_info: ParachainInfoConfig { - parachain_id, - ..Default::default() - }, - balances: astar_runtime::BalancesConfig { balances }, - vesting: astar_runtime::VestingConfig { vesting: vec![] }, - session: astar_runtime::SessionConfig { - keys: authorities - .iter() - .map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone()))) - .collect::>(), - }, - aura: astar_runtime::AuraConfig { - authorities: vec![], - }, - aura_ext: Default::default(), - collator_selection: astar_runtime::CollatorSelectionConfig { - desired_candidates: 32, - candidacy_bond: 3_200_000 * ASTR, - invulnerables: authorities.iter().map(|x| x.0.clone()).collect::>(), - }, - evm: EVMConfig { - // We need _some_ code inserted at the precompile address so that - // the evm will actually call the address. - accounts: Precompiles::used_addresses_h160() - .map(|addr| { - ( - addr, - fp_evm::GenesisAccount { - nonce: Default::default(), - balance: Default::default(), - storage: Default::default(), - code: revert_bytecode.clone(), - }, - ) - }) - .collect(), - ..Default::default() - }, - ethereum: Default::default(), - polkadot_xcm: Default::default(), - assets: Default::default(), - parachain_system: Default::default(), - transaction_payment: Default::default(), - dapp_staking: DappStakingConfig { - reward_portion: vec![ - Permill::from_percent(40), - Permill::from_percent(30), - Permill::from_percent(20), - Permill::from_percent(10), - ], - slot_distribution: vec![ - Permill::from_percent(10), - Permill::from_percent(20), - Permill::from_percent(30), - Permill::from_percent(40), - ], - // percentages below are calulated based on total issuance at the time when dApp staking v3 was launched (8.4B) - tier_thresholds: vec![ - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(35_700_000), // 3.57% - minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(8_900_000), // 0.89% - minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(2_380_000), // 0.238% - minimum_required_percentage: Perbill::from_parts(1_790_000), // 0.179% - }, - TierThreshold::FixedPercentage { - required_percentage: Perbill::from_parts(200_000), // 0.02% - }, - ], - slots_per_tier: vec![10, 20, 30, 40], - safeguard: Some(false), - ..Default::default() - }, - inflation: InflationConfig { - params: InflationParameters::default(), - ..Default::default() - }, - oracle_membership: OracleMembershipConfig { - members: vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - ] - .try_into() - .expect("Assumption is that at least two members will be allowed."), - ..Default::default() - }, - price_aggregator: PriceAggregatorConfig { - circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] - .try_into() - .expect("Must work since buffer should have at least a single value."), - }, - }; - - serde_json::to_value(&config).expect("Could not build genesis config.") -} - -type AccountPublic = ::Signer; - -/// Helper function to generate an account ID from seed -fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} diff --git a/bin/collator/src/parachain/chain_spec/mod.rs b/bin/collator/src/parachain/chain_spec/mod.rs index 14a3909092..3c2a6a89f4 100644 --- a/bin/collator/src/parachain/chain_spec/mod.rs +++ b/bin/collator/src/parachain/chain_spec/mod.rs @@ -16,11 +16,9 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . +use astar_primitives::Block; use sc_chain_spec::ChainSpecExtension; use serde::{Deserialize, Serialize}; -use sp_core::{Pair, Public}; - -use astar_primitives::Block; pub mod astar; pub mod shibuya; @@ -51,10 +49,3 @@ impl Extensions { sc_chain_spec::get_extension(chain_spec.extensions()) } } - -/// Helper function to generate a crypto pair from seed -fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} diff --git a/bin/collator/src/parachain/chain_spec/shibuya.rs b/bin/collator/src/parachain/chain_spec/shibuya.rs index cab9754a5c..fa38806c30 100644 --- a/bin/collator/src/parachain/chain_spec/shibuya.rs +++ b/bin/collator/src/parachain/chain_spec/shibuya.rs @@ -18,46 +18,16 @@ //! Shibuya chain specifications. -use cumulus_primitives_core::ParaId; +use super::Extensions; +use astar_primitives::parachain::SHIBUYA_ID; use sc_service::ChainType; -use shibuya_runtime::{ - wasm_binary_unwrap, AccountId, AuraConfig, AuraId, Balance, BalancesConfig, - CollatorSelectionConfig, CommunityCouncilMembershipConfig, CouncilMembershipConfig, - DappStakingConfig, EVMChainIdConfig, EVMConfig, InflationConfig, InflationParameters, - OracleMembershipConfig, ParachainInfoConfig, Precompiles, PriceAggregatorConfig, - RuntimeGenesisConfig, SessionConfig, SessionKeys, Signature, SudoConfig, - TechnicalCommitteeMembershipConfig, TierThreshold, VestingConfig, SBY, -}; -use sp_core::{sr25519, Pair, Public}; - -use astar_primitives::oracle::CurrencyAmount; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - Perbill, Permill, -}; - -use super::{get_from_seed, Extensions}; - -const PARA_ID: u32 = 1000; +use shibuya_runtime::{wasm_binary_unwrap, RuntimeGenesisConfig}; /// Specialized `ChainSpec` for Shibuya testnet. pub type ShibuyaChainSpec = sc_service::GenericChainSpec; -/// Gen Shibuya chain specification for given parachain id. +/// Gen Shibuya chain specification. pub fn get_chain_spec() -> ShibuyaChainSpec { - // Alice as default - let sudo_key = get_account_id_from_seed::("Alice"); - let endowned = vec![ - ( - get_account_id_from_seed::("Alice"), - 1_000_000_000 * SBY, - ), - ( - get_account_id_from_seed::("Bob"), - 1_000_000_000 * SBY, - ), - ]; - let mut properties = serde_json::map::Map::new(); properties.insert("tokenSymbol".into(), "SBY".into()); properties.insert("tokenDecimals".into(), 18.into()); @@ -67,195 +37,13 @@ pub fn get_chain_spec() -> ShibuyaChainSpec { Extensions { bad_blocks: Default::default(), relay_chain: "tokyo".into(), - para_id: PARA_ID, + para_id: SHIBUYA_ID, }, ) .with_name("Shibuya Testnet") .with_id("shibuya") .with_chain_type(ChainType::Development) .with_properties(properties) - .with_genesis_config(make_genesis( - endowned.clone(), - sudo_key.clone(), - PARA_ID.into(), - )) + .with_genesis_config(shibuya_runtime::genesis_config::default_config(SHIBUYA_ID)) .build() } - -fn session_keys(aura: AuraId) -> SessionKeys { - SessionKeys { aura } -} - -/// Helper function to create Shibuya RuntimeGenesisConfig. -fn make_genesis( - balances: Vec<(AccountId, Balance)>, - root_key: AccountId, - parachain_id: ParaId, -) -> serde_json::Value { - let authorities = vec![ - ( - get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), - ), - ]; - let accounts: Vec = vec!["Alice", "Bob", "Charlie", "Dave", "Eve"] - .iter() - .map(|s| get_account_id_from_seed::(s)) - .collect(); - - // This is supposed the be the simplest bytecode to revert without returning any data. - // We will pre-deploy it under all of our precompiles to ensure they can be called from - // within contracts. - // (PUSH1 0x00 PUSH1 0x00 REVERT) - let revert_bytecode = vec![0x60, 0x00, 0x60, 0x00, 0xFD]; - - let config = RuntimeGenesisConfig { - system: Default::default(), - sudo: SudoConfig { - key: Some(root_key), - }, - parachain_info: ParachainInfoConfig { - parachain_id, - ..Default::default() - }, - balances: BalancesConfig { balances }, - vesting: VestingConfig { vesting: vec![] }, - session: SessionConfig { - keys: authorities - .iter() - .map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone()))) - .collect::>(), - }, - aura: AuraConfig { - authorities: vec![], - }, - aura_ext: Default::default(), - collator_selection: CollatorSelectionConfig { - desired_candidates: 32, - candidacy_bond: 32_000 * SBY, - invulnerables: authorities.iter().map(|x| x.0.clone()).collect::>(), - }, - evm: EVMConfig { - // We need _some_ code inserted at the precompile address so that - // the evm will actually call the address. - accounts: Precompiles::used_addresses_h160() - .map(|addr| { - ( - addr, - fp_evm::GenesisAccount { - nonce: Default::default(), - balance: Default::default(), - storage: Default::default(), - code: revert_bytecode.clone(), - }, - ) - }) - .collect(), - ..Default::default() - }, - evm_chain_id: EVMChainIdConfig { - chain_id: 0x51, - ..Default::default() - }, - ethereum: Default::default(), - polkadot_xcm: Default::default(), - assets: Default::default(), - parachain_system: Default::default(), - transaction_payment: Default::default(), - dapp_staking: DappStakingConfig { - reward_portion: vec![ - Permill::from_percent(40), - Permill::from_percent(30), - Permill::from_percent(20), - Permill::from_percent(10), - ], - slot_distribution: vec![ - Permill::from_percent(10), - Permill::from_percent(20), - Permill::from_percent(30), - Permill::from_percent(40), - ], - // percentages below are calulated based on a total issuance at the time when dApp staking v3 was launched (147M) - tier_thresholds: vec![ - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(20_000), // 0.0020% - minimum_required_percentage: Perbill::from_parts(17_000), // 0.0017% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(13_000), // 0.0013% - minimum_required_percentage: Perbill::from_parts(10_000), // 0.0010% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(5_400), // 0.00054% - minimum_required_percentage: Perbill::from_parts(3_400), // 0.00034% - }, - TierThreshold::FixedPercentage { - required_percentage: Perbill::from_parts(1_400), // 0.00014% - }, - ], - slots_per_tier: vec![10, 20, 30, 40], - safeguard: Some(false), - ..Default::default() - }, - inflation: InflationConfig { - params: InflationParameters::default(), - ..Default::default() - }, - oracle_membership: OracleMembershipConfig { - members: vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - ] - .try_into() - .expect("Assumption is that at least two members will be allowed."), - ..Default::default() - }, - price_aggregator: PriceAggregatorConfig { - circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] - .try_into() - .expect("Must work since buffer should have at least a single value."), - }, - council_membership: CouncilMembershipConfig { - members: accounts - .clone() - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - technical_committee_membership: TechnicalCommitteeMembershipConfig { - members: accounts[..3] - .to_vec() - .try_into() - .expect("Should support at least 3 members."), - phantom: Default::default(), - }, - community_council_membership: CommunityCouncilMembershipConfig { - members: accounts - .try_into() - .expect("Should support at least 5 members."), - phantom: Default::default(), - }, - council: Default::default(), - technical_committee: Default::default(), - community_council: Default::default(), - democracy: Default::default(), - treasury: Default::default(), - community_treasury: Default::default(), - }; - - serde_json::to_value(&config).expect("Could not build genesis config.") -} - -type AccountPublic = ::Signer; - -/// Helper function to generate an account ID from seed -fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} diff --git a/bin/collator/src/parachain/chain_spec/shiden.rs b/bin/collator/src/parachain/chain_spec/shiden.rs index a0d77b4456..4efc239a2b 100644 --- a/bin/collator/src/parachain/chain_spec/shiden.rs +++ b/bin/collator/src/parachain/chain_spec/shiden.rs @@ -18,44 +18,17 @@ //! Shiden chain specifications. -use cumulus_primitives_core::ParaId; +use super::Extensions; +use astar_primitives::parachain::SHIDEN_ID; use sc_service::ChainType; -use shiden_runtime::{ - wasm_binary_unwrap, AccountId, AuraId, Balance, DappStakingConfig, EVMConfig, InflationConfig, - InflationParameters, OracleMembershipConfig, ParachainInfoConfig, Precompiles, - PriceAggregatorConfig, RuntimeGenesisConfig, Signature, TierThreshold, SDN, -}; -use sp_core::{sr25519, Pair, Public}; - -use astar_primitives::oracle::CurrencyAmount; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - Perbill, Permill, -}; - -use super::{get_from_seed, Extensions}; - -const PARA_ID: u32 = 2007; +use shiden_runtime::wasm_binary_unwrap; /// Specialized `ChainSpec` for Shiden Network. pub type ShidenChainSpec = sc_service::GenericChainSpec; -/// Gen Shiden chain specification for given parachain id. +/// Gen Shiden chain specification. pub fn get_chain_spec() -> ShidenChainSpec { - // Alice as default - let sudo_key = get_account_id_from_seed::("Alice"); - let endowned = vec![ - ( - get_account_id_from_seed::("Alice"), - 1_000_000_000 * SDN, - ), - ( - get_account_id_from_seed::("Bob"), - 1_000_000_000 * SDN, - ), - ]; - let mut properties = serde_json::map::Map::new(); properties.insert("tokenSymbol".into(), "SDN".into()); properties.insert("tokenDecimals".into(), 18.into()); @@ -65,161 +38,13 @@ pub fn get_chain_spec() -> ShidenChainSpec { Extensions { bad_blocks: Default::default(), relay_chain: "tokyo".into(), - para_id: PARA_ID, + para_id: SHIDEN_ID, }, ) .with_name("Shiden Testnet") .with_id("shiden") .with_chain_type(ChainType::Development) .with_properties(properties) - .with_genesis_config(make_genesis( - endowned.clone(), - sudo_key.clone(), - PARA_ID.into(), - )) + .with_genesis_config(shiden_runtime::genesis_config::default_config(SHIDEN_ID)) .build() } - -fn session_keys(aura: AuraId) -> shiden_runtime::SessionKeys { - shiden_runtime::SessionKeys { aura } -} - -/// Helper function to create RuntimeGenesisConfig. -fn make_genesis( - balances: Vec<(AccountId, Balance)>, - root_key: AccountId, - parachain_id: ParaId, -) -> serde_json::Value { - let authorities = vec![ - ( - get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), - ), - ]; - - // This is supposed the be the simplest bytecode to revert without returning any data. - // We will pre-deploy it under all of our precompiles to ensure they can be called from - // within contracts. - // (PUSH1 0x00 PUSH1 0x00 REVERT) - let revert_bytecode = vec![0x60, 0x00, 0x60, 0x00, 0xFD]; - - let config = RuntimeGenesisConfig { - system: Default::default(), - sudo: shiden_runtime::SudoConfig { - key: Some(root_key), - }, - parachain_info: ParachainInfoConfig { - parachain_id, - ..Default::default() - }, - balances: shiden_runtime::BalancesConfig { balances }, - vesting: shiden_runtime::VestingConfig { vesting: vec![] }, - session: shiden_runtime::SessionConfig { - keys: authorities - .iter() - .map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone()))) - .collect::>(), - }, - aura: shiden_runtime::AuraConfig { - authorities: vec![], - }, - aura_ext: Default::default(), - collator_selection: shiden_runtime::CollatorSelectionConfig { - desired_candidates: 32, - candidacy_bond: 32_000 * SDN, - invulnerables: authorities.iter().map(|x| x.0.clone()).collect::>(), - }, - evm: EVMConfig { - // We need _some_ code inserted at the precompile address so that - // the evm will actually call the address. - accounts: Precompiles::used_addresses_h160() - .map(|addr| { - ( - addr, - fp_evm::GenesisAccount { - nonce: Default::default(), - balance: Default::default(), - storage: Default::default(), - code: revert_bytecode.clone(), - }, - ) - }) - .collect(), - ..Default::default() - }, - ethereum: Default::default(), - polkadot_xcm: Default::default(), - assets: Default::default(), - parachain_system: Default::default(), - transaction_payment: Default::default(), - dapp_staking: DappStakingConfig { - reward_portion: vec![ - Permill::from_percent(40), - Permill::from_percent(30), - Permill::from_percent(20), - Permill::from_percent(10), - ], - slot_distribution: vec![ - Permill::from_percent(10), - Permill::from_percent(20), - Permill::from_percent(30), - Permill::from_percent(40), - ], - // percentages below are calulated based on a total issuance at the time when dApp staking v3 was launched (84.3M) - tier_thresholds: vec![ - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(35_700_000), // 3.57% - minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(8_900_000), // 0.89% - minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% - }, - TierThreshold::DynamicPercentage { - percentage: Perbill::from_parts(2_380_000), // 0.238% - minimum_required_percentage: Perbill::from_parts(1_790_000), // 0.179% - }, - TierThreshold::FixedPercentage { - required_percentage: Perbill::from_parts(600_000), // 0.06% - }, - ], - slots_per_tier: vec![10, 20, 30, 40], - safeguard: Some(false), - ..Default::default() - }, - inflation: InflationConfig { - params: InflationParameters::default(), - ..Default::default() - }, - oracle_membership: OracleMembershipConfig { - members: vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - ] - .try_into() - .expect("Assumption is that at least two members will be allowed."), - ..Default::default() - }, - price_aggregator: PriceAggregatorConfig { - circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] - .try_into() - .expect("Must work since buffer should have at least a single value."), - }, - }; - - serde_json::to_value(&config).expect("Could not build genesis config.") -} - -type AccountPublic = ::Signer; - -/// Helper function to generate an account ID from seed -fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} diff --git a/bin/collator/src/parachain/fake_runtime_api.rs b/bin/collator/src/parachain/fake_runtime_api.rs new file mode 100644 index 0000000000..6583330f4d --- /dev/null +++ b/bin/collator/src/parachain/fake_runtime_api.rs @@ -0,0 +1,299 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +#![allow(missing_docs)] + +use astar_primitives::{AccountId, Balance, Block, Nonce}; +use frame_support::weights::Weight; +use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; +use sp_api::impl_runtime_apis; +use sp_consensus_aura::sr25519::AuthorityId as AuraId; +use sp_core::{OpaqueMetadata, H160, H256, U256}; +use sp_inherents::{CheckInherentsResult, InherentData}; +use sp_runtime::{ + traits::Block as BlockT, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, Permill, +}; +use sp_version::RuntimeVersion; + +pub struct Runtime; + +impl_runtime_apis! { + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + unimplemented!() + } + + fn execute_block(_block: Block) { + unimplemented!() + } + + fn initialize_block(_header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { + unimplemented!() + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + unimplemented!() + } + + fn metadata_at_version(_version: u32) -> Option { + unimplemented!() + } + + fn metadata_versions() -> sp_std::vec::Vec { + unimplemented!() + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(_header: &::Header) -> cumulus_primitives_core::CollationInfo { + unimplemented!() + } + } + + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + unimplemented!() + } + + fn authorities() -> Vec { + unimplemented!() + } + } + + impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { + fn can_build_upon(_included_hash: ::Hash, _slot: cumulus_primitives_aura::Slot) -> bool { + unimplemented!() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(_extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + unimplemented!() + } + + fn finalize_block() -> ::Header { + unimplemented!() + } + + fn inherent_extrinsics(_data: InherentData) -> Vec<::Extrinsic> { + unimplemented!() + } + + fn check_inherents(_block: Block, _data: InherentData) -> CheckInherentsResult { + unimplemented!() + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(_account: AccountId) -> Nonce { + unimplemented!() + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(_seed: Option>) -> Vec { + unimplemented!() + } + + fn decode_session_keys(_encoded: Vec) -> Option, sp_core::crypto::KeyTypeId)>> { + unimplemented!() + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi< + Block, + Balance, + > for Runtime { + fn query_info(_uxt: ::Extrinsic, _len: u32) -> RuntimeDispatchInfo { + unimplemented!() + } + fn query_fee_details(_uxt: ::Extrinsic, _len: u32) -> FeeDetails { + unimplemented!() + } + fn query_weight_to_fee(_weight: Weight) -> Balance { + unimplemented!() + } + fn query_length_to_fee(_length: u32) -> Balance { + unimplemented!() + } + } + + impl fp_rpc::EthereumRuntimeRPCApi for Runtime { + fn chain_id() -> u64 { + unimplemented!() + } + + fn account_basic(_address: H160) -> pallet_evm::Account { + unimplemented!() + } + + fn gas_price() -> U256 { + unimplemented!() + } + + fn account_code_at(_address: H160) -> Vec { + unimplemented!() + } + + fn author() -> H160 { + unimplemented!() + } + + fn storage_at(_address: H160, _index: U256) -> H256 { + unimplemented!() + } + + fn call( + _from: H160, + _to: H160, + _data: Vec, + _value: U256, + _gas_limit: U256, + _max_fee_per_gas: Option, + _max_priority_fee_per_gas: Option, + _nonce: Option, + _estimate: bool, + _access_list: Option)>>, + ) -> Result { + unimplemented!() + } + + fn create( + _from: H160, + _data: Vec, + _value: U256, + _gas_limit: U256, + _max_fee_per_gas: Option, + _max_priority_fee_per_gas: Option, + _nonce: Option, + _estimate: bool, + _access_list: Option)>>, + ) -> Result { + unimplemented!() + } + + fn current_transaction_statuses() -> Option> { + unimplemented!() + } + + fn current_block() -> Option { + unimplemented!() + } + + fn current_receipts() -> Option> { + unimplemented!() + } + + fn current_all() -> ( + Option, + Option>, + Option>, + ) { + unimplemented!() + } + + fn extrinsic_filter(_xts: Vec<::Extrinsic>) -> Vec { + unimplemented!() + } + + fn elasticity() -> Option { + unimplemented!() + } + + fn gas_limit_multiplier_support() {} + + fn pending_block(_xts: Vec<::Extrinsic>) -> (Option, Option>) { + unimplemented!() + } + } + + impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { + fn convert_transaction(_transaction: pallet_ethereum::Transaction) -> ::Extrinsic { + unimplemented!() + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction(_source: TransactionSource, _tx: ::Extrinsic, _block_hash: ::Hash) -> TransactionValidity { + unimplemented!() + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(_header: &::Header) { + unimplemented!() + } + } + + impl moonbeam_rpc_primitives_debug::DebugRuntimeApi for Runtime { + fn trace_transaction(_extrinsics: Vec<::Extrinsic>, _traced_transaction: &pallet_ethereum::Transaction, _header: &::Header) -> Result<(), sp_runtime::DispatchError> { + unimplemented!() + } + + fn trace_block(_extrinsics: Vec<::Extrinsic>, _known_transactions: Vec, _header: &::Header) -> Result<(), sp_runtime::DispatchError> { + unimplemented!() + } + + fn trace_call( + _header: &::Header, + _from: H160, + _to: H160, + _data: Vec, + _value: U256, + _gas_limit: U256, + _max_fee_per_gas: Option, + _max_priority_fee_per_gas: Option, + _nonce: Option, + _access_list: Option)>>, + ) -> Result<(), sp_runtime::DispatchError> { + unimplemented!() + } + } + + impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi for Runtime { + fn extrinsic_filter(_xts_ready: Vec<::Extrinsic>, _xts_future: Vec<::Extrinsic>) -> moonbeam_rpc_primitives_txpool::TxPoolResponse { + unimplemented!() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(_extra: bool) -> (Vec, Vec) { + unimplemented!() + } + + fn dispatch_benchmark(_config: frame_benchmarking::BenchmarkConfig) -> Result, sp_runtime::RuntimeString> { + unimplemented!() + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(_checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + unimplemented!() + } + + fn execute_block(_block: Block, _state_root_check: bool, _signature_check: bool, _select: frame_try_runtime::TryStateSelect) -> Weight { + unimplemented!() + } + } +} diff --git a/bin/collator/src/parachain/mod.rs b/bin/collator/src/parachain/mod.rs index b93711ae27..a33508da8d 100644 --- a/bin/collator/src/parachain/mod.rs +++ b/bin/collator/src/parachain/mod.rs @@ -27,10 +27,9 @@ pub mod service; /// Parachain specs. pub mod chain_spec; -pub use service::{ - build_import_queue, build_import_queue_fallback, new_partial, start_astar_node, - start_shibuya_node, start_shiden_node, HostFunctions, -}; +pub mod fake_runtime_api; + +pub use service::{build_import_queue, new_partial, start_node, HostFunctions}; pub(crate) use shell_upgrade::{ AuraConsensusDataProviderFallback, PendingCrateInherentDataProvider, diff --git a/bin/collator/src/parachain/service.rs b/bin/collator/src/parachain/service.rs index 7c60d8c941..a1dbb4b5b2 100644 --- a/bin/collator/src/parachain/service.rs +++ b/bin/collator/src/parachain/service.rs @@ -27,7 +27,6 @@ use cumulus_client_service::{ prepare_node_config, start_relay_chain_tasks, BuildNetworkParams, DARecoveryProfile, StartRelayChainTasksParams, }; -use cumulus_primitives_aura::AuraUnincludedSegmentApi; use cumulus_primitives_core::{ relay_chain::{CollatorPair, ValidationCode}, ParaId, @@ -42,105 +41,64 @@ use futures::StreamExt; use sc_client_api::BlockchainEvents; use sc_consensus::{import_queue::BasicQueue, ImportQueue}; use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY}; -use sc_network::{NetworkBackend, NetworkBlock}; +use sc_network::{config::NetworkBackendType, NetworkBackend, NetworkBlock}; use sc_network_sync::SyncingService; use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; -use sp_api::{ConstructRuntimeApi, ProvideRuntimeApi}; +use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_consensus_aura::{ sr25519::AuthorityId as AuraId, sr25519::AuthorityPair as AuraPair, AuraApi, }; use sp_keystore::KeystorePtr; -use sp_runtime::{ - traits::{BlakeTwo256, Block as BlockT}, - Percent, -}; +use sp_runtime::{traits::Block as BlockT, Percent}; use std::{collections::BTreeMap, sync::Arc, time::Duration}; use substrate_prometheus_endpoint::Registry; use super::shell_upgrade::*; -#[cfg(feature = "evm-tracing")] use crate::{ evm_tracing_types::{EthApi as EthApiCmd, EvmTracingConfig}, rpc::tracing, }; /// Parachain host functions -#[cfg(feature = "evm-tracing")] pub type HostFunctions = ( cumulus_client_service::ParachainHostFunctions, moonbeam_primitives_ext::moonbeam_ext::HostFunctions, ); -/// Parachain host functions -#[cfg(not(feature = "evm-tracing"))] -pub type HostFunctions = (cumulus_client_service::ParachainHostFunctions,); - /// Parachain executor pub type ParachainExecutor = WasmExecutor; +type FullClient = + TFullClient; + /// Starts a `ServiceBuilder` for a full service. /// /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. -pub fn new_partial( +pub fn new_partial( config: &Configuration, - build_import_queue: BIQ, ) -> Result< PartialComponents< - TFullClient, + FullClient, TFullBackend, (), sc_consensus::DefaultImportQueue, - sc_transaction_pool::FullPool>, + sc_transaction_pool::FullPool, ( ParachainBlockImport< Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, + FrontierBlockImport, FullClient>, TFullBackend, >, Option, Option, - Arc>>, + Arc>, ), >, sc_service::Error, -> -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + fp_rpc::EthereumRuntimeRPCApi, - sc_client_api::StateBackendFor, Block>: - sc_client_api::backend::StateBackend, - BIQ: FnOnce( - Arc>, - ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - &Configuration, - Option, - &TaskManager, - ) -> sc_consensus::DefaultImportQueue, -{ +> { let telemetry = config .telemetry_endpoints .clone() @@ -167,7 +125,7 @@ where .build(); let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts_record_import::( + sc_service::new_full_parts_record_import::( config, telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), executor, @@ -251,309 +209,10 @@ async fn build_relay_chain_interface( ) } } -/// Start a node with the given parachain `Configuration` and relay chain `Configuration`. -/// -/// This is the actual implementation that is abstract over the executor and the runtime api. -#[cfg(not(feature = "evm-tracing"))] -#[sc_tracing::logging::prefix_logs_with("Parachain")] -async fn start_node_impl( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - additional_config: AdditionalConfig, - build_import_queue: BIQ, - start_consensus: SC, -) -> sc_service::error::Result<( - TaskManager, - Arc>, -)> -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + substrate_frame_rpc_system::AccountNonceApi - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + fp_rpc::EthereumRuntimeRPCApi - + fp_rpc::ConvertTransactionRuntimeApi - + cumulus_primitives_core::CollectCollationInfo - + AuraApi, - sc_client_api::StateBackendFor, Block>: - sc_client_api::backend::StateBackend, - BIQ: FnOnce( - Arc>, - ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - &Configuration, - Option, - &TaskManager, - ) -> sc_consensus::DefaultImportQueue, - SC: FnOnce( - Arc>, - Arc>, - ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - Option<&Registry>, - Option, - &TaskManager, - Arc, - Arc>>, - Arc>, - KeystorePtr, - ParaId, - CollatorPair, - AdditionalConfig, - ) -> Result<(), sc_service::Error>, - N: NetworkBackend::Hash>, -{ - let parachain_config = prepare_node_config(parachain_config); - - let params = new_partial::(¶chain_config, build_import_queue)?; - let (parachain_block_import, mut telemetry, telemetry_worker_handle, frontier_backend) = - params.other; - let net_config = - sc_network::config::FullNetworkConfiguration::<_, _, N>::new(¶chain_config.network); - - let client = params.client.clone(); - let backend = params.backend.clone(); - - let mut task_manager = params.task_manager; - let (relay_chain_interface, collator_key) = build_relay_chain_interface( - polkadot_config, - ¶chain_config, - telemetry_worker_handle, - &mut task_manager, - collator_options.clone(), - additional_config.hwbench.clone(), - ) - .await - .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?; - - let is_authority = parachain_config.role.is_authority(); - let prometheus_registry = parachain_config.prometheus_registry().cloned(); - let transaction_pool = params.transaction_pool.clone(); - let import_queue_service = params.import_queue.service(); - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = - cumulus_client_service::build_network(BuildNetworkParams { - parachain_config: ¶chain_config, - net_config, - para_id: id, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue: params.import_queue, - relay_chain_interface: relay_chain_interface.clone(), - sybil_resistance_level: cumulus_client_service::CollatorSybilResistance::Resistant, - }) - .await?; - - let filter_pool: FilterPool = Arc::new(std::sync::Mutex::new(BTreeMap::new())); - let fee_history_cache: FeeHistoryCache = Arc::new(std::sync::Mutex::new(BTreeMap::new())); - let storage_override = Arc::new(StorageOverrideHandler::new(client.clone())); - - // Sinks for pubsub notifications. - // Everytime a new subscription is created, a new mpsc channel is added to the sink pool. - // The MappingSyncWorker sends through the channel on block import and the subscription emits a notification to the subscriber on receiving a message through this channel. - // This way we avoid race conditions when using native substrate block import notification stream. - let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks< - fc_mapping_sync::EthereumBlockNotification, - > = Default::default(); - let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks); - - // Frontier offchain DB task. Essential. - // Maps emulated ethereum data to substrate native data. - task_manager.spawn_essential_handle().spawn( - "frontier-mapping-sync-worker", - Some("frontier"), - fc_mapping_sync::kv::MappingSyncWorker::new( - client.import_notification_stream(), - Duration::new(6, 0), - client.clone(), - backend.clone(), - storage_override.clone(), - frontier_backend.clone(), - 3, - 0, - fc_mapping_sync::SyncStrategy::Parachain, - sync_service.clone(), - pubsub_notification_sinks.clone(), - ) - .for_each(|()| futures::future::ready(())), - ); - - // Frontier `EthFilterApi` maintenance. Manages the pool of user-created Filters. - // Each filter is allowed to stay in the pool for 100 blocks. - const FILTER_RETAIN_THRESHOLD: u64 = 100; - task_manager.spawn_essential_handle().spawn( - "frontier-filter-pool", - Some("frontier"), - fc_rpc::EthTask::filter_pool_task( - client.clone(), - filter_pool.clone(), - FILTER_RETAIN_THRESHOLD, - ), - ); - - const FEE_HISTORY_LIMIT: u64 = 2048; - task_manager.spawn_essential_handle().spawn( - "frontier-fee-history", - Some("frontier"), - fc_rpc::EthTask::fee_history_task( - client.clone(), - storage_override.clone(), - fee_history_cache.clone(), - FEE_HISTORY_LIMIT, - ), - ); - - let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new( - task_manager.spawn_handle(), - storage_override.clone(), - 50, - 50, - prometheus_registry.clone(), - )); - - let rpc_extensions_builder = { - let client = client.clone(); - let network = network.clone(); - let transaction_pool = transaction_pool.clone(); - let sync = sync_service.clone(); - let pubsub_notification_sinks = pubsub_notification_sinks.clone(); - - Box::new(move |deny_unsafe, subscription| { - let deps = crate::rpc::FullDeps { - client: client.clone(), - pool: transaction_pool.clone(), - graph: transaction_pool.pool().clone(), - network: network.clone(), - sync: sync.clone(), - is_authority, - deny_unsafe, - frontier_backend: frontier_backend.clone(), - filter_pool: filter_pool.clone(), - fee_history_limit: FEE_HISTORY_LIMIT, - fee_history_cache: fee_history_cache.clone(), - block_data_cache: block_data_cache.clone(), - storage_override: storage_override.clone(), - enable_evm_rpc: additional_config.enable_evm_rpc, - #[cfg(feature = "manual-seal")] - command_sink: None, - }; - - crate::rpc::create_full(deps, subscription, pubsub_notification_sinks.clone()) - .map_err(Into::into) - }) - }; - - // Spawn basic services. - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - rpc_builder: rpc_extensions_builder, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - task_manager: &mut task_manager, - config: parachain_config, - keystore: params.keystore_container.keystore(), - backend: backend.clone(), - network: network.clone(), - system_rpc_tx, - sync_service: sync_service.clone(), - tx_handler_controller, - telemetry: telemetry.as_mut(), - })?; - - if let Some(hwbench) = additional_config.hwbench.clone() { - sc_sysinfo::print_hwbench(&hwbench); - if is_authority { - warn_if_slow_hardware(&hwbench); - } - - if let Some(ref mut telemetry) = telemetry { - let telemetry_handle = telemetry.handle(); - task_manager.spawn_handle().spawn( - "telemetry_hwbench", - None, - sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench), - ); - } - } - - let announce_block = { - let sync_service = sync_service.clone(); - Arc::new(move |hash, data| sync_service.announce_block(hash, data)) - }; - - let relay_chain_slot_duration = Duration::from_secs(6); - - let overseer_handle = relay_chain_interface - .overseer_handle() - .map_err(|e| sc_service::Error::Application(Box::new(e)))?; - - start_relay_chain_tasks(StartRelayChainTasksParams { - client: client.clone(), - announce_block: announce_block.clone(), - task_manager: &mut task_manager, - para_id: id, - relay_chain_interface: relay_chain_interface.clone(), - relay_chain_slot_duration, - import_queue: import_queue_service, - recovery_handle: Box::new(overseer_handle.clone()), - sync_service: sync_service.clone(), - da_recovery_profile: if is_authority { - DARecoveryProfile::Collator - } else { - DARecoveryProfile::FullNode - }, - })?; - - if is_authority { - start_consensus( - client.clone(), - backend, - parachain_block_import, - prometheus_registry.as_ref(), - telemetry.map(|t| t.handle()), - &mut task_manager, - relay_chain_interface, - transaction_pool, - sync_service, - params.keystore_container.keystore(), - id, - collator_key.expect("Command line arguments do not allow this. qed"), - additional_config, - )?; - } - - start_network.start_network(); - - Ok((task_manager, client)) -} #[derive(Clone)] /// To add additional config to start_xyz_node functions pub struct AdditionalConfig { - #[cfg(feature = "evm-tracing")] /// EVM tracing configuration pub evm_tracing_config: EvmTracingConfig, @@ -573,93 +232,33 @@ pub struct AdditionalConfig { /// Start a node with the given parachain `Configuration` and relay chain `Configuration`. /// /// This is the actual implementation that is abstract over the executor and the runtime api. -#[cfg(feature = "evm-tracing")] #[sc_tracing::logging::prefix_logs_with("Parachain")] -async fn start_node_impl( +async fn start_node_impl( parachain_config: Configuration, polkadot_config: Configuration, collator_options: CollatorOptions, - id: ParaId, + para_id: ParaId, additional_config: AdditionalConfig, - build_import_queue: BIQ, - start_consensus: SC, -) -> sc_service::error::Result<( - TaskManager, - Arc>, -)> +) -> sc_service::error::Result<(TaskManager, Arc)> where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + substrate_frame_rpc_system::AccountNonceApi - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + moonbeam_rpc_primitives_debug::DebugRuntimeApi - + moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi - + fp_rpc::EthereumRuntimeRPCApi - + fp_rpc::ConvertTransactionRuntimeApi - + cumulus_primitives_core::CollectCollationInfo - + AuraApi, - sc_client_api::StateBackendFor, Block>: - sc_client_api::backend::StateBackend, - BIQ: FnOnce( - Arc>, - ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - &Configuration, - Option, - &TaskManager, - ) -> sc_consensus::DefaultImportQueue, - SC: FnOnce( - Arc>, - Arc>, - ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - Option<&Registry>, - Option, - &TaskManager, - Arc, - Arc>>, - Arc>, - KeystorePtr, - ParaId, - CollatorPair, - AdditionalConfig, - ) -> Result<(), sc_service::Error>, N: NetworkBackend::Hash>, { let parachain_config = prepare_node_config(parachain_config); - let params = new_partial::(¶chain_config, build_import_queue)?; - let (parachain_block_import, mut telemetry, telemetry_worker_handle, frontier_backend) = - params.other; + let PartialComponents { + client, + backend, + mut task_manager, + keystore_container, + select_chain: _, + import_queue, + transaction_pool, + other: (parachain_block_import, mut telemetry, telemetry_worker_handle, frontier_backend), + } = new_partial(¶chain_config)?; + let net_config = sc_network::config::FullNetworkConfiguration::<_, _, N>::new(¶chain_config.network); - let client = params.client.clone(); - let backend = params.backend.clone(); - - let mut task_manager = params.task_manager; let (relay_chain_interface, collator_key) = build_relay_chain_interface( polkadot_config, ¶chain_config, @@ -673,17 +272,16 @@ where let is_authority = parachain_config.role.is_authority(); let prometheus_registry = parachain_config.prometheus_registry().cloned(); - let transaction_pool = params.transaction_pool.clone(); - let import_queue_service = params.import_queue.service(); + let import_queue_service = import_queue.service(); let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = cumulus_client_service::build_network(BuildNetworkParams { parachain_config: ¶chain_config, net_config, - para_id: id, + para_id, client: client.clone(), transaction_pool: transaction_pool.clone(), spawn_handle: task_manager.spawn_handle(), - import_queue: params.import_queue, + import_queue, relay_chain_interface: relay_chain_interface.clone(), sybil_resistance_level: cumulus_client_service::CollatorSybilResistance::Resistant, }) @@ -827,7 +425,7 @@ where transaction_pool: transaction_pool.clone(), task_manager: &mut task_manager, config: parachain_config, - keystore: params.keystore_container.keystore(), + keystore: keystore_container.keystore(), backend: backend.clone(), network: network.clone(), system_rpc_tx, @@ -857,8 +455,6 @@ where Arc::new(move |hash, data| sync_service.announce_block(hash, data)) }; - let relay_chain_slot_duration = Duration::from_secs(6); - let overseer_handle = relay_chain_interface .overseer_handle() .map_err(|e| sc_service::Error::Application(Box::new(e)))?; @@ -867,9 +463,9 @@ where client: client.clone(), announce_block: announce_block.clone(), task_manager: &mut task_manager, - para_id: id, + para_id, relay_chain_interface: relay_chain_interface.clone(), - relay_chain_slot_duration, + relay_chain_slot_duration: Duration::from_secs(6), import_queue: import_queue_service, recovery_handle: Box::new(overseer_handle.clone()), sync_service: sync_service.clone(), @@ -881,7 +477,7 @@ where })?; if is_authority { - start_consensus( + start_aura_consensus( client.clone(), backend, parachain_block_import, @@ -891,8 +487,8 @@ where relay_chain_interface, transaction_pool, sync_service, - params.keystore_container.keystore(), - id, + keystore_container.keystore(), + para_id, collator_key.expect("Command line arguments do not allow this. qed"), additional_config, )?; @@ -905,63 +501,44 @@ where /// Build aura import queue with fallback to relay-chain verifier. /// Starts with relay-chain verifier until aura becomes available. -pub fn build_import_queue_fallback( - client: Arc>, +pub fn build_import_queue( + client: Arc, block_import: ParachainBlockImport< Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, + FrontierBlockImport, FullClient>, TFullBackend, >, config: &Configuration, telemetry_handle: Option, task_manager: &TaskManager, -) -> sc_consensus::DefaultImportQueue -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + fp_rpc::EthereumRuntimeRPCApi - + AuraApi, - sc_client_api::StateBackendFor, Block>: - sc_client_api::StateBackend, -{ +) -> sc_consensus::DefaultImportQueue { let verifier_client = client.clone(); - let aura_verifier = cumulus_client_consensus_aura::build_verifier::( - cumulus_client_consensus_aura::BuildVerifierParams { - client: verifier_client.clone(), - create_inherent_data_providers: move |parent_hash, _| { - let cidp_client = verifier_client.clone(); - async move { - let slot_duration = cumulus_client_consensus_aura::slot_duration_at( - &*cidp_client, - parent_hash, - )?; - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = + let aura_verifier = Box::new(cumulus_client_consensus_aura::build_verifier::< + AuraPair, + _, + _, + _, + >(cumulus_client_consensus_aura::BuildVerifierParams { + client: verifier_client.clone(), + create_inherent_data_providers: move |parent_hash, _| { + let cidp_client = verifier_client.clone(); + async move { + let slot_duration = + cumulus_client_consensus_aura::slot_duration_at(&*cidp_client, parent_hash)?; + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( *timestamp, slot_duration, ); - Ok((slot, timestamp)) - } - }, - telemetry: telemetry_handle, + Ok((slot, timestamp)) + } }, - ); + telemetry: telemetry_handle, + })); let relay_chain_verifier = Box::new(RelayChainVerifier::new(client.clone(), |_, _| async { Ok(()) @@ -970,7 +547,7 @@ where let verifier = Verifier { client, relay_chain_verifier, - aura_verifier: Box::new(aura_verifier), + aura_verifier, }; let registry = config.prometheus_registry(); @@ -979,263 +556,26 @@ where BasicQueue::new(verifier, Box::new(block_import), None, &spawner, registry) } -/// Build aura only import queue. -pub fn build_import_queue( - client: Arc>, - block_import: ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - config: &Configuration, - telemetry_handle: Option, - task_manager: &TaskManager, -) -> sc_consensus::DefaultImportQueue -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + fp_rpc::EthereumRuntimeRPCApi - + AuraApi, - sc_client_api::StateBackendFor, Block>: - sc_client_api::StateBackend, -{ - let cidp_client = client.clone(); - - cumulus_client_consensus_aura::equivocation_import_queue::fully_verifying_import_queue::< - AuraPair, - _, - _, - _, - _, - >( - client, - block_import, - move |parent_hash, _| { - let cidp_client = cidp_client.clone(); - async move { - let slot_duration = - sc_consensus_aura::standalone::slot_duration_at(&*cidp_client, parent_hash)?; - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *timestamp, - slot_duration, - ); - - Ok((slot, timestamp)) - } - }, - &task_manager.spawn_essential_handle(), - config.prometheus_registry(), - telemetry_handle, - ) -} - /// Start collating with the `shell` runtime while waiting for an upgrade to an Aura compatible runtime. -fn start_aura_consensus_fallback( - client: Arc>, - backend: Arc>, - parachain_block_import: ParachainBlockImport< - Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, - TFullBackend, - >, - prometheus_registry: Option<&Registry>, - telemetry: Option, - task_manager: &TaskManager, - relay_chain_interface: Arc, - transaction_pool: Arc< - sc_transaction_pool::FullPool>, - >, - sync_oracle: Arc>, - keystore: KeystorePtr, - para_id: ParaId, - collator_key: CollatorPair, - additional_config: AdditionalConfig, -) -> Result<(), sc_service::Error> -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + fp_rpc::EthereumRuntimeRPCApi - + AuraApi - + AuraUnincludedSegmentApi - + cumulus_primitives_core::CollectCollationInfo, - sc_client_api::StateBackendFor, Block>: - sc_client_api::StateBackend, -{ - let mut proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( - task_manager.spawn_handle(), - client.clone(), - transaction_pool, - prometheus_registry, - telemetry, - ); - - proposer_factory.set_default_block_size_limit(additional_config.proposer_block_size_limit); - proposer_factory.set_soft_deadline(Percent::from_percent( - additional_config.proposer_soft_deadline_percent, - )); - - let overseer_handle = relay_chain_interface - .overseer_handle() - .map_err(|e| sc_service::Error::Application(Box::new(e)))?; - - let spawner = task_manager.spawn_handle(); - let client_ = client.clone(); - - let collation_future = Box::pin(async move { - use parity_scale_codec::Decode; - use sp_api::ApiExt; - - let client = client_.clone(); - - // Start collating with the `shell` runtime while waiting for an upgrade to an Aura - // compatible runtime. - let mut request_stream = cumulus_client_collator::relay_chain_driven::init( - collator_key.clone(), - para_id.clone(), - overseer_handle.clone(), - ) - .await; - - while let Some(request) = request_stream.next().await { - let pvd = request.persisted_validation_data().clone(); - let last_head_hash = - match ::Header::decode(&mut &pvd.parent_head.0[..]) { - Ok(header) => header.hash(), - Err(e) => { - log::error!("Could not decode the head data: {e}"); - request.complete(None); - continue; - } - }; - - // Check if we have upgraded to an Aura compatible runtime and transition if - // necessary. - if client - .runtime_api() - .has_api::>(last_head_hash) - .unwrap_or_default() - { - // Respond to this request before transitioning to Aura. - request.complete(None); - break; - } - } - - // Move to Aura consensus. - let announce_block = { - let sync_service = sync_oracle.clone(); - Arc::new(move |hash, data| sync_service.announce_block(hash, data)) - }; - - let collator_service = cumulus_client_collator::service::CollatorService::new( - client.clone(), - Arc::new(spawner), - announce_block, - client.clone(), - ); - - aura::run::(AuraParams { - create_inherent_data_providers: move |_, ()| async move { Ok(()) }, - block_import: parachain_block_import.clone(), - para_client: client.clone(), - para_backend: backend, - relay_client: relay_chain_interface.clone(), - code_hash_provider: move |block_hash| { - client - .code_at(block_hash) - .ok() - .map(|c| ValidationCode::from(c).hash()) - }, - sync_oracle: sync_oracle.clone(), - keystore, - collator_key, - para_id, - overseer_handle, - relay_chain_slot_duration: Duration::from_secs(6), - proposer: cumulus_client_consensus_proposer::Proposer::new(proposer_factory), - collator_service, - authoring_duration: Duration::from_millis(1500), - reinitialize: true, - }) - .await - }); - - task_manager - .spawn_essential_handle() - .spawn("aura", None, collation_future); - Ok(()) -} - -fn start_aura_consensus( - client: Arc>, +fn start_aura_consensus( + client: Arc, backend: Arc>, parachain_block_import: ParachainBlockImport< Block, - FrontierBlockImport< - Block, - Arc>, - TFullClient, - >, + FrontierBlockImport, FullClient>, TFullBackend, >, prometheus_registry: Option<&Registry>, telemetry: Option, task_manager: &TaskManager, relay_chain_interface: Arc, - transaction_pool: Arc< - sc_transaction_pool::FullPool>, - >, + transaction_pool: Arc>, sync_oracle: Arc>, keystore: KeystorePtr, para_id: ParaId, collator_key: CollatorPair, additional_config: AdditionalConfig, -) -> Result<(), sc_service::Error> -where - RuntimeApi: ConstructRuntimeApi> - + Send - + Sync - + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + fp_rpc::EthereumRuntimeRPCApi - + AuraApi - + AuraUnincludedSegmentApi - + cumulus_primitives_core::CollectCollationInfo, - sc_client_api::StateBackendFor, Block>: - sc_client_api::StateBackend, -{ +) -> Result<(), sc_service::Error> { let mut proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), client.clone(), @@ -1265,17 +605,20 @@ where client.clone(), ); - let fut = aura::run::(AuraParams { + let params = AuraParams { create_inherent_data_providers: move |_, ()| async move { Ok(()) }, block_import: parachain_block_import.clone(), para_client: client.clone(), para_backend: backend, relay_client: relay_chain_interface.clone(), - code_hash_provider: move |block_hash| { - client - .code_at(block_hash) - .ok() - .map(|c| ValidationCode::from(c).hash()) + code_hash_provider: { + let client = client.clone(); + move |block_hash| { + client + .code_at(block_hash) + .ok() + .map(|c| ValidationCode::from(c).hash()) + } }, sync_oracle: sync_oracle.clone(), keystore, @@ -1285,84 +628,44 @@ where relay_chain_slot_duration: Duration::from_secs(6), proposer: cumulus_client_consensus_proposer::Proposer::new(proposer_factory), collator_service, - authoring_duration: Duration::from_millis(1500), + authoring_duration: Duration::from_millis(2000), reinitialize: false, - }); + }; + + let fut = async move { + wait_for_aura(client).await; + aura::run::(params).await + }; task_manager .spawn_essential_handle() .spawn("aura", None, fut); - Ok(()) } -/// Start a parachain node for Astar. -pub async fn start_astar_node( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - additional_config: AdditionalConfig, -) -> sc_service::error::Result<( - TaskManager, - Arc>, -)> { - start_node_impl::>( - parachain_config, - polkadot_config, - collator_options, - id, - additional_config.clone(), - build_import_queue, - start_aura_consensus, - ) - .await -} - -/// Start a parachain node for Shiden. -pub async fn start_shiden_node( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - additional_config: AdditionalConfig, -) -> sc_service::error::Result<( - TaskManager, - Arc>, -)> { - start_node_impl::>( - parachain_config, - polkadot_config, - collator_options, - id, - additional_config.clone(), - build_import_queue_fallback, - start_aura_consensus_fallback, - ) - .await -} +/// Wait for the Aura runtime API to appear on chain. +/// This is useful for chains that started out without Aura. Components that +/// are depending on Aura functionality will wait until Aura appears in the runtime. +async fn wait_for_aura(client: Arc) { + let finalized_hash = client.chain_info().finalized_hash; + if client + .runtime_api() + .has_api::>(finalized_hash) + .unwrap_or_default() + { + return; + }; -/// Start a parachain node for Shibuya. -pub async fn start_shibuya_node( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - additional_config: AdditionalConfig, -) -> sc_service::error::Result<( - TaskManager, - Arc>, -)> { - start_node_impl::>( - parachain_config, - polkadot_config, - collator_options, - id, - additional_config.clone(), - build_import_queue, - start_aura_consensus, - ) - .await + let mut stream = client.finality_notification_stream(); + while let Some(notification) = stream.next().await { + if client + .runtime_api() + .has_api::>(notification.hash) + .unwrap_or_default() + { + return; + } + } } /// Checks that the hardware meets the requirements and print a warning otherwise. @@ -1377,3 +680,35 @@ fn warn_if_slow_hardware(hwbench: &sc_sysinfo::HwBench) { ); } } + +/// Start a parachain node. +pub async fn start_node( + parachain_config: Configuration, + polkadot_config: Configuration, + collator_options: CollatorOptions, + para_id: ParaId, + additional_config: AdditionalConfig, +) -> sc_service::error::Result<(TaskManager, Arc)> { + match parachain_config.network.network_backend { + NetworkBackendType::Libp2p => { + start_node_impl::>( + parachain_config, + polkadot_config, + collator_options, + para_id, + additional_config, + ) + .await + } + NetworkBackendType::Litep2p => { + start_node_impl::( + parachain_config, + polkadot_config, + collator_options, + para_id, + additional_config, + ) + .await + } + } +} diff --git a/bin/collator/src/rpc.rs b/bin/collator/src/rpc.rs index dde4630bb8..f87e589de6 100644 --- a/bin/collator/src/rpc.rs +++ b/bin/collator/src/rpc.rs @@ -46,20 +46,15 @@ use sp_runtime::traits::BlakeTwo256; use std::sync::Arc; use substrate_frame_rpc_system::{System, SystemApiServer}; -#[cfg(feature = "evm-tracing")] use moonbeam_rpc_debug::{Debug, DebugServer}; -#[cfg(feature = "evm-tracing")] use moonbeam_rpc_trace::{Trace, TraceServer}; // TODO: get rid of this completely now that it's part of frontier? -#[cfg(feature = "evm-tracing")] use moonbeam_rpc_txpool::{TxPool as MoonbeamTxPool, TxPoolServer}; use astar_primitives::*; -#[cfg(feature = "evm-tracing")] pub mod tracing; -#[cfg(feature = "evm-tracing")] #[derive(Clone)] pub struct EvmTracingConfig { pub tracing_requesters: tracing::RpcRequesters, @@ -142,7 +137,6 @@ pub struct FullDeps { } /// Instantiate all RPC extensions and Tracing RPC. -#[cfg(feature = "evm-tracing")] pub fn create_full( deps: FullDeps, subscription_task_executor: SubscriptionTaskExecutor, @@ -207,45 +201,6 @@ where Ok(io) } -/// Instantiate all RPC extensions. -#[cfg(not(feature = "evm-tracing"))] -pub fn create_full( - deps: FullDeps, - subscription_task_executor: SubscriptionTaskExecutor, - pubsub_notification_sinks: Arc< - fc_mapping_sync::EthereumBlockNotificationSinks< - fc_mapping_sync::EthereumBlockNotification, - >, - >, -) -> Result, Box> -where - C: ProvideRuntimeApi - + HeaderBackend - + UsageProvider - + CallApiAt - + AuxStore - + StorageProvider - + HeaderMetadata - + BlockchainEvents - + Send - + Sync - + 'static, - C: sc_client_api::BlockBackend, - C::Api: substrate_frame_rpc_system::AccountNonceApi - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + fp_rpc::ConvertTransactionRuntimeApi - + fp_rpc::EthereumRuntimeRPCApi - + BlockBuilder - + AuraApi, - P: TransactionPool + Sync + Send + 'static, - BE: Backend + 'static, - BE::State: StateBackend, - BE::Blockchain: BlockchainBackend, - A: ChainApi + 'static, -{ - create_full_rpc(deps, subscription_task_executor, pubsub_notification_sinks) -} - fn create_full_rpc( deps: FullDeps, subscription_task_executor: SubscriptionTaskExecutor, diff --git a/pallets/dapp-staking-v3/Cargo.toml b/pallets/dapp-staking/Cargo.toml similarity index 97% rename from pallets/dapp-staking-v3/Cargo.toml rename to pallets/dapp-staking/Cargo.toml index 68c6ff468a..61d9ff225d 100644 --- a/pallets/dapp-staking-v3/Cargo.toml +++ b/pallets/dapp-staking/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pallet-dapp-staking-v3" +name = "pallet-dapp-staking" version = "0.1.0" description = "Pallet for dApp staking v3 protocol" authors.workspace = true diff --git a/pallets/dapp-staking-v3/README.md b/pallets/dapp-staking/README.md similarity index 100% rename from pallets/dapp-staking-v3/README.md rename to pallets/dapp-staking/README.md diff --git a/pallets/dapp-staking-v3/rpc/runtime-api/Cargo.toml b/pallets/dapp-staking/rpc/runtime-api/Cargo.toml similarity index 92% rename from pallets/dapp-staking-v3/rpc/runtime-api/Cargo.toml rename to pallets/dapp-staking/rpc/runtime-api/Cargo.toml index 37b20002ab..637ce49e50 100644 --- a/pallets/dapp-staking-v3/rpc/runtime-api/Cargo.toml +++ b/pallets/dapp-staking/rpc/runtime-api/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "dapp-staking-v3-runtime-api" +name = "dapp-staking-runtime-api" version = "0.1.0" description = "dApp Staking v3 runtime API" authors.workspace = true diff --git a/pallets/dapp-staking-v3/rpc/runtime-api/src/lib.rs b/pallets/dapp-staking/rpc/runtime-api/src/lib.rs similarity index 100% rename from pallets/dapp-staking-v3/rpc/runtime-api/src/lib.rs rename to pallets/dapp-staking/rpc/runtime-api/src/lib.rs diff --git a/pallets/dapp-staking-v3/src/benchmarking/mod.rs b/pallets/dapp-staking/src/benchmarking/mod.rs similarity index 100% rename from pallets/dapp-staking-v3/src/benchmarking/mod.rs rename to pallets/dapp-staking/src/benchmarking/mod.rs diff --git a/pallets/dapp-staking-v3/src/benchmarking/utils.rs b/pallets/dapp-staking/src/benchmarking/utils.rs similarity index 100% rename from pallets/dapp-staking-v3/src/benchmarking/utils.rs rename to pallets/dapp-staking/src/benchmarking/utils.rs diff --git a/pallets/dapp-staking-v3/src/lib.rs b/pallets/dapp-staking/src/lib.rs similarity index 99% rename from pallets/dapp-staking-v3/src/lib.rs rename to pallets/dapp-staking/src/lib.rs index 63f061602b..a8dc283af8 100644 --- a/pallets/dapp-staking-v3/src/lib.rs +++ b/pallets/dapp-staking/src/lib.rs @@ -509,6 +509,7 @@ pub mod pallet { pub tier_thresholds: Vec, pub slots_per_tier: Vec, pub safeguard: Option, + #[serde(skip)] pub _config: PhantomData, } diff --git a/pallets/dapp-staking-v3/src/migration.rs b/pallets/dapp-staking/src/migration.rs similarity index 93% rename from pallets/dapp-staking-v3/src/migration.rs rename to pallets/dapp-staking/src/migration.rs index b2e81c3a38..35e27ccfba 100644 --- a/pallets/dapp-staking-v3/src/migration.rs +++ b/pallets/dapp-staking/src/migration.rs @@ -161,7 +161,7 @@ mod v8 { let old_config = v7::TierConfig::::get().ok_or_else(|| { TryRuntimeError::Other( - "dapp-staking-v3::migration::v8: No old configuration found for TierConfig", + "dapp-staking::migration::v8: No old configuration found for TierConfig", ) })?; Ok((old_config.number_of_slots, old_config.tier_thresholds).encode()) @@ -169,9 +169,13 @@ mod v8 { #[cfg(feature = "try-runtime")] fn post_upgrade(data: Vec) -> Result<(), TryRuntimeError> { - let (old_number_of_slots, old_tier_thresholds): (u16, BoundedVec) = - Decode::decode(&mut &data[..]).map_err(|_| { - TryRuntimeError::Other("dapp-staking-v3::migration::v8: Failed to decode old v7 version of tier config") + let (old_number_of_slots, old_tier_thresholds): ( + u16, + BoundedVec, + ) = Decode::decode(&mut &data[..]).map_err(|_| { + TryRuntimeError::Other( + "dapp-staking::migration::v8: Failed to decode old v7 version of tier config", + ) })?; // 0. Prerequisites @@ -180,7 +184,7 @@ mod v8 { ensure!( Pallet::::on_chain_storage_version() >= 8, - "dapp-staking-v3::migration::v8: Wrong storage version." + "dapp-staking::migration::v8: Wrong storage version." ); // 1. Ensure the number of slots is preserved @@ -190,7 +194,7 @@ mod v8 { assert!( within_tolerance.contains(&actual_number_of_slots), - "dapp-staking-v3::migration::v8: New TiersConfiguration format not set correctly, number of slots has diverged. Old: {}. Actual: {}.", + "dapp-staking::migration::v8: New TiersConfiguration format not set correctly, number of slots has diverged. Old: {}. Actual: {}.", old_number_of_slots, actual_number_of_slots ); @@ -203,7 +207,7 @@ mod v8 { BoundedVec::try_from(TierThresholds::get().to_vec()); ensure!( expected_tier_thresholds.is_ok(), - "dapp-staking-v3::migration::v8: Failed to convert expected tier thresholds." + "dapp-staking::migration::v8: Failed to convert expected tier thresholds." ); let actual_tier_thresholds = actual_tier_params.clone().tier_thresholds; assert_eq!(expected_tier_thresholds.unwrap(), actual_tier_thresholds); @@ -222,7 +226,7 @@ mod v8 { ensure!( old_threshold_amounts.is_ok(), - "dapp-staking-v3::migration::v8: Failed to convert old v7 version tier thresholds to balance amounts." + "dapp-staking::migration::v8: Failed to convert old v7 version tier thresholds to balance amounts." ); let old_threshold_amounts = old_threshold_amounts.unwrap(); let expected_new_threshold_amounts = actual_config @@ -242,7 +246,7 @@ mod v8 { assert!( (lower_bound..=upper_bound).contains(&actual_amount), - "dapp-staking-v3::migration::v8: New tier threshold amounts diverged to much from old values, consider adjusting static tier parameters. Old: {}. Actual: {}.", + "dapp-staking::migration::v8: New tier threshold amounts diverged to much from old values, consider adjusting static tier parameters. Old: {}. Actual: {}.", old_amount, actual_amount ); @@ -379,7 +383,7 @@ mod v7 { fn post_upgrade(_data: Vec) -> Result<(), TryRuntimeError> { ensure!( Pallet::::on_chain_storage_version() >= 7, - "dapp-staking-v3::migration::v7: wrong storage version" + "dapp-staking::migration::v7: wrong storage version" ); Ok(()) } diff --git a/pallets/dapp-staking-v3/src/test/mock.rs b/pallets/dapp-staking/src/test/mock.rs similarity index 100% rename from pallets/dapp-staking-v3/src/test/mock.rs rename to pallets/dapp-staking/src/test/mock.rs diff --git a/pallets/dapp-staking-v3/src/test/mod.rs b/pallets/dapp-staking/src/test/mod.rs similarity index 100% rename from pallets/dapp-staking-v3/src/test/mod.rs rename to pallets/dapp-staking/src/test/mod.rs diff --git a/pallets/dapp-staking-v3/src/test/testing_utils.rs b/pallets/dapp-staking/src/test/testing_utils.rs similarity index 100% rename from pallets/dapp-staking-v3/src/test/testing_utils.rs rename to pallets/dapp-staking/src/test/testing_utils.rs diff --git a/pallets/dapp-staking-v3/src/test/tests.rs b/pallets/dapp-staking/src/test/tests.rs similarity index 100% rename from pallets/dapp-staking-v3/src/test/tests.rs rename to pallets/dapp-staking/src/test/tests.rs diff --git a/pallets/dapp-staking-v3/src/test/tests_types.rs b/pallets/dapp-staking/src/test/tests_types.rs similarity index 100% rename from pallets/dapp-staking-v3/src/test/tests_types.rs rename to pallets/dapp-staking/src/test/tests_types.rs diff --git a/pallets/dapp-staking-v3/src/types.rs b/pallets/dapp-staking/src/types.rs similarity index 100% rename from pallets/dapp-staking-v3/src/types.rs rename to pallets/dapp-staking/src/types.rs diff --git a/pallets/dapp-staking-v3/src/weights.rs b/pallets/dapp-staking/src/weights.rs similarity index 99% rename from pallets/dapp-staking-v3/src/weights.rs rename to pallets/dapp-staking/src/weights.rs index fabcfbeb5b..f7c46df534 100644 --- a/pallets/dapp-staking-v3/src/weights.rs +++ b/pallets/dapp-staking/src/weights.rs @@ -17,7 +17,7 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -//! Autogenerated weights for pallet_dapp_staking_v3 +//! Autogenerated weights for pallet_dapp_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2024-02-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` @@ -32,12 +32,12 @@ // --chain=shiden-dev // --steps=50 // --repeat=20 -// --pallet=pallet_dapp_staking_v3 +// --pallet=pallet_dapp_staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./benchmark-results/shiden-dev/dapp_staking_v3_weights.rs +// --output=./benchmark-results/shiden-dev/dapp_staking_weights.rs // --template=./scripts/templates/weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -47,7 +47,7 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -/// Weight functions needed for pallet_dapp_staking_v3. +/// Weight functions needed for pallet_dapp_staking. pub trait WeightInfo { fn maintenance_mode() -> Weight; fn register() -> Weight; @@ -75,7 +75,7 @@ pub trait WeightInfo { fn on_idle_cleanup() -> Weight; } -/// Weights for pallet_dapp_staking_v3 using the Substrate node and recommended hardware. +/// Weights for pallet_dapp_staking using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn maintenance_mode() -> Weight { diff --git a/pallets/inflation/src/lib.rs b/pallets/inflation/src/lib.rs index 72a745c879..25fa4bd505 100644 --- a/pallets/inflation/src/lib.rs +++ b/pallets/inflation/src/lib.rs @@ -201,6 +201,7 @@ pub mod pallet { #[derive(DefaultNoBound)] pub struct GenesisConfig { pub params: InflationParameters, + #[serde(skip)] pub _config: sp_std::marker::PhantomData, } diff --git a/precompiles/dapp-staking-v3/Cargo.toml b/precompiles/dapp-staking/Cargo.toml similarity index 90% rename from precompiles/dapp-staking-v3/Cargo.toml rename to precompiles/dapp-staking/Cargo.toml index 00a9828666..c72023cb10 100644 --- a/precompiles/dapp-staking-v3/Cargo.toml +++ b/precompiles/dapp-staking/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "pallet-evm-precompile-dapp-staking-v3" +name = "pallet-evm-precompile-dapp-staking" version = "0.1.0" license = "GPL-3.0-or-later" description = "dApp Staking EVM precompiles" @@ -23,7 +23,7 @@ sp-std = { workspace = true } # Astar astar-primitives = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } precompile-utils = { workspace = true, default-features = false } # Frontier @@ -53,7 +53,7 @@ std = [ "fp-evm/std", "frame-support/std", "frame-system/std", - "pallet-dapp-staking-v3/std", + "pallet-dapp-staking/std", "pallet-evm/std", "precompile-utils/std", "pallet-balances/std", @@ -62,7 +62,7 @@ std = [ "num_enum/std", ] runtime-benchmarks = [ - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", "astar-primitives/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", diff --git a/precompiles/dapp-staking-v3/DappsStakingV2.sol b/precompiles/dapp-staking/DappsStakingV2.sol similarity index 100% rename from precompiles/dapp-staking-v3/DappsStakingV2.sol rename to precompiles/dapp-staking/DappsStakingV2.sol diff --git a/precompiles/dapp-staking-v3/DappsStakingV3.sol b/precompiles/dapp-staking/DappsStakingV3.sol similarity index 99% rename from precompiles/dapp-staking-v3/DappsStakingV3.sol rename to precompiles/dapp-staking/DappsStakingV3.sol index 40c55af6c4..941d00de76 100644 --- a/precompiles/dapp-staking-v3/DappsStakingV3.sol +++ b/precompiles/dapp-staking/DappsStakingV3.sol @@ -5,7 +5,7 @@ pragma solidity >=0.8.0; /// Predeployed at the address 0x0000000000000000000000000000000000005001 /// For better understanding check the source code: /// repo: https://github.com/AstarNetwork/Astar -/// code: pallets/dapp-staking-v3 +/// code: pallets/dapp-staking interface DAppStaking { // Types diff --git a/precompiles/dapp-staking-v3/README.md b/precompiles/dapp-staking/README.md similarity index 100% rename from precompiles/dapp-staking-v3/README.md rename to precompiles/dapp-staking/README.md diff --git a/precompiles/dapp-staking-v3/src/lib.rs b/precompiles/dapp-staking/src/lib.rs similarity index 90% rename from precompiles/dapp-staking-v3/src/lib.rs rename to precompiles/dapp-staking/src/lib.rs index 0b102c7fd7..c1750f2237 100644 --- a/precompiles/dapp-staking-v3/src/lib.rs +++ b/precompiles/dapp-staking/src/lib.rs @@ -45,7 +45,7 @@ use sp_std::{marker::PhantomData, prelude::*}; extern crate alloc; use astar_primitives::{dapp_staking::SmartContractHandle, AccountId, Balance, BlockNumber}; -use pallet_dapp_staking_v3::{ +use pallet_dapp_staking::{ AccountLedgerFor, ActiveProtocolState, ContractStake, ContractStakeAmount, CurrentEraInfo, DAppInfoFor, EraInfo, EraRewardSpanFor, EraRewards, IntegratedDApps, Ledger, Pallet as DAppStaking, ProtocolState, SingularStakingInfo, StakerInfo, Subperiod, @@ -116,12 +116,12 @@ pub struct DappStakingV3Precompile(PhantomData); impl DappStakingV3Precompile where R: pallet_evm::Config - + pallet_dapp_staking_v3::Config + + pallet_dapp_staking::Config + frame_system::Config, BlockNumberFor: IsType, ::RuntimeOrigin: From>, R::RuntimeCall: Dispatchable + GetDispatchInfo, - R::RuntimeCall: From>, + R::RuntimeCall: From>, { // v1 functions @@ -144,7 +144,7 @@ where #[precompile::view] fn read_unbonding_period(_: &mut impl PrecompileHandle) -> EvmResult { // constant, no DB read - Ok(::UnlockingPeriod::get().into()) + Ok(::UnlockingPeriod::get().into()) } /// Read the total assigned reward pool for the given era. @@ -237,7 +237,7 @@ where handle.record_db_read::( 24 + AccountLedgerFor::::max_encoded_len() + ProtocolState::max_encoded_len() - + ::SmartContract::max_encoded_len(), + + ::SmartContract::max_encoded_len(), )?; let staker = Self::parse_input_address(staker.into())?; @@ -267,12 +267,12 @@ where // Blake2_128Concat(16 + SmartContract::max_encoded_len) + SingularStakingInfo::max_encoded_len handle.record_db_read::( 24 + ProtocolState::max_encoded_len() - + ::SmartContract::max_encoded_len() + + ::SmartContract::max_encoded_len() + SingularStakingInfo::max_encoded_len(), )?; let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); // parse the staker account let staker = Self::parse_input_address(staker.into())?; @@ -307,13 +307,13 @@ where // Twox64Concat(8) + EraIndex(4) + ContractStakeAmount::max_encoded_len handle.record_db_read::( 36 + ProtocolState::max_encoded_len() - + ::SmartContract::max_encoded_len() + + ::SmartContract::max_encoded_len() + DAppInfoFor::::max_encoded_len() + ContractStakeAmount::max_encoded_len(), )?; let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); let current_period_number = ActiveProtocolState::::get().period_number(); let dapp_info = match IntegratedDApps::::get(&smart_contract) { @@ -356,11 +356,11 @@ where handle.record_db_read::( 24 + AccountLedgerFor::::max_encoded_len() + ProtocolState::max_encoded_len() - + ::SmartContract::max_encoded_len(), + + ::SmartContract::max_encoded_len(), )?; let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); log::trace!(target: "ds-precompile", "bond_and_stake {:?}, {:?}", smart_contract, amount); // Read total locked & staked amounts @@ -375,12 +375,12 @@ where if stakeable_amount < amount { let delta = amount.saturating_sub(stakeable_amount); - let lock_call = pallet_dapp_staking_v3::Call::::lock { amount: delta }; + let lock_call = pallet_dapp_staking::Call::::lock { amount: delta }; RuntimeHelper::::try_dispatch(handle, Some(origin.clone()).into(), lock_call)?; } // Now, with best effort, we can try & stake the given `value`. - let stake_call = pallet_dapp_staking_v3::Call::::stake { + let stake_call = pallet_dapp_staking::Call::::stake { smart_contract, amount, }; @@ -403,12 +403,12 @@ where // Blake2_128Concat(16 + SmartContract::max_encoded_len) + SingularStakingInfo::max_encoded_len handle.record_db_read::( 24 + ProtocolState::max_encoded_len() - + ::SmartContract::max_encoded_len() + + ::SmartContract::max_encoded_len() + SingularStakingInfo::max_encoded_len(), )?; let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); let origin = R::AddressMapping::into_account_id(handle.context().caller); log::trace!(target: "ds-precompile", "unbond_and_unstake {:?}, {:?}", smart_contract, amount); @@ -418,7 +418,7 @@ where // If there is, we need to unstake it before calling `unlock` if staker_info.period_number() == protocol_state.period_number() { - let unstake_call = pallet_dapp_staking_v3::Call::::unstake { + let unstake_call = pallet_dapp_staking::Call::::unstake { smart_contract, amount, }; @@ -426,7 +426,7 @@ where } // Now we can try and `unlock` the given `amount` - let unlock_call = pallet_dapp_staking_v3::Call::::unlock { amount }; + let unlock_call = pallet_dapp_staking::Call::::unlock { amount }; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), unlock_call)?; Ok(true) @@ -436,7 +436,7 @@ where #[precompile::public("withdraw_unbonded()")] fn withdraw_unbonded(handle: &mut impl PrecompileHandle) -> EvmResult { let origin = R::AddressMapping::into_account_id(handle.context().caller); - let call = pallet_dapp_staking_v3::Call::::claim_unlocked {}; + let call = pallet_dapp_staking::Call::::claim_unlocked {}; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), call)?; @@ -451,7 +451,7 @@ where era: u128, ) -> EvmResult { let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); // parse era let era = era @@ -462,7 +462,7 @@ where log::trace!(target: "ds-precompile", "claim_dapp {:?}, era {:?}", smart_contract, era); let origin = R::AddressMapping::into_account_id(handle.context().caller); - let call = pallet_dapp_staking_v3::Call::::claim_dapp_reward { + let call = pallet_dapp_staking::Call::::claim_dapp_reward { smart_contract, era, }; @@ -481,7 +481,7 @@ where _contract_h160: Address, ) -> EvmResult { let origin = R::AddressMapping::into_account_id(handle.context().caller); - let call = pallet_dapp_staking_v3::Call::::claim_staker_rewards {}; + let call = pallet_dapp_staking::Call::::claim_staker_rewards {}; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), call)?; @@ -503,11 +503,11 @@ where contract_h160: Address, ) -> EvmResult { let smart_contract = - ::SmartContract::evm(contract_h160.into()); + ::SmartContract::evm(contract_h160.into()); log::trace!(target: "ds-precompile", "withdraw_from_unregistered {:?}", smart_contract); let origin = R::AddressMapping::into_account_id(handle.context().caller); - let call = pallet_dapp_staking_v3::Call::::unstake_from_unregistered { smart_contract }; + let call = pallet_dapp_staking::Call::::unstake_from_unregistered { smart_contract }; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), call)?; @@ -528,14 +528,14 @@ where // Storage item: StakerInfo: // Blake2_128Concat(16 + SmartContract::max_encoded_len) + SingularStakingInfo::max_encoded_len handle.record_db_read::( - 16 + ::SmartContract::max_encoded_len() + 16 + ::SmartContract::max_encoded_len() + SingularStakingInfo::max_encoded_len(), )?; let origin_smart_contract = - ::SmartContract::evm(origin_contract_h160.into()); + ::SmartContract::evm(origin_contract_h160.into()); let target_smart_contract = - ::SmartContract::evm(target_contract_h160.into()); + ::SmartContract::evm(target_contract_h160.into()); log::trace!(target: "ds-precompile", "nomination_transfer {:?} {:?} {:?}", origin_smart_contract, amount, target_smart_contract); // Find out how much staker has staked on the origin contract @@ -546,7 +546,7 @@ where // if value comes from the past period. let staked_amount = staker_info.total_staked_amount(); let minimum_allowed_stake_amount = - ::MinimumStakeAmount::get(); + ::MinimumStakeAmount::get(); // In case the remaining staked amount on the origin contract is less than the minimum allowed stake amount, // everything will be unstaked. To keep in line with legacy `nomination_transfer` behavior, we should transfer @@ -562,14 +562,14 @@ where }; // First call unstake from the origin smart contract - let unstake_call = pallet_dapp_staking_v3::Call::::unstake { + let unstake_call = pallet_dapp_staking::Call::::unstake { smart_contract: origin_smart_contract, amount, }; RuntimeHelper::::try_dispatch(handle, Some(origin.clone()).into(), unstake_call)?; // Then call stake on the target smart contract - let stake_call = pallet_dapp_staking_v3::Call::::stake { + let stake_call = pallet_dapp_staking::Call::::stake { smart_contract: target_smart_contract, amount: stake_amount, }; @@ -611,7 +611,7 @@ where fn lock(handle: &mut impl PrecompileHandle, amount: u128) -> EvmResult { // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let lock_call = pallet_dapp_staking_v3::Call::::lock { amount }; + let lock_call = pallet_dapp_staking::Call::::lock { amount }; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), lock_call)?; Ok(true) @@ -622,7 +622,7 @@ where fn unlock(handle: &mut impl PrecompileHandle, amount: u128) -> EvmResult { // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let unlock_call = pallet_dapp_staking_v3::Call::::unlock { amount }; + let unlock_call = pallet_dapp_staking::Call::::unlock { amount }; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), unlock_call)?; Ok(true) @@ -633,7 +633,7 @@ where fn claim_unlocked(handle: &mut impl PrecompileHandle) -> EvmResult { // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let claim_unlocked_call = pallet_dapp_staking_v3::Call::::claim_unlocked {}; + let claim_unlocked_call = pallet_dapp_staking::Call::::claim_unlocked {}; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), claim_unlocked_call)?; Ok(true) @@ -650,7 +650,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let stake_call = pallet_dapp_staking_v3::Call::::stake { + let stake_call = pallet_dapp_staking::Call::::stake { smart_contract, amount, }; @@ -670,7 +670,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let unstake_call = pallet_dapp_staking_v3::Call::::unstake { + let unstake_call = pallet_dapp_staking::Call::::unstake { smart_contract, amount, }; @@ -684,7 +684,7 @@ where fn claim_staker_rewards(handle: &mut impl PrecompileHandle) -> EvmResult { // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let claim_staker_rewards_call = pallet_dapp_staking_v3::Call::::claim_staker_rewards {}; + let claim_staker_rewards_call = pallet_dapp_staking::Call::::claim_staker_rewards {}; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), claim_staker_rewards_call)?; Ok(true) @@ -701,7 +701,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); let claim_bonus_reward_call = - pallet_dapp_staking_v3::Call::::claim_bonus_reward { smart_contract }; + pallet_dapp_staking::Call::::claim_bonus_reward { smart_contract }; RuntimeHelper::::try_dispatch(handle, Some(origin).into(), claim_bonus_reward_call)?; Ok(true) @@ -722,7 +722,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); - let claim_dapp_reward_call = pallet_dapp_staking_v3::Call::::claim_dapp_reward { + let claim_dapp_reward_call = pallet_dapp_staking::Call::::claim_dapp_reward { smart_contract, era, }; @@ -742,7 +742,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); let unstake_from_unregistered_call = - pallet_dapp_staking_v3::Call::::unstake_from_unregistered { smart_contract }; + pallet_dapp_staking::Call::::unstake_from_unregistered { smart_contract }; RuntimeHelper::::try_dispatch( handle, Some(origin).into(), @@ -758,7 +758,7 @@ where // Prepare call & dispatch it let origin = R::AddressMapping::into_account_id(handle.context().caller); let cleanup_expired_entries_call = - pallet_dapp_staking_v3::Call::::cleanup_expired_entries {}; + pallet_dapp_staking::Call::::cleanup_expired_entries {}; RuntimeHelper::::try_dispatch( handle, Some(origin).into(), @@ -773,7 +773,7 @@ where /// Helper method to decode smart contract struct for v2 calls pub(crate) fn decode_smart_contract( smart_contract: SmartContractV2, - ) -> EvmResult<::SmartContract> { + ) -> EvmResult<::SmartContract> { let smart_contract = match smart_contract.contract_type { SmartContractTypes::Evm => { ensure!( @@ -781,7 +781,7 @@ where revert("Invalid address length for Astar EVM smart contract.") ); let h160_address = H160::from_slice(smart_contract.address.as_bytes()); - ::SmartContract::evm(h160_address) + ::SmartContract::evm(h160_address) } SmartContractTypes::Wasm => { ensure!( @@ -791,7 +791,7 @@ where let mut staker_bytes = [0_u8; 32]; staker_bytes[..].clone_from_slice(&smart_contract.address.as_bytes()); - ::SmartContract::wasm(staker_bytes.into()) + ::SmartContract::wasm(staker_bytes.into()) } }; diff --git a/precompiles/dapp-staking-v3/src/test/mock.rs b/precompiles/dapp-staking/src/test/mock.rs similarity index 95% rename from precompiles/dapp-staking-v3/src/test/mock.rs rename to precompiles/dapp-staking/src/test/mock.rs index a59b456124..bc0ad4e1dc 100644 --- a/precompiles/dapp-staking-v3/src/test/mock.rs +++ b/precompiles/dapp-staking/src/test/mock.rs @@ -48,7 +48,7 @@ use astar_primitives::{ oracle::PriceProvider, AccountId, Balance, BlockNumber, }; -use pallet_dapp_staking_v3::TierThreshold; +use pallet_dapp_staking::TierThreshold; type Block = frame_system::mocking::MockBlockU32; @@ -240,7 +240,7 @@ impl CycleConfiguration for DummyCycleConfiguration { #[cfg(feature = "runtime-benchmarks")] pub struct BenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper +impl pallet_dapp_staking::BenchmarkHelper for BenchmarkHelper { fn get_smart_contract(id: u32) -> MockSmartContract { @@ -254,7 +254,7 @@ parameter_types! { pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100); } -impl pallet_dapp_staking_v3::Config for Test { +impl pallet_dapp_staking::Config for Test { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -279,7 +279,7 @@ impl pallet_dapp_staking_v3::Config for Test { type MinimumStakeAmount = ConstU128<3>; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; - type WeightInfo = pallet_dapp_staking_v3::weights::SubstrateWeight; + type WeightInfo = pallet_dapp_staking::weights::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = BenchmarkHelper; } @@ -290,7 +290,7 @@ construct_runtime!( Balances: pallet_balances, Evm: pallet_evm, Timestamp: pallet_timestamp, - DappStaking: pallet_dapp_staking_v3, + DappStaking: pallet_dapp_staking, } ); @@ -301,8 +301,8 @@ impl ExternalityBuilder { .build_storage() .unwrap(); - pallet_dapp_staking_v3::GenesisConfig::::assimilate_storage( - &pallet_dapp_staking_v3::GenesisConfig:: { + pallet_dapp_staking::GenesisConfig::::assimilate_storage( + &pallet_dapp_staking::GenesisConfig:: { reward_portion: vec![ Permill::from_percent(40), Permill::from_percent(30), @@ -343,7 +343,7 @@ impl ExternalityBuilder { let alice_native = AddressMapper::into_account_id(ALICE); assert_ok!( - ::Currency::write_balance( + ::Currency::write_balance( &alice_native, 1000_000_000_000_000_000_000 as Balance, ) @@ -364,7 +364,7 @@ pub const ALICE: H160 = H160::repeat_byte(0xAA); /// Used to register a smart contract, and stake some funds on it. pub fn register_and_stake( account: H160, - smart_contract: ::SmartContract, + smart_contract: ::SmartContract, amount: Balance, ) { let alice_native = AddressMapper::into_account_id(account); @@ -466,12 +466,12 @@ pub(crate) fn advance_to_next_period() { } // Return all dApp staking events from the event buffer. -pub fn dapp_staking_events() -> Vec> { +pub fn dapp_staking_events() -> Vec> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| { - ::RuntimeEvent::from(e) + ::RuntimeEvent::from(e) .try_into() .ok() }) diff --git a/precompiles/dapp-staking-v3/src/test/mod.rs b/precompiles/dapp-staking/src/test/mod.rs similarity index 100% rename from precompiles/dapp-staking-v3/src/test/mod.rs rename to precompiles/dapp-staking/src/test/mod.rs diff --git a/precompiles/dapp-staking-v3/src/test/tests_v2.rs b/precompiles/dapp-staking/src/test/tests_v2.rs similarity index 91% rename from precompiles/dapp-staking-v3/src/test/tests_v2.rs rename to precompiles/dapp-staking/src/test/tests_v2.rs index f53ecf2968..df47e7b3f4 100644 --- a/precompiles/dapp-staking-v3/src/test/tests_v2.rs +++ b/precompiles/dapp-staking/src/test/tests_v2.rs @@ -27,7 +27,7 @@ use sp_runtime::traits::Zero; use assert_matches::assert_matches; use astar_primitives::dapp_staking::EraNumber; -use pallet_dapp_staking_v3::{ActiveProtocolState, EraRewards}; +use pallet_dapp_staking::{ActiveProtocolState, EraRewards}; #[test] fn read_current_era_is_ok() { @@ -62,7 +62,7 @@ fn read_unbonding_period_is_ok() { initialize(); let unlocking_period_in_eras: EraNumber = - ::UnlockingPeriod::get(); + ::UnlockingPeriod::get(); precompiles() .prepare_test( @@ -122,7 +122,7 @@ fn read_era_staked_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); let anchor_era = ActiveProtocolState::::get().era; @@ -200,7 +200,7 @@ fn read_staked_amount_is_ok() { // 2. Stake some amount and check again let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); for staker in &dynamic_addresses { @@ -241,7 +241,7 @@ fn read_staked_amount_on_contract_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let dynamic_addresses = into_dynamic_addresses(staker_h160); // 1. Sanity checks - must be zero before anything is staked. @@ -316,7 +316,7 @@ fn read_contract_stake_is_ok() { // 2. Stake some amount and check again let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -391,7 +391,7 @@ fn bond_and_stake_with_two_calls_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); assert_ok!(DappStaking::register( RawOrigin::Root.into(), AddressMapper::into_account_id(staker_h160), @@ -425,14 +425,14 @@ fn bond_and_stake_with_two_calls_is_ok() { let additional_lock_amount = stake_amount - pre_lock_amount; assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Locked { + pallet_dapp_staking::Event::Locked { amount, .. } if amount == additional_lock_amount ); assert_matches!( events[1].clone(), - pallet_dapp_staking_v3::Event::Stake { + pallet_dapp_staking::Event::Stake { smart_contract, amount, .. @@ -450,7 +450,7 @@ fn bond_and_stake_with_single_call_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); assert_ok!(DappStaking::register( RawOrigin::Root.into(), AddressMapper::into_account_id(staker_h160), @@ -482,7 +482,7 @@ fn bond_and_stake_with_single_call_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Stake { + pallet_dapp_staking::Event::Stake { smart_contract, amount, .. @@ -500,7 +500,7 @@ fn unbond_and_unstake_with_two_calls_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -522,7 +522,7 @@ fn unbond_and_unstake_with_two_calls_is_ok() { assert_eq!(events.len(), 2); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unstake { + pallet_dapp_staking::Event::Unstake { smart_contract, amount, .. @@ -530,7 +530,7 @@ fn unbond_and_unstake_with_two_calls_is_ok() { ); assert_matches!( events[1].clone(), - pallet_dapp_staking_v3::Event::Unlocking { amount, .. } if amount == amount + pallet_dapp_staking::Event::Unlocking { amount, .. } if amount == amount ); }); } @@ -544,7 +544,7 @@ fn unbond_and_unstake_with_single_calls_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -573,7 +573,7 @@ fn unbond_and_unstake_with_single_calls_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unlocking { amount, .. } if amount == amount + pallet_dapp_staking::Event::Unlocking { amount, .. } if amount == amount ); }); } @@ -588,7 +588,7 @@ fn withdraw_unbonded_is_ok() { let staker_native = AddressMapper::into_account_id(staker_h160); let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -623,7 +623,7 @@ fn withdraw_unbonded_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::ClaimedUnlocked { + pallet_dapp_staking::Event::ClaimedUnlocked { amount, .. } if amount == unlock_amount @@ -640,7 +640,7 @@ fn claim_dapp_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -666,7 +666,7 @@ fn claim_dapp_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::DAppReward { + pallet_dapp_staking::Event::DAppReward { era, smart_contract, .. @@ -684,7 +684,7 @@ fn claim_staker_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -712,7 +712,7 @@ fn claim_staker_is_ok() { for era in 2..target_era { assert_matches!( events[era as usize - 2].clone(), - pallet_dapp_staking_v3::Event::Reward { era, .. } if era == era + pallet_dapp_staking::Event::Reward { era, .. } if era == era ); } }); @@ -727,7 +727,7 @@ fn withdraw_from_unregistered_is_ok() { let staker_h160 = ALICE; let smart_contract_address = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_address); + ::SmartContract::evm(smart_contract_address); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract.clone(), amount); @@ -754,7 +754,7 @@ fn withdraw_from_unregistered_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::UnstakeFromUnregistered { + pallet_dapp_staking::Event::UnstakeFromUnregistered { smart_contract, amount, .. @@ -773,14 +773,14 @@ fn nomination_transfer_is_ok() { let staker_native = AddressMapper::into_account_id(staker_h160); let smart_contract_address_1 = H160::repeat_byte(0xFA); let smart_contract_1 = - ::SmartContract::evm(smart_contract_address_1); + ::SmartContract::evm(smart_contract_address_1); let amount = 1_000_000_000_000; register_and_stake(staker_h160, smart_contract_1.clone(), amount); // Register the second dApp. let smart_contract_address_2 = H160::repeat_byte(0xBF); let smart_contract_2 = - ::SmartContract::evm(smart_contract_address_2); + ::SmartContract::evm(smart_contract_address_2); assert_ok!(DappStaking::register( RawOrigin::Root.into(), staker_native.clone(), @@ -790,7 +790,7 @@ fn nomination_transfer_is_ok() { // 1st scenario - transfer enough amount from the first to second dApp to cover the stake, // but not enough for full unstake. let minimum_stake_amount: Balance = - ::MinimumStakeAmount::get(); + ::MinimumStakeAmount::get(); System::reset_events(); precompiles() @@ -811,7 +811,7 @@ fn nomination_transfer_is_ok() { assert_eq!(events.len(), 2); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unstake { + pallet_dapp_staking::Event::Unstake { smart_contract, amount, .. @@ -819,7 +819,7 @@ fn nomination_transfer_is_ok() { ); assert_matches!( events[1].clone(), - pallet_dapp_staking_v3::Event::Stake { + pallet_dapp_staking::Event::Stake { smart_contract, amount, .. @@ -850,7 +850,7 @@ fn nomination_transfer_is_ok() { assert_eq!(events.len(), 2); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unstake { + pallet_dapp_staking::Event::Unstake { smart_contract, amount, .. @@ -858,7 +858,7 @@ fn nomination_transfer_is_ok() { ); assert_matches!( events[1].clone(), - pallet_dapp_staking_v3::Event::Stake { + pallet_dapp_staking::Event::Stake { smart_contract, amount, .. diff --git a/precompiles/dapp-staking-v3/src/test/tests_v3.rs b/precompiles/dapp-staking/src/test/tests_v3.rs similarity index 89% rename from precompiles/dapp-staking-v3/src/test/tests_v3.rs rename to precompiles/dapp-staking/src/test/tests_v3.rs index af5c6a6587..522f1fb764 100644 --- a/precompiles/dapp-staking-v3/src/test/tests_v3.rs +++ b/precompiles/dapp-staking/src/test/tests_v3.rs @@ -29,7 +29,7 @@ use astar_primitives::{ dapp_staking::{CycleConfiguration, EraNumber}, BlockNumber, }; -use pallet_dapp_staking_v3::ActiveProtocolState; +use pallet_dapp_staking::ActiveProtocolState; #[test] fn protocol_state_is_ok() { @@ -65,9 +65,9 @@ fn unlocking_period_is_ok() { initialize(); let unlocking_period_in_eras: EraNumber = - ::UnlockingPeriod::get(); + ::UnlockingPeriod::get(); let era_length: BlockNumber = - ::CycleConfiguration::blocks_per_era(); + ::CycleConfiguration::blocks_per_era(); let expected_outcome = era_length * unlocking_period_in_eras; @@ -99,7 +99,7 @@ fn lock_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Locked { + pallet_dapp_staking::Event::Locked { amount, .. } if amount == amount @@ -136,7 +136,7 @@ fn unlock_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unlocking { + pallet_dapp_staking::Event::Unlocking { amount, .. } if amount == unlock_amount @@ -180,7 +180,7 @@ fn claim_unlocked_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::ClaimedUnlocked { + pallet_dapp_staking::Event::ClaimedUnlocked { amount, .. } if amount == amount @@ -197,7 +197,7 @@ fn stake_is_ok() { let staker_h160 = ALICE; let smart_contract_h160 = H160::repeat_byte(0xFA); let smart_contract = - ::SmartContract::evm(smart_contract_h160); + ::SmartContract::evm(smart_contract_h160); assert_ok!(DappStaking::register( RawOrigin::Root.into(), AddressMapper::into_account_id(staker_h160), @@ -234,7 +234,7 @@ fn stake_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Stake { + pallet_dapp_staking::Event::Stake { smart_contract, amount, .. @@ -251,7 +251,7 @@ fn unstake_is_ok() { // Register a dApp for staking let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); assert_ok!(DappStaking::register( @@ -295,7 +295,7 @@ fn unstake_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::Unstake { + pallet_dapp_staking::Event::Unstake { smart_contract, amount, .. @@ -312,7 +312,7 @@ fn claim_staker_rewards_is_ok() { // Register a dApp and stake on it let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); let amount = 1234; @@ -340,7 +340,7 @@ fn claim_staker_rewards_is_ok() { for era in 2..target_era { assert_matches!( events[era as usize - 2].clone(), - pallet_dapp_staking_v3::Event::Reward { era, .. } if era == era + pallet_dapp_staking::Event::Reward { era, .. } if era == era ); } }); @@ -354,7 +354,7 @@ fn claim_bonus_reward_is_ok() { // Register a dApp and stake on it, loyally let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); let amount = 1234; @@ -385,7 +385,7 @@ fn claim_bonus_reward_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::BonusReward { smart_contract, .. } if smart_contract == smart_contract + pallet_dapp_staking::Event::BonusReward { smart_contract, .. } if smart_contract == smart_contract ); }); } @@ -398,7 +398,7 @@ fn claim_dapp_reward_is_ok() { // Register a dApp and stake on it let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); let amount = 1234; @@ -431,7 +431,7 @@ fn claim_dapp_reward_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::DAppReward { era, smart_contract, .. } if era == claim_era && smart_contract == smart_contract + pallet_dapp_staking::Event::DAppReward { era, smart_contract, .. } if era == claim_era && smart_contract == smart_contract ); }); } @@ -444,7 +444,7 @@ fn unstake_from_unregistered_is_ok() { // Register a dApp and stake on it let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); let amount = 1234; @@ -478,7 +478,7 @@ fn unstake_from_unregistered_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::UnstakeFromUnregistered { smart_contract, amount, .. } if smart_contract == smart_contract && amount == amount + pallet_dapp_staking::Event::UnstakeFromUnregistered { smart_contract, amount, .. } if smart_contract == smart_contract && amount == amount ); }); } @@ -499,7 +499,7 @@ fn cleanup_expired_entries_is_ok() { // Register a dApp and stake on it let staker_h160 = ALICE; let smart_contract_address = [0xAF; 32]; - let smart_contract = ::SmartContract::wasm( + let smart_contract = ::SmartContract::wasm( smart_contract_address.into(), ); let amount = 1234; @@ -523,7 +523,7 @@ fn cleanup_expired_entries_is_ok() { assert_eq!(events.len(), 1); assert_matches!( events[0].clone(), - pallet_dapp_staking_v3::Event::ExpiredEntriesRemoved { count, .. } if count == 1 + pallet_dapp_staking::Event::ExpiredEntriesRemoved { count, .. } if count == 1 ); }); } diff --git a/precompiles/dapp-staking-v3/src/test/types.rs b/precompiles/dapp-staking/src/test/types.rs similarity index 94% rename from precompiles/dapp-staking-v3/src/test/types.rs rename to precompiles/dapp-staking/src/test/types.rs index c691ef7a6c..7ad523c1f7 100644 --- a/precompiles/dapp-staking-v3/src/test/types.rs +++ b/precompiles/dapp-staking/src/test/types.rs @@ -57,7 +57,9 @@ fn decode_smart_contract_is_ok() { }; assert_eq!( - Ok(::SmartContract::evm(address)), + Ok(::SmartContract::evm( + address + )), DappStakingV3Precompile::::decode_smart_contract(smart_contract_v2) ); } @@ -71,7 +73,9 @@ fn decode_smart_contract_is_ok() { }; assert_eq!( - Ok(::SmartContract::wasm(address.into())), + Ok(::SmartContract::wasm( + address.into() + )), DappStakingV3Precompile::::decode_smart_contract(smart_contract_v2) ); } diff --git a/primitives/src/genesis.rs b/primitives/src/genesis.rs new file mode 100644 index 0000000000..a4b25a3ae8 --- /dev/null +++ b/primitives/src/genesis.rs @@ -0,0 +1,75 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +use scale_info::prelude::format; +use sp_core::{Pair, Public}; +use sp_runtime::traits::{IdentifyAccount, Verify}; + +use super::{AccountId, Signature}; + +type AccountPublic = ::Signer; + +/// Helper function to generate a crypto pair from seed +pub fn get_from_seed(seed: &str) -> ::Public { + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() +} + +/// Helper function to generate an account ID from seed +pub fn get_account_id_from_seed(seed: &str) -> AccountId +where + AccountPublic: From<::Public>, +{ + AccountPublic::from(get_from_seed::(seed)).into_account() +} + +/// Helper struct for genesis configuration. +#[derive(Clone, PartialEq, Eq)] +pub struct GenesisAccount { + /// Account ID + pub account_id: AccountId, + /// Public key + pub pub_key: ::Public, +} + +impl GenesisAccount +where + AccountPublic: From<::Public>, +{ + /// Create a new genesis account from a seed. + pub fn from_seed(seed: &str) -> Self { + let pub_key = get_from_seed::(seed); + let account_id = AccountPublic::from(pub_key.clone()).into_account(); + + Self { + account_id, + pub_key, + } + } + + /// Return the `account Id` (address) of the genesis account. + pub fn account_id(&self) -> AccountId { + self.account_id.clone() + } + + /// Return the `public key` of the genesis account. + pub fn pub_key(&self) -> ::Public { + self.pub_key.clone() + } +} diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index c8ce3d4608..e67d8059b2 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -44,6 +44,12 @@ pub mod oracle; /// Governance primitives. pub mod governance; +/// Genesis generation helpers & primitives. +pub mod genesis; + +/// Parachain related constants. +pub mod parachain; + /// Benchmark primitives #[cfg(feature = "runtime-benchmarks")] pub mod benchmarks; diff --git a/primitives/src/parachain.rs b/primitives/src/parachain.rs new file mode 100644 index 0000000000..04dc95676b --- /dev/null +++ b/primitives/src/parachain.rs @@ -0,0 +1,24 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +/// Shibuya parachain Id used in production. +pub const SHIBUYA_ID: u32 = 1000; +/// Astar parachain Id used in production. +pub const ASTAR_ID: u32 = 2006; +/// Shiden parachain Id used in production. +pub const SHIDEN_ID: u32 = 2007; diff --git a/runtime/astar/Cargo.toml b/runtime/astar/Cargo.toml index ae2a36cd8c..c8961aa07c 100644 --- a/runtime/astar/Cargo.toml +++ b/runtime/astar/Cargo.toml @@ -14,9 +14,11 @@ log = { workspace = true, optional = true } num_enum = { workspace = true } parity-scale-codec = { workspace = true } scale-info = { workspace = true } +serde_json = { workspace = true } smallvec = { workspace = true } # primitives +fp-evm = { workspace = true } fp-rpc = { workspace = true } fp-self-contained = { workspace = true } sp-api = { workspace = true } @@ -108,9 +110,9 @@ frame-try-runtime = { workspace = true, optional = true } astar-primitives = { workspace = true } astar-xcm-benchmarks = { workspace = true, optional = true } pallet-collator-selection = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-evm-precompile-assets-erc20 = { workspace = true } -pallet-evm-precompile-dapp-staking-v3 = { workspace = true } +pallet-evm-precompile-dapp-staking = { workspace = true } pallet-evm-precompile-dispatch-lockdrop = { workspace = true } pallet-evm-precompile-sr25519 = { workspace = true } pallet-evm-precompile-substrate-ecdsa = { workspace = true } @@ -120,7 +122,7 @@ pallet-price-aggregator = { workspace = true } pallet-xc-asset-config = { workspace = true } pallet-xcm = { workspace = true } -dapp-staking-v3-runtime-api = { workspace = true } +dapp-staking-runtime-api = { workspace = true } # Moonbeam tracing moonbeam-evm-tracer = { workspace = true, optional = true } @@ -138,8 +140,10 @@ substrate-wasm-builder = { workspace = true, optional = true } default = ["std"] std = [ "parity-scale-codec/std", + "serde_json/std", "sp-genesis-builder/std", "fp-rpc/std", + "fp-evm/std", "fp-self-contained/std", "sp-std/std", "sp-api/std", @@ -167,11 +171,11 @@ std = [ "pallet-aura/std", "pallet-balances/std", "pallet-proxy/std", - "pallet-dapp-staking-v3/std", + "pallet-dapp-staking/std", "xcm-fee-payment-runtime-api/std", - "dapp-staking-v3-runtime-api/std", + "dapp-staking-runtime-api/std", "pallet-inflation/std", - "pallet-evm-precompile-dapp-staking-v3/std", + "pallet-evm-precompile-dapp-staking/std", "pallet-evm-precompile-sr25519/std", "pallet-evm-precompile-assets-erc20/std", "pallet-evm-precompile-substrate-ecdsa/std", @@ -246,7 +250,7 @@ runtime-benchmarks = [ "pallet-proxy/runtime-benchmarks", 'pallet-timestamp/runtime-benchmarks', "pallet-ethereum/runtime-benchmarks", - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", "pallet-price-aggregator/runtime-benchmarks", "pallet-inflation/runtime-benchmarks", "pallet-membership/runtime-benchmarks", @@ -269,7 +273,7 @@ runtime-benchmarks = [ "pallet-contracts/runtime-benchmarks", "pallet-evm/runtime-benchmarks", "pallet-evm-precompile-assets-erc20/runtime-benchmarks", - "pallet-evm-precompile-dapp-staking-v3/runtime-benchmarks", + "pallet-evm-precompile-dapp-staking/runtime-benchmarks", "pallet-evm-precompile-xcm/runtime-benchmarks", "pallet-identity/runtime-benchmarks", "pallet-multisig/runtime-benchmarks", @@ -295,7 +299,7 @@ try-runtime = [ "pallet-aura/try-runtime", "pallet-balances/try-runtime", "pallet-proxy/try-runtime", - "pallet-dapp-staking-v3/try-runtime", + "pallet-dapp-staking/try-runtime", "pallet-inflation/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", diff --git a/runtime/astar/src/genesis_config.rs b/runtime/astar/src/genesis_config.rs new file mode 100644 index 0000000000..5e45a694e2 --- /dev/null +++ b/runtime/astar/src/genesis_config.rs @@ -0,0 +1,161 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +use crate::*; +use astar_primitives::{evm::EVM_REVERT_CODE, genesis::GenesisAccount, parachain::ASTAR_ID}; + +/// Provides the JSON representation of predefined genesis config for given `id`. +pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { + let genesis = match id.try_into() { + Ok("development") => default_config(ASTAR_ID), + _ => return None, + }; + Some( + serde_json::to_string(&genesis) + .expect("serialization to json is expected to work. qed.") + .into_bytes(), + ) +} + +/// Get the default genesis config for the Astar runtime. +pub fn default_config(para_id: u32) -> serde_json::Value { + let alice = GenesisAccount::::from_seed("Alice"); + let bob = GenesisAccount::::from_seed("Bob"); + + let balances: Vec<(AccountId, Balance)> = vec![ + (alice.account_id(), 1_000_000_000_000 * ASTR), + (bob.account_id(), 1_000_000_000_000 * ASTR), + ( + TreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * ASTR, + ), + ]; + + let authorities = vec![&alice, &bob]; + + let config = RuntimeGenesisConfig { + system: Default::default(), + sudo: SudoConfig { + key: Some(alice.account_id()), + }, + parachain_info: ParachainInfoConfig { + parachain_id: para_id.into(), + ..Default::default() + }, + balances: BalancesConfig { balances }, + vesting: VestingConfig { vesting: vec![] }, + session: SessionConfig { + keys: authorities + .iter() + .map(|x| { + ( + x.account_id(), + x.account_id(), + SessionKeys { + aura: x.pub_key().into(), + }, + ) + }) + .collect::>(), + }, + aura: AuraConfig { + authorities: vec![], + }, + aura_ext: Default::default(), + collator_selection: CollatorSelectionConfig { + desired_candidates: 32, + candidacy_bond: 3_200_000 * ASTR, + invulnerables: authorities + .iter() + .map(|x| x.account_id()) + .collect::>(), + }, + evm: EVMConfig { + // We need _some_ code inserted at the precompile address so that + // the evm will actually call the address. + accounts: Precompiles::used_addresses_h160() + .map(|addr| { + ( + addr, + fp_evm::GenesisAccount { + nonce: Default::default(), + balance: Default::default(), + storage: Default::default(), + code: EVM_REVERT_CODE.into(), + }, + ) + }) + .collect(), + ..Default::default() + }, + ethereum: Default::default(), + polkadot_xcm: Default::default(), + assets: Default::default(), + parachain_system: Default::default(), + transaction_payment: Default::default(), + dapp_staking: DappStakingConfig { + reward_portion: vec![ + Permill::from_percent(40), + Permill::from_percent(30), + Permill::from_percent(20), + Permill::from_percent(10), + ], + slot_distribution: vec![ + Permill::from_percent(10), + Permill::from_percent(20), + Permill::from_percent(30), + Permill::from_percent(40), + ], + // percentages below are calculated based on a total issuance at the time when dApp staking v3 was launched (84.3M) + tier_thresholds: vec![ + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(35_700_000), // 3.57% + minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(8_900_000), // 0.89% + minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(2_380_000), // 0.238% + minimum_required_percentage: Perbill::from_parts(1_790_000), // 0.179% + }, + TierThreshold::FixedPercentage { + required_percentage: Perbill::from_parts(600_000), // 0.06% + }, + ], + slots_per_tier: vec![10, 20, 30, 40], + safeguard: Some(false), + ..Default::default() + }, + inflation: Default::default(), + oracle_membership: OracleMembershipConfig { + members: vec![alice.account_id(), bob.account_id()] + .try_into() + .expect("Assumption is that at least two members will be allowed."), + ..Default::default() + }, + price_aggregator: PriceAggregatorConfig { + circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] + .try_into() + .expect("Must work since buffer should have at least a single value."), + }, + }; + + serde_json::to_value(&config).expect("Could not build genesis config.") +} diff --git a/runtime/astar/src/lib.rs b/runtime/astar/src/lib.rs index 248f93e636..400f120046 100644 --- a/runtime/astar/src/lib.rs +++ b/runtime/astar/src/lib.rs @@ -26,8 +26,7 @@ use cumulus_primitives_core::AggregateMessageOrigin; use frame_support::{ construct_runtime, dispatch::DispatchClass, - genesis_builder_helper::{build_state, get_preset}, - parameter_types, + genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit}, AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, Contains, FindAuthor, Get, Imbalance, @@ -56,7 +55,7 @@ use pallet_transaction_payment::{ use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::BlockHashCount; use sp_api::impl_runtime_apis; -use sp_core::{OpaqueMetadata, H160, H256, U256}; +use sp_core::{sr25519, OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -80,13 +79,13 @@ use astar_primitives::{ PeriodNumber, RankedTier, SmartContract, StandardTierSlots, }, evm::EvmRevertCodeHandler, - oracle::{CurrencyId, DummyCombineData, Price}, + oracle::{CurrencyAmount, CurrencyId, DummyCombineData, Price}, xcm::AssetLocationIdConverter, Address, AssetId, BlockNumber, Hash, Header, Nonce, UnfreezeChainOnFailedMigration, }; pub use astar_primitives::{governance::OracleMembershipInst, AccountId, Balance, Signature}; -pub use pallet_dapp_staking_v3::TierThreshold; +pub use pallet_dapp_staking::TierThreshold; pub use pallet_inflation::InflationParameters; pub use crate::precompiles::WhitelistedCalls; @@ -103,6 +102,7 @@ pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::BuildStorage; mod chain_extensions; +pub mod genesis_config; mod precompiles; mod weights; mod xcm_config; @@ -362,7 +362,7 @@ parameter_types! { #[cfg(feature = "runtime-benchmarks")] pub struct DAppStakingBenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper, AccountId> +impl pallet_dapp_staking::BenchmarkHelper, AccountId> for DAppStakingBenchmarkHelper, AccountId> { fn get_smart_contract(id: u32) -> SmartContract { @@ -387,7 +387,7 @@ impl DappStakingAccountCheck for AccountCheck { } } -impl pallet_dapp_staking_v3::Config for Runtime { +impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -412,7 +412,7 @@ impl pallet_dapp_staking_v3::Config for Runtime { type MinimumStakeAmount = MinimumStakingAmount; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; - type WeightInfo = weights::pallet_dapp_staking_v3::SubstrateWeight; + type WeightInfo = weights::pallet_dapp_staking::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = DAppStakingBenchmarkHelper, AccountId>; } @@ -1056,7 +1056,7 @@ impl InstanceFilter for ProxyType { matches!( c, RuntimeCall::DappStaking( - pallet_dapp_staking_v3::Call::claim_staker_rewards { .. } + pallet_dapp_staking::Call::claim_staker_rewards { .. } ) ) } @@ -1229,7 +1229,7 @@ construct_runtime!( // logic is executed. // TODO: Address this later. It would be best if Inflation was first pallet. Inflation: pallet_inflation = 33, - DappStaking: pallet_dapp_staking_v3 = 34, + DappStaking: pallet_dapp_staking = 34, Assets: pallet_assets = 36, PriceAggregator: pallet_price_aggregator = 37, Oracle: orml_oracle = 38, @@ -1331,7 +1331,7 @@ pub type Migrations = (Unreleased, Permanent); /// Unreleased migrations. Add new ones here: pub type Unreleased = ( // dApp-staking dyn tier threshold migrations - pallet_dapp_staking_v3::migration::versioned_migrations::V7ToV8< + pallet_dapp_staking::migration::versioned_migrations::V7ToV8< Runtime, TierThresholds, ThresholdVariationPercentage, @@ -1421,7 +1421,7 @@ mod benches { [pallet_assets, pallet_assets::Pallet::] [pallet_balances, Balances] [pallet_timestamp, Timestamp] - [pallet_dapp_staking_v3, DappStaking] + [pallet_dapp_staking, DappStaking] [pallet_inflation, Inflation] [pallet_migrations, MultiBlockMigrations] [pallet_xc_asset_config, XcAssetConfig] @@ -1897,7 +1897,7 @@ impl_runtime_apis! { } } - impl dapp_staking_v3_runtime_api::DappStakingApi for Runtime { + impl dapp_staking_runtime_api::DappStakingApi for Runtime { fn periods_per_cycle() -> PeriodNumber { InflationCycleConfig::periods_per_cycle() } @@ -1980,15 +1980,17 @@ impl_runtime_apis! { impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) + genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) + genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) } fn preset_names() -> Vec { - vec![] + vec![ + sp_genesis_builder::PresetId::from("development"), + ] } } diff --git a/runtime/astar/src/precompiles.rs b/runtime/astar/src/precompiles.rs index 28b6feea82..c2d85d0010 100644 --- a/runtime/astar/src/precompiles.rs +++ b/runtime/astar/src/precompiles.rs @@ -24,7 +24,7 @@ use frame_support::{parameter_types, traits::Contains}; use pallet_evm_precompile_assets_erc20::Erc20AssetsPrecompileSet; use pallet_evm_precompile_blake2::Blake2F; use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_dapp_staking_v3::DappStakingV3Precompile; +use pallet_evm_precompile_dapp_staking::DappStakingV3Precompile; use pallet_evm_precompile_dispatch::Dispatch; use pallet_evm_precompile_dispatch_lockdrop::DispatchLockdrop; use pallet_evm_precompile_ed25519::Ed25519Verify; @@ -78,12 +78,8 @@ impl Contains for WhitelistedLockdropCalls { | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => calls .iter() .all(|call| WhitelistedLockdropCalls::contains(call)), - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::unbond_and_unstake { - .. - }) => true, - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::withdraw_unbonded { - .. - }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::unbond_and_unstake { .. }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::withdraw_unbonded { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_all { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => true, diff --git a/runtime/astar/src/weights/mod.rs b/runtime/astar/src/weights/mod.rs index 0b665ae16e..476c43da5b 100644 --- a/runtime/astar/src/weights/mod.rs +++ b/runtime/astar/src/weights/mod.rs @@ -18,7 +18,7 @@ pub mod orml_oracle; pub mod pallet_assets; -pub mod pallet_dapp_staking_v3; +pub mod pallet_dapp_staking; pub mod pallet_inflation; pub mod pallet_xcm; pub mod xcm; diff --git a/runtime/astar/src/weights/pallet_dapp_staking_v3.rs b/runtime/astar/src/weights/pallet_dapp_staking.rs similarity index 98% rename from runtime/astar/src/weights/pallet_dapp_staking_v3.rs rename to runtime/astar/src/weights/pallet_dapp_staking.rs index d7e546f98c..6bb3456bb5 100644 --- a/runtime/astar/src/weights/pallet_dapp_staking_v3.rs +++ b/runtime/astar/src/weights/pallet_dapp_staking.rs @@ -17,7 +17,7 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -//! Autogenerated weights for pallet_dapp_staking_v3 +//! Autogenerated weights for pallet_dapp_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2024-04-30, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` @@ -32,12 +32,12 @@ // --chain=astar-dev // --steps=50 // --repeat=20 -// --pallet=pallet_dapp_staking_v3 +// --pallet=pallet_dapp_staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./benchmark-results/astar-dev/dapp_staking_v3_weights.rs +// --output=./benchmark-results/astar-dev/dapp_staking_weights.rs // --template=./scripts/templates/weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -46,9 +46,9 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -use pallet_dapp_staking_v3::WeightInfo; +use pallet_dapp_staking::WeightInfo; -// Weights for pallet_dapp_staking_v3 using the Substrate node and recommended hardware. +// Weights for pallet_dapp_staking using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn maintenance_mode() -> Weight { diff --git a/runtime/local/Cargo.toml b/runtime/local/Cargo.toml index f12ab053a0..7e00f2eaad 100644 --- a/runtime/local/Cargo.toml +++ b/runtime/local/Cargo.toml @@ -12,8 +12,10 @@ log = { workspace = true, optional = true } num_enum = { workspace = true } parity-scale-codec = { workspace = true } scale-info = { workspace = true } +serde_json = { workspace = true } smallvec = { workspace = true } +fp-evm = { workspace = true } fp-rpc = { workspace = true } fp-self-contained = { workspace = true } frame-executive = { workspace = true } @@ -71,10 +73,10 @@ pallet-transaction-payment-rpc-runtime-api = { workspace = true } astar-primitives = { workspace = true } pallet-chain-extension-unified-accounts = { workspace = true } pallet-collective-proxy = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-dynamic-evm-base-fee = { workspace = true } pallet-evm-precompile-assets-erc20 = { workspace = true } -pallet-evm-precompile-dapp-staking-v3 = { workspace = true } +pallet-evm-precompile-dapp-staking = { workspace = true } pallet-evm-precompile-dispatch-lockdrop = { workspace = true } pallet-evm-precompile-sr25519 = { workspace = true } pallet-evm-precompile-substrate-ecdsa = { workspace = true } @@ -83,7 +85,7 @@ pallet-inflation = { workspace = true } pallet-static-price-provider = { workspace = true } pallet-unified-accounts = { workspace = true } -dapp-staking-v3-runtime-api = { workspace = true } +dapp-staking-runtime-api = { workspace = true } precompile-utils = { workspace = true } @@ -110,7 +112,9 @@ substrate-wasm-builder = { workspace = true, optional = true } default = ["std"] std = [ "parity-scale-codec/std", + "serde_json/std", "fp-rpc/std", + "fp-evm/std", "fp-self-contained/std", "frame-executive/std", "frame-support/std", @@ -123,8 +127,8 @@ std = [ "pallet-balances/std", "pallet-contracts/std", "pallet-chain-extension-unified-accounts/std", - "pallet-dapp-staking-v3/std", - "dapp-staking-v3-runtime-api/std", + "pallet-dapp-staking/std", + "dapp-staking-runtime-api/std", "pallet-inflation/std", "pallet-static-price-provider/std", "pallet-dynamic-evm-base-fee/std", @@ -138,7 +142,7 @@ std = [ "pallet-evm-precompile-ed25519/std", "pallet-evm-precompile-modexp/std", "pallet-evm-precompile-sha3fips/std", - "pallet-evm-precompile-dapp-staking-v3/std", + "pallet-evm-precompile-dapp-staking/std", "pallet-evm-precompile-sr25519/std", "pallet-evm-precompile-substrate-ecdsa/std", "pallet-evm-precompile-unified-accounts/std", @@ -206,7 +210,7 @@ runtime-benchmarks = [ "pallet-unified-accounts/runtime-benchmarks", "astar-primitives/runtime-benchmarks", "pallet-assets/runtime-benchmarks", - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", "pallet-inflation/runtime-benchmarks", "pallet-membership/runtime-benchmarks", "pallet-dynamic-evm-base-fee/runtime-benchmarks", @@ -215,7 +219,7 @@ runtime-benchmarks = [ "pallet-contracts/runtime-benchmarks", "pallet-evm/runtime-benchmarks", "pallet-evm-precompile-assets-erc20/runtime-benchmarks", - "pallet-evm-precompile-dapp-staking-v3/runtime-benchmarks", + "pallet-evm-precompile-dapp-staking/runtime-benchmarks", "pallet-grandpa/runtime-benchmarks", "pallet-proxy/runtime-benchmarks", "pallet-scheduler/runtime-benchmarks", @@ -235,7 +239,7 @@ try-runtime = [ "pallet-balances/try-runtime", "pallet-contracts/try-runtime", "pallet-collective-proxy/try-runtime", - "pallet-dapp-staking-v3/try-runtime", + "pallet-dapp-staking/try-runtime", "pallet-treasury/try-runtime", "pallet-inflation/try-runtime", "pallet-membership/try-runtime", @@ -262,11 +266,6 @@ try-runtime = [ "pallet-chain-extension-assets/try-runtime", "sp-runtime/try-runtime", ] -evm-tracing = [ - "moonbeam-evm-tracer", - "moonbeam-rpc-primitives-debug", - "moonbeam-rpc-primitives-txpool", -] # Enable metadata hash generation at compile time for the `CheckMetadataHash` extension. metadata-hash = ["substrate-wasm-builder?/metadata-hash"] diff --git a/runtime/local/src/genesis_config.rs b/runtime/local/src/genesis_config.rs new file mode 100644 index 0000000000..621efc7e51 --- /dev/null +++ b/runtime/local/src/genesis_config.rs @@ -0,0 +1,175 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +use crate::*; +use astar_primitives::{ + evm::EVM_REVERT_CODE, + genesis::{get_from_seed, GenesisAccount}, +}; + +/// Provides the JSON representation of predefined genesis config for given `id`. +pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { + let genesis = match id.try_into() { + Ok("development") => default_config(), + _ => return None, + }; + Some( + serde_json::to_string(&genesis) + .expect("serialization to json is expected to work. qed.") + .into_bytes(), + ) +} + +/// Get the default genesis config for the local runtime. +pub fn default_config() -> serde_json::Value { + let alice = GenesisAccount::::from_seed("Alice"); + let bob = GenesisAccount::::from_seed("Bob"); + let charlie = GenesisAccount::::from_seed("Charlie"); + let dave = GenesisAccount::::from_seed("Dave"); + let eve = GenesisAccount::::from_seed("Eve"); + + let balances: Vec<(AccountId, Balance)> = vec![ + (alice.account_id(), 1_000_000_000 * AST), + (bob.account_id(), 1_000_000_000 * AST), + ( + TreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * AST, + ), + ( + CommunityTreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * AST, + ), + ]; + + let accounts = vec![&alice, &bob, &charlie, &dave, &eve] + .iter() + .map(|x| x.account_id()) + .collect::>(); + + let config = RuntimeGenesisConfig { + system: Default::default(), + sudo: SudoConfig { + key: Some(alice.account_id()), + }, + balances: BalancesConfig { balances }, + vesting: VestingConfig { vesting: vec![] }, + aura: AuraConfig { + authorities: vec![get_from_seed::("Alice")], + }, + grandpa: GrandpaConfig { + authorities: vec![(get_from_seed::("Alice"), 1)], + ..Default::default() + }, + evm: EVMConfig { + // We need _some_ code inserted at the precompile address so that + // the evm will actually call the address. + accounts: Precompiles::used_addresses_h160() + .map(|addr| { + ( + addr, + fp_evm::GenesisAccount { + nonce: Default::default(), + balance: Default::default(), + storage: Default::default(), + code: EVM_REVERT_CODE.into(), + }, + ) + }) + .collect(), + ..Default::default() + }, + ethereum: Default::default(), + assets: Default::default(), + transaction_payment: Default::default(), + dapp_staking: DappStakingConfig { + reward_portion: vec![ + Permill::from_percent(40), + Permill::from_percent(30), + Permill::from_percent(20), + Permill::from_percent(10), + ], + slot_distribution: vec![ + Permill::from_percent(10), + Permill::from_percent(20), + Permill::from_percent(30), + Permill::from_percent(40), + ], + tier_thresholds: vec![ + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(35_700_000), // 3.57% + minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(8_900_000), // 0.89% + minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(23_800_000), // 2.38% + minimum_required_percentage: Perbill::from_parts(17_900_000), // 1.79% + }, + TierThreshold::FixedPercentage { + required_percentage: Perbill::from_parts(600_000), // 0.06% + }, + ], + slots_per_tier: vec![10, 20, 30, 40], + safeguard: Some(false), + ..Default::default() + }, + inflation: InflationConfig { + params: InflationParameters { + max_inflation_rate: Perquintill::from_percent(7), + treasury_part: Perquintill::from_percent(5), + collators_part: Perquintill::from_percent(3), + dapps_part: Perquintill::from_percent(20), + base_stakers_part: Perquintill::from_percent(25), + adjustable_stakers_part: Perquintill::from_percent(35), + bonus_part: Perquintill::from_percent(12), + ideal_staking_rate: Perquintill::from_percent(50), + }, + ..Default::default() + }, + council_membership: CouncilMembershipConfig { + members: accounts + .clone() + .try_into() + .expect("Should support at least 5 members."), + phantom: Default::default(), + }, + technical_committee_membership: TechnicalCommitteeMembershipConfig { + members: accounts[..3] + .to_vec() + .try_into() + .expect("Should support at least 3 members."), + phantom: Default::default(), + }, + community_council_membership: CommunityCouncilMembershipConfig { + members: accounts + .try_into() + .expect("Should support at least 5 members."), + phantom: Default::default(), + }, + council: Default::default(), + technical_committee: Default::default(), + community_council: Default::default(), + democracy: Default::default(), + treasury: Default::default(), + community_treasury: Default::default(), + }; + + serde_json::to_value(&config).expect("Could not build genesis config.") +} diff --git a/runtime/local/src/lib.rs b/runtime/local/src/lib.rs index a76b1007d4..3326113f70 100644 --- a/runtime/local/src/lib.rs +++ b/runtime/local/src/lib.rs @@ -25,9 +25,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use frame_support::{ - construct_runtime, - genesis_builder_helper::{build_state, get_preset}, - parameter_types, + construct_runtime, genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, tokens::{PayFromAccount, UnityAssetBalanceConversion}, @@ -52,7 +50,7 @@ use pallet_grandpa::{fg_primitives, AuthorityList as GrandpaAuthorityList}; use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment}; use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen}; use sp_api::impl_runtime_apis; -use sp_core::{crypto::KeyTypeId, ConstBool, OpaqueMetadata, H160, H256, U256}; +use sp_core::{crypto::KeyTypeId, sr25519, ConstBool, OpaqueMetadata, H160, H256, U256}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ @@ -83,7 +81,7 @@ use astar_primitives::{ }; pub use astar_primitives::{AccountId, Signature}; -pub use pallet_dapp_staking_v3::TierThreshold; +pub use pallet_dapp_staking::TierThreshold; pub use crate::precompiles::WhitelistedCalls; #[cfg(feature = "std")] @@ -134,6 +132,7 @@ pub type Precompiles = LocalPrecompiles; mod chain_extensions; pub use chain_extensions::LocalChainExtensions; +pub mod genesis_config; mod weights; /// Constant values used within the runtime. @@ -357,8 +356,8 @@ impl pallet_assets::Config for Runtime { // These values are based on the Astar 2.0 Tokenomics Modeling report. parameter_types! { - pub const TransactionLengthFeeFactor: Balance = 23_500_000_000_000; // 0.000_023_500_000_000_000 SBY per byte - pub const WeightFeeFactor: Balance = 30_855_000_000_000_000; // Around 0.03 SBY per unit of ref time. + pub const TransactionLengthFeeFactor: Balance = 23_500_000_000_000; // 0.000_023_500_000_000_000 AST per byte + pub const WeightFeeFactor: Balance = 30_855_000_000_000_000; // Around 0.03 AST per unit of ref time. pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); pub const OperationalFeeMultiplier: u8 = 5; pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(000_015, 1_000_000); // 0.000_015 @@ -444,7 +443,7 @@ impl pallet_static_price_provider::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] pub struct BenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper, AccountId> +impl pallet_dapp_staking::BenchmarkHelper, AccountId> for BenchmarkHelper, AccountId> { fn get_smart_contract(id: u32) -> SmartContract { @@ -462,7 +461,7 @@ parameter_types! { pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100); } -impl pallet_dapp_staking_v3::Config for Runtime { +impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -487,7 +486,7 @@ impl pallet_dapp_staking_v3::Config for Runtime { type MinimumStakeAmount = ConstU128; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; - type WeightInfo = pallet_dapp_staking_v3::weights::SubstrateWeight; + type WeightInfo = pallet_dapp_staking::weights::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = BenchmarkHelper, AccountId>; } @@ -845,7 +844,7 @@ impl InstanceFilter for ProxyType { matches!( c, RuntimeCall::DappStaking( - pallet_dapp_staking_v3::Call::claim_staker_rewards { .. } + pallet_dapp_staking::Call::claim_staker_rewards { .. } ) ) } @@ -1137,7 +1136,7 @@ construct_runtime!( TransactionPayment: pallet_transaction_payment = 30, Balances: pallet_balances = 31, Vesting: pallet_vesting = 32, - DappStaking: pallet_dapp_staking_v3 = 34, + DappStaking: pallet_dapp_staking = 34, Inflation: pallet_inflation = 35, Assets: pallet_assets = 36, StaticPriceProvider: pallet_static_price_provider = 37, @@ -1285,7 +1284,7 @@ mod benches { [pallet_balances, Balances] [pallet_timestamp, Timestamp] [pallet_ethereum_checked, EthereumChecked] - [pallet_dapp_staking_v3, DappStaking] + [pallet_dapp_staking, DappStaking] [pallet_inflation, Inflation] [pallet_dynamic_evm_base_fee, DynamicEvmBaseFee] ); @@ -1775,7 +1774,7 @@ impl_runtime_apis! { } } - impl dapp_staking_v3_runtime_api::DappStakingApi for Runtime { + impl dapp_staking_runtime_api::DappStakingApi for Runtime { fn periods_per_cycle() -> PeriodNumber { InflationCycleConfig::periods_per_cycle() } @@ -1801,15 +1800,17 @@ impl_runtime_apis! { impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) + genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) + genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) } fn preset_names() -> Vec { - vec![] + vec![ + sp_genesis_builder::PresetId::from("development"), + ] } } @@ -1854,7 +1855,6 @@ impl_runtime_apis! { } } - #[cfg(feature = "evm-tracing")] impl moonbeam_rpc_primitives_debug::DebugRuntimeApi for Runtime { fn trace_transaction( extrinsics: Vec<::Extrinsic>, @@ -2007,7 +2007,6 @@ impl_runtime_apis! { } } - #[cfg(feature = "evm-tracing")] impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi for Runtime { fn extrinsic_filter( xts_ready: Vec<::Extrinsic>, diff --git a/runtime/local/src/precompiles.rs b/runtime/local/src/precompiles.rs index 662d56cf14..0daf444b5f 100644 --- a/runtime/local/src/precompiles.rs +++ b/runtime/local/src/precompiles.rs @@ -25,7 +25,7 @@ use frame_support::{parameter_types, traits::Contains}; use pallet_evm_precompile_assets_erc20::Erc20AssetsPrecompileSet; use pallet_evm_precompile_blake2::Blake2F; use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_dapp_staking_v3::DappStakingV3Precompile; +use pallet_evm_precompile_dapp_staking::DappStakingV3Precompile; use pallet_evm_precompile_dispatch::Dispatch; use pallet_evm_precompile_dispatch_lockdrop::DispatchLockdrop; use pallet_evm_precompile_ed25519::Ed25519Verify; @@ -76,12 +76,8 @@ impl Contains for WhitelistedLockdropCalls { | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => calls .iter() .all(|call| WhitelistedLockdropCalls::contains(call)), - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::unbond_and_unstake { - .. - }) => true, - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::withdraw_unbonded { - .. - }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::unbond_and_unstake { .. }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::withdraw_unbonded { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_all { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => true, diff --git a/runtime/shibuya/Cargo.toml b/runtime/shibuya/Cargo.toml index 3dbd0cbe63..1baec69013 100644 --- a/runtime/shibuya/Cargo.toml +++ b/runtime/shibuya/Cargo.toml @@ -14,9 +14,11 @@ log = { workspace = true, optional = true } num_enum = { workspace = true } parity-scale-codec = { workspace = true } scale-info = { workspace = true } +serde_json = { workspace = true } smallvec = { workspace = true } # primitives +fp-evm = { workspace = true } fp-rpc = { workspace = true } fp-self-contained = { workspace = true } sp-api = { workspace = true } @@ -108,11 +110,11 @@ astar-primitives = { workspace = true } astar-xcm-benchmarks = { workspace = true, optional = true } pallet-chain-extension-unified-accounts = { workspace = true } pallet-collator-selection = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-dynamic-evm-base-fee = { workspace = true } pallet-ethereum-checked = { workspace = true } pallet-evm-precompile-assets-erc20 = { workspace = true } -pallet-evm-precompile-dapp-staking-v3 = { workspace = true } +pallet-evm-precompile-dapp-staking = { workspace = true } pallet-evm-precompile-dispatch-lockdrop = { workspace = true } pallet-evm-precompile-sr25519 = { workspace = true } pallet-evm-precompile-substrate-ecdsa = { workspace = true } @@ -125,7 +127,7 @@ pallet-xc-asset-config = { workspace = true } pallet-xcm = { workspace = true } pallet-xcm-benchmarks = { workspace = true, optional = true } -dapp-staking-v3-runtime-api = { workspace = true } +dapp-staking-runtime-api = { workspace = true } precompile-utils = { workspace = true } @@ -152,7 +154,9 @@ substrate-wasm-builder = { workspace = true, optional = true } default = ["std"] std = [ "parity-scale-codec/std", + "serde_json/std", "fp-rpc/std", + "fp-evm/std", "fp-self-contained/std", "sp-std/std", "sp-api/std", @@ -195,7 +199,7 @@ std = [ "pallet-evm-precompile-ed25519/std", "pallet-evm-precompile-modexp/std", "pallet-evm-precompile-sha3fips/std", - "pallet-evm-precompile-dapp-staking-v3/std", + "pallet-evm-precompile-dapp-staking/std", "pallet-evm-precompile-sr25519/std", "pallet-evm-precompile-substrate-ecdsa/std", "pallet-evm-precompile-assets-erc20/std", @@ -203,9 +207,9 @@ std = [ "pallet-evm-precompile-unified-accounts/std", "xcm-fee-payment-runtime-api/std", "pallet-evm-precompile-dispatch-lockdrop/std", - "pallet-dapp-staking-v3/std", + "pallet-dapp-staking/std", "orml-oracle/std", - "dapp-staking-v3-runtime-api/std", + "dapp-staking-runtime-api/std", "pallet-inflation/std", "pallet-price-aggregator/std", "pallet-identity/std", @@ -275,7 +279,7 @@ runtime-benchmarks = [ "frame-system-benchmarking/runtime-benchmarks", "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", "pallet-inflation/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-membership/runtime-benchmarks", @@ -302,7 +306,7 @@ runtime-benchmarks = [ "pallet-contracts/runtime-benchmarks", "pallet-evm/runtime-benchmarks", "pallet-evm-precompile-assets-erc20/runtime-benchmarks", - "pallet-evm-precompile-dapp-staking-v3/runtime-benchmarks", + "pallet-evm-precompile-dapp-staking/runtime-benchmarks", "pallet-evm-precompile-xcm/runtime-benchmarks", "pallet-identity/runtime-benchmarks", "pallet-multisig/runtime-benchmarks", @@ -330,7 +334,7 @@ try-runtime = [ "frame-system/try-runtime", "pallet-aura/try-runtime", "pallet-balances/try-runtime", - "pallet-dapp-staking-v3/try-runtime", + "pallet-dapp-staking/try-runtime", "pallet-inflation/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", diff --git a/runtime/shibuya/src/genesis_config.rs b/runtime/shibuya/src/genesis_config.rs new file mode 100644 index 0000000000..1b6ce2db93 --- /dev/null +++ b/runtime/shibuya/src/genesis_config.rs @@ -0,0 +1,202 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +use crate::*; +use astar_primitives::{evm::EVM_REVERT_CODE, genesis::GenesisAccount, parachain::SHIBUYA_ID}; + +/// Provides the JSON representation of predefined genesis config for given `id`. +pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { + let genesis = match id.try_into() { + Ok("development") => default_config(SHIBUYA_ID), + _ => return None, + }; + Some( + serde_json::to_string(&genesis) + .expect("serialization to json is expected to work. qed.") + .into_bytes(), + ) +} + +/// Get the default genesis config for the Shibuya runtime. +pub fn default_config(para_id: u32) -> serde_json::Value { + let alice = GenesisAccount::::from_seed("Alice"); + let bob = GenesisAccount::::from_seed("Bob"); + let charlie = GenesisAccount::::from_seed("Charlie"); + let dave = GenesisAccount::::from_seed("Dave"); + let eve = GenesisAccount::::from_seed("Eve"); + + let balances: Vec<(AccountId, Balance)> = vec![ + (alice.account_id(), 1_000_000_000 * SBY), + (bob.account_id(), 1_000_000_000 * SBY), + ( + TreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * SBY, + ), + ( + CommunityTreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * SBY, + ), + ]; + + let authorities = vec![&alice, &bob]; + let accounts = vec![&alice, &bob, &charlie, &dave, &eve] + .iter() + .map(|x| x.account_id()) + .collect::>(); + + let config = RuntimeGenesisConfig { + system: Default::default(), + sudo: SudoConfig { + key: Some(alice.account_id()), + }, + parachain_info: ParachainInfoConfig { + parachain_id: para_id.into(), + ..Default::default() + }, + balances: BalancesConfig { balances }, + vesting: VestingConfig { vesting: vec![] }, + session: SessionConfig { + keys: authorities + .iter() + .map(|x| { + ( + x.account_id(), + x.account_id(), + SessionKeys { + aura: x.pub_key().into(), + }, + ) + }) + .collect::>(), + }, + aura: AuraConfig { + authorities: vec![], + }, + aura_ext: Default::default(), + collator_selection: CollatorSelectionConfig { + desired_candidates: 32, + candidacy_bond: 32_000 * SBY, + invulnerables: authorities + .iter() + .map(|x| x.account_id()) + .collect::>(), + }, + evm: EVMConfig { + // We need _some_ code inserted at the precompile address so that + // the evm will actually call the address. + accounts: Precompiles::used_addresses_h160() + .map(|addr| { + ( + addr, + fp_evm::GenesisAccount { + nonce: Default::default(), + balance: Default::default(), + storage: Default::default(), + code: EVM_REVERT_CODE.into(), + }, + ) + }) + .collect(), + ..Default::default() + }, + evm_chain_id: EVMChainIdConfig { + chain_id: 0x51, + ..Default::default() + }, + ethereum: Default::default(), + polkadot_xcm: Default::default(), + assets: Default::default(), + parachain_system: Default::default(), + transaction_payment: Default::default(), + dapp_staking: DappStakingConfig { + reward_portion: vec![ + Permill::from_percent(40), + Permill::from_percent(30), + Permill::from_percent(20), + Permill::from_percent(10), + ], + slot_distribution: vec![ + Permill::from_percent(10), + Permill::from_percent(20), + Permill::from_percent(30), + Permill::from_percent(40), + ], + // percentages below are calulated based on a total issuance at the time when dApp staking v3 was launched (147M) + tier_thresholds: vec![ + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(20_000), // 0.0020% + minimum_required_percentage: Perbill::from_parts(17_000), // 0.0017% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(13_000), // 0.0013% + minimum_required_percentage: Perbill::from_parts(10_000), // 0.0010% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(5_400), // 0.00054% + minimum_required_percentage: Perbill::from_parts(3_400), // 0.00034% + }, + TierThreshold::FixedPercentage { + required_percentage: Perbill::from_parts(1_400), // 0.00014% + }, + ], + slots_per_tier: vec![10, 20, 30, 40], + safeguard: Some(false), + ..Default::default() + }, + inflation: Default::default(), + oracle_membership: OracleMembershipConfig { + members: vec![alice.account_id(), bob.account_id()] + .try_into() + .expect("Assumption is that at least two members will be allowed."), + ..Default::default() + }, + price_aggregator: PriceAggregatorConfig { + circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] + .try_into() + .expect("Must work since buffer should have at least a single value."), + }, + council_membership: CouncilMembershipConfig { + members: accounts + .clone() + .try_into() + .expect("Should support at least 5 members."), + phantom: Default::default(), + }, + technical_committee_membership: TechnicalCommitteeMembershipConfig { + members: accounts[..3] + .to_vec() + .try_into() + .expect("Should support at least 3 members."), + phantom: Default::default(), + }, + community_council_membership: CommunityCouncilMembershipConfig { + members: accounts + .try_into() + .expect("Should support at least 5 members."), + phantom: Default::default(), + }, + council: Default::default(), + technical_committee: Default::default(), + community_council: Default::default(), + democracy: Default::default(), + treasury: Default::default(), + community_treasury: Default::default(), + }; + + serde_json::to_value(&config).expect("Could not build genesis config.") +} diff --git a/runtime/shibuya/src/lib.rs b/runtime/shibuya/src/lib.rs index a8450369b9..c0d81cadae 100644 --- a/runtime/shibuya/src/lib.rs +++ b/runtime/shibuya/src/lib.rs @@ -26,8 +26,7 @@ use cumulus_primitives_core::AggregateMessageOrigin; use frame_support::{ construct_runtime, dispatch::DispatchClass, - genesis_builder_helper::{build_state, get_preset}, - parameter_types, + genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, tokens::{PayFromAccount, UnityAssetBalanceConversion}, @@ -57,7 +56,7 @@ use pallet_transaction_payment::{ use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::BlockHashCount; use sp_api::impl_runtime_apis; -use sp_core::{OpaqueMetadata, H160, H256, U256}; +use sp_core::{sr25519, OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -90,13 +89,13 @@ use astar_primitives::{ MainCouncilMembershipInst, MainTreasuryInst, OracleMembershipInst, TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst, }, - oracle::{CurrencyId, DummyCombineData, Price}, + oracle::{CurrencyAmount, CurrencyId, DummyCombineData, Price}, xcm::AssetLocationIdConverter, Address, AssetId, BlockNumber, Hash, Header, Nonce, UnfreezeChainOnFailedMigration, }; pub use astar_primitives::{AccountId, Balance, Signature}; -pub use pallet_dapp_staking_v3::TierThreshold; +pub use pallet_dapp_staking::TierThreshold; pub use pallet_inflation::InflationParameters; pub use crate::precompiles::WhitelistedCalls; @@ -115,6 +114,7 @@ pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::BuildStorage; mod chain_extensions; +pub mod genesis_config; mod precompiles; mod weights; mod xcm_config; @@ -432,7 +432,7 @@ impl pallet_preimage::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] pub struct DAppStakingBenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper, AccountId> +impl pallet_dapp_staking::BenchmarkHelper, AccountId> for DAppStakingBenchmarkHelper, AccountId> { fn get_smart_contract(id: u32) -> SmartContract { @@ -462,7 +462,7 @@ parameter_types! { pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100); } -impl pallet_dapp_staking_v3::Config for Runtime { +impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -487,7 +487,7 @@ impl pallet_dapp_staking_v3::Config for Runtime { type MinimumStakeAmount = MinimumStakingAmount; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; - type WeightInfo = weights::pallet_dapp_staking_v3::SubstrateWeight; + type WeightInfo = weights::pallet_dapp_staking::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = DAppStakingBenchmarkHelper, AccountId>; } @@ -1097,7 +1097,7 @@ impl InstanceFilter for ProxyType { matches!( c, RuntimeCall::DappStaking( - pallet_dapp_staking_v3::Call::claim_staker_rewards { .. } + pallet_dapp_staking::Call::claim_staker_rewards { .. } ) ) } @@ -1558,7 +1558,7 @@ construct_runtime!( TransactionPayment: pallet_transaction_payment = 30, Balances: pallet_balances = 31, Vesting: pallet_vesting = 32, - DappStaking: pallet_dapp_staking_v3 = 34, + DappStaking: pallet_dapp_staking = 34, Inflation: pallet_inflation = 35, Assets: pallet_assets = 36, PriceAggregator: pallet_price_aggregator = 37, @@ -1682,7 +1682,7 @@ pub type Migrations = (Unreleased, Permanent); /// Unreleased migrations. Add new ones here: pub type Unreleased = ( // dApp-staking dyn tier threshold migrations - pallet_dapp_staking_v3::migration::versioned_migrations::V7ToV8< + pallet_dapp_staking::migration::versioned_migrations::V7ToV8< Runtime, TierThresholds, ThresholdVariationPercentage, @@ -1772,7 +1772,7 @@ mod benches { [pallet_assets, pallet_assets::Pallet::] [pallet_balances, Balances] [pallet_timestamp, Timestamp] - [pallet_dapp_staking_v3, DappStaking] + [pallet_dapp_staking, DappStaking] [pallet_inflation, Inflation] [pallet_migrations, MultiBlockMigrations] [pallet_xc_asset_config, XcAssetConfig] @@ -2253,7 +2253,7 @@ impl_runtime_apis! { } } - impl dapp_staking_v3_runtime_api::DappStakingApi for Runtime { + impl dapp_staking_runtime_api::DappStakingApi for Runtime { fn periods_per_cycle() -> PeriodNumber { InflationCycleConfig::periods_per_cycle() } @@ -2337,15 +2337,17 @@ impl_runtime_apis! { impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) + genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) + genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) } fn preset_names() -> Vec { - vec![] + vec![ + sp_genesis_builder::PresetId::from("development"), + ] } } diff --git a/runtime/shibuya/src/precompiles.rs b/runtime/shibuya/src/precompiles.rs index 5fb0d3e256..642e7e491c 100644 --- a/runtime/shibuya/src/precompiles.rs +++ b/runtime/shibuya/src/precompiles.rs @@ -25,7 +25,7 @@ use frame_support::{parameter_types, traits::Contains}; use pallet_evm_precompile_assets_erc20::Erc20AssetsPrecompileSet; use pallet_evm_precompile_blake2::Blake2F; use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_dapp_staking_v3::DappStakingV3Precompile; +use pallet_evm_precompile_dapp_staking::DappStakingV3Precompile; use pallet_evm_precompile_dispatch::Dispatch; use pallet_evm_precompile_dispatch_lockdrop::DispatchLockdrop; use pallet_evm_precompile_ed25519::Ed25519Verify; @@ -79,12 +79,8 @@ impl Contains for WhitelistedLockdropCalls { | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => calls .iter() .all(|call| WhitelistedLockdropCalls::contains(call)), - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::unbond_and_unstake { - .. - }) => true, - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::withdraw_unbonded { - .. - }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::unbond_and_unstake { .. }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::withdraw_unbonded { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_all { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => true, diff --git a/runtime/shibuya/src/weights/mod.rs b/runtime/shibuya/src/weights/mod.rs index 91d43f0856..93a7d79b6f 100644 --- a/runtime/shibuya/src/weights/mod.rs +++ b/runtime/shibuya/src/weights/mod.rs @@ -19,7 +19,7 @@ pub mod orml_oracle; pub mod pallet_assets; pub mod pallet_balances; -pub mod pallet_dapp_staking_v3; +pub mod pallet_dapp_staking; pub mod pallet_inflation; pub mod pallet_xcm; pub mod xcm; diff --git a/runtime/shibuya/src/weights/pallet_dapp_staking_v3.rs b/runtime/shibuya/src/weights/pallet_dapp_staking.rs similarity index 98% rename from runtime/shibuya/src/weights/pallet_dapp_staking_v3.rs rename to runtime/shibuya/src/weights/pallet_dapp_staking.rs index 10d37c5590..1b2808c35b 100644 --- a/runtime/shibuya/src/weights/pallet_dapp_staking_v3.rs +++ b/runtime/shibuya/src/weights/pallet_dapp_staking.rs @@ -17,7 +17,7 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -//! Autogenerated weights for pallet_dapp_staking_v3 +//! Autogenerated weights for pallet_dapp_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2024-04-30, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` @@ -32,12 +32,12 @@ // --chain=shibuya-dev // --steps=50 // --repeat=20 -// --pallet=pallet_dapp_staking_v3 +// --pallet=pallet_dapp_staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./benchmark-results/shibuya-dev/dapp_staking_v3_weights.rs +// --output=./benchmark-results/shibuya-dev/dapp_staking_weights.rs // --template=./scripts/templates/weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -46,9 +46,9 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -use pallet_dapp_staking_v3::WeightInfo; +use pallet_dapp_staking::WeightInfo; -/// Weights for pallet_dapp_staking_v3 using the Substrate node and recommended hardware. +/// Weights for pallet_dapp_staking using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn maintenance_mode() -> Weight { diff --git a/runtime/shiden/Cargo.toml b/runtime/shiden/Cargo.toml index c6a01c5704..cc11dde64c 100644 --- a/runtime/shiden/Cargo.toml +++ b/runtime/shiden/Cargo.toml @@ -14,9 +14,11 @@ log = { workspace = true, optional = true } num_enum = { workspace = true } parity-scale-codec = { workspace = true } scale-info = { workspace = true } +serde_json = { workspace = true } smallvec = { workspace = true } # primitives +fp-evm = { workspace = true } fp-rpc = { workspace = true } fp-self-contained = { workspace = true } @@ -110,9 +112,9 @@ frame-try-runtime = { workspace = true, optional = true } astar-primitives = { workspace = true } astar-xcm-benchmarks = { workspace = true, optional = true } pallet-collator-selection = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-evm-precompile-assets-erc20 = { workspace = true } -pallet-evm-precompile-dapp-staking-v3 = { workspace = true } +pallet-evm-precompile-dapp-staking = { workspace = true } pallet-evm-precompile-dispatch-lockdrop = { workspace = true } pallet-evm-precompile-sr25519 = { workspace = true } pallet-evm-precompile-substrate-ecdsa = { workspace = true } @@ -122,7 +124,7 @@ pallet-price-aggregator = { workspace = true } pallet-xc-asset-config = { workspace = true } pallet-xcm = { workspace = true } -dapp-staking-v3-runtime-api = { workspace = true } +dapp-staking-runtime-api = { workspace = true } precompile-utils = { workspace = true } @@ -141,8 +143,10 @@ substrate-wasm-builder = { workspace = true, optional = true } default = ["std"] std = [ "parity-scale-codec/std", + "serde_json/std", "fp-rpc/std", "fp-self-contained/std", + "fp-evm/std", "sp-std/std", "sp-api/std", "sp-core/std", @@ -178,10 +182,10 @@ std = [ "pallet-evm-precompile-modexp/std", "xcm-fee-payment-runtime-api/std", "pallet-evm-precompile-sha3fips/std", - "pallet-dapp-staking-v3/std", - "dapp-staking-v3-runtime-api/std", + "pallet-dapp-staking/std", + "dapp-staking-runtime-api/std", "pallet-inflation/std", - "pallet-evm-precompile-dapp-staking-v3/std", + "pallet-evm-precompile-dapp-staking/std", "pallet-evm-precompile-sr25519/std", "pallet-evm-precompile-assets-erc20/std", "pallet-evm-precompile-substrate-ecdsa/std", @@ -241,13 +245,14 @@ std = [ "scale-info/std", ] runtime-benchmarks = [ + "log", "frame-benchmarking", "frame-support/runtime-benchmarks", "frame-system-benchmarking/runtime-benchmarks", "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "pallet-balances/runtime-benchmarks", - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", "pallet-inflation/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-ethereum/runtime-benchmarks", @@ -271,7 +276,7 @@ runtime-benchmarks = [ "pallet-contracts/runtime-benchmarks", "pallet-evm/runtime-benchmarks", "pallet-evm-precompile-assets-erc20/runtime-benchmarks", - "pallet-evm-precompile-dapp-staking-v3/runtime-benchmarks", + "pallet-evm-precompile-dapp-staking/runtime-benchmarks", "pallet-evm-precompile-xcm/runtime-benchmarks", "pallet-identity/runtime-benchmarks", "pallet-multisig/runtime-benchmarks", @@ -302,7 +307,7 @@ try-runtime = [ "orml-oracle/try-runtime", "pallet-price-aggregator/try-runtime", "pallet-membership/try-runtime", - "pallet-dapp-staking-v3/try-runtime", + "pallet-dapp-staking/try-runtime", "pallet-inflation/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", diff --git a/runtime/shiden/src/genesis_config.rs b/runtime/shiden/src/genesis_config.rs new file mode 100644 index 0000000000..1e72dae59c --- /dev/null +++ b/runtime/shiden/src/genesis_config.rs @@ -0,0 +1,161 @@ +// This file is part of Astar. + +// Copyright (C) Stake Technologies Pte.Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +// Astar is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Astar is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Astar. If not, see . + +use crate::*; +use astar_primitives::{evm::EVM_REVERT_CODE, genesis::GenesisAccount, parachain::SHIDEN_ID}; + +/// Provides the JSON representation of predefined genesis config for given `id`. +pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { + let genesis = match id.try_into() { + Ok("development") => default_config(SHIDEN_ID), + _ => return None, + }; + Some( + serde_json::to_string(&genesis) + .expect("serialization to json is expected to work. qed.") + .into_bytes(), + ) +} + +/// Get the default genesis config for the Shiden runtime. +pub fn default_config(para_id: u32) -> serde_json::Value { + let alice = GenesisAccount::::from_seed("Alice"); + let bob = GenesisAccount::::from_seed("Bob"); + + let balances: Vec<(AccountId, Balance)> = vec![ + (alice.account_id(), 1_000_000_000_000 * SDN), + (bob.account_id(), 1_000_000_000_000 * SDN), + ( + TreasuryPalletId::get().into_account_truncating(), + 1_000_000_000 * SDN, + ), + ]; + + let authorities = vec![&alice, &bob]; + + let config = RuntimeGenesisConfig { + system: Default::default(), + sudo: SudoConfig { + key: Some(alice.account_id()), + }, + parachain_info: ParachainInfoConfig { + parachain_id: para_id.into(), + ..Default::default() + }, + balances: BalancesConfig { balances }, + vesting: VestingConfig { vesting: vec![] }, + session: SessionConfig { + keys: authorities + .iter() + .map(|x| { + ( + x.account_id(), + x.account_id(), + SessionKeys { + aura: x.pub_key().into(), + }, + ) + }) + .collect::>(), + }, + aura: AuraConfig { + authorities: vec![], + }, + aura_ext: Default::default(), + collator_selection: CollatorSelectionConfig { + desired_candidates: 32, + candidacy_bond: 32_000 * SDN, + invulnerables: authorities + .iter() + .map(|x| x.account_id()) + .collect::>(), + }, + evm: EVMConfig { + // We need _some_ code inserted at the precompile address so that + // the evm will actually call the address. + accounts: Precompiles::used_addresses_h160() + .map(|addr| { + ( + addr, + fp_evm::GenesisAccount { + nonce: Default::default(), + balance: Default::default(), + storage: Default::default(), + code: EVM_REVERT_CODE.into(), + }, + ) + }) + .collect(), + ..Default::default() + }, + ethereum: Default::default(), + polkadot_xcm: Default::default(), + assets: Default::default(), + parachain_system: Default::default(), + transaction_payment: Default::default(), + dapp_staking: DappStakingConfig { + reward_portion: vec![ + Permill::from_percent(40), + Permill::from_percent(30), + Permill::from_percent(20), + Permill::from_percent(10), + ], + slot_distribution: vec![ + Permill::from_percent(10), + Permill::from_percent(20), + Permill::from_percent(30), + Permill::from_percent(40), + ], + // percentages below are calculated based on a total issuance at the time when dApp staking v3 was launched (84.3M) + tier_thresholds: vec![ + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(35_700_000), // 3.57% + minimum_required_percentage: Perbill::from_parts(23_800_000), // 2.38% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(8_900_000), // 0.89% + minimum_required_percentage: Perbill::from_parts(6_000_000), // 0.6% + }, + TierThreshold::DynamicPercentage { + percentage: Perbill::from_parts(2_380_000), // 0.238% + minimum_required_percentage: Perbill::from_parts(1_790_000), // 0.179% + }, + TierThreshold::FixedPercentage { + required_percentage: Perbill::from_parts(600_000), // 0.06% + }, + ], + slots_per_tier: vec![10, 20, 30, 40], + safeguard: Some(false), + ..Default::default() + }, + inflation: Default::default(), + oracle_membership: OracleMembershipConfig { + members: vec![alice.account_id(), bob.account_id()] + .try_into() + .expect("Assumption is that at least two members will be allowed."), + ..Default::default() + }, + price_aggregator: PriceAggregatorConfig { + circular_buffer: vec![CurrencyAmount::from_rational(5, 10)] + .try_into() + .expect("Must work since buffer should have at least a single value."), + }, + }; + + serde_json::to_value(&config).expect("Could not build genesis config.") +} diff --git a/runtime/shiden/src/lib.rs b/runtime/shiden/src/lib.rs index a37cbef95b..18d6ee401a 100644 --- a/runtime/shiden/src/lib.rs +++ b/runtime/shiden/src/lib.rs @@ -26,8 +26,7 @@ use cumulus_primitives_core::AggregateMessageOrigin; use frame_support::{ construct_runtime, dispatch::DispatchClass, - genesis_builder_helper::{build_state, get_preset}, - parameter_types, + genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit}, AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, Contains, FindAuthor, Get, Imbalance, @@ -55,7 +54,7 @@ use pallet_transaction_payment::{ use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::BlockHashCount; use sp_api::impl_runtime_apis; -use sp_core::{OpaqueMetadata, H160, H256, U256}; +use sp_core::{sr25519, OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -80,13 +79,13 @@ use astar_primitives::{ }, evm::EvmRevertCodeHandler, governance::OracleMembershipInst, - oracle::{CurrencyId, DummyCombineData, Price}, + oracle::{CurrencyAmount, CurrencyId, DummyCombineData, Price}, xcm::AssetLocationIdConverter, Address, AssetId, BlockNumber, Hash, Header, Nonce, UnfreezeChainOnFailedMigration, }; pub use astar_primitives::{AccountId, Balance, Signature}; -pub use pallet_dapp_staking_v3::TierThreshold; +pub use pallet_dapp_staking::TierThreshold; pub use pallet_inflation::InflationParameters; pub use crate::precompiles::WhitelistedCalls; @@ -104,6 +103,7 @@ pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::BuildStorage; mod chain_extensions; +pub mod genesis_config; mod precompiles; mod weights; mod xcm_config; @@ -388,7 +388,7 @@ impl pallet_multisig::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] pub struct DAppStakingBenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper, AccountId> +impl pallet_dapp_staking::BenchmarkHelper, AccountId> for DAppStakingBenchmarkHelper, AccountId> { fn get_smart_contract(id: u32) -> SmartContract { @@ -427,7 +427,7 @@ parameter_types! { pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100); } -impl pallet_dapp_staking_v3::Config for Runtime { +impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -452,7 +452,7 @@ impl pallet_dapp_staking_v3::Config for Runtime { type MinimumStakeAmount = MinimumStakingAmount; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; - type WeightInfo = weights::pallet_dapp_staking_v3::SubstrateWeight; + type WeightInfo = weights::pallet_dapp_staking::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = DAppStakingBenchmarkHelper, AccountId>; } @@ -1055,7 +1055,7 @@ impl InstanceFilter for ProxyType { matches!( c, RuntimeCall::DappStaking( - pallet_dapp_staking_v3::Call::claim_staker_rewards { .. } + pallet_dapp_staking::Call::claim_staker_rewards { .. } ) ) } @@ -1228,7 +1228,7 @@ construct_runtime!( // logic is executed. // TODO: Address this later. It would be best if Inflation was first pallet. Inflation: pallet_inflation = 33, - DappStaking: pallet_dapp_staking_v3 = 34, + DappStaking: pallet_dapp_staking = 34, Assets: pallet_assets = 36, PriceAggregator: pallet_price_aggregator = 37, Oracle: orml_oracle = 38, @@ -1331,7 +1331,7 @@ pub type Migrations = (Unreleased, Permanent); /// Unreleased migrations. Add new ones here: pub type Unreleased = ( // dApp-staking dyn tier threshold migrations - pallet_dapp_staking_v3::migration::versioned_migrations::V7ToV8< + pallet_dapp_staking::migration::versioned_migrations::V7ToV8< Runtime, TierThresholds, ThresholdVariationPercentage, @@ -1421,7 +1421,7 @@ mod benches { [pallet_assets, pallet_assets::Pallet::] [pallet_balances, Balances] [pallet_timestamp, Timestamp] - [pallet_dapp_staking_v3, DappStaking] + [pallet_dapp_staking, DappStaking] [pallet_inflation, Inflation] [pallet_migrations, MultiBlockMigrations] [pallet_xc_asset_config, XcAssetConfig] @@ -1898,7 +1898,7 @@ impl_runtime_apis! { } } - impl dapp_staking_v3_runtime_api::DappStakingApi for Runtime { + impl dapp_staking_runtime_api::DappStakingApi for Runtime { fn periods_per_cycle() -> PeriodNumber { InflationCycleConfig::periods_per_cycle() } @@ -1981,15 +1981,17 @@ impl_runtime_apis! { impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) + genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) + genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) } fn preset_names() -> Vec { - vec![] + vec![ + sp_genesis_builder::PresetId::from("development"), + ] } } diff --git a/runtime/shiden/src/precompiles.rs b/runtime/shiden/src/precompiles.rs index 34a6290215..d5821340eb 100644 --- a/runtime/shiden/src/precompiles.rs +++ b/runtime/shiden/src/precompiles.rs @@ -25,7 +25,7 @@ use frame_support::{parameter_types, traits::Contains}; use pallet_evm_precompile_assets_erc20::Erc20AssetsPrecompileSet; use pallet_evm_precompile_blake2::Blake2F; use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_dapp_staking_v3::DappStakingV3Precompile; +use pallet_evm_precompile_dapp_staking::DappStakingV3Precompile; use pallet_evm_precompile_dispatch::Dispatch; use pallet_evm_precompile_dispatch_lockdrop::DispatchLockdrop; use pallet_evm_precompile_ed25519::Ed25519Verify; @@ -77,12 +77,8 @@ impl Contains for WhitelistedLockdropCalls { | RuntimeCall::Utility(pallet_utility::Call::batch_all { calls }) => calls .iter() .all(|call| WhitelistedLockdropCalls::contains(call)), - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::unbond_and_unstake { - .. - }) => true, - RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::withdraw_unbonded { - .. - }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::unbond_and_unstake { .. }) => true, + RuntimeCall::DappStaking(pallet_dapp_staking::Call::withdraw_unbonded { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_all { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_keep_alive { .. }) => true, RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => true, diff --git a/runtime/shiden/src/weights/mod.rs b/runtime/shiden/src/weights/mod.rs index 0b665ae16e..476c43da5b 100644 --- a/runtime/shiden/src/weights/mod.rs +++ b/runtime/shiden/src/weights/mod.rs @@ -18,7 +18,7 @@ pub mod orml_oracle; pub mod pallet_assets; -pub mod pallet_dapp_staking_v3; +pub mod pallet_dapp_staking; pub mod pallet_inflation; pub mod pallet_xcm; pub mod xcm; diff --git a/runtime/shiden/src/weights/pallet_dapp_staking_v3.rs b/runtime/shiden/src/weights/pallet_dapp_staking.rs similarity index 98% rename from runtime/shiden/src/weights/pallet_dapp_staking_v3.rs rename to runtime/shiden/src/weights/pallet_dapp_staking.rs index c6f7c4f9c7..9ccd24fabb 100644 --- a/runtime/shiden/src/weights/pallet_dapp_staking_v3.rs +++ b/runtime/shiden/src/weights/pallet_dapp_staking.rs @@ -17,7 +17,7 @@ // You should have received a copy of the GNU General Public License // along with Astar. If not, see . -//! Autogenerated weights for pallet_dapp_staking_v3 +//! Autogenerated weights for pallet_dapp_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2024-05-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` @@ -32,12 +32,12 @@ // --chain=shiden-dev // --steps=50 // --repeat=20 -// --pallet=pallet_dapp_staking_v3 +// --pallet=pallet_dapp_staking // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./benchmark-results/shiden-dev/dapp_staking_v3_weights.rs +// --output=./benchmark-results/shiden-dev/dapp_staking_weights.rs // --template=./scripts/templates/weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -46,9 +46,9 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -use pallet_dapp_staking_v3::WeightInfo; +use pallet_dapp_staking::WeightInfo; -/// Weights for pallet_dapp_staking_v3 using the Substrate node and recommended hardware. +/// Weights for pallet_dapp_staking using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn maintenance_mode() -> Weight { diff --git a/tests/integration/Cargo.toml b/tests/integration/Cargo.toml index daeb2402e8..19e075fc54 100644 --- a/tests/integration/Cargo.toml +++ b/tests/integration/Cargo.toml @@ -47,7 +47,7 @@ xcm-fee-payment-runtime-api = { workspace = true } assets-chain-extension-types = { workspace = true } pallet-collator-selection = { workspace = true } pallet-collective-proxy = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-ethereum-checked = { workspace = true } pallet-evm-precompile-assets-erc20 = { workspace = true } pallet-evm-precompile-dispatch = { workspace = true } @@ -98,7 +98,7 @@ std = [ "cumulus-pallet-parachain-system/std", "pallet-democracy/std", "pallet-timestamp/std", - "pallet-dapp-staking-v3/std", + "pallet-dapp-staking/std", "pallet-ethereum?/std", "pallet-ethereum-checked/std", "pallet-evm/std", diff --git a/tests/integration/src/dapp_staking_v3.rs b/tests/integration/src/dapp_staking.rs similarity index 94% rename from tests/integration/src/dapp_staking_v3.rs rename to tests/integration/src/dapp_staking.rs index 3737c16d8e..bff9c14ced 100644 --- a/tests/integration/src/dapp_staking_v3.rs +++ b/tests/integration/src/dapp_staking.rs @@ -21,7 +21,7 @@ use crate::setup::*; use pallet_collator_selection::{CandidateInfo, Candidates}; -use pallet_dapp_staking_v3::*; +use pallet_dapp_staking::*; #[test] fn dapp_staking_triggers_inflation_recalculation() { @@ -93,10 +93,10 @@ fn lock_not_possible_for_collator_candidate_account() { // Now try to participate in dApp staking with Alice and expect an error let minimum_lock_amount = - ::MinimumLockedAmount::get(); + ::MinimumLockedAmount::get(); assert_noop!( DappStaking::lock(RuntimeOrigin::signed(ALICE.clone()), minimum_lock_amount,), - pallet_dapp_staking_v3::Error::::AccountNotAvailableForDappStaking + pallet_dapp_staking::Error::::AccountNotAvailableForDappStaking ); }); } @@ -107,7 +107,7 @@ fn collator_selection_candidacy_not_possible_for_dapp_staking_participant() { new_test_ext().execute_with(|| { // Lock some amount with Alice let minimum_lock_amount = - ::MinimumLockedAmount::get(); + ::MinimumLockedAmount::get(); assert_ok!(DappStaking::lock( RuntimeOrigin::signed(ALICE.clone()), minimum_lock_amount, diff --git a/tests/integration/src/governance.rs b/tests/integration/src/governance.rs index 01087cea5d..ac8667b5fe 100644 --- a/tests/integration/src/governance.rs +++ b/tests/integration/src/governance.rs @@ -126,7 +126,7 @@ fn community_council_can_execute_dapp_staking_calls() { Balances::make_free_balance_be(&proxy_account, lock_amount); // Prepare the wrapped dApp staking lock call - let lock_call = RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::lock { + let lock_call = RuntimeCall::DappStaking(pallet_dapp_staking::Call::lock { amount: lock_amount, }); let collective_proxy_call = @@ -162,7 +162,7 @@ fn community_council_can_execute_dapp_staking_calls() { // Check that the lock was successful assert_eq!( - pallet_dapp_staking_v3::Ledger::::get(&proxy_account).locked, + pallet_dapp_staking::Ledger::::get(&proxy_account).locked, lock_amount ); }) diff --git a/tests/integration/src/lib.rs b/tests/integration/src/lib.rs index 1196eaa092..a46917f7d0 100644 --- a/tests/integration/src/lib.rs +++ b/tests/integration/src/lib.rs @@ -36,7 +36,7 @@ mod dispatch_precompile_filter; mod unified_accounts; #[cfg(any(feature = "shibuya", feature = "shiden", feature = "astar"))] -mod dapp_staking_v3; +mod dapp_staking; #[cfg(any(feature = "shibuya", feature = "shiden", feature = "astar"))] mod assets_chain_extensions; diff --git a/tests/integration/src/proxy.rs b/tests/integration/src/proxy.rs index 177e6f73f3..533e106175 100644 --- a/tests/integration/src/proxy.rs +++ b/tests/integration/src/proxy.rs @@ -18,7 +18,7 @@ use crate::setup::*; use astar_primitives::dapp_staking::SmartContractHandle; -use pallet_dapp_staking_v3::ForcingType; +use pallet_dapp_staking::ForcingType; #[test] fn test_utility_call_pass_for_any() { @@ -180,9 +180,8 @@ fn test_staker_reward_claim_proxy_works() { 0 )); - let contract = ::SmartContract::evm( - H160::repeat_byte(0x01), - ); + let contract = + ::SmartContract::evm(H160::repeat_byte(0x01)); let staker_reward_claim_call = RuntimeCall::DappStaking(DappStakingCall::Call::claim_staker_rewards {}); let call = Box::new(staker_reward_claim_call); diff --git a/tests/integration/src/setup.rs b/tests/integration/src/setup.rs index 5235da21bb..8b555ae235 100644 --- a/tests/integration/src/setup.rs +++ b/tests/integration/src/setup.rs @@ -106,7 +106,7 @@ pub const INIT_PRICE: Price = Price::from_rational(1, 10); pub type SystemError = frame_system::Error; pub use pallet_balances::Call as BalancesCall; -pub use pallet_dapp_staking_v3 as DappStakingCall; +pub use pallet_dapp_staking as DappStakingCall; pub use pallet_proxy::Event as ProxyEvent; pub use pallet_utility::{Call as UtilityCall, Event as UtilityEvent}; use parity_scale_codec::Decode; @@ -195,21 +195,21 @@ impl ExtBuilder { ext.execute_with(|| { System::set_block_number(1); - let era_length = ::CycleConfiguration::blocks_per_era(); + let era_length = ::CycleConfiguration::blocks_per_era(); let voting_period_length_in_eras = - ::CycleConfiguration::eras_per_voting_subperiod(); + ::CycleConfiguration::eras_per_voting_subperiod(); - pallet_dapp_staking_v3::ActiveProtocolState::::put(pallet_dapp_staking_v3::ProtocolState { + pallet_dapp_staking::ActiveProtocolState::::put(pallet_dapp_staking::ProtocolState { era: 1, next_era_start: era_length.saturating_mul(voting_period_length_in_eras.into()) + 1, - period_info: pallet_dapp_staking_v3::PeriodInfo { + period_info: pallet_dapp_staking::PeriodInfo { number: 1, - subperiod: pallet_dapp_staking_v3::Subperiod::Voting, + subperiod: pallet_dapp_staking::Subperiod::Voting, next_subperiod_start_era: 2, }, maintenance: false, }); - pallet_dapp_staking_v3::Safeguard::::put(false); + pallet_dapp_staking::Safeguard::::put(false); // Ensure the initial state is set for the first block AllPalletsWithSystem::on_initialize(1); diff --git a/tests/xcm-simulator/Cargo.toml b/tests/xcm-simulator/Cargo.toml index e76a38a443..904c27d23f 100644 --- a/tests/xcm-simulator/Cargo.toml +++ b/tests/xcm-simulator/Cargo.toml @@ -33,7 +33,7 @@ sp-tracing = { workspace = true } # Custom Astar inclusions astar-primitives = { workspace = true } astar-test-utils = { workspace = true } -pallet-dapp-staking-v3 = { workspace = true } +pallet-dapp-staking = { workspace = true } pallet-xc-asset-config = { workspace = true } # polkadot deps @@ -81,7 +81,7 @@ std = [ "orml-xtokens/std", "orml-traits/std", "orml-xcm-support/std", - "pallet-dapp-staking-v3/std", + "pallet-dapp-staking/std", ] runtime-benchmarks = [ "frame-system/runtime-benchmarks", @@ -97,5 +97,5 @@ runtime-benchmarks = [ "orml-xtokens/runtime-benchmarks", "astar-primitives/runtime-benchmarks", "pallet-message-queue/runtime-benchmarks", - "pallet-dapp-staking-v3/runtime-benchmarks", + "pallet-dapp-staking/runtime-benchmarks", ] diff --git a/tests/xcm-simulator/src/mocks/parachain.rs b/tests/xcm-simulator/src/mocks/parachain.rs index 9346305cc2..22ce689034 100644 --- a/tests/xcm-simulator/src/mocks/parachain.rs +++ b/tests/xcm-simulator/src/mocks/parachain.rs @@ -320,7 +320,7 @@ impl InstanceFilter for ProxyType { matches!( c, RuntimeCall::DappStaking( - pallet_dapp_staking_v3::Call::claim_staker_rewards { .. } + pallet_dapp_staking::Call::claim_staker_rewards { .. } ) | RuntimeCall::Utility(..) ) } @@ -684,7 +684,7 @@ pub(crate) type MockSmartContract = SmartContract; #[cfg(feature = "runtime-benchmarks")] pub struct BenchmarkHelper(sp_std::marker::PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] -impl pallet_dapp_staking_v3::BenchmarkHelper +impl pallet_dapp_staking::BenchmarkHelper for BenchmarkHelper { fn get_smart_contract(id: u32) -> MockSmartContract { @@ -702,7 +702,7 @@ parameter_types! { pub const BaseNativeCurrencyPrice: FixedU128 = FixedU128::from_rational(5, 100); } -impl pallet_dapp_staking_v3::Config for Runtime { +impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; @@ -743,7 +743,7 @@ construct_runtime!( Assets: pallet_assets, XcAssetConfig: pallet_xc_asset_config, CumulusXcm: cumulus_pallet_xcm, - DappStaking: pallet_dapp_staking_v3, + DappStaking: pallet_dapp_staking, Proxy: pallet_proxy, Utility: pallet_utility, Randomness: pallet_insecure_randomness_collective_flip, diff --git a/tests/xcm-simulator/src/tests/general.rs b/tests/xcm-simulator/src/tests/general.rs index cf67a27527..6c1f3253ce 100644 --- a/tests/xcm-simulator/src/tests/general.rs +++ b/tests/xcm-simulator/src/tests/general.rs @@ -220,7 +220,7 @@ fn remote_dapps_staking_staker_claim() { )); // advance enough blocks so we at least get to era 5 - this gives us era 2, 3 and 4 for claiming - while pallet_dapp_staking_v3::ActiveProtocolState::::get().era < 5 { + while pallet_dapp_staking::ActiveProtocolState::::get().era < 5 { advance_parachain_block_to(parachain::System::block_number() + 1); } // Ensure it's not first block so event storage is clear @@ -235,7 +235,7 @@ fn remote_dapps_staking_staker_claim() { )); }); - let claim_staker_call = parachain::RuntimeCall::DappStaking(pallet_dapp_staking_v3::Call::< + let claim_staker_call = parachain::RuntimeCall::DappStaking(pallet_dapp_staking::Call::< parachain::Runtime, >::claim_staker_rewards {}); @@ -276,16 +276,16 @@ fn remote_dapps_staking_staker_claim() { .into_iter() .map(|r| r.event) .filter_map(|e| { - ::RuntimeEvent::from(e) + ::RuntimeEvent::from(e) .try_into() .ok() }) - .collect::>>(); + .collect::>>(); assert_eq!(dapp_staking_events.len(), 1); assert_matches::assert_matches!( dapp_staking_events[0].clone(), - pallet_dapp_staking_v3::Event::Reward { account, .. } + pallet_dapp_staking::Event::Reward { account, .. } if account == ALICE ); @@ -336,9 +336,7 @@ fn remote_dapps_staking_staker_claim() { .iter() .filter(|r| matches!( r.event, - parachain::RuntimeEvent::DappStaking( - pallet_dapp_staking_v3::Event::Reward { .. } - ) + parachain::RuntimeEvent::DappStaking(pallet_dapp_staking::Event::Reward { .. }) )) .count(), 2 diff --git a/third-party/zombienet/multi_parachains.toml b/third-party/zombienet/multi_parachains.toml index 16ffe4551e..bdab728b03 100644 --- a/third-party/zombienet/multi_parachains.toml +++ b/third-party/zombienet/multi_parachains.toml @@ -25,8 +25,7 @@ chain = "rococo-local" validator = true [[parachains]] -# Right now this has to be 2000 but soon we might be able to use arbitrary para-id -id = 2000 +id = 1000 # Replace this with whichever chain you need to run, e.g. `astar-dev` if you need Astar chain = "shibuya-dev" cumulus_based = true diff --git a/third-party/zombienet/single_parachain.toml b/third-party/zombienet/single_parachain.toml index 9f4a890b02..1e61143312 100644 --- a/third-party/zombienet/single_parachain.toml +++ b/third-party/zombienet/single_parachain.toml @@ -33,8 +33,7 @@ name = "dave" validator = true [[parachains]] -# Right now this has to be 2000 but soon we might be able to use arbitrary para-id -id = 2000 +id = 1000 # Replace this with whichever chain you need to run, e.g. `astar-dev` if you need Astar chain = "shibuya-dev" cumulus_based = true diff --git a/third-party/zombienet/smoke.toml b/third-party/zombienet/smoke.toml index 40ddb4228a..34bdad214e 100644 --- a/third-party/zombienet/smoke.toml +++ b/third-party/zombienet/smoke.toml @@ -24,8 +24,7 @@ chain = "rococo-local" validator = true [[parachains]] -# Right now this has to be 2000 but soon we might be able to use arbitrary para-id -id = 2000 +id = 1000 chain = "{{CHAIN}}" cumulus_based = true