--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -23,4 +23,4 @@
WORKDIR /dev_chain
-RUN cargo test --features=limit-testing
+CMD cargo test --features=limit-testing
--- /dev/null
+++ b/.docker/Dockerfile-parachain-node-only
@@ -0,0 +1,103 @@
+# ===== Rust builder =====
+FROM ubuntu:20.04 as rust-builder
+LABEL maintainer="Unique.Network"
+
+ARG RUST_TOOLCHAIN=
+
+ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
+ENV CARGO_HOME="/cargo-home"
+ENV PATH="/cargo-home/bin:$PATH"
+ENV TZ=UTC
+RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
+
+RUN apt-get update && \
+ apt-get install -y curl cmake pkg-config libssl-dev git clang && \
+ apt-get clean && \
+ rm -r /var/lib/apt/lists/*
+
+RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
+
+RUN rustup toolchain uninstall $(rustup toolchain list) && \
+ rustup toolchain install $RUST_TOOLCHAIN && \
+ rustup default $RUST_TOOLCHAIN && \
+ rustup target list --installed && \
+ rustup show
+RUN rustup target add wasm32-unknown-unknown --toolchain $RUST_TOOLCHAIN
+
+RUN mkdir /unique_parachain
+WORKDIR /unique_parachain
+
+
+# ===== BUILD current version ======
+FROM rust-builder as builder-unique-current
+
+ARG PROFILE=release
+ARG FEATURE=
+ARG MAINNET_BRANCH=
+ARG REPO_URL=
+
+WORKDIR /unique_parachain
+
+RUN git clone $REPO_URL -b $MAINNET_BRANCH . && \
+ cargo build --features=$FEATURE --$PROFILE
+
+# ===== BUILD target version ======
+FROM rust-builder as builder-unique-target
+
+ARG PROFILE=release
+ARG FEATURE=
+
+COPY . /unique_parachain
+WORKDIR /unique_parachain
+
+RUN cargo build --features=$FEATURE --$PROFILE
+
+# ===== BUILD POLKADOT =====
+FROM rust-builder as builder-polkadot
+
+ARG POLKADOT_BUILD_BRANCH=
+ENV POLKADOT_BUILD_BRANCH $POLKADOT_BUILD_BRANCH
+
+
+WORKDIR /unique_parachain
+
+RUN git clone -b $POLKADOT_BUILD_BRANCH --depth 1 https://github.com/paritytech/polkadot.git && \
+ cd polkadot && \
+ cargo build --release
+
+# ===== RUN ======
+
+FROM ubuntu:20.04
+
+ARG RUNTIME=
+ENV RUNTIME $RUNTIME
+
+RUN apt-get -y update && \
+ apt-get -y install curl git && \
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash && \
+ export NVM_DIR="$HOME/.nvm" && \
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+ nvm install v16.16.0 && \
+ nvm use v16.16.0
+
+RUN git clone https://github.com/uniquenetwork/polkadot-launch -b feature/runtime-upgrade-testing
+
+RUN export NVM_DIR="$HOME/.nvm" && \
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+ cd /polkadot-launch && \
+ npm install --global yarn && \
+ yarn install
+
+RUN echo "$RUNTIME"
+
+COPY --from=builder-unique-current /unique_parachain/target/release/unique-collator /unique-chain/current/release/
+COPY --from=builder-unique-target /unique_parachain/target/release/unique-collator /unique-chain/target/release/
+COPY --from=builder-unique-target /unique_parachain/target/release/wbuild/"$RUNTIME"-runtime/"$RUNTIME"_runtime.compact.compressed.wasm /unique-chain/target/release/wbuild/"$RUNTIME"-runtime/"$RUNTIME"_runtime.compact.compressed.wasm
+
+COPY --from=builder-polkadot /unique_parachain/polkadot/target/release/polkadot /polkadot/target/release/
+COPY --from=builder-polkadot /unique_parachain/polkadot/target/release/wbuild/westend-runtime/westend_runtime.compact.compressed.wasm /polkadot/target/release/wbuild/westend-runtime/westend_runtime.compact.compressed.wasm
+
+CMD export NVM_DIR="$HOME/.nvm" && \
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+ cd /polkadot-launch && \
+ yarn start launch-config.json --test-upgrade-parachains -w -n
--- /dev/null
+++ b/.docker/docker-compose.tmp-node.j2
@@ -0,0 +1,33 @@
+version: "3.5"
+
+services:
+ node-parachain:
+ build:
+ args:
+ - "RUST_TOOLCHAIN={{ RUST_TOOLCHAIN }}"
+ - "BRANCH={{ BRANCH }}"
+ - "REPO_URL={{ REPO_URL }}"
+ - "FEATURE={{ FEATURE }}"
+ - "RUNTIME={{ RUNTIME }}"
+ - "POLKADOT_BUILD_BRANCH={{ POLKADOT_BUILD_BRANCH }}"
+ - "MAINNET_TAG={{ MAINNET_TAG }}"
+ - "MAINNET_BRANCH={{ MAINNET_BRANCH }}"
+ context: ../
+ dockerfile: .docker/Dockerfile-parachain-node-only
+ image: node-parachain
+ container_name: node-parachain
+ volumes:
+ - type: bind
+ source: ./launch-config-forkless-nodata.json
+ target: /polkadot-launch/launch-config.json
+ read_only: true
+ expose:
+ - 9944
+ - 9933
+ ports:
+ - 127.0.0.1:9944:9944
+ - 127.0.0.1:9933:9933
+ logging:
+ options:
+ max-size: "1m"
+ max-file: "3"
--- a/.docker/forkless-config/launch-config-forkless-data.j2
+++ b/.docker/forkless-config/launch-config-forkless-data.j2
@@ -86,7 +86,7 @@
},
"parachains": [
{
- "bin": "/unique-chain/target/release/unique-collator",
+ "bin": "/unique-chain/current/release/unique-collator",
"upgradeBin": "/unique-chain/target/release/unique-collator",
"upgradeWasm": "/unique-chain/target/release/wbuild/{{ FEATURE }}/{{ RUNTIME }}_runtime.compact.compressed.wasm",
"id": "1000",
--- a/.docker/forkless-config/launch-config-forkless-nodata.j2
+++ b/.docker/forkless-config/launch-config-forkless-nodata.j2
@@ -101,7 +101,8 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace"
+ "-lxcm=trace",
+ "--ws-max-connections=1000"
]
},
{
@@ -113,7 +114,8 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace"
+ "-lxcm=trace",
+ "--ws-max-connections=1000"
]
}
]
--- a/.github/workflows/build-test-master.yml
+++ /dev/null
@@ -1,127 +0,0 @@
-name: yarn test para
-
-# Controls when the action will run.
-on:
- # Triggers the workflow on push or pull request events but only for the master branch
- pull_request:
- branches:
- - master
- types:
- - opened
- - reopened
- - synchronize #commit(s) pushed to the pull request
- - ready_for_review
-
- # Allows you to run this workflow manually from the Actions tab
- workflow_dispatch:
-
-#Define Workflow variables
-env:
- REPO_URL: ${{ github.server_url }}/${{ github.repository }}
-
-concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: true
-
-# A workflow run is made up of one or more jobs that can run sequentially or in parallel
-jobs:
-
- master-build-and-test:
- # The type of runner that the job will run on
- runs-on: [self-hosted-ci,large]
- timeout-minutes: 1380
-
- name: ${{ matrix.network }}
-
- continue-on-error: true #Do not stop testing of matrix runs failed.
-
- strategy:
- matrix:
- include:
- - network: "opal"
- features: "opal-runtime"
- - network: "quartz"
- features: "quartz-runtime"
- - network: "unique"
- features: "unique-runtime"
-
- steps:
- - name: Skip if pull request is in Draft
- # `if: github.event.pull_request.draft == true` should be kept here, at
- # the step level, rather than at the job level. The latter is not
- # recommended because when the PR is moved from "Draft" to "Ready to
- # review" the workflow will immediately be passing (since it was skipped),
- # even though it hasn't actually ran, since it takes a few seconds for
- # the workflow to start. This is also disclosed in:
- # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
- # That scenario would open an opportunity for the check to be bypassed:
- # 1. Get your PR approved
- # 2. Move it to Draft
- # 3. Push whatever commits you want
- # 4. Move it to "Ready for review"; now the workflow is passing (it was
- # skipped) and "Check reviews" is also passing (it won't be updated
- # until the workflow is finished)
- if: github.event.pull_request.draft == true
- run: exit 1
-
- - name: Clean Workspace
- uses: AutoModality/action-clean@v1.1.0
-
- # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- - uses: actions/checkout@v3
- with:
- ref: ${{ github.head_ref }}
-
- - name: Read .env file
- uses: xom9ikk/dotenv@v1.0.2
-
- - name: Generate ENV related extend file for docker-compose
- uses: cuchi/jinja2-action@v1.2.0
- with:
- template: .docker/docker-compose.tmp-master.j2
- output_file: .docker/docker-compose.${{ matrix.network }}.yml
- variables: |
- REPO_URL=${{ github.server_url }}/${{ github.repository }}.git
- RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
- POLKADOT_BUILD_BRANCH=${{ env.POLKADOT_BUILD_BRANCH }}
- FEATURE=${{ matrix.features }}
- BRANCH=${{ github.head_ref }}
-
- - name: Show build configuration
- run: cat .docker/docker-compose.${{ matrix.network }}.yml
-
- - name: Build the stack
- run: docker-compose -f ".docker/docker-compose-master.yml" -f ".docker/docker-compose.${{ matrix.network }}.yml" up -d --build
-
- - uses: actions/setup-node@v3
- with:
- node-version: 16
-
- - name: Run tests
- run: |
- cd tests
- yarn install
- yarn add mochawesome
- echo "Ready to start tests"
- node scripts/readyness.js
- NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
- env:
- RPC_URL: http://127.0.0.1:9933/
-
- - name: Test Report
- uses: phoenix-actions/test-reporting@v8
- id: test-report
- if: success() || failure() # run this step even if previous step failed
- with:
- name: Tests ${{ matrix.network }} # Name of the check run which will be created
- path: tests/mochawesome-report/test-*.json # Path to test results
- reporter: mochawesome-json
- fail-on-error: 'false'
-
- - name: Read output variables
- run: |
- echo "url is ${{ steps.test-report.outputs.runHtmlUrl }}"
-
- - name: Stop running containers
- if: always() # run this step always
- run: docker-compose -f ".docker/docker-compose-master.yml" -f ".docker/docker-compose.${{ matrix.network }}.yml" down
--- a/.github/workflows/codestyle.yml
+++ b/.github/workflows/codestyle.yml
@@ -49,7 +49,7 @@
run: cargo fmt -- --check # In that mode it returns only exit code.
- name: Cargo fmt state
if: success()
- run: echo "Nothing to do. Cargo fmt returned exit code 0."
+ run: echo "Nothing to do. Command 'cargo fmt -- --check' returned exit code 0."
clippy:
--- a/.github/workflows/dev-build-tests.yml
+++ b/.github/workflows/dev-build-tests.yml
@@ -123,66 +123,3 @@
- name: Stop running containers
if: always() # run this step always
run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.${{ matrix.network }}.yml" down
-
-
- dev_build_unit_test:
- # The type of runner that the job will run on
- runs-on: [self-hosted-ci,medium]
- timeout-minutes: 1380
-
- name: unit tests
-
-
- continue-on-error: true #Do not stop testing of matrix runs failed. As it decided during PR review - it required 50/50& Let's check it with false.
-
-
- steps:
- - name: Skip if pull request is in Draft
- # `if: github.event.pull_request.draft == true` should be kept here, at
- # the step level, rather than at the job level. The latter is not
- # recommended because when the PR is moved from "Draft" to "Ready to
- # review" the workflow will immediately be passing (since it was skipped),
- # even though it hasn't actually ran, since it takes a few seconds for
- # the workflow to start. This is also disclosed in:
- # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
- # That scenario would open an opportunity for the check to be bypassed:
- # 1. Get your PR approved
- # 2. Move it to Draft
- # 3. Push whatever commits you want
- # 4. Move it to "Ready for review"; now the workflow is passing (it was
- # skipped) and "Check reviews" is also passing (it won't be updated
- # until the workflow is finished)
- if: github.event.pull_request.draft == true
- run: exit 1
-
- - name: Clean Workspace
- uses: AutoModality/action-clean@v1.1.0
-
- # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- - uses: actions/checkout@v3
- with:
- ref: ${{ github.head_ref }} #Checking out head commit
-
- - name: Read .env file
- uses: xom9ikk/dotenv@v1.0.2
-
- - name: Generate ENV related extend file for docker-compose
- uses: cuchi/jinja2-action@v1.2.0
- with:
- template: .docker/docker-compose.tmp-unit.j2
- output_file: .docker/docker-compose.unit.yml
- variables: |
- RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
- FEATURE=${{ matrix.features }}
-
-
- - name: Show build configuration
- run: cat .docker/docker-compose.unit.yml
-
- - name: Build the stack
- run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.unit.yml" up -d --build --remove-orphans
-
-
- - name: Stop running containers
- if: always() # run this step always
- run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.unit.yml" down
--- /dev/null
+++ b/.github/workflows/nodes-only-update.yml
@@ -0,0 +1,301 @@
+name: nodes-only update
+
+# Controls when the action will run.
+on:
+ # Triggers the workflow on push or pull request events but only for the master branch
+ pull_request:
+ branches:
+ - master
+ types:
+ - opened
+ - reopened
+ - synchronize #commit(s) pushed to the pull request
+ - ready_for_review
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+#Define Workflow variables
+env:
+ REPO_URL: ${{ github.server_url }}/${{ github.repository }}
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
+
+ prepare-execution-marix:
+
+ name: Prepare execution matrix
+
+ runs-on: self-hosted-ci
+ outputs:
+ matrix: ${{ steps.create_matrix.outputs.matrix }}
+
+ steps:
+
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v1.0.2
+
+ - name: Create Execution matrix
+ uses: fabiocaccamo/create-matrix-action@v2
+ id: create_matrix
+ with:
+ matrix: |
+ network {opal}, runtime {opal}, features {opal-runtime}, mainnet_branch {${{ env.QUARTZ_MAINNET_TAG }}}
+ network {quartz}, runtime {quartz}, features {quartz-runtime}, mainnet_branch {${{ env.QUARTZ_MAINNET_TAG }}}
+ network {unique}, runtime {unique}, features {unique-runtime}, mainnet_branch {${{ env.UNIQUE_MAINNET_TAG }}}
+
+
+
+ forkless-update-nodata:
+ needs: prepare-execution-marix
+ # The type of runner that the job will run on
+ runs-on: [self-hosted-ci,large]
+
+
+
+ timeout-minutes: 1380
+
+ name: ${{ matrix.network }}
+
+ continue-on-error: true #Do not stop testing of matrix runs failed. As it decided during PR review - it required 50/50& Let's check it with false.
+
+ strategy:
+ matrix:
+ include: ${{fromJson(needs.prepare-execution-marix.outputs.matrix)}}
+
+
+ steps:
+ - name: Skip if pull request is in Draft
+ # `if: github.event.pull_request.draft == true` should be kept here, at
+ # the step level, rather than at the job level. The latter is not
+ # recommended because when the PR is moved from "Draft" to "Ready to
+ # review" the workflow will immediately be passing (since it was skipped),
+ # even though it hasn't actually ran, since it takes a few seconds for
+ # the workflow to start. This is also disclosed in:
+ # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
+ # That scenario would open an opportunity for the check to be bypassed:
+ # 1. Get your PR approved
+ # 2. Move it to Draft
+ # 3. Push whatever commits you want
+ # 4. Move it to "Ready for review"; now the workflow is passing (it was
+ # skipped) and "Check reviews" is also passing (it won't be updated
+ # until the workflow is finished)
+ if: github.event.pull_request.draft == true
+ run: exit 1
+
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v1.0.2
+
+ - name: Generate ENV related extend file for docker-compose
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/docker-compose.tmp-node.j2
+ output_file: .docker/docker-compose.node.${{ matrix.network }}.yml
+ variables: |
+ REPO_URL=${{ github.server_url }}/${{ github.repository }}.git
+ RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+ POLKADOT_BUILD_BRANCH=${{ env.POLKADOT_BUILD_BRANCH }}
+ POLKADOT_MAINNET_BRANCH=${{ env.POLKADOT_MAINNET_BRANCH }}
+ MAINNET_TAG=${{ matrix.mainnet_tag }}
+ MAINNET_BRANCH=${{ matrix.mainnet_branch }}
+ FEATURE=${{ matrix.features }}
+ RUNTIME=${{ matrix.runtime }}
+ BRANCH=${{ github.head_ref }}
+
+ - name: Show build configuration
+ run: cat .docker/docker-compose.node.${{ matrix.network }}.yml
+
+ - name: Generate launch-config-forkless-nodata.json
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/forkless-config/launch-config-forkless-nodata.j2
+ output_file: .docker/launch-config-forkless-nodata.json
+ variables: |
+ FEATURE=${{ matrix.features }}
+ RUNTIME=${{ matrix.runtime }}
+
+ - name: Show launch-config-forkless configuration
+ run: cat .docker/launch-config-forkless-nodata.json
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 16
+
+ - name: Build the stack
+ run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" up -d --build --remove-orphans --force-recreate --timeout 300
+
+ # 🚀 POLKADOT LAUNCH COMPLETE 🚀
+ - name: Check if docker logs consist messages related to testing of Node Parachain Upgrade.
+ if: success()
+ run: |
+ counter=160
+ function check_container_status {
+ docker inspect -f {{.State.Running}} node-parachain
+ }
+ function do_docker_logs {
+ docker logs --details node-parachain 2>&1
+ }
+ function is_started {
+ if [ "$(check_container_status)" == "true" ]; then
+ echo "Container: node-parachain RUNNING";
+ echo "Check Docker logs"
+ DOCKER_LOGS=$(do_docker_logs)
+ if [[ ${DOCKER_LOGS} = *"POLKADOT LAUNCH COMPLETE"* ]];then
+ echo "🚀 POLKADOT LAUNCH COMPLETE 🚀"
+ return 0
+ else
+ echo "Message not found in logs output, repeating..."
+ return 1
+ fi
+ else
+ echo "Container node-parachain NOT RUNNING"
+ echo "Halting all future checks"
+ exit 1
+ fi
+ echo "something goes wrong"
+ exit 1
+ }
+ while ! is_started; do
+ echo "Waiting for special message in log files "
+ sleep 30s
+ counter=$(( $counter - 1 ))
+ echo "Counter: $counter"
+ if [ "$counter" -gt "0" ]; then
+ continue
+ else
+ break
+ fi
+ done
+ echo "Halting script"
+ exit 0
+ shell: bash
+
+ - name: Run tests before Node Parachain upgrade
+ working-directory: tests
+ run: |
+ yarn install
+ yarn add mochawesome
+ echo "Ready to start tests"
+ NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
+ env:
+ RPC_URL: http://127.0.0.1:9933/
+
+ - name: Test Report Before Node upgrade
+ uses: phoenix-actions/test-reporting@v8
+ id: test-report-before
+ if: success() || failure() # run this step even if previous step failed
+ with:
+ name: Tests before node upgrade ${{ matrix.network }} # Name of the check run which will be created
+ path: tests/mochawesome-report/test-*.json # Path to test results
+ reporter: mochawesome-json
+ fail-on-error: 'false'
+
+ - name: Send SIGUSR1 to polkadotlaunch process
+ if: success() || failure()
+ run: |
+ #Get PID of polkadot-launch
+ PID=$(docker exec node-parachain pidof 'polkadot-launch')
+ echo "Polkadot-launch PID: $PID"
+ #Send SIGUSR1 signal to $PID
+ docker exec node-parachain kill -SIGUSR1 ${PID}
+
+ # 🌗 All parachain collators restarted with the new binaries.
+ - name: Check if docker logs consist messages related to testing of Node Parachain Upgrade.
+ if: success()
+ run: |
+ counter=160
+ function check_container_status {
+ docker inspect -f {{.State.Running}} node-parachain
+ }
+ function do_docker_logs {
+ docker logs --details node-parachain 2>&1
+ }
+ function is_started {
+ if [ "$(check_container_status)" == "true" ]; then
+ echo "Container: node-parachain RUNNING";
+ echo "Check Docker logs"
+ DOCKER_LOGS=$(do_docker_logs)
+ if [[ ${DOCKER_LOGS} = *"All parachain collators restarted with the new binaries."* ]];then
+ echo "🌗 All parachain collators restarted with the new binaries."
+ return 0
+ else
+ echo "Message not found in logs output, repeating..."
+ return 1
+ fi
+ else
+ echo "Container node-parachain NOT RUNNING"
+ echo "Halting all future checks"
+ exit 1
+ fi
+ echo "something goes wrong"
+ exit 1
+ }
+ while ! is_started; do
+ echo "Waiting for special message in log files "
+ sleep 30s
+ counter=$(( $counter - 1 ))
+ echo "Counter: $counter"
+ if [ "$counter" -gt "0" ]; then
+ continue
+ else
+ break
+ fi
+ done
+ echo "Halting script"
+ exit 0
+ shell: bash
+
+ - name: Run tests after Node Parachain upgrade
+ working-directory: tests
+ run: |
+ yarn install
+ yarn add mochawesome
+ echo "Ready to start tests"
+ NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
+ env:
+ RPC_URL: http://127.0.0.1:9933/
+
+ - name: Test Report After Node upgrade
+ uses: phoenix-actions/test-reporting@v8
+ id: test-report-after
+ if: success() || failure() # run this step even if previous step failed
+ with:
+ name: Tests after node upgrade ${{ matrix.network }} # Name of the check run which will be created
+ path: tests/mochawesome-report/test-*.json # Path to test results
+ reporter: mochawesome-json
+ fail-on-error: 'false'
+
+
+ - name: Stop running containers
+ if: always() # run this step always
+ run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" down --volumes
+
+ - name: Remove builder cache
+ if: always() # run this step always
+ run: |
+ docker builder prune -f
+ docker system prune -f
+
+ - name: Clean Workspace
+ if: always()
+ uses: AutoModality/action-clean@v1.1.0
--- /dev/null
+++ b/.github/workflows/unit-test.yml
@@ -0,0 +1,84 @@
+name: unit tests
+
+# Controls when the action will run.
+on:
+ # Triggers the workflow on push or pull request events but only for the master branch
+ pull_request:
+ branches:
+ - develop
+ - master
+ types:
+ - opened
+ - reopened
+ - synchronize #commit(s) pushed to the pull request
+ - ready_for_review
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
+
+ unit_tests:
+ # The type of runner that the job will run on
+ runs-on: [self-hosted-ci,medium]
+ timeout-minutes: 1380
+
+ name: ${{ github.base_ref }}
+
+ continue-on-error: true #Do not stop testing of matrix runs failed. As it decided during PR review - it required 50/50& Let's check it with false.
+
+
+ steps:
+ - name: Skip if pull request is in Draft
+ # `if: github.event.pull_request.draft == true` should be kept here, at
+ # the step level, rather than at the job level. The latter is not
+ # recommended because when the PR is moved from "Draft" to "Ready to
+ # review" the workflow will immediately be passing (since it was skipped),
+ # even though it hasn't actually ran, since it takes a few seconds for
+ # the workflow to start. This is also disclosed in:
+ # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
+ # That scenario would open an opportunity for the check to be bypassed:
+ # 1. Get your PR approved
+ # 2. Move it to Draft
+ # 3. Push whatever commits you want
+ # 4. Move it to "Ready for review"; now the workflow is passing (it was
+ # skipped) and "Check reviews" is also passing (it won't be updated
+ # until the workflow is finished)
+ if: github.event.pull_request.draft == true
+ run: exit 1
+
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v1.0.2
+
+ - name: Generate ENV related extend file for docker-compose
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/docker-compose.tmp-unit.j2
+ output_file: .docker/docker-compose.unit.yml
+ variables: |
+ RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+ FEATURE=${{ matrix.features }}
+
+
+ - name: Show build configuration
+ run: cat .docker/docker-compose.unit.yml
+
+ - name: Build the stack
+ run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.unit.yml" up --build --force-recreate --timeout 300 --remove-orphans --exit-code-from node-dev
+
+ - name: Stop running containers
+ if: always() # run this step always
+ run: docker-compose -f ".docker/docker-compose-dev.yaml" -f ".docker/docker-compose.unit.yml" down
--- a/.maintain/frame-weight-template.hbs
+++ b/.maintain/frame-weight-template.hbs
@@ -14,6 +14,7 @@
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
+#![allow(missing_docs)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1772,41 +1772,6 @@
]
[[package]]
-name = "darling"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c"
-dependencies = [
- "darling_core",
- "darling_macro",
-]
-
-[[package]]
-name = "darling_core"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610"
-dependencies = [
- "fnv",
- "ident_case",
- "proc-macro2",
- "quote",
- "strsim",
- "syn",
-]
-
-[[package]]
-name = "darling_macro"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835"
-dependencies = [
- "darling_core",
- "quote",
- "syn",
-]
-
-[[package]]
name = "data-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2204,27 +2169,27 @@
[[package]]
name = "evm-coder"
-version = "0.1.1"
+version = "0.1.3"
dependencies = [
"ethereum",
- "evm-coder-macros",
+ "evm-coder-procedural",
"evm-core",
"hex",
"hex-literal",
"impl-trait-for-tuples",
"primitive-types",
+ "sp-std",
]
[[package]]
-name = "evm-coder-macros"
-version = "0.1.0"
+name = "evm-coder-procedural"
+version = "0.2.0"
dependencies = [
"Inflector",
- "darling",
"hex",
"proc-macro2",
"quote",
- "sha3 0.9.1",
+ "sha3 0.10.2",
"syn",
]
@@ -2345,7 +2310,7 @@
[[package]]
name = "fc-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"async-trait",
"fc-db",
@@ -2364,7 +2329,7 @@
[[package]]
name = "fc-db"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"fp-storage",
"kvdb-rocksdb",
@@ -2380,7 +2345,7 @@
[[package]]
name = "fc-mapping-sync"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"fc-db",
"fp-consensus",
@@ -2397,7 +2362,7 @@
[[package]]
name = "fc-rpc"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2437,7 +2402,7 @@
[[package]]
name = "fc-rpc-core"
version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2578,7 +2543,7 @@
[[package]]
name = "fp-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"parity-scale-codec 3.1.5",
@@ -2590,7 +2555,7 @@
[[package]]
name = "fp-evm"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"evm",
"frame-support",
@@ -2604,7 +2569,7 @@
[[package]]
name = "fp-evm-mapping"
version = "0.1.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"frame-support",
"sp-core",
@@ -2613,7 +2578,7 @@
[[package]]
name = "fp-rpc"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2630,7 +2595,7 @@
[[package]]
name = "fp-self-contained"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"frame-support",
@@ -2646,7 +2611,7 @@
[[package]]
name = "fp-storage"
version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"parity-scale-codec 3.1.5",
]
@@ -3429,12 +3394,6 @@
]
[[package]]
-name = "ident_case"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
-
-[[package]]
name = "idna"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5531,7 +5490,7 @@
[[package]]
name = "pallet-base-fee"
version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"fp-evm",
"frame-support",
@@ -5638,7 +5597,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.5"
+version = "0.1.8"
dependencies = [
"ethereum",
"evm-coder",
@@ -5746,7 +5705,7 @@
[[package]]
name = "pallet-ethereum"
version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"ethereum",
"ethereum-types",
@@ -5775,7 +5734,7 @@
[[package]]
name = "pallet-evm"
version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#64915c0986fcf2bbe942794b838c0cf359c93c21"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27#69945f20e8dc06ab9e0dd636848a8db6a408c71c"
dependencies = [
"evm",
"fp-evm",
@@ -5819,7 +5778,7 @@
[[package]]
name = "pallet-evm-contract-helpers"
-version = "0.1.2"
+version = "0.2.0"
dependencies = [
"evm-coder",
"fp-evm-mapping",
@@ -5903,7 +5862,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.3"
+version = "0.1.5"
dependencies = [
"ethereum",
"evm-coder",
@@ -6145,7 +6104,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.4"
+version = "0.1.5"
dependencies = [
"ethereum",
"evm-coder",
@@ -6267,7 +6226,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.3"
+version = "0.2.4"
dependencies = [
"derivative",
"ethereum",
--- a/crates/evm-coder-macros/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "evm-coder-macros"
-version = "0.1.0"
-license = "GPLv3"
-edition = "2021"
-
-[lib]
-proc-macro = true
-
-[dependencies]
-sha3 = "0.9.1"
-quote = "1.0"
-proc-macro2 = "1.0"
-syn = { version = "1.0", features = ["full"] }
-hex = "0.4.3"
-Inflector = "0.11.4"
-darling = "0.13.0"
--- a/crates/evm-coder-macros/src/lib.rs
+++ /dev/null
@@ -1,300 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see .
-
-#![allow(dead_code)]
-
-use darling::FromMeta;
-use inflector::cases;
-use proc_macro::TokenStream;
-use quote::quote;
-use sha3::{Digest, Keccak256};
-use syn::{
- AttributeArgs, DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,
- PathSegment, Type, parse_macro_input, spanned::Spanned,
-};
-
-mod solidity_interface;
-mod to_log;
-
-fn fn_selector_str(input: &str) -> u32 {
- let mut hasher = Keccak256::new();
- hasher.update(input.as_bytes());
- let result = hasher.finalize();
-
- let mut selector_bytes = [0; 4];
- selector_bytes.copy_from_slice(&result[0..4]);
-
- u32::from_be_bytes(selector_bytes)
-}
-
-/// Returns solidity function selector (first 4 bytes of hash) by its
-/// textual representation
-///
-/// ```ignore
-/// use evm_coder_macros::fn_selector;
-///
-/// assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
-/// ```
-#[proc_macro]
-pub fn fn_selector(input: TokenStream) -> TokenStream {
- let input = input.to_string().replace(' ', "");
- let selector = fn_selector_str(&input);
-
- (quote! {
- #selector
- })
- .into()
-}
-
-fn event_selector_str(input: &str) -> [u8; 32] {
- let mut hasher = Keccak256::new();
- hasher.update(input.as_bytes());
- let result = hasher.finalize();
-
- let mut selector_bytes = [0; 32];
- selector_bytes.copy_from_slice(&result[0..32]);
- selector_bytes
-}
-
-/// Returns solidity topic (hash) by its textual representation
-///
-/// ```ignore
-/// use evm_coder_macros::event_topic;
-///
-/// assert_eq!(
-/// format!("{:x}", event_topic!(Transfer(address, address, uint256))),
-/// "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
-/// );
-/// ```
-#[proc_macro]
-pub fn event_topic(stream: TokenStream) -> TokenStream {
- let input = stream.to_string().replace(' ', "");
- let selector_bytes = event_selector_str(&input);
-
- (quote! {
- ::primitive_types::H256([#(
- #selector_bytes,
- )*])
- })
- .into()
-}
-
-fn parse_path(ty: &Type) -> syn::Result<&Path> {
- match &ty {
- syn::Type::Path(pat) => {
- if let Some(qself) = &pat.qself {
- return Err(syn::Error::new(qself.ty.span(), "no receiver expected"));
- }
- Ok(&pat.path)
- }
- _ => Err(syn::Error::new(ty.span(), "expected ty to be path")),
- }
-}
-
-fn parse_path_segment(path: &Path) -> syn::Result<&PathSegment> {
- if path.segments.len() != 1 {
- return Err(syn::Error::new(
- path.span(),
- "expected path to have only segment",
- ));
- }
- let last_segment = &path.segments.last().unwrap();
- Ok(last_segment)
-}
-
-fn parse_ident_from_pat(pat: &Pat) -> syn::Result<&Ident> {
- match pat {
- Pat::Ident(i) => Ok(&i.ident),
- _ => Err(syn::Error::new(pat.span(), "expected pat ident")),
- }
-}
-
-fn parse_ident_from_segment(segment: &PathSegment, allow_generics: bool) -> syn::Result<&Ident> {
- if segment.arguments != PathArguments::None && !allow_generics {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "unexpected generic type",
- ));
- }
- Ok(&segment.ident)
-}
-
-fn parse_ident_from_path(path: &Path, allow_generics: bool) -> syn::Result<&Ident> {
- let segment = parse_path_segment(path)?;
- parse_ident_from_segment(segment, allow_generics)
-}
-
-fn parse_ident_from_type(ty: &Type, allow_generics: bool) -> syn::Result<&Ident> {
- let path = parse_path(ty)?;
- parse_ident_from_path(path, allow_generics)
-}
-
-// Gets T out of Result
-fn parse_result_ok(ty: &Type) -> syn::Result<&Type> {
- let path = parse_path(ty)?;
- let segment = parse_path_segment(path)?;
-
- if segment.ident != "Result" {
- return Err(syn::Error::new(
- ty.span(),
- "expected Result as return type (no renamed aliases allowed)",
- ));
- }
- let args = match &segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "missing Result generics",
- ))
- }
- };
-
- let args = &args.args;
- let arg = args.first().unwrap();
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "expected first generic to be type",
- ))
- }
- };
-
- Ok(ty)
-}
-
-fn pascal_ident_to_call(ident: &Ident) -> Ident {
- let name = format!("{}Call", ident);
- Ident::new(&name, ident.span())
-}
-fn snake_ident_to_pascal(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::pascalcase::to_pascal_case(&name);
- Ident::new(&name, ident.span())
-}
-fn snake_ident_to_screaming(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::screamingsnakecase::to_screaming_snake_case(&name);
- Ident::new(&name, ident.span())
-}
-fn pascal_ident_to_snake_call(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::snakecase::to_snake_case(&name);
- let name = format!("call_{}", name);
- Ident::new(&name, ident.span())
-}
-
-/// Derives call enum implementing [`evm_coder::Callable`], [`evm_coder::Weighted`]
-/// and [`evm_coder::Call`] from impl block
-///
-/// ## Macro syntax
-///
-/// `#[solidity_interface(name, is, inline_is, events)]`
-/// - *name*: used in generated code, and for Call enum name
-/// - *is*: used to provide call inheritance, not found methods will be delegated to all contracts
-/// specified in is/inline_is
-/// - *inline_is*: same as is, but selectors for passed contracts will be used by derived ERC165
-/// implementation
-///
-/// `#[weight(value)]`
-/// Can be added to every method of impl block, used for deriving [`evm_coder::Weighted`], which
-/// is used by substrate bridge
-/// - *value*: expression, which evaluates to weight required to call this method.
-/// This expression can use call arguments to calculate non-constant execution time.
-/// This expression should evaluate faster than actual execution does, and may provide worser case
-/// than one is called
-///
-/// `#[solidity_interface(rename_selector)]`
-/// - *rename_selector*: by default, selector name will be generated by transforming method name
-/// from snake_case to camelCase. Use this option, if other naming convention is required.
-/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name
-/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`
-/// explicitly
-///
-/// Also, any contract method may have doc comments, which will be automatically added to generated
-/// solidity interface definitions
-///
-/// ## Example
-///
-/// ```ignore
-/// struct SuperContract;
-/// struct InlineContract;
-/// struct Contract;
-///
-/// #[derive(ToLog)]
-/// enum ContractEvents {
-/// Event(#[indexed] uint32),
-/// }
-///
-/// #[solidity_interface(name = "MyContract", is(SuperContract), inline_is(InlineContract))]
-/// impl Contract {
-/// /// Multiply two numbers
-/// #[weight(200 + a + b)]
-/// #[solidity_interface(rename_selector = "mul")]
-/// fn mul(&mut self, a: uint32, b: uint32) -> Result {
-/// Ok(a.checked_mul(b).ok_or("overflow")?)
-/// }
-/// }
-/// ```
-#[proc_macro_attribute]
-pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {
- let args = parse_macro_input!(args as AttributeArgs);
- let args = solidity_interface::InterfaceInfo::from_list(&args).unwrap();
-
- let input: ItemImpl = match syn::parse(stream) {
- Ok(t) => t,
- Err(e) => return e.to_compile_error().into(),
- };
-
- let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {
- Ok(v) => v.expand(),
- Err(e) => e.to_compile_error(),
- };
-
- (quote! {
- #input
-
- #expanded
- })
- .into()
-}
-
-#[proc_macro_attribute]
-pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {
- stream
-}
-#[proc_macro_attribute]
-pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {
- stream
-}
-
-/// ## Syntax
-///
-/// `#[indexed]`
-/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data
-#[proc_macro_derive(ToLog, attributes(indexed))]
-pub fn to_log(value: TokenStream) -> TokenStream {
- let input = parse_macro_input!(value as DeriveInput);
-
- match to_log::Events::try_from(&input) {
- Ok(e) => e.expand(),
- Err(e) => e.to_compile_error(),
- }
- .into()
-}
--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ /dev/null
@@ -1,1005 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see .
-
-#![allow(dead_code)]
-
-use quote::quote;
-use darling::{FromMeta, ToTokens};
-use inflector::cases;
-use std::fmt::Write;
-use syn::{
- Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
- MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
- parse_str,
-};
-
-use crate::{
- fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,
- parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,
- snake_ident_to_screaming,
-};
-
-struct Is {
- name: Ident,
- pascal_call_name: Ident,
- snake_call_name: Ident,
- via: Option<(Type, Ident)>,
-}
-impl Is {
- fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result {
- let name = parse_ident_from_path(path, false)?.clone();
- Ok(Self {
- pascal_call_name: pascal_ident_to_call(&name),
- snake_call_name: pascal_ident_to_snake_call(&name),
- name,
- via,
- })
- }
- fn new(path: &Path) -> syn::Result {
- Self::new_via(path, None)
- }
-
- fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- #name(#pascal_call_name #gen_ref)
- }
- }
-
- fn expand_interface_id(&self) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());
- }
- }
-
- fn expand_supports_interface(
- &self,
- generics: &proc_macro2::TokenStream,
- ) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- <#pascal_call_name #generics>::supports_interface(interface_id)
- }
- }
-
- fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
- let name = &self.name;
- quote! {
- Self::#name(call) => call.weight()
- }
- }
-
- fn expand_variant_call(
- &self,
- call_name: &proc_macro2::Ident,
- generics: &proc_macro2::TokenStream,
- ) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- let via_typ = self
- .via
- .as_ref()
- .map(|(t, _)| quote! {#t})
- .unwrap_or_else(|| quote! {Self});
- let via_map = self
- .via
- .as_ref()
- .map(|(_, i)| quote! {.#i()})
- .unwrap_or_default();
- quote! {
- #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
- call,
- caller: c.caller,
- value: c.value,
- })
- }
- }
-
- fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {
- return Ok(Some(Self::#name(parsed_call)))
- }
- }
- }
-
- fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);
- }
- }
-
- fn expand_event_generator(&self) -> proc_macro2::TokenStream {
- let name = &self.name;
- quote! {
- #name::generate_solidity_interface(tc, is_impl);
- }
- }
-}
-
-#[derive(Default)]
-struct IsList(Vec);
-impl FromMeta for IsList {
- fn from_list(items: &[NestedMeta]) -> darling::Result {
- let mut out = Vec::new();
- for item in items {
- match item {
- NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
- // TODO: replace meta parsing with manual
- NestedMeta::Meta(Meta::List(list))
- if list.path.is_ident("via") && list.nested.len() == 3 =>
- {
- let mut data = list.nested.iter();
- let typ = match data.next().expect("len == 3") {
- NestedMeta::Lit(Lit::Str(s)) => {
- let v = s.value();
- let typ: Type = parse_str(&v)?;
- typ
- }
- _ => {
- return Err(syn::Error::new(
- item.span(),
- "via typ should be type in string",
- )
- .into())
- }
- };
- let via = match data.next().expect("len == 3") {
- NestedMeta::Meta(Meta::Path(path)) => path
- .get_ident()
- .ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
- _ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
- };
- let path = match data.next().expect("len == 3") {
- NestedMeta::Meta(Meta::Path(path)) => path,
- _ => return Err(syn::Error::new(item.span(), "path should be path").into()),
- };
-
- out.push(Is::new_via(path, Some((typ, via.clone())))?)
- }
- _ => {
- return Err(syn::Error::new(
- item.span(),
- "expected either Name or via(\"Type\", getter, Name)",
- )
- .into())
- }
- }
- }
- Ok(Self(out))
- }
-}
-
-#[derive(FromMeta)]
-pub struct InterfaceInfo {
- name: Ident,
- #[darling(default)]
- is: IsList,
- #[darling(default)]
- inline_is: IsList,
- #[darling(default)]
- events: IsList,
-}
-
-#[derive(FromMeta)]
-struct MethodInfo {
- #[darling(default)]
- rename_selector: Option,
-}
-
-enum AbiType {
- // type
- Plain(Ident),
- // (type1,type2)
- Tuple(Vec),
- // type[]
- Vec(Box),
- // type[20]
- Array(Box, usize),
-}
-impl AbiType {
- fn try_from(value: &Type) -> syn::Result {
- let value = Self::try_maybe_special_from(value)?;
- if value.is_special() {
- return Err(syn::Error::new(value.span(), "unexpected special type"));
- }
- Ok(value)
- }
- fn try_maybe_special_from(value: &Type) -> syn::Result {
- match value {
- Type::Array(arr) => {
- let wrapped = AbiType::try_from(&arr.elem)?;
- match &arr.len {
- Expr::Lit(l) => match &l.lit {
- Lit::Int(i) => {
- let num = i.base10_parse::()?;
- Ok(AbiType::Array(Box::new(wrapped), num as usize))
- }
- _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
- },
- _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
- }
- }
- Type::Path(_) => {
- let path = parse_path(value)?;
- let segment = parse_path_segment(path)?;
- if segment.ident == "Vec" {
- let args = match &segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "missing Vec generic",
- ))
- }
- };
- let args = &args.args;
- if args.len() != 1 {
- return Err(syn::Error::new(
- args.span(),
- "expected only one generic for vec",
- ));
- }
- let arg = args.first().unwrap();
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "expected first generic to be type",
- ))
- }
- };
-
- let wrapped = AbiType::try_from(ty)?;
- Ok(Self::Vec(Box::new(wrapped)))
- } else {
- if !segment.arguments.is_empty() {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "unexpected generic arguments for non-vec type",
- ));
- }
- Ok(Self::Plain(segment.ident.clone()))
- }
- }
- Type::Tuple(t) => {
- let mut out = Vec::with_capacity(t.elems.len());
- for el in t.elems.iter() {
- out.push(AbiType::try_from(el)?)
- }
- Ok(Self::Tuple(out))
- }
- _ => Err(syn::Error::new(
- value.span(),
- "unexpected type, only arrays, plain types and tuples are supported",
- )),
- }
- }
- fn is_value(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "value")
- }
- fn is_caller(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "caller")
- }
- fn is_special(&self) -> bool {
- self.is_caller() || self.is_value()
- }
- fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {
- match self {
- AbiType::Plain(t) => {
- write!(buf, "{}", t)
- }
- AbiType::Tuple(t) => {
- write!(buf, "(")?;
- for (i, t) in t.iter().enumerate() {
- if i != 0 {
- write!(buf, ",")?;
- }
- t.selector_ty_buf(buf)?;
- }
- write!(buf, ")")
- }
- AbiType::Vec(v) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[]")
- }
- AbiType::Array(v, len) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[{}]", len)
- }
- }
- }
- fn selector_ty(&self) -> String {
- let mut out = String::new();
- self.selector_ty_buf(&mut out).expect("no fmt error");
- out
- }
-}
-impl ToTokens for AbiType {
- fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
- match self {
- AbiType::Plain(t) => tokens.extend(quote! {#t}),
- AbiType::Tuple(t) => {
- tokens.extend(quote! {(
- #(#t),*
- )});
- }
- AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),
- AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),
- }
- }
-}
-
-struct MethodArg {
- name: Ident,
- camel_name: String,
- ty: AbiType,
-}
-impl MethodArg {
- fn try_from(value: &PatType) -> syn::Result {
- let name = parse_ident_from_pat(&value.pat)?.clone();
- Ok(Self {
- camel_name: cases::camelcase::to_camel_case(&name.to_string()),
- name,
- ty: AbiType::try_maybe_special_from(&value.ty)?,
- })
- }
- fn is_value(&self) -> bool {
- self.ty.is_value()
- }
- fn is_caller(&self) -> bool {
- self.ty.is_caller()
- }
- fn is_special(&self) -> bool {
- self.ty.is_special()
- }
- fn selector_ty(&self) -> String {
- assert!(!self.is_special());
- self.ty.selector_ty()
- }
-
- fn expand_call_def(&self) -> proc_macro2::TokenStream {
- assert!(!self.is_special());
- let name = &self.name;
- let ty = &self.ty;
-
- quote! {
- #name: #ty
- }
- }
-
- fn expand_parse(&self) -> proc_macro2::TokenStream {
- assert!(!self.is_special());
- let name = &self.name;
- quote! {
- #name: reader.abi_read()?
- }
- }
-
- fn expand_call_arg(&self) -> proc_macro2::TokenStream {
- if self.is_value() {
- quote! {
- c.value.clone()
- }
- } else if self.is_caller() {
- quote! {
- c.caller.clone()
- }
- } else {
- let name = &self.name;
- quote! {
- #name
- }
- }
- }
-
- fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {
- let camel_name = &self.camel_name.to_string();
- let ty = &self.ty;
- quote! {
- >::new(#camel_name)
- }
- }
-}
-
-#[derive(PartialEq)]
-enum Mutability {
- Mutable,
- View,
- Pure,
-}
-
-pub struct WeightAttr(syn::Expr);
-
-mod keyword {
- syn::custom_keyword!(weight);
-}
-
-impl syn::parse::Parse for WeightAttr {
- fn parse(input: syn::parse::ParseStream) -> syn::Result {
- input.parse::()?;
- let content;
- syn::bracketed!(content in input);
- content.parse::()?;
-
- let weight_content;
- syn::parenthesized!(weight_content in content);
- Ok(WeightAttr(weight_content.parse::()?))
- }
-}
-
-struct Method {
- name: Ident,
- camel_name: String,
- pascal_name: Ident,
- screaming_name: Ident,
- selector_str: String,
- selector: u32,
- args: Vec,
- has_normal_args: bool,
- mutability: Mutability,
- result: Type,
- weight: Option,
- docs: Vec,
-}
-impl Method {
- fn try_from(value: &ImplItemMethod) -> syn::Result {
- let mut info = MethodInfo {
- rename_selector: None,
- };
- let mut docs = Vec::new();
- let mut weight = None;
- for attr in &value.attrs {
- let ident = parse_ident_from_path(&attr.path, false)?;
- if ident == "solidity" {
- let args = attr.parse_meta().unwrap();
- info = MethodInfo::from_meta(&args).unwrap();
- } else if ident == "doc" {
- let args = attr.parse_meta().unwrap();
- let value = match args {
- Meta::NameValue(MetaNameValue {
- lit: Lit::Str(str), ..
- }) => str.value(),
- _ => unreachable!(),
- };
- docs.push(value);
- } else if ident == "weight" {
- weight = Some(syn::parse2::(attr.to_token_stream())?.0);
- }
- }
- let ident = &value.sig.ident;
- let ident_str = ident.to_string();
- if !cases::snakecase::is_snake_case(&ident_str) {
- return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));
- }
-
- let mut mutability = Mutability::Pure;
-
- if let Some(FnArg::Receiver(receiver)) = value
- .sig
- .inputs
- .iter()
- .find(|arg| matches!(arg, FnArg::Receiver(_)))
- {
- if receiver.reference.is_none() {
- return Err(syn::Error::new(
- receiver.span(),
- "receiver should be by ref",
- ));
- }
- if receiver.mutability.is_some() {
- mutability = Mutability::Mutable;
- } else {
- mutability = Mutability::View;
- }
- }
- let mut args = Vec::new();
- for typ in value
- .sig
- .inputs
- .iter()
- .filter(|arg| matches!(arg, FnArg::Typed(_)))
- {
- let typ = match typ {
- FnArg::Typed(typ) => typ,
- _ => unreachable!(),
- };
- args.push(MethodArg::try_from(typ)?);
- }
-
- if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {
- return Err(syn::Error::new(
- args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),
- "payable function should be mutable",
- ));
- }
-
- let result = match &value.sig.output {
- ReturnType::Type(_, ty) => ty,
- _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result\nif there is no value to return - specify void (which is alias to unit)")),
- };
- let result = parse_result_ok(result)?;
-
- let camel_name = info
- .rename_selector
- .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));
- let mut selector_str = camel_name.clone();
- selector_str.push('(');
- let mut has_normal_args = false;
- for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {
- if i != 0 {
- selector_str.push(',');
- }
- write!(selector_str, "{}", arg.selector_ty()).unwrap();
- has_normal_args = true;
- }
- selector_str.push(')');
- let selector = fn_selector_str(&selector_str);
-
- Ok(Self {
- name: ident.clone(),
- camel_name,
- pascal_name: snake_ident_to_pascal(ident),
- screaming_name: snake_ident_to_screaming(ident),
- selector_str,
- selector,
- args,
- has_normal_args,
- mutability,
- result: result.clone(),
- weight,
- docs,
- })
- }
- fn expand_call_def(&self) -> proc_macro2::TokenStream {
- let defs = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| a.expand_call_def());
- let pascal_name = &self.pascal_name;
-
- if self.has_normal_args {
- quote! {
- #pascal_name {
- #(
- #defs,
- )*
- }
- }
- } else {
- quote! {#pascal_name}
- }
- }
-
- fn expand_const(&self) -> proc_macro2::TokenStream {
- let screaming_name = &self.screaming_name;
- let selector = u32::to_be_bytes(self.selector);
- let selector_str = &self.selector_str;
- quote! {
- #[doc = #selector_str]
- const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];
- }
- }
-
- fn expand_interface_id(&self) -> proc_macro2::TokenStream {
- let screaming_name = &self.screaming_name;
- quote! {
- interface_id ^= u32::from_be_bytes(Self::#screaming_name);
- }
- }
-
- fn expand_parse(&self) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- let screaming_name = &self.screaming_name;
- if self.has_normal_args {
- let parsers = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| a.expand_parse());
- quote! {
- Self::#screaming_name => return Ok(Some(Self::#pascal_name {
- #(
- #parsers,
- )*
- }))
- }
- } else {
- quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }
- }
- }
-
- fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- let name = &self.name;
-
- let matcher = if self.has_normal_args {
- let names = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| &a.name);
-
- quote! {{
- #(
- #names,
- )*
- }}
- } else {
- quote! {}
- };
-
- let receiver = match self.mutability {
- Mutability::Mutable | Mutability::View => quote! {self.},
- Mutability::Pure => quote! {Self::},
- };
- let args = self.args.iter().map(|a| a.expand_call_arg());
-
- quote! {
- #call_name::#pascal_name #matcher => {
- let result = #receiver #name(
- #(
- #args,
- )*
- )?;
- (&result).to_result()
- }
- }
- }
-
- fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- if let Some(weight) = &self.weight {
- let matcher = if self.has_normal_args {
- let names = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| &a.name);
-
- quote! {{
- #(
- #names,
- )*
- }}
- } else {
- quote! {}
- };
- quote! {
- Self::#pascal_name #matcher => (#weight).into()
- }
- } else {
- let matcher = if self.has_normal_args {
- quote! {{..}}
- } else {
- quote! {}
- };
- quote! {
- Self::#pascal_name #matcher => ().into()
- }
- }
- }
-
- fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
- let camel_name = &self.camel_name;
- let mutability = match self.mutability {
- Mutability::Mutable => quote! {SolidityMutability::Mutable},
- Mutability::View => quote! { SolidityMutability::View },
- Mutability::Pure => quote! {SolidityMutability::Pure},
- };
- let result = &self.result;
-
- let args = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(MethodArg::expand_solidity_argument);
- let docs = self.docs.iter();
- let selector = format!("{} {:0>8x}", self.selector_str, self.selector);
-
- quote! {
- SolidityFunction {
- docs: &[#(#docs),*],
- selector: #selector,
- name: #camel_name,
- mutability: #mutability,
- args: (
- #(
- #args,
- )*
- ),
- result: >::default(),
- }
- }
- }
-}
-
-fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {
- if gen.params.is_empty() {
- return quote! {};
- }
- let params = gen.params.iter().map(|p| match p {
- syn::GenericParam::Type(id) => {
- let v = &id.ident;
- quote! {#v}
- }
- syn::GenericParam::Lifetime(lt) => {
- let v = <.lifetime;
- quote! {#v}
- }
- syn::GenericParam::Const(c) => {
- let i = &c.ident;
- quote! {#i}
- }
- });
- quote! { #(#params),* }
-}
-fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {
- if gen.params.is_empty() {
- return quote! {};
- }
- let list = generics_list(gen);
- quote! { <#list> }
-}
-fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {
- let list = generics_list(gen);
- if gen.params.len() == 1 {
- quote! {#list}
- } else {
- quote! { (#list) }
- }
-}
-
-pub struct SolidityInterface {
- generics: Generics,
- name: Box,
- info: InterfaceInfo,
- methods: Vec,
-}
-impl SolidityInterface {
- pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result {
- let mut methods = Vec::new();
-
- for item in &value.items {
- if let ImplItem::Method(method) = item {
- methods.push(Method::try_from(method)?)
- }
- }
- Ok(Self {
- generics: value.generics.clone(),
- name: value.self_ty.clone(),
- info,
- methods,
- })
- }
- pub fn expand(self) -> proc_macro2::TokenStream {
- let name = self.name;
-
- let solidity_name = self.info.name.to_string();
- let call_name = pascal_ident_to_call(&self.info.name);
- let generics = self.generics;
- let gen_ref = generics_reference(&generics);
- let gen_data = generics_data(&generics);
- let gen_where = &generics.where_clause;
-
- let call_sub = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|c| Is::expand_call_def(c, &gen_ref));
- let call_parse = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|is| Is::expand_parse(is, &gen_ref));
- let call_variants = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));
- let weight_variants = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(Is::expand_variant_weight);
-
- let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);
- let supports_interface = self
- .info
- .is
- .0
- .iter()
- .map(|is| Is::expand_supports_interface(is, &gen_ref));
-
- let calls = self.methods.iter().map(Method::expand_call_def);
- let consts = self.methods.iter().map(Method::expand_const);
- let interface_id = self.methods.iter().map(Method::expand_interface_id);
- let parsers = self.methods.iter().map(Method::expand_parse);
- let call_variants_this = self
- .methods
- .iter()
- .map(|m| Method::expand_variant_call(m, &call_name));
- let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);
- let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);
-
- // TODO: Inline inline_is
- let solidity_is = self
- .info
- .is
- .0
- .iter()
- .chain(self.info.inline_is.0.iter())
- .map(|is| is.name.to_string());
- let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());
- let solidity_generators = self
- .info
- .is
- .0
- .iter()
- .chain(self.info.inline_is.0.iter())
- .map(|is| Is::expand_generator(is, &gen_ref));
- let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);
-
- // let methods = self.methods.iter().map(Method::solidity_def);
-
- quote! {
- #[derive(Debug)]
- pub enum #call_name #gen_ref {
- ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),
- #(
- #calls,
- )*
- #(
- #call_sub,
- )*
- }
- impl #gen_ref #call_name #gen_ref {
- #(
- #consts
- )*
- pub fn interface_id() -> ::evm_coder::types::bytes4 {
- let mut interface_id = 0;
- #(#interface_id)*
- #(#inline_interface_id)*
- u32::to_be_bytes(interface_id)
- }
- pub fn supports_interface(interface_id: ::evm_coder::types::bytes4) -> bool {
- interface_id != u32::to_be_bytes(0xffffff) && (
- interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
- interface_id == Self::interface_id()
- #(
- || #supports_interface
- )*
- )
- }
- pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {
- use evm_coder::solidity::*;
- use core::fmt::Write;
- let interface = SolidityInterface {
- name: #solidity_name,
- selector: Self::interface_id(),
- is: &["Dummy", "ERC165", #(
- #solidity_is,
- )* #(
- #solidity_events_is,
- )* ],
- functions: (#(
- #solidity_functions,
- )*),
- };
- if is_impl {
- tc.collect("// Common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());
- } else {
- tc.collect("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());
- }
- #(
- #solidity_generators
- )*
- #(
- #solidity_event_generators
- )*
-
- let mut out = string::new();
- // In solidity interface usage (is) should be preceeded by interface definition
- // This comment helps to sort it in a set
- if #solidity_name.starts_with("Inline") {
- out.push_str("// Inline\n");
- }
- let _ = interface.format(is_impl, &mut out, tc);
- tc.collect(out);
- }
- }
- impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {
- fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result