├── .dockerignore ├── .editorconfig ├── .gitignore ├── .maintain ├── Dockerfile ├── HEADER-GPL3 ├── build-docs │ ├── build-docs.sh │ └── index.html ├── build-only-wasm.sh ├── common │ └── lib.sh ├── debian │ ├── deb-maintainer-scripts │ │ └── postinst │ ├── defaults │ └── oak-collator.service ├── deny.toml ├── docker │ ├── subkey.Dockerfile │ └── substrate.Dockerfile ├── ensure-deps.sh ├── frame-weight-template.hbs ├── generate-release-notes ├── getgoing.sh ├── github │ └── check_labels.sh ├── gitlab │ ├── check_line_width.sh │ ├── check_polkadot_companion_build.sh │ ├── check_polkadot_companion_status.sh │ ├── check_runtime.sh │ ├── check_signed.sh │ ├── generate_changelog.sh │ ├── publish_draft_release.sh │ ├── skip_if_draft.sh │ └── trigger_pipeline.sh ├── init.sh ├── kubernetes │ ├── Chart.yaml │ ├── README.md │ ├── templates │ │ ├── poddisruptionbudget.yaml │ │ ├── secrets.yaml │ │ ├── service.yaml │ │ ├── serviceaccount.yaml │ │ └── statefulset.yaml │ └── values.yaml ├── local-docker-test-network │ ├── docker-compose.yml │ ├── grafana │ │ └── provisioning │ │ │ ├── dashboards │ │ │ └── dashboards.yml │ │ │ └── datasources │ │ │ └── datasource.yml │ └── prometheus │ │ └── prometheus.yml ├── monitoring │ ├── alerting-rules │ │ ├── alerting-rule-tests.yaml │ │ └── alerting-rules.yaml │ └── grafana-dashboards │ │ ├── README_dashboard.md │ │ ├── substrate-networking.json │ │ └── substrate-service-tasks.json ├── node-template-release.sh ├── node-template-release │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── rename-crates-for-2.0.sh ├── runtime-dep.py ├── rustdoc-header.html ├── test-coverage │ └── test-coverage.sh ├── update-copyright.sh └── update-deps.sh ├── .rustfmt.toml ├── .vscode ├── launch.json └── tasks.json ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── distribution ├── neumann_alloc.json ├── neumann_vest_test_alloc.json ├── neumann_vesting.json ├── oak_alloc.json ├── oak_staging_alloc.json ├── oak_vesting.json ├── turing_alloc.json ├── turing_staging_alloc.json └── turing_vesting.json ├── docker ├── neumann │ ├── Dockerfile │ └── build.sh └── turing │ ├── Dockerfile │ └── build.sh ├── media ├── readme-parachain-post-registration.png └── readme-parachain-registration.png ├── node ├── Cargo.toml ├── build.rs ├── res │ ├── neumann-rococo-testnet.json │ ├── neumann.json │ ├── turing-staging.json │ └── turing.json └── src │ ├── chain_spec │ ├── mod.rs │ ├── neumann.rs │ ├── oak.rs │ └── turing.rs │ ├── cli.rs │ ├── command.rs │ ├── main.rs │ ├── rpc.rs │ └── service.rs ├── pallets ├── automation-price │ ├── Cargo.toml │ ├── rpc │ │ ├── Cargo.toml │ │ ├── runtime-api │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ │ └── lib.rs │ │ └── src │ │ │ └── lib.rs │ └── src │ │ ├── benchmarking.rs │ │ ├── fees.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── trigger.rs │ │ ├── types.rs │ │ └── weights.rs ├── automation-time │ ├── Cargo.toml │ ├── rpc │ │ ├── Cargo.toml │ │ ├── runtime-api │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ │ └── lib.rs │ │ └── src │ │ │ └── lib.rs │ └── src │ │ ├── autocompounding.rs │ │ ├── benchmarking.rs │ │ ├── fees.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── valve │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── traits.rs │ │ └── weights.rs ├── vesting │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs └── xcmp-handler │ ├── Cargo.toml │ ├── rpc │ ├── Cargo.toml │ ├── runtime-api │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ └── src │ │ └── lib.rs │ └── src │ ├── lib.rs │ ├── migrations │ └── mod.rs │ ├── mock.rs │ └── tests.rs ├── parachain-launch ├── config.yml ├── docker-compose.yml ├── local-2000.json ├── parachain-2000.Dockerfile ├── relaychain.Dockerfile └── rococo-local.json ├── primitives ├── Cargo.toml └── src │ ├── assets.rs │ └── lib.rs ├── resources ├── neumann-testnet-parachain.yaml ├── rococo-local.json ├── rococo-testnet-relaychain.yaml ├── rococo-testnet.json ├── rococo.json └── types.json ├── runtime ├── common │ ├── Cargo.toml │ └── src │ │ ├── constants.rs │ │ ├── fees.rs │ │ └── lib.rs ├── neumann │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── lib.rs │ │ ├── weights │ │ ├── asset_registry_weights.rs │ │ ├── mod.rs │ │ └── pallet_xcm.rs │ │ └── xcm_config.rs ├── oak │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── lib.rs │ │ ├── weights │ │ ├── asset_registry_weights.rs │ │ ├── mod.rs │ │ └── pallet_xcm.rs │ │ └── xcm_config.rs └── turing │ ├── Cargo.toml │ ├── build.rs │ └── src │ ├── lib.rs │ ├── migrations │ └── mod.rs │ ├── weights │ ├── asset_registry_weights.rs │ ├── mod.rs │ └── pallet_xcm.rs │ └── xcm_config.rs ├── rust-toolchain.toml ├── scripts ├── run-pallet-benchmarks.sh └── try-runtime.sh └── zombienets ├── neumann ├── single-chain.toml └── xcmp.toml ├── oak ├── single-chain.toml └── xcmp.toml └── turing ├── mangata.toml ├── moonbase.toml ├── shibuya.toml ├── turing-multi-collator.toml └── turing-simple.toml /.dockerignore: -------------------------------------------------------------------------------- 1 | .github 2 | .git 3 | .vscode 4 | target 5 | data 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style=space 5 | indent_size=2 6 | tab_width=2 7 | end_of_line=lf 8 | charset=utf-8 9 | trim_trailing_whitespace=true 10 | insert_final_newline = true 11 | 12 | [*.{rs,toml}] 13 | indent_style=tab 14 | indent_size=tab 15 | tab_width=4 16 | max_line_length=100 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | **/target/ 4 | # These are backup files generated by rustfmt 5 | **/*.rs.bk 6 | 7 | .DS_Store 8 | 9 | # The cache for docker container dependency 10 | .cargo 11 | 12 | # The cache for chain data in container 13 | .local 14 | /data/ 15 | 16 | # Parachain registration files 17 | genesis-state 18 | genesis-wasm 19 | 20 | # zombienet binary for MacOS to run scripts in the ./zombienets folder 21 | zombienet-macos -------------------------------------------------------------------------------- /.maintain/Dockerfile: -------------------------------------------------------------------------------- 1 | # Note: We don't use Alpine and its packaged Rust/Cargo because they're too often out of date, 2 | # preventing them from being used to build Substrate/Polkadot. 3 | 4 | FROM phusion/baseimage:0.11 as builder 5 | LABEL maintainer="chevdor@gmail.com" 6 | LABEL description="This is the build stage for Substrate. Here we create the binary." 7 | 8 | ENV DEBIAN_FRONTEND=noninteractive 9 | 10 | ARG PROFILE=release 11 | WORKDIR /substrate 12 | 13 | COPY . /substrate 14 | 15 | RUN apt-get update && \ 16 | apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold" && \ 17 | apt-get install -y cmake pkg-config libssl-dev git clang 18 | 19 | RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \ 20 | export PATH="$PATH:$HOME/.cargo/bin" && \ 21 | rustup toolchain install nightly && \ 22 | rustup target add wasm32-unknown-unknown --toolchain nightly && \ 23 | rustup default stable && \ 24 | cargo build "--$PROFILE" 25 | 26 | # ===== SECOND STAGE ====== 27 | 28 | FROM phusion/baseimage:0.11 29 | LABEL maintainer="chevdor@gmail.com" 30 | LABEL description="This is the 2nd stage: a very small image where we copy the Substrate binary." 31 | ARG PROFILE=release 32 | 33 | RUN mv /usr/share/ca* /tmp && \ 34 | rm -rf /usr/share/* && \ 35 | mv /tmp/ca-certificates /usr/share/ && \ 36 | useradd -m -u 1000 -U -s /bin/sh -d /substrate substrate && \ 37 | mkdir -p /substrate/.local/share/substrate && \ 38 | chown -R substrate:substrate /substrate/.local && \ 39 | ln -s /substrate/.local/share/substrate /data 40 | 41 | COPY --from=builder /substrate/target/$PROFILE/substrate /usr/local/bin 42 | COPY --from=builder /substrate/target/$PROFILE/subkey /usr/local/bin 43 | COPY --from=builder /substrate/target/$PROFILE/node-rpc-client /usr/local/bin 44 | COPY --from=builder /substrate/target/$PROFILE/node-template /usr/local/bin 45 | COPY --from=builder /substrate/target/$PROFILE/chain-spec-builder /usr/local/bin 46 | 47 | # checks 48 | RUN ldd /usr/local/bin/substrate && \ 49 | /usr/local/bin/substrate --version 50 | 51 | # Shrinking 52 | RUN rm -rf /usr/lib/python* && \ 53 | rm -rf /usr/bin /usr/sbin /usr/share/man 54 | 55 | USER substrate 56 | EXPOSE 30333 9933 9944 9615 57 | VOLUME ["/data"] 58 | 59 | CMD ["/usr/local/bin/substrate"] 60 | -------------------------------------------------------------------------------- /.maintain/HEADER-GPL3: -------------------------------------------------------------------------------- 1 | // This file is part of OAK-blockchain. 2 | 3 | // Copyright (C) OAK Network Ltd. 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | -------------------------------------------------------------------------------- /.maintain/build-docs/build-docs.sh: -------------------------------------------------------------------------------- 1 | cargo doc 2 | cp ./.maintain/build-docs/index.html target/doc/ 3 | -------------------------------------------------------------------------------- /.maintain/build-docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.maintain/build-only-wasm.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # Script for building only the WASM binary of the given project. 4 | 5 | set -e 6 | 7 | PROJECT_ROOT=`git rev-parse --show-toplevel` 8 | 9 | if [ "$#" -lt 1 ]; then 10 | echo "You need to pass the name of the crate you want to compile!" 11 | exit 1 12 | fi 13 | 14 | WASM_BUILDER_RUNNER="$PROJECT_ROOT/target/release/wbuild-runner/$1" 15 | 16 | if [ -z "$2" ]; then 17 | export WASM_TARGET_DIRECTORY=$(pwd) 18 | else 19 | export WASM_TARGET_DIRECTORY=$2 20 | fi 21 | 22 | if [ -d $WASM_BUILDER_RUNNER ]; then 23 | export DEBUG=false 24 | export OUT_DIR="$PROJECT_ROOT/target/release/build" 25 | cargo run --release --manifest-path="$WASM_BUILDER_RUNNER/Cargo.toml" \ 26 | | grep -vE "cargo:rerun-if-|Executing build command" 27 | else 28 | cargo build --release -p $1 29 | fi 30 | -------------------------------------------------------------------------------- /.maintain/common/lib.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | api_base="https://api.github.com/repos" 4 | 5 | # Function to take 2 git tags/commits and get any lines from commit messages 6 | # that contain something that looks like a PR reference: e.g., (#1234) 7 | sanitised_git_logs(){ 8 | git --no-pager log --pretty=format:"%s" "$1...$2" | 9 | # Only find messages referencing a PR 10 | grep -E '\(#[0-9]+\)' | 11 | # Strip any asterisks 12 | sed 's/^* //g' | 13 | # And add them all back 14 | sed 's/^/* /g' 15 | } 16 | 17 | # Returns the last published release on github 18 | # Note: we can't just use /latest because that ignores prereleases 19 | # repo: 'organization/repo' 20 | # Usage: last_github_release "$repo" 21 | last_github_release(){ 22 | i=0 23 | # Iterate over releases until we find the last release that's not just a draft 24 | while [ $i -lt 29 ]; do 25 | out=$(curl -H "Authorization: token $GITHUB_RELEASE_TOKEN" -s "$api_base/$1/releases" | jq ".[$i]") 26 | echo "$out" 27 | # Ugh when echoing to jq, we need to translate newlines into spaces :/ 28 | if [ "$(echo "$out" | tr '\r\n' ' ' | jq '.draft')" = "false" ]; then 29 | echo "$out" | tr '\r\n' ' ' | jq '.tag_name' 30 | return 31 | else 32 | i=$((i + 1)) 33 | fi 34 | done 35 | } 36 | 37 | # Checks whether a tag on github has been verified 38 | # repo: 'organization/repo' 39 | # tagver: 'v1.2.3' 40 | # Usage: check_tag $repo $tagver 41 | check_tag () { 42 | repo=$1 43 | tagver=$2 44 | tag_out=$(curl -H "Authorization: token $GITHUB_RELEASE_TOKEN" -s "$api_base/$repo/git/refs/tags/$tagver") 45 | tag_sha=$(echo "$tag_out" | jq -r .object.sha) 46 | object_url=$(echo "$tag_out" | jq -r .object.url) 47 | if [ "$tag_sha" = "null" ]; then 48 | return 2 49 | fi 50 | verified_str=$(curl -H "Authorization: token $GITHUB_RELEASE_TOKEN" -s "$object_url" | jq -r .verification.verified) 51 | if [ "$verified_str" = "true" ]; then 52 | # Verified, everything is good 53 | return 0 54 | else 55 | # Not verified. Bad juju. 56 | return 1 57 | fi 58 | } 59 | 60 | # Checks whether a given PR has a given label. 61 | # repo: 'organization/repo' 62 | # pr_id: 12345 63 | # label: B1-silent 64 | # Usage: has_label $repo $pr_id $label 65 | has_label(){ 66 | repo="$1" 67 | pr_id="$2" 68 | label="$3" 69 | 70 | # These will exist if the function is called in Gitlab. 71 | # If the function's called in Github, we should have GITHUB_ACCESS_TOKEN set 72 | # already. 73 | if [ -n "$GITHUB_RELEASE_TOKEN" ]; then 74 | GITHUB_TOKEN="$GITHUB_RELEASE_TOKEN" 75 | elif [ -n "$GITHUB_PR_TOKEN" ]; then 76 | GITHUB_TOKEN="$GITHUB_PR_TOKEN" 77 | fi 78 | 79 | out=$(curl -H "Authorization: token $GITHUB_TOKEN" -s "$api_base/$repo/pulls/$pr_id") 80 | [ -n "$(echo "$out" | tr -d '\r\n' | jq ".labels | .[] | select(.name==\"$label\")")" ] 81 | } 82 | 83 | # Formats a message into a JSON string for posting to Matrix 84 | # message: 'any plaintext message' 85 | # formatted_message: 'optional message formatted in html' 86 | # Usage: structure_message $content $formatted_content (optional) 87 | structure_message() { 88 | if [ -z "$2" ]; then 89 | body=$(jq -Rs --arg body "$1" '{"msgtype": "m.text", $body}' < /dev/null) 90 | else 91 | body=$(jq -Rs --arg body "$1" --arg formatted_body "$2" '{"msgtype": "m.text", $body, "format": "org.matrix.custom.html", $formatted_body}' < /dev/null) 92 | fi 93 | echo "$body" 94 | } 95 | 96 | # Post a message to a matrix room 97 | # body: '{body: "JSON string produced by structure_message"}' 98 | # room_id: !fsfSRjgjBWEWffws:matrix.parity.io 99 | # access_token: see https://matrix.org/docs/guides/client-server-api/ 100 | # Usage: send_message $body (json formatted) $room_id $access_token 101 | send_message() { 102 | curl -XPOST -d "$1" "https://matrix.parity.io/_matrix/client/r0/rooms/$2/send/m.room.message?access_token=$3" 103 | } 104 | 105 | # Check for runtime changes between two commits. This is defined as any changes 106 | # to bin/node/src/runtime, frame/ and primitives/sr_* trees. 107 | has_runtime_changes() { 108 | from=$1 109 | to=$2 110 | if git diff --name-only "${from}...${to}" \ 111 | | grep -q -e '^frame/' -e '^primitives/' 112 | then 113 | return 0 114 | else 115 | return 1 116 | fi 117 | } 118 | -------------------------------------------------------------------------------- /.maintain/debian/deb-maintainer-scripts/postinst: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | CONFIG_FILE=/etc/default/oak-collator 5 | 6 | if [ "$1" = "configure" ]; then 7 | getent group oak > /dev/null 2&>1 || \ 8 | addgroup --system oak 9 | 10 | getent passwd oak > /dev/null 2&>1 || \ 11 | adduser --system --home /home/oak --ingroup oak --disabled-password oak 12 | 13 | if [ ! -e $CONFIG_FILE ]; then 14 | cp /usr/share/oak-collator/oak-collator $CONFIG_FILE 15 | fi 16 | fi 17 | -------------------------------------------------------------------------------- /.maintain/debian/defaults: -------------------------------------------------------------------------------- 1 | # CONFIGURATION FILE FOR OAK-COLLATOR 2 | 3 | OAK_CLI_ARGS="" 4 | -------------------------------------------------------------------------------- /.maintain/debian/oak-collator.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description="OAK Collator" 3 | After=network.target 4 | StartLimitIntervalSec=0 5 | 6 | [Service] 7 | EnvironmentFile=-/etc/default/oak-collator 8 | ExecStart=/usr/bin/oak-collator $OAK_CLI_ARGS 9 | Type=simple 10 | Restart=on-failure 11 | RestartSec=10 12 | KillSignal=SIGHUP 13 | User=oak 14 | Group=oak 15 | 16 | [Install] 17 | WantedBy=multi-user.target 18 | -------------------------------------------------------------------------------- /.maintain/docker/subkey.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:stretch-slim 2 | 3 | # metadata 4 | ARG VCS_REF 5 | ARG BUILD_DATE 6 | 7 | LABEL io.parity.image.authors="devops-team@parity.io" \ 8 | io.parity.image.vendor="Parity Technologies" \ 9 | io.parity.image.title="parity/subkey" \ 10 | io.parity.image.description="Subkey: key generating utility for Substrate." \ 11 | io.parity.image.source="https://github.com/paritytech/substrate/blob/${VCS_REF}/.maintain/docker/subkey.Dockerfile" \ 12 | io.parity.image.revision="${VCS_REF}" \ 13 | io.parity.image.created="${BUILD_DATE}" \ 14 | io.parity.image.documentation="https://github.com/paritytech/substrate/tree/${VCS_REF}/subkey" 15 | 16 | # show backtraces 17 | ENV RUST_BACKTRACE 1 18 | 19 | # add user 20 | RUN useradd -m -u 1000 -U -s /bin/sh -d /subkey subkey 21 | 22 | # add subkey binary to docker image 23 | COPY ./subkey /usr/local/bin 24 | 25 | USER subkey 26 | 27 | # check if executable works in this container 28 | RUN /usr/local/bin/subkey --version 29 | 30 | ENTRYPOINT ["/usr/local/bin/subkey"] 31 | 32 | -------------------------------------------------------------------------------- /.maintain/docker/substrate.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:stretch-slim 2 | 3 | # metadata 4 | ARG VCS_REF 5 | ARG BUILD_DATE 6 | 7 | LABEL io.parity.image.authors="devops-team@parity.io" \ 8 | io.parity.image.vendor="Parity Technologies" \ 9 | io.parity.image.title="parity/substrate" \ 10 | io.parity.image.description="Substrate: The platform for blockchain innovators." \ 11 | io.parity.image.source="https://github.com/paritytech/substrate/blob/${VCS_REF}/.maintain/docker/Dockerfile" \ 12 | io.parity.image.revision="${VCS_REF}" \ 13 | io.parity.image.created="${BUILD_DATE}" \ 14 | io.parity.image.documentation="https://wiki.parity.io/Parity-Substrate" 15 | 16 | # show backtraces 17 | ENV RUST_BACKTRACE 1 18 | 19 | # install tools and dependencies 20 | RUN apt-get update && \ 21 | DEBIAN_FRONTEND=noninteractive apt-get upgrade -y && \ 22 | DEBIAN_FRONTEND=noninteractive apt-get install -y \ 23 | libssl1.1 \ 24 | ca-certificates \ 25 | curl && \ 26 | # apt cleanup 27 | apt-get autoremove -y && \ 28 | apt-get clean && \ 29 | find /var/lib/apt/lists/ -type f -not -name lock -delete; \ 30 | # add user 31 | useradd -m -u 1000 -U -s /bin/sh -d /substrate substrate 32 | 33 | # add substrate binary to docker image 34 | COPY ./substrate /usr/local/bin 35 | 36 | USER substrate 37 | 38 | # check if executable works in this container 39 | RUN /usr/local/bin/substrate --version 40 | 41 | EXPOSE 30333 9933 9944 42 | VOLUME ["/substrate"] 43 | 44 | ENTRYPOINT ["/usr/local/bin/substrate"] 45 | 46 | -------------------------------------------------------------------------------- /.maintain/ensure-deps.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # The script is meant to check if the rules regarding packages 4 | # dependencies are satisfied. 5 | # The general format is: 6 | # [top-lvl-dir] MESSAGE/[other-top-dir] 7 | 8 | # For instance no crate within `./client` directory 9 | # is allowed to import any crate with a directory path containing `frame`. 10 | # Such rule is just: `client crates must not depend on anything in /frame`. 11 | 12 | # The script should be run from the main repo directory! 13 | 14 | set -u 15 | 16 | # HARD FAILING 17 | MUST_NOT=( 18 | "client crates must not depend on anything in /frame" 19 | "client crates must not depend on anything in /node" 20 | "frame crates must not depend on anything in /node" 21 | "frame crates must not depend on anything in /client" 22 | "primitives crates must not depend on anything in /frame" 23 | ) 24 | 25 | # ONLY DISPLAYED, script still succeeds 26 | PLEASE_DONT=( 27 | "primitives crates should not depend on anything in /client" 28 | ) 29 | 30 | VIOLATIONS=() 31 | PACKAGES=() 32 | 33 | function check_rule() { 34 | rule=$1 35 | from=$(echo $rule | cut -f1 -d\ ) 36 | to=$(echo $rule | cut -f2 -d\/) 37 | 38 | cd $from 39 | echo "Checking rule '$rule'" 40 | packages=$(find -name Cargo.toml | xargs grep -wn "path.*\.\.\/$to") 41 | has_references=$(echo -n $packages | wc -c) 42 | if [ "$has_references" != "0" ]; then 43 | VIOLATIONS+=("$rule") 44 | # Find packages that violate: 45 | PACKAGES+=("$packages") 46 | fi 47 | cd - > /dev/null 48 | } 49 | 50 | for rule in "${MUST_NOT[@]}" 51 | do 52 | check_rule "$rule"; 53 | done 54 | 55 | # Only the MUST NOT will be counted towards failure 56 | HARD_VIOLATIONS=${#VIOLATIONS[@]} 57 | 58 | 59 | for rule in "${PLEASE_DONT[@]}" 60 | do 61 | check_rule "$rule"; 62 | done 63 | 64 | # Display violations and fail 65 | I=0 66 | for v in "${VIOLATIONS[@]}" 67 | do 68 | cat << EOF 69 | 70 | =========================================== 71 | ======= Violation of rule: $v 72 | =========================================== 73 | ${PACKAGES[$I]} 74 | 75 | 76 | EOF 77 | I=$I+1 78 | done 79 | 80 | exit $HARD_VIOLATIONS 81 | -------------------------------------------------------------------------------- /.maintain/frame-weight-template.hbs: -------------------------------------------------------------------------------- 1 | {{header}} 2 | //! Autogenerated weights for {{pallet}} 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 5 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 6 | //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` 7 | //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` 8 | //! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} 9 | 10 | // Executed Command: 11 | {{#each args as |arg|}} 12 | // {{arg}} 13 | {{/each}} 14 | 15 | // Summary: 16 | {{#each benchmarks as |benchmark|}} 17 | //:{{benchmark.name}} {{underscore benchmark.base_weight}},{{benchmark.base_calculated_proof_size}} 18 | {{/each}} 19 | 20 | #![cfg_attr(rustfmt, rustfmt_skip)] 21 | #![allow(unused_parens)] 22 | #![allow(unused_imports)] 23 | #![allow(missing_docs)] 24 | 25 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 26 | use core::marker::PhantomData; 27 | 28 | /// Weight functions needed for {{pallet}}. 29 | pub trait WeightInfo { 30 | {{#each benchmarks as |benchmark|}} 31 | fn {{benchmark.name~}} 32 | ( 33 | {{~#each benchmark.components as |c| ~}} 34 | {{c.name}}: u32, {{/each~}} 35 | ) -> Weight; 36 | {{/each}} 37 | } 38 | 39 | /// Weights for {{pallet}} using the Substrate node and recommended hardware. 40 | pub struct SubstrateWeight(PhantomData); 41 | {{#if (eq pallet "frame_system")}} 42 | impl WeightInfo for SubstrateWeight { 43 | {{else}} 44 | impl WeightInfo for SubstrateWeight { 45 | {{/if}} 46 | {{#each benchmarks as |benchmark|}} 47 | {{#each benchmark.comments as |comment|}} 48 | /// {{comment}} 49 | {{/each}} 50 | {{#each benchmark.component_ranges as |range|}} 51 | /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. 52 | {{/each}} 53 | fn {{benchmark.name~}} 54 | ( 55 | {{~#each benchmark.components as |c| ~}} 56 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 57 | ) -> Weight { 58 | // Proof Size summary in bytes: 59 | // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 60 | // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 61 | // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. 62 | Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) 63 | {{#each benchmark.component_weight as |cw|}} 64 | // Standard Error: {{underscore cw.error}} 65 | .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) 66 | {{/each}} 67 | {{#if (ne benchmark.base_reads "0")}} 68 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}_u64)) 69 | {{/if}} 70 | {{#each benchmark.component_reads as |cr|}} 71 | .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) 72 | {{/each}} 73 | {{#if (ne benchmark.base_writes "0")}} 74 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}_u64)) 75 | {{/if}} 76 | {{#each benchmark.component_writes as |cw|}} 77 | .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) 78 | {{/each}} 79 | {{#each benchmark.component_calculated_proof_size as |cp|}} 80 | .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) 81 | {{/each}} 82 | } 83 | {{/each}} 84 | } 85 | 86 | // For backwards compatibility and tests 87 | impl WeightInfo for () { 88 | {{#each benchmarks as |benchmark|}} 89 | {{#each benchmark.comments as |comment|}} 90 | /// {{comment}} 91 | {{/each}} 92 | {{#each benchmark.component_ranges as |range|}} 93 | /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. 94 | {{/each}} 95 | fn {{benchmark.name~}} 96 | ( 97 | {{~#each benchmark.components as |c| ~}} 98 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 99 | ) -> Weight { 100 | // Proof Size summary in bytes: 101 | // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 102 | // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 103 | // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. 104 | Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) 105 | {{#each benchmark.component_weight as |cw|}} 106 | // Standard Error: {{underscore cw.error}} 107 | .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) 108 | {{/each}} 109 | {{#if (ne benchmark.base_reads "0")}} 110 | .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}}_u64)) 111 | {{/if}} 112 | {{#each benchmark.component_reads as |cr|}} 113 | .saturating_add(RocksDbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) 114 | {{/each}} 115 | {{#if (ne benchmark.base_writes "0")}} 116 | .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}}_u64)) 117 | {{/if}} 118 | {{#each benchmark.component_writes as |cw|}} 119 | .saturating_add(RocksDbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) 120 | {{/each}} 121 | {{#each benchmark.component_calculated_proof_size as |cp|}} 122 | .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) 123 | {{/each}} 124 | } 125 | {{/each}} 126 | } 127 | -------------------------------------------------------------------------------- /.maintain/generate-release-notes: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | tag=$1 4 | 5 | generate_srtool_block() { 6 | digest_file=$1; shift 7 | 8 | runtime=$(cat $digest_file) 9 | rust=$(echo $runtime | jq --raw-output .rustc) 10 | spec_name=$( 11 | echo $runtime \ 12 | | jq --raw-output .runtimes.compressed.subwasm.core_version.specName 13 | ) 14 | impl_name=$( 15 | echo $runtime \ 16 | | jq --raw-output .runtimes.compressed.subwasm.core_version.implName 17 | ) 18 | spec_version=$( 19 | echo $runtime \ 20 | | jq --raw-output .runtimes.compressed.subwasm.core_version.specVersion 21 | ) 22 | impl_version=$( 23 | echo $runtime \ 24 | | jq --raw-output .runtimes.compressed.subwasm.core_version.implVersion 25 | ) 26 | authoring_version=$( 27 | echo $runtime \ 28 | | jq --raw-output .runtimes.compressed.subwasm.core_version.authoringVersion 29 | ) 30 | transaction_version=$( 31 | echo $runtime \ 32 | | jq --raw-output .runtimes.compressed.subwasm.core_version.transactionVersion 33 | ) 34 | size=$(echo $runtime| jq --raw-output .runtimes.compressed.size) 35 | proposal=$(echo $runtime | jq --raw-output .runtimes.compressed.prop) 36 | ipfs=$(echo $runtime | jq --raw-output .runtimes.compressed.ipfs) 37 | blake2_256=$(echo $runtime | jq --raw-output .runtimes.compressed.blake2_256) 38 | 39 | spec="$spec_name-$spec_version" 40 | extended="$impl_name-$impl_version.tx$transaction_version.au$authoring_version" 41 | 42 | echo "## $spec_name srtool output" 43 | echo 44 | 45 | cat <<-EOF 46 | \`\`\` 47 | Rust : $rust 48 | Spec version : $spec_version 49 | Impl version : $impl_version 50 | Tx version : $transaction_version 51 | Size : $size 52 | Proposal : $proposal 53 | IPFS : $ipfs 54 | BLAKE2_256 : $blake2_256 55 | \`\`\` 56 | EOF 57 | } 58 | 59 | notes=$( 60 | curl -s -L \ 61 | -X POST \ 62 | -H "Authorization: token $GITHUB_TOKEN" \ 63 | -H "Accept: application/vnd.github+json" \ 64 | -d '{"tag_name":"'$tag'","target_commitish":"'$tag'"}' \ 65 | https://api.github.com/repos/OAK-Foundation/OAK-blockchain/releases/generate-notes 66 | ) 67 | 68 | echo $notes | jq .body | sed -e 's/^"//' -e 's/"$//' -e 's/\\n/\n/g' 69 | echo 70 | 71 | for digest in $(ls *-srtool-digest.json); do 72 | generate_srtool_block $digest 73 | done 74 | -------------------------------------------------------------------------------- /.maintain/getgoing.sh: -------------------------------------------------------------------------------- 1 | /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 2 | brew install openssl cmake 3 | curl https://sh.rustup.rs -sSf | sh 4 | source ~/.cargo/env 5 | cargo install --git https://github.com/paritytech/substrate subkey 6 | cargo install --git https://github.com/paritytech/substrate substrate 7 | -------------------------------------------------------------------------------- /.maintain/github/check_labels.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | #shellcheck source=../common/lib.sh 5 | source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../common/lib.sh" 6 | 7 | repo="$GITHUB_REPOSITORY" 8 | pr="$GITHUB_PR" 9 | 10 | ensure_labels() { 11 | for label in "$@"; do 12 | if has_label "$repo" "$pr" "$label"; then 13 | return 0 14 | fi 15 | done 16 | return 1 17 | } 18 | 19 | # Must have one of the following labels 20 | releasenotes_labels=( 21 | 'B0-silent' 22 | 'B3-apinoteworthy' 23 | 'B5-clientnoteworthy' 24 | 'B7-runtimenoteworthy' 25 | ) 26 | 27 | criticality_labels=( 28 | 'C1-low 📌' 29 | 'C3-medium 📣' 30 | 'C7-high ❗️' 31 | 'C9-critical ‼️' 32 | ) 33 | 34 | audit_labels=( 35 | 'D1-audited 👍' 36 | 'D2-notlive 💤' 37 | 'D3-trivial 🧸' 38 | 'D5-nicetohaveaudit ⚠️' 39 | 'D9-needsaudit 👮' 40 | ) 41 | 42 | echo "[+] Checking release notes (B) labels" 43 | if ensure_labels "${releasenotes_labels[@]}"; then 44 | echo "[+] Release notes label detected. All is well." 45 | else 46 | echo "[!] Release notes label not detected. Please add one of: ${releasenotes_labels[*]}" 47 | exit 1 48 | fi 49 | 50 | echo "[+] Checking release criticality (C) labels" 51 | if ensure_labels "${criticality_labels[@]}"; then 52 | echo "[+] Release criticality label detected. All is well." 53 | else 54 | echo "[!] Release criticality label not detected. Please add one of: ${criticality_labels[*]}" 55 | exit 1 56 | fi 57 | 58 | if has_runtime_changes origin/master "${HEAD_SHA}"; then 59 | echo "[+] Runtime changes detected. Checking audit (D) labels" 60 | if ensure_labels "${audit_labels[@]}"; then 61 | echo "[+] Release audit label detected. All is well." 62 | else 63 | echo "[!] Release audit label not detected. Please add one of: ${audit_labels[*]}" 64 | exit 1 65 | fi 66 | fi 67 | 68 | exit 0 69 | -------------------------------------------------------------------------------- /.maintain/gitlab/check_line_width.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # check if line width of rust source files is not beyond x characters 4 | # 5 | set -e 6 | set -o pipefail 7 | 8 | BASE_ORIGIN="origin" 9 | BASE_BRANCH_NAME="master" 10 | LINE_WIDTH="120" 11 | GOOD_LINE_WIDTH="100" 12 | BASE_BRANCH="${BASE_ORIGIN}/${BASE_BRANCH_NAME}" 13 | git fetch ${BASE_ORIGIN} ${BASE_BRANCH_NAME} --depth 100 14 | BASE_HASH=$(git merge-base ${BASE_BRANCH} HEAD) 15 | 16 | git diff --name-only ${BASE_HASH} -- \*.rs | ( while read file 17 | do 18 | if [ ! -f ${file} ]; 19 | then 20 | echo "Skipping removed file." 21 | elif git diff ${BASE_HASH} -- ${file} | grep -q "^+.\{$(( $LINE_WIDTH + 1 ))\}" 22 | then 23 | if [ -z "${FAIL}" ] 24 | then 25 | echo "| error!" 26 | echo "| Lines must not be longer than ${LINE_WIDTH} characters." 27 | echo "| " 28 | echo "| see more https://github.com/paritytech/substrate/blob/master/docs/STYLE_GUIDE.md" 29 | echo "|" 30 | FAIL="true" 31 | fi 32 | echo "| file: ${file}" 33 | git diff ${BASE_HASH} -- ${file} \ 34 | | grep -n "^+.\{$(( $LINE_WIDTH + 1))\}" 35 | echo "|" 36 | else 37 | if git diff ${BASE_HASH} -- ${file} | grep -q "^+.\{$(( $GOOD_LINE_WIDTH + 1 ))\}" 38 | then 39 | if [ -z "${FAIL}" ] 40 | then 41 | echo "| warning!" 42 | echo "| Lines should be longer than ${GOOD_LINE_WIDTH} characters only in exceptional circumstances!" 43 | echo "| " 44 | echo "| see more https://github.com/paritytech/substrate/blob/master/docs/STYLE_GUIDE.md" 45 | echo "|" 46 | fi 47 | echo "| file: ${file}" 48 | git diff ${BASE_HASH} -- ${file} | grep -n "^+.\{$(( $GOOD_LINE_WIDTH + 1 ))\}" 49 | echo "|" 50 | fi 51 | fi 52 | done 53 | 54 | test -z "${FAIL}" 55 | ) 56 | -------------------------------------------------------------------------------- /.maintain/gitlab/check_polkadot_companion_build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | # 3 | # check if a pr is compatible with polkadot companion pr or master if not 4 | # available 5 | # 6 | # to override one that was just mentioned mark companion pr in the body of the 7 | # polkadot pr like 8 | # 9 | # polkadot companion: paritytech/polkadot#567 10 | # 11 | 12 | set -e 13 | 14 | github_api_substrate_pull_url="https://api.github.com/repos/paritytech/substrate/pulls" 15 | # use github api v3 in order to access the data without authentication 16 | github_header="Authorization: token ${GITHUB_PR_TOKEN}" 17 | 18 | boldprint () { printf "|\n| \033[1m${@}\033[0m\n|\n" ; } 19 | boldcat () { printf "|\n"; while read l; do printf "| \033[1m${l}\033[0m\n"; done; printf "|\n" ; } 20 | 21 | 22 | 23 | boldcat <<-EOT 24 | 25 | 26 | check_polkadot_companion_build 27 | ============================== 28 | 29 | this job checks if there is a string in the description of the pr like 30 | 31 | polkadot companion: paritytech/polkadot#567 32 | 33 | 34 | it will then run cargo check from this polkadot's branch with substrate code 35 | from this pull request. otherwise, it will uses master instead 36 | 37 | 38 | EOT 39 | 40 | # Set the user name and email to make merging work 41 | git config --global user.name 'CI system' 42 | git config --global user.email '<>' 43 | 44 | # Merge master into our branch before building Polkadot to make sure we don't miss 45 | # any commits that are required by Polkadot. 46 | git fetch --depth 100 origin 47 | git merge origin/master 48 | 49 | # Clone the current Polkadot master branch into ./polkadot. 50 | # NOTE: we need to pull enough commits to be able to find a common 51 | # ancestor for successfully performing merges below. 52 | git clone --depth 20 https://github.com/paritytech/polkadot.git 53 | 54 | cd polkadot 55 | 56 | # either it's a pull request then check for a companion otherwise use 57 | # polkadot:master 58 | if expr match "${CI_COMMIT_REF_NAME}" '^[0-9]\+$' >/dev/null 59 | then 60 | boldprint "this is pull request no ${CI_COMMIT_REF_NAME}" 61 | 62 | pr_data_file="$(mktemp)" 63 | # get the last reference to a pr in polkadot 64 | curl -sSL -H "${github_header}" -o "${pr_data_file}" \ 65 | "${github_api_substrate_pull_url}/${CI_COMMIT_REF_NAME}" 66 | 67 | pr_body="$(sed -n -r 's/^[[:space:]]+"body": (".*")[^"]+$/\1/p' "${pr_data_file}")" 68 | 69 | pr_companion="$(echo "${pr_body}" | sed -n -r \ 70 | -e 's;^.*[Cc]ompanion.*paritytech/polkadot#([0-9]+).*$;\1;p' \ 71 | -e 's;^.*[Cc]ompanion.*https://github.com/paritytech/polkadot/pull/([0-9]+).*$;\1;p' \ 72 | | tail -n 1)" 73 | 74 | if [ "${pr_companion}" ] 75 | then 76 | boldprint "companion pr specified/detected: #${pr_companion}" 77 | git fetch origin refs/pull/${pr_companion}/head:pr/${pr_companion} 78 | git checkout pr/${pr_companion} 79 | git merge origin/master 80 | else 81 | boldprint "no companion branch found - building polkadot:master" 82 | fi 83 | rm -f "${pr_data_file}" 84 | else 85 | boldprint "this is not a pull request - building polkadot:master" 86 | fi 87 | 88 | # Patch all Substrate crates in Polkadot 89 | diener patch --crates-to-patch ../ --substrate --path Cargo.toml 90 | 91 | # Test Polkadot pr or master branch with this Substrate commit. 92 | time cargo test --all --release --verbose 93 | -------------------------------------------------------------------------------- /.maintain/gitlab/check_polkadot_companion_status.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # check for a polkadot companion pr and ensure it has approvals and is 4 | # mergeable 5 | # 6 | 7 | github_api_substrate_pull_url="https://api.github.com/repos/paritytech/substrate/pulls" 8 | github_api_polkadot_pull_url="https://api.github.com/repos/paritytech/polkadot/pulls" 9 | # use github api v3 in order to access the data without authentication 10 | github_header="Authorization: token ${GITHUB_PR_TOKEN}" 11 | 12 | boldprint () { printf "|\n| \033[1m${@}\033[0m\n|\n" ; } 13 | boldcat () { printf "|\n"; while read l; do printf "| \033[1m${l}\033[0m\n"; done; printf "|\n" ; } 14 | 15 | 16 | 17 | boldcat <<-EOT 18 | 19 | 20 | check_polkadot_companion_status 21 | =============================== 22 | 23 | this job checks if there is a string in the description of the pr like 24 | 25 | polkadot companion: paritytech/polkadot#567 26 | 27 | and checks its status. 28 | 29 | 30 | EOT 31 | 32 | 33 | if ! [ "${CI_COMMIT_REF_NAME}" -gt 0 2>/dev/null ] 34 | then 35 | boldprint "this doesn't seem to be a pull request" 36 | exit 1 37 | fi 38 | 39 | boldprint "this is pull request no ${CI_COMMIT_REF_NAME}" 40 | 41 | pr_body="$(curl -H "${github_header}" -s ${github_api_substrate_pull_url}/${CI_COMMIT_REF_NAME} \ 42 | | sed -n -r 's/^[[:space:]]+"body": (".*")[^"]+$/\1/p')" 43 | 44 | # get companion if explicitly specified 45 | pr_companion="$(echo "${pr_body}" | sed -n -r \ 46 | -e 's;^.*[Cc]ompanion.*paritytech/polkadot#([0-9]+).*$;\1;p' \ 47 | -e 's;^.*[Cc]ompanion.*https://github.com/paritytech/polkadot/pull/([0-9]+).*$;\1;p' \ 48 | | tail -n 1)" 49 | 50 | if [ -z "${pr_companion}" ] 51 | then 52 | boldprint "no companion pr found" 53 | exit 0 54 | fi 55 | 56 | boldprint "companion pr: #${pr_companion}" 57 | 58 | # check the status of that pull request - needs to be 59 | # approved and mergable 60 | 61 | curl -H "${github_header}" -sS -o companion_pr.json \ 62 | ${github_api_polkadot_pull_url}/${pr_companion} 63 | 64 | pr_head_sha=$(jq -r -e '.head.sha' < companion_pr.json) 65 | boldprint "Polkadot PR's HEAD SHA: $pr_head_sha" 66 | 67 | curl -H "${github_header}" -sS -o companion_pr_reviews.json \ 68 | ${github_api_polkadot_pull_url}/${pr_companion}/reviews 69 | 70 | # If there are any 'CHANGES_REQUESTED' reviews for the *current* review 71 | jq -r -e '.[] | select(.state == "CHANGES_REQUESTED").commit_id' \ 72 | < companion_pr_reviews.json > companion_pr_reviews_current.json 73 | while IFS= read -r line; do 74 | if [ "$line" = "$pr_head_sha" ]; then 75 | boldprint "polkadot pr #${pr_companion} has CHANGES_REQUESTED for the latest commit" 76 | exit 1 77 | fi 78 | done < companion_pr_reviews_current.json 79 | 80 | # Then we check for at least 1 APPROVED 81 | if [ -z "$(jq -r -e '.[].state | select(. == "APPROVED")' < companion_pr_reviews.json)" ]; then 82 | boldprint "polkadot pr #${pr_companion} not APPROVED" 83 | exit 1 84 | fi 85 | 86 | boldprint "polkadot pr #${pr_companion} state APPROVED" 87 | 88 | if jq -e .merged < companion_pr.json >/dev/null 89 | then 90 | boldprint "polkadot pr #${pr_companion} already merged" 91 | exit 0 92 | fi 93 | 94 | if jq -e '.mergeable' < companion_pr.json >/dev/null 95 | then 96 | boldprint "polkadot pr #${pr_companion} mergeable" 97 | else 98 | boldprint "polkadot pr #${pr_companion} not mergeable" 99 | exit 1 100 | fi 101 | 102 | exit 0 103 | -------------------------------------------------------------------------------- /.maintain/gitlab/check_runtime.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # 4 | # check for any changes in the node/src/runtime, frame/ and primitives/sr_* trees. if 5 | # there are any changes found, it should mark the PR breaksconsensus and 6 | # "auto-fail" the PR if there isn't a change in the runtime/src/lib.rs file 7 | # that alters the version. 8 | 9 | set -e # fail on any error 10 | 11 | #shellcheck source=../common/lib.sh 12 | . "$(dirname "${0}")/../common/lib.sh" 13 | 14 | VERSIONS_FILE="bin/node/runtime/src/lib.rs" 15 | 16 | boldprint () { printf "|\n| \033[1m%s\033[0m\n|\n" "${@}"; } 17 | boldcat () { printf "|\n"; while read -r l; do printf "| \033[1m%s\033[0m\n" "${l}"; done; printf "|\n" ; } 18 | 19 | github_label () { 20 | echo 21 | echo "# run github-api job for labeling it ${1}" 22 | curl -sS -X POST \ 23 | -F "token=${CI_JOB_TOKEN}" \ 24 | -F "ref=master" \ 25 | -F "variables[LABEL]=${1}" \ 26 | -F "variables[PRNO]=${CI_COMMIT_REF_NAME}" \ 27 | "${GITLAB_API}/projects/${GITHUB_API_PROJECT}/trigger/pipeline" 28 | } 29 | 30 | 31 | boldprint "latest 10 commits of ${CI_COMMIT_REF_NAME}" 32 | git log --graph --oneline --decorate=short -n 10 33 | 34 | boldprint "make sure the master branch and release tag are available in shallow clones" 35 | git fetch --depth="${GIT_DEPTH:-100}" origin master 36 | git fetch --depth="${GIT_DEPTH:-100}" origin release 37 | git tag -f release FETCH_HEAD 38 | git log -n1 release 39 | 40 | 41 | boldprint "check if the wasm sources changed" 42 | if ! has_runtime_changes origin/master "${CI_COMMIT_SHA}" 43 | then 44 | boldcat <<-EOT 45 | 46 | no changes to the runtime source code detected 47 | 48 | EOT 49 | 50 | exit 0 51 | fi 52 | 53 | 54 | 55 | # check for spec_version updates: if the spec versions changed, then there is 56 | # consensus-critical logic that has changed. the runtime wasm blobs must be 57 | # rebuilt. 58 | 59 | add_spec_version="$(git diff "tags/release...${CI_COMMIT_SHA}" "${VERSIONS_FILE}" \ 60 | | sed -n -r "s/^\+[[:space:]]+spec_version: +([0-9]+),$/\1/p")" 61 | sub_spec_version="$(git diff "tags/release...${CI_COMMIT_SHA}" "${VERSIONS_FILE}" \ 62 | | sed -n -r "s/^\-[[:space:]]+spec_version: +([0-9]+),$/\1/p")" 63 | 64 | 65 | 66 | if [ "${add_spec_version}" != "${sub_spec_version}" ] 67 | then 68 | 69 | boldcat <<-EOT 70 | 71 | changes to the runtime sources and changes in the spec version. 72 | 73 | spec_version: ${sub_spec_version} -> ${add_spec_version} 74 | 75 | EOT 76 | exit 0 77 | 78 | else 79 | # check for impl_version updates: if only the impl versions changed, we assume 80 | # there is no consensus-critical logic that has changed. 81 | 82 | add_impl_version="$(git diff "tags/release...${CI_COMMIT_SHA}" "${VERSIONS_FILE}" \ 83 | | sed -n -r 's/^\+[[:space:]]+impl_version: +([0-9]+),$/\1/p')" 84 | sub_impl_version="$(git diff "tags/release...${CI_COMMIT_SHA}" "${VERSIONS_FILE}" \ 85 | | sed -n -r 's/^\-[[:space:]]+impl_version: +([0-9]+),$/\1/p')" 86 | 87 | 88 | # see if the impl version changed 89 | if [ "${add_impl_version}" != "${sub_impl_version}" ] 90 | then 91 | boldcat <<-EOT 92 | 93 | changes to the runtime sources and changes in the impl version. 94 | 95 | impl_version: ${sub_impl_version} -> ${add_impl_version} 96 | 97 | EOT 98 | exit 0 99 | fi 100 | 101 | 102 | boldcat <<-EOT 103 | 104 | wasm source files changed but not the spec/impl version. If changes made do not alter logic, 105 | just bump 'impl_version'. If they do change logic, bump 'spec_version'. 106 | 107 | source file directories: 108 | - bin/node/src/runtime 109 | - frame 110 | - primitives/sr-* 111 | 112 | versions file: ${VERSIONS_FILE} 113 | 114 | EOT 115 | fi 116 | 117 | # dropped through. there's something wrong; exit 1. 118 | 119 | exit 1 120 | 121 | # vim: noexpandtab 122 | -------------------------------------------------------------------------------- /.maintain/gitlab/check_signed.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # shellcheck source=../common/lib.sh 4 | source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../common/lib.sh" 5 | 6 | version="$CI_COMMIT_TAG" 7 | 8 | echo '[+] Checking tag has been signed' 9 | check_tag "paritytech/substrate" "$version" 10 | case $? in 11 | 0) echo '[+] Tag found and has been signed'; exit 0 12 | ;; 13 | 1) echo '[!] Tag found but has not been signed. Aborting release.'; exit 1 14 | ;; 15 | 2) echo '[!] Tag not found. Aborting release.'; exit 1 16 | esac 17 | -------------------------------------------------------------------------------- /.maintain/gitlab/generate_changelog.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # shellcheck source=../common/lib.sh 4 | source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../common/lib.sh" 5 | 6 | version="$2" 7 | last_version="$1" 8 | 9 | all_changes="$(sanitised_git_logs "$last_version" "$version")" 10 | runtime_changes="" 11 | api_changes="" 12 | client_changes="" 13 | changes="" 14 | migrations="" 15 | 16 | while IFS= read -r line; do 17 | pr_id=$(echo "$line" | sed -E 's/.*#([0-9]+)\)$/\1/') 18 | 19 | # Skip if the PR has the silent label - this allows us to skip a few requests 20 | if has_label 'paritytech/substrate' "$pr_id" 'B0-silent'; then 21 | continue 22 | fi 23 | if has_label 'paritytech/substrate' "$pr_id" 'B3-apinoteworthy' ; then 24 | api_changes="$api_changes 25 | $line" 26 | fi 27 | if has_label 'paritytech/substrate' "$pr_id" 'B5-clientnoteworthy'; then 28 | client_changes="$client_changes 29 | $line" 30 | fi 31 | if has_label 'paritytech/substrate' "$pr_id" 'B7-runtimenoteworthy'; then 32 | runtime_changes="$runtime_changes 33 | $line" 34 | fi 35 | if has_label 'paritytech/substrate' "$pr_id" 'E1-runtime-migration'; then 36 | migrations="$migrations 37 | $line" 38 | fi 39 | done <<< "$all_changes" 40 | 41 | # Make the substrate section if there are any substrate changes 42 | if [ -n "$runtime_changes" ] || 43 | [ -n "$api_changes" ] || 44 | [ -n "$client_changes" ] || 45 | [ -n "$migrations" ]; then 46 | changes=$(cat << EOF 47 | Substrate changes 48 | ----------------- 49 | 50 | EOF 51 | ) 52 | if [ -n "$runtime_changes" ]; then 53 | changes="$changes 54 | 55 | Runtime 56 | ------- 57 | $runtime_changes" 58 | fi 59 | if [ -n "$client_changes" ]; then 60 | changes="$changes 61 | 62 | Client 63 | ------ 64 | $client_changes" 65 | fi 66 | if [ -n "$api_changes" ]; then 67 | changes="$changes 68 | 69 | API 70 | --- 71 | $api_changes" 72 | fi 73 | release_text="$release_text 74 | 75 | $changes" 76 | fi 77 | if [ -n "$migrations" ]; then 78 | changes="$changes 79 | 80 | Runtime Migrations 81 | ------------------ 82 | $migrations" 83 | fi 84 | 85 | echo "$changes" 86 | -------------------------------------------------------------------------------- /.maintain/gitlab/publish_draft_release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # shellcheck source=../common/lib.sh 4 | source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../common/lib.sh" 5 | 6 | version="$CI_COMMIT_TAG" 7 | 8 | # Note that this is not the last *tagged* version, but the last *published* version 9 | last_version=$(last_github_release 'paritytech/substrate') 10 | 11 | release_text="$(./generate_release_text.sh "$last_version" "$version")" 12 | 13 | echo "[+] Pushing release to github" 14 | # Create release on github 15 | release_name="Substrate $version" 16 | data=$(jq -Rs --arg version "$version" \ 17 | --arg release_name "$release_name" \ 18 | --arg release_text "$release_text" \ 19 | '{ 20 | "tag_name": $version, 21 | "target_commitish": "master", 22 | "name": $release_name, 23 | "body": $release_text, 24 | "draft": true, 25 | "prerelease": false 26 | }' < /dev/null) 27 | 28 | out=$(curl -s -X POST --data "$data" -H "Authorization: token $GITHUB_RELEASE_TOKEN" "$api_base/paritytech/substrate/releases") 29 | 30 | html_url=$(echo "$out" | jq -r .html_url) 31 | 32 | if [ "$html_url" == "null" ] 33 | then 34 | echo "[!] Something went wrong posting:" 35 | echo "$out" 36 | else 37 | echo "[+] Release draft created: $html_url" 38 | fi 39 | 40 | echo '[+] Sending draft release URL to Matrix' 41 | 42 | msg_body=$(cat <Release pipeline for Substrate $version complete.
49 | Draft release created: $html_url 50 | EOF 51 | ) 52 | send_message "$(structure_message "$msg_body" "$formatted_msg_body")" "$MATRIX_ROOM_ID" "$MATRIX_ACCESS_TOKEN" 53 | 54 | echo "[+] Done! Maybe the release worked..." 55 | -------------------------------------------------------------------------------- /.maintain/gitlab/skip_if_draft.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | url="https://api.github.com/repos/paritytech/substrate/pulls/${CI_COMMIT_REF_NAME}" 3 | echo "[+] API URL: $url" 4 | 5 | draft_state=$(curl -H "Authorization: token ${GITHUB_PR_TOKEN}" "$url" | jq -r .draft) 6 | echo "[+] Draft state: $draft_state" 7 | 8 | if [ "$draft_state" = 'true' ]; then 9 | echo "[!] PR is currently a draft, stopping pipeline" 10 | exit 1 11 | else 12 | echo "[+] PR is not a draft. Proceeding with CI pipeline" 13 | exit 0 14 | fi 15 | -------------------------------------------------------------------------------- /.maintain/gitlab/trigger_pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eu 4 | # API trigger another project's pipeline 5 | echo "Triggering Simnet pipeline." 6 | 7 | curl --silent \ 8 | -X POST \ 9 | -F "token=${CI_JOB_TOKEN}" \ 10 | -F "ref=master" \ 11 | -F "variables[TRGR_PROJECT]=${TRGR_PROJECT}" \ 12 | -F "variables[TRGR_REF]=${TRGR_REF}" \ 13 | -F "variables[IMAGE_NAME]=${IMAGE_NAME}" \ 14 | -F "variables[IMAGE_TAG]=${IMAGE_TAG}" \ 15 | "https://${CI_SERVER_HOST}/api/v4/projects/${DWNSTRM_ID}/trigger/pipeline" | \ 16 | tee pipeline 17 | 18 | PIPELINE_ID=$(cat pipeline | jq ".id") 19 | PIPELINE_URL=$(cat pipeline | jq ".web_url") 20 | echo 21 | echo "Simnet pipeline ${PIPELINE_URL} was successfully triggered." 22 | echo "Now we're polling it to obtain the distinguished status." 23 | 24 | # This is a workaround for a Gitlab bug, waits here until 25 | # https://gitlab.com/gitlab-org/gitlab/-/issues/326137 gets fixed. 26 | # The timeout is 360 curls with 8 sec interval, roughly an hour. 27 | 28 | function get_status() { 29 | curl --silent \ 30 | --header "PRIVATE-TOKEN: ${PIPELINE_TOKEN}" \ 31 | "https://${CI_SERVER_HOST}/api/v4/projects/${DWNSTRM_ID}/pipelines/${PIPELINE_ID}" | \ 32 | jq --raw-output ".status"; 33 | } 34 | 35 | echo "Waiting on ${PIPELINE_ID} status..." 36 | 37 | for i in $(seq 1 360); do 38 | STATUS=$(get_status); 39 | echo "Triggered pipeline status is ${STATUS}"; 40 | if [[ ${STATUS} =~ ^(pending|running|created)$ ]]; then 41 | echo "${STATUS}"..."; 42 | elif [[ ${STATUS} =~ ^(failed|canceled|skipped|manual)$ ]]; then 43 | echo "Oh noes! Something's broken in: ${PIPELINE_URL}"; exit 1; 44 | elif [[ ${STATUS} =~ ^(success)$ ]]; then 45 | echo "Look how green it is: ${PIPELINE_URL}"; exit 0; 46 | else 47 | echo "Something else has happened in ${PIPELINE_URL}"; exit 1; 48 | fi 49 | sleep 8; 50 | done 51 | -------------------------------------------------------------------------------- /.maintain/init.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | echo "*** Initializing WASM build environment" 6 | 7 | if [ -z $CI_PROJECT_NAME ] ; then 8 | rustup update nightly 9 | rustup update stable 10 | fi 11 | 12 | rustup target add wasm32-unknown-unknown --toolchain nightly 13 | -------------------------------------------------------------------------------- /.maintain/kubernetes/Chart.yaml: -------------------------------------------------------------------------------- 1 | name: substrate 2 | version: 0.2 3 | appVersion: 0.9.1 4 | description: "Substrate: The platform for blockchain innovators" 5 | home: https://substrate.network/ 6 | icon: https://substrate.network/favicon.ico 7 | sources: 8 | - https://github.com/paritytech/substrate/ 9 | maintainers: 10 | - name: Paritytech Devops Team 11 | email: devops-team@parity.io 12 | tillerVersion: ">=2.8.0" 13 | -------------------------------------------------------------------------------- /.maintain/kubernetes/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Substrate Kubernetes Helm Chart 4 | 5 | This [Helm Chart](https://helm.sh/) can be used for deploying containerized 6 | **Substrate** to a [Kubernetes](https://kubernetes.io/) cluster. 7 | 8 | 9 | ## Prerequisites 10 | 11 | - Tested on Kubernetes 1.10.7-gke.6 12 | 13 | ## Installation 14 | 15 | To install the chart with the release name `my-release` into namespace 16 | `my-namespace` from within this directory: 17 | 18 | ```console 19 | $ helm install --namespace my-namespace --name my-release --values values.yaml ./ 20 | ``` 21 | 22 | The command deploys Substrate on the Kubernetes cluster in the configuration 23 | given in `values.yaml`. When the namespace is omitted it'll be installed in 24 | the default one. 25 | 26 | 27 | ## Removal of the Chart 28 | 29 | To uninstall/delete the `my-release` deployment: 30 | 31 | ```console 32 | $ helm delete --namespace my-namespace my-release 33 | ``` 34 | 35 | The command removes all the Kubernetes components associated with the chart and deletes the release. 36 | 37 | 38 | ## Upgrading 39 | 40 | Once the chart is installed and a new version should be deployed helm takes 41 | care of this by 42 | 43 | ```console 44 | $ helm upgrade --namespace my-namespace --values values.yaml my-release ./ 45 | ``` 46 | 47 | 48 | -------------------------------------------------------------------------------- /.maintain/kubernetes/templates/poddisruptionbudget.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: policy/v1beta1 2 | kind: PodDisruptionBudget 3 | metadata: 4 | name: {{ .Values.GitlabEnvSlug | default .Values.app }} 5 | spec: 6 | selector: 7 | matchLabels: 8 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 9 | maxUnavailable: 1 10 | 11 | -------------------------------------------------------------------------------- /.maintain/kubernetes/templates/secrets.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.validator.keys }} 2 | apiVersion: v1 3 | kind: Secret 4 | metadata: 5 | name: {{ .Values.app }}-secrets 6 | labels: 7 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 8 | type: Opaque 9 | data: 10 | secrets: {{ .Values.validator.keys | default "" }} 11 | {{- end }} 12 | -------------------------------------------------------------------------------- /.maintain/kubernetes/templates/service.yaml: -------------------------------------------------------------------------------- 1 | # see: 2 | # https://kubernetes.io/docs/tutorials/services/ 3 | # https://kubernetes.io/docs/concepts/services-networking/service/ 4 | # headless service for rpc 5 | apiVersion: v1 6 | kind: Service 7 | metadata: 8 | name: {{ .Values.app }}-rpc 9 | spec: 10 | ports: 11 | - port: 9933 12 | name: http-rpc 13 | - port: 9944 14 | name: websocket-rpc 15 | selector: 16 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 17 | sessionAffinity: None 18 | type: ClusterIP 19 | clusterIP: None 20 | --- 21 | {{- if .Values.listen_node_port }} 22 | apiVersion: v1 23 | kind: Service 24 | metadata: 25 | name: {{ .Values.app }} 26 | spec: 27 | ports: 28 | - port: 30333 29 | name: p2p 30 | nodePort: 30333 31 | protocol: TCP 32 | selector: 33 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 34 | sessionAffinity: None 35 | type: NodePort 36 | # don't route external traffic to non-local pods 37 | externalTrafficPolicy: Local 38 | {{- else if .Values.validator.keys }} 39 | {{- $root := . -}} 40 | {{- range until (int .Values.nodes.replicas) }} 41 | --- 42 | kind: Service 43 | apiVersion: v1 44 | metadata: 45 | name: {{ $root.Values.app }}-{{ . }} 46 | spec: 47 | selector: 48 | statefulset.kubernetes.io/pod-name: {{ $root.Values.app }}-{{ . }} 49 | ports: 50 | - port: 30333 51 | targetPort: 30333 52 | protocol: TCP 53 | {{- end }} 54 | {{- end }} 55 | -------------------------------------------------------------------------------- /.maintain/kubernetes/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rbac.enable }} 2 | # service account for substrate pods themselves 3 | # no permissions for the api are required 4 | apiVersion: v1 5 | kind: ServiceAccount 6 | metadata: 7 | labels: 8 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 9 | name: {{ .Values.rbac.name }} 10 | {{- end }} 11 | -------------------------------------------------------------------------------- /.maintain/kubernetes/templates/statefulset.yaml: -------------------------------------------------------------------------------- 1 | # https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/ 2 | # https://cloud.google.com/kubernetes-engine/docs/concepts/statefulset 3 | apiVersion: apps/v1 4 | kind: StatefulSet 5 | metadata: 6 | name: {{ .Values.app }} 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 11 | serviceName: {{ .Values.app }} 12 | replicas: {{ .Values.nodes.replicas }} 13 | updateStrategy: 14 | type: RollingUpdate 15 | podManagementPolicy: Parallel 16 | template: 17 | metadata: 18 | labels: 19 | app: {{ .Values.GitlabEnvSlug | default .Values.app }} 20 | spec: 21 | {{- if .Values.rbac.enable }} 22 | serviceAccountName: {{ .Values.rbac.name }} 23 | {{- else }} 24 | serviceAccountName: default 25 | {{- end }} 26 | affinity: 27 | nodeAffinity: 28 | requiredDuringSchedulingIgnoredDuringExecution: 29 | nodeSelectorTerms: 30 | - matchExpressions: 31 | - key: node 32 | operator: In 33 | values: 34 | - substrate 35 | {{- if .Values.listen_node_port }} 36 | podAntiAffinity: 37 | requiredDuringSchedulingIgnoredDuringExecution: 38 | - labelSelector: 39 | matchExpressions: 40 | - key: "app" 41 | operator: In 42 | values: 43 | - {{ .Values.app }} 44 | topologyKey: "kubernetes.io/hostname" 45 | {{- end }} 46 | terminationGracePeriodSeconds: 300 47 | {{- if .Values.validator.keys }} 48 | volumes: 49 | - name: {{ .Values.app }}-validator-secrets 50 | secret: 51 | secretName: {{ .Values.app }}-secrets 52 | initContainers: 53 | - name: prepare-secrets 54 | image: busybox 55 | command: [ "/bin/sh" ] 56 | args: 57 | - -c 58 | - sed -n -r "s/^${POD_NAME}-key ([^ ]+)$/\1/p" /etc/validator/secrets > {{ .Values.image.basepath }}/key; 59 | sed -n -r "s/^${POD_NAME}-node-key ([^ ]+)$/\1/p" /etc/validator/secrets > {{ .Values.image.basepath }}/node-key; 60 | sed -n -r "s/^${POD_NAME}-name ([^ ]+)$/\1/p" /etc/validator/secrets > {{ .Values.image.basepath }}/name; 61 | test -s {{ .Values.image.basepath }}/name || echo "${POD_NAME}" > {{ .Values.image.basepath }}/name 62 | env: 63 | # from (workaround for hostname) 64 | # https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/ 65 | - name: POD_NAME 66 | valueFrom: 67 | fieldRef: 68 | fieldPath: metadata.name 69 | volumeMounts: 70 | - name: {{ .Values.app }}-validator-secrets 71 | readOnly: true 72 | mountPath: "/etc/validator" 73 | - name: {{ .Values.app }}dir 74 | mountPath: {{ .Values.image.basepath }} 75 | {{- end }} 76 | containers: 77 | - name: {{ .Values.app }} 78 | imagePullPolicy: "{{ .Values.image.pullPolicy }}" 79 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 80 | {{- if .Values.resources }} 81 | resources: 82 | requests: 83 | memory: {{ .Values.resources.memory }} 84 | cpu: {{ .Values.resources.cpu }} 85 | {{- end }} 86 | ports: 87 | - containerPort: 30333 88 | name: p2p 89 | - containerPort: 9933 90 | name: http-rpc 91 | - containerPort: 9944 92 | name: websocket-rpc 93 | command: ["/bin/sh"] 94 | args: 95 | - -c 96 | - exec /usr/local/bin/substrate 97 | --base-path {{ .Values.image.basepath }} 98 | {{- if .Values.validator.keys }} 99 | --validator 100 | --name $(cat {{ .Values.image.basepath }}/name) 101 | --key $(cat {{ .Values.image.basepath }}/key) 102 | --node-key $(cat {{ .Values.image.basepath }}/node-key) 103 | {{- else }} 104 | --name $(POD_NAME) 105 | {{- end }} 106 | {{- range .Values.nodes.args }} {{ . }} {{- end }} 107 | env: 108 | - name: POD_NAME 109 | valueFrom: 110 | fieldRef: 111 | fieldPath: metadata.name 112 | volumeMounts: 113 | - name: {{ .Values.app }}dir 114 | mountPath: {{ .Values.image.basepath }} 115 | readinessProbe: 116 | httpGet: 117 | path: /health 118 | port: http-rpc 119 | initialDelaySeconds: 10 120 | periodSeconds: 10 121 | livenessProbe: 122 | httpGet: 123 | path: /health 124 | port: http-rpc 125 | initialDelaySeconds: 10 126 | periodSeconds: 10 127 | securityContext: 128 | runAsUser: 1000 129 | fsGroup: 1000 130 | volumeClaimTemplates: 131 | - metadata: 132 | name: {{ .Values.app }}dir 133 | spec: 134 | accessModes: [ "ReadWriteOnce" ] 135 | storageClassName: ssd 136 | resources: 137 | requests: 138 | storage: 32Gi 139 | 140 | -------------------------------------------------------------------------------- /.maintain/kubernetes/values.yaml: -------------------------------------------------------------------------------- 1 | # set tag manually --set image.tag=latest 2 | image: 3 | repository: parity/substrate 4 | tag: latest 5 | pullPolicy: Always 6 | basepath: /substrate 7 | 8 | 9 | # if set to true a service account for substrate will be created 10 | rbac: 11 | enable: true 12 | name: substrate 13 | 14 | 15 | # name of the statefulset 16 | app: substrate 17 | listen_node_port: true 18 | 19 | nodes: 20 | replicas: 2 21 | args: 22 | # name and data directory are set by the chart itself 23 | # key and node-key may be provided on commandline invocation 24 | # 25 | # - --chain 26 | # - krummelanke 27 | # serve rpc within the local network 28 | # - fenced off the world via firewall 29 | # - used for health checks 30 | - --rpc-external 31 | - --ws-external 32 | # - --log 33 | # - sub-libp2p=trace 34 | 35 | 36 | validator: {} 37 | # providing 'keys' string via --set commandline parameter will run the nodes 38 | # in validator mode (--validator). 39 | # 40 | # name, key and node-key can be given in a base64 encoded keyfile string (at 41 | # validator.keys) which has the following format: 42 | # 43 | # substrate-0-name 44 | # substrate-0-key 45 | # substrate-0-node-key 46 | # substrate-1-name 47 | # substrate-1-key 48 | # substrate-1-node-key 49 | # 50 | # pod names are canonical. changing these or providing different amount of 51 | # keys than the replicas count will lead to behavior no one ever has 52 | # experienced before. 53 | 54 | 55 | # maybe adopt resource limits here to the nodes of the pool 56 | # resources: 57 | # memory: "5Gi" 58 | # cpu: "1.5" 59 | 60 | -------------------------------------------------------------------------------- /.maintain/local-docker-test-network/docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Docker compose file to start a multi node local test network. 2 | # 3 | # # Nodes 4 | # 5 | # - Validator node A 6 | # - Validator node B 7 | # - Light client C 8 | # 9 | # # Auxiliary nodes 10 | # 11 | # - Prometheus monitoring each node. 12 | # - Grafana pointed at the Prometheus node, configured with all dashboards. 13 | # 14 | # # Usage 15 | # 16 | # 1. Build `target/release/substrate` binary: `cargo build --release` 17 | # 2. Start networks and containers: 18 | # `sudo docker-compose -f .maintain/sentry-node/docker-compose.yml up` 19 | # 3. Connect to nodes: 20 | # - validator-a: localhost:9944 21 | # - validator-b: localhost:9945 22 | # - light-c: localhost:9946 23 | # - via polkadot.js/apps: https://polkadot.js.org/apps/?rpc=ws%3A%2F%2Flocalhost%3A#/explorer 24 | # - grafana: localhost:3001 25 | # - prometheus: localhost:9090 26 | 27 | 28 | version: "3.7" 29 | services: 30 | 31 | validator-a: 32 | ports: 33 | - "9944:9944" 34 | - "9615:9615" 35 | volumes: 36 | - ../../target/release/substrate:/usr/local/bin/substrate 37 | image: parity/substrate 38 | networks: 39 | - internet 40 | command: 41 | - "--node-key" 42 | - "0000000000000000000000000000000000000000000000000000000000000001" 43 | - "--base-path" 44 | - "/tmp/alice" 45 | - "--chain=local" 46 | - "--port" 47 | - "30333" 48 | - "--validator" 49 | - "--alice" 50 | - "--bootnodes" 51 | - "/dns/validator-b/tcp/30333/p2p/12D3KooWHdiAxVd8uMQR1hGWXccidmfCwLqcMpGwR6QcTP6QRMuD" 52 | # Not only bind to localhost. 53 | - "--unsafe-ws-external" 54 | - "--unsafe-rpc-external" 55 | - "--log" 56 | - "sub-libp2p=trace" 57 | - "--no-telemetry" 58 | - "--rpc-cors" 59 | - "all" 60 | - "--prometheus-external" 61 | 62 | validator-b: 63 | image: parity/substrate 64 | ports: 65 | - "9945:9944" 66 | volumes: 67 | - ../../target/release/substrate:/usr/local/bin/substrate 68 | networks: 69 | - internet 70 | command: 71 | - "--node-key" 72 | - "0000000000000000000000000000000000000000000000000000000000000002" 73 | - "--base-path" 74 | - "/tmp/bob" 75 | - "--chain=local" 76 | - "--port" 77 | - "30333" 78 | - "--validator" 79 | - "--bob" 80 | - "--bootnodes" 81 | - "/dns/validator-a/tcp/30333/p2p/12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp" 82 | - "--no-telemetry" 83 | - "--rpc-cors" 84 | - "all" 85 | # Not only bind to localhost. 86 | - "--unsafe-ws-external" 87 | - "--unsafe-rpc-external" 88 | - "--log" 89 | - "sub-libp2p=trace" 90 | - "--prometheus-external" 91 | 92 | light-c: 93 | image: parity/substrate 94 | ports: 95 | - "9946:9944" 96 | volumes: 97 | - ../../target/release/substrate:/usr/local/bin/substrate 98 | networks: 99 | - internet 100 | command: 101 | - "--node-key" 102 | - "0000000000000000000000000000000000000000000000000000000000000003" 103 | - "--base-path" 104 | - "/tmp/light" 105 | - "--chain=local" 106 | - "--port" 107 | - "30333" 108 | - "--light" 109 | - "--bootnodes" 110 | - "/dns/validator-a/tcp/30333/p2p/12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp" 111 | - "--bootnodes" 112 | - "/dns/validator-b/tcp/30333/p2p/12D3KooWHdiAxVd8uMQR1hGWXccidmfCwLqcMpGwR6QcTP6QRMuD" 113 | - "--no-telemetry" 114 | - "--rpc-cors" 115 | - "all" 116 | # Not only bind to localhost. 117 | - "--unsafe-ws-external" 118 | - "--unsafe-rpc-external" 119 | - "--log" 120 | - "sub-libp2p=trace" 121 | - "--prometheus-external" 122 | 123 | prometheus: 124 | image: prom/prometheus 125 | networks: 126 | - internet 127 | ports: 128 | - "9090:9090" 129 | links: 130 | - validator-a:validator-a 131 | - validator-b:validator-b 132 | - light-c:light-c 133 | volumes: 134 | - ./prometheus/:/etc/prometheus/ 135 | restart: always 136 | 137 | grafana: 138 | image: grafana/grafana 139 | user: "104" 140 | depends_on: 141 | - prometheus 142 | networks: 143 | - internet 144 | ports: 145 | - 3001:3000 146 | volumes: 147 | - ./grafana/provisioning/:/etc/grafana/provisioning 148 | - ../monitoring/grafana-dashboards/:/etc/grafana/provisioning/dashboard-definitions 149 | restart: always 150 | 151 | networks: 152 | network-a: 153 | internet: 154 | -------------------------------------------------------------------------------- /.maintain/local-docker-test-network/grafana/provisioning/dashboards/dashboards.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | 3 | providers: 4 | - name: 'Prometheus' 5 | orgId: 1 6 | folder: '' 7 | type: file 8 | disableDeletion: false 9 | editable: false 10 | options: 11 | path: /etc/grafana/provisioning/dashboard-definitions 12 | -------------------------------------------------------------------------------- /.maintain/local-docker-test-network/grafana/provisioning/datasources/datasource.yml: -------------------------------------------------------------------------------- 1 | # config file version 2 | apiVersion: 1 3 | 4 | # list of datasources that should be deleted from the database 5 | deleteDatasources: 6 | - name: Prometheus 7 | orgId: 1 8 | 9 | # list of datasources to insert/update depending 10 | # whats available in the database 11 | datasources: 12 | # name of the datasource. Required 13 | - name: Prometheus 14 | # datasource type. Required 15 | type: prometheus 16 | # access mode. direct or proxy. Required 17 | access: proxy 18 | # org id. will default to orgId 1 if not specified 19 | orgId: 1 20 | # url 21 | url: http://prometheus:9090 22 | # database password, if used 23 | password: 24 | # database user, if used 25 | user: 26 | # database name, if used 27 | database: 28 | # enable/disable basic auth 29 | basicAuth: false 30 | # basic auth username, if used 31 | basicAuthUser: 32 | # basic auth password, if used 33 | basicAuthPassword: 34 | # enable/disable with credentials headers 35 | withCredentials: 36 | # mark as default datasource. Max one per org 37 | isDefault: true 38 | # fields that will be converted to json and stored in json_data 39 | jsonData: 40 | graphiteVersion: "1.1" 41 | tlsAuth: false 42 | tlsAuthWithCACert: false 43 | # json object of data that will be encrypted. 44 | secureJsonData: 45 | tlsCACert: "..." 46 | tlsClientCert: "..." 47 | tlsClientKey: "..." 48 | version: 1 49 | # allow users to edit datasources from the UI. 50 | editable: true 51 | -------------------------------------------------------------------------------- /.maintain/local-docker-test-network/prometheus/prometheus.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 15s 3 | 4 | scrape_configs: 5 | - job_name: 'substrate-nodes' 6 | static_configs: 7 | - targets: ['validator-a:9615'] 8 | labels: 9 | network: dev 10 | - targets: ['validator-b:9615'] 11 | labels: 12 | network: dev 13 | - targets: ['light-c:9615'] 14 | labels: 15 | network: dev 16 | -------------------------------------------------------------------------------- /.maintain/monitoring/grafana-dashboards/README_dashboard.md: -------------------------------------------------------------------------------- 1 | ## Substrate Dashboard 2 | 3 | Shared templated Grafana dashboards. 4 | 5 | To import the dashboards follow the [Grafana 6 | documentation](https://grafana.com/docs/grafana/latest/reference/export_import/). 7 | You can see an example setup [here](../../../.maintain/sentry-node). 8 | -------------------------------------------------------------------------------- /.maintain/node-template-release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | export TERM=xterm 6 | PROJECT_ROOT=`git rev-parse --show-toplevel` 7 | 8 | if [ "$#" -ne 1 ]; then 9 | echo "node-template-release.sh path_to_target_archive" 10 | exit 1 11 | fi 12 | 13 | PATH_TO_ARCHIVE=$1 14 | cd $PROJECT_ROOT/.maintain/node-template-release 15 | 16 | cargo run $PROJECT_ROOT/bin/node-template $PATH_TO_ARCHIVE 17 | -------------------------------------------------------------------------------- /.maintain/node-template-release/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "node-template-release" 3 | version = "3.0.0" 4 | authors = ["Parity Technologies "] 5 | edition = "2021" 6 | license = "GPL-3.0" 7 | 8 | [dependencies] 9 | toml = "0.4" 10 | tar = "0.4" 11 | glob = "0.2" 12 | clap = { version = "3.2.6", features = [ "derive" ] } 13 | tempfile = "3" 14 | fs_extra = "1" 15 | git2 = "0.8" 16 | flate2 = "1.0" 17 | 18 | [workspace] 19 | 20 | [package.metadata.docs.rs] 21 | targets = ["x86_64-unknown-linux-gnu"] 22 | -------------------------------------------------------------------------------- /.maintain/rename-crates-for-2.0.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function rust_rename() { 4 | sed -i "s/$1/$2/g" `grep -Rl --include="*.rs" --include="*.stderr" "$1" *` > /dev/null 5 | } 6 | 7 | function cargo_rename() { 8 | find . -name "Cargo.toml" -exec sed -i "s/\(^\|[^\/]\)$1/\1$2/g" {} \; 9 | } 10 | 11 | function rename_gitlabci() { 12 | sed -i "s/$1/$2/g" .gitlab-ci.yml 13 | } 14 | 15 | function rename() { 16 | old=$(echo $1 | cut -f1 -d\ ); 17 | new=$(echo $1 | cut -f2 -d\ ); 18 | 19 | echo "Renaming $old to $new" 20 | # rename in Cargo.tomls 21 | cargo_rename $old $new 22 | rename_gitlabci $old $new 23 | # and it appears, we have the same syntax in rust files 24 | rust_rename $old $new 25 | 26 | # but generally we have the snail case syntax in rust files 27 | old=$(echo $old | sed s/-/_/g ); 28 | new=$(echo $new | sed s/-/_/g ); 29 | 30 | echo " > $old to $new" 31 | rust_rename $old $new 32 | } 33 | 34 | TO_RENAME=( 35 | # OLD-CRATE-NAME NEW-CRATE-NAME 36 | 37 | # post initial rename fixes 38 | "sc-application-crypto sp-application-crypto" 39 | "sp-transaction-pool-api sp-transaction-pool" 40 | "sp-transaction-pool-runtime-api sp-transaction-pool" 41 | "sp-core-storage sp-storage" 42 | "transaction-factory node-transaction-factory" 43 | "sp-finality-granpda sp-finality-grandpa" 44 | "sp-sesssion sp-session" 45 | "sp-tracing-pool sp-transaction-pool" 46 | "sc-basic-authority sc-basic-authorship" 47 | "sc-api sc-client-api" 48 | "sc-database sc-client-db" 49 | 50 | # PRIMITIVES 51 | "substrate-application-crypto sp-application-crypto" 52 | "substrate-authority-discovery-primitives sp-authority-discovery" 53 | "substrate-block-builder-runtime-api sp-block-builder" 54 | "substrate-consensus-aura-primitives sp-consensus-aura" 55 | "substrate-consensus-babe-primitives sp-consensus-babe" 56 | "substrate-consensus-common sp-consensus" 57 | "substrate-consensus-pow-primitives sp-consensus-pow" 58 | "substrate-primitives sp-core" 59 | "substrate-debug-derive sp-debug-derive" 60 | "substrate-primitives-storage sp-storage" 61 | "substrate-externalities sp-externalities" 62 | "substrate-finality-grandpa-primitives sp-finality-grandpa" 63 | "substrate-inherents sp-inherents" 64 | "substrate-keyring sp-keyring" 65 | "substrate-offchain-primitives sp-offchain" 66 | "substrate-panic-handler sp-panic-handler" 67 | "substrate-phragmen sp-npos-elections" 68 | "substrate-rpc-primitives sp-rpc" 69 | "substrate-runtime-interface sp-runtime-interface" 70 | "substrate-runtime-interface-proc-macro sp-runtime-interface-proc-macro" 71 | "substrate-runtime-interface-test-wasm sp-runtime-interface-test-wasm" 72 | "substrate-serializer sp-serializer" 73 | "substrate-session sp-session" 74 | "sr-api sp-api" 75 | "sr-api-proc-macro sp-api-proc-macro" 76 | "sr-api-test sp-api-test" 77 | "sr-arithmetic sp-arithmetic" 78 | "sr-arithmetic-fuzzer sp-arithmetic-fuzzer" 79 | "sr-io sp-io" 80 | "sr-primitives sp-runtime" 81 | "sr-sandbox sp-sandbox" 82 | "sr-staking-primitives sp-staking" 83 | "sr-std sp-std" 84 | "sr-version sp-version" 85 | "substrate-state-machine sp-state-machine" 86 | "substrate-transaction-pool-runtime-api sp-transaction-pool" 87 | "substrate-trie sp-trie" 88 | "substrate-wasm-interface sp-wasm-interface" 89 | 90 | # # CLIENT 91 | "substrate-client sc-client" 92 | "substrate-client-api sc-client-api" 93 | "substrate-authority-discovery sc-authority-discovery" 94 | "substrate-basic-authorship sc-basic-authorship" 95 | "substrate-block-builder sc-block-builder" 96 | "substrate-chain-spec sc-chain-spec" 97 | "substrate-chain-spec-derive sc-chain-spec-derive" 98 | "substrate-cli sc-cli" 99 | "substrate-consensus-aura sc-consensus-aura" 100 | "substrate-consensus-babe sc-consensus-babe" 101 | "substrate-consensus-pow sc-consensus-pow" 102 | "substrate-consensus-slots sc-consensus-slots" 103 | "substrate-consensus-uncles sc-consensus-uncles" 104 | "substrate-client-db sc-client-db" 105 | "substrate-executor sc-executor" 106 | "substrate-runtime-test sc-runtime-test" 107 | "substrate-finality-grandpa sc-finality-grandpa" 108 | "substrate-keystore sc-keystore" 109 | "substrate-network sc-network" 110 | "substrate-offchain sc-offchain" 111 | "substrate-peerset sc-peerset" 112 | "substrate-rpc-servers sc-rpc-server" 113 | "substrate-rpc sc-rpc" 114 | "substrate-service sc-service" 115 | "substrate-service-test sc-service-test" 116 | "substrate-state-db sc-state-db" 117 | "substrate-telemetry sc-telemetry" 118 | "substrate-test-primitives sp-test-primitives" 119 | "substrate-tracing sc-tracing" 120 | 121 | ); 122 | 123 | for rule in "${TO_RENAME[@]}" 124 | do 125 | rename "$rule"; 126 | done 127 | -------------------------------------------------------------------------------- /.maintain/runtime-dep.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # To run this script, you need to install the 'toml' python package and install the 'graphviz' package: 4 | # pip install toml 5 | # sudo apt-get install graphviz 6 | # the first parameter is the runtime folder 7 | # python ./.maintain/runtime-dep.py ./substrate/runtime | dot -Tpng -o output.png 8 | import sys 9 | import os 10 | import toml 11 | 12 | if len(sys.argv) != 2: 13 | print("needs the runtime folder.") 14 | sys.exit(-1) 15 | 16 | runtime_dir = sys.argv[1] 17 | 18 | files = [os.path.join(runtime_dir, f, 'Cargo.toml') for f in os.listdir(runtime_dir) if os.path.isfile(os.path.join(runtime_dir, f, 'Cargo.toml')) and f != 'example'] 19 | 20 | print("digraph G {") 21 | 22 | 23 | PREFIX = "substrate-runtime-" 24 | 25 | for f in files: 26 | manifest = toml.load(f) 27 | 28 | package_name = manifest['package']['name'] 29 | deps = [d for d in manifest['dependencies'].keys() if d.startswith(PREFIX)] 30 | 31 | for d in deps: 32 | print(" \"{}\" -> \"{}\";".format(package_name, d)) 33 | 34 | print("}") 35 | -------------------------------------------------------------------------------- /.maintain/rustdoc-header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 11 | -------------------------------------------------------------------------------- /.maintain/test-coverage/test-coverage.sh: -------------------------------------------------------------------------------- 1 | export CARGO_INCREMENTAL=0 2 | export SKIP_BUILD_WASM=true 3 | export BUILD_DUMMY_WASM_BINARY=true 4 | export LLVM_PROFILE_FILE="llvmcoveragedata-%p-%m.profraw" 5 | export WASM_TARGET_DIRECTORY=/tmp/wasm 6 | cargo build --features all-nodes 7 | export RUSTFLAGS="-Zinstrument-coverage" 8 | rm -rf target/debug 9 | cargo test --all --features all-nodes 10 | # grcov generate lcov.info 11 | # https://github.com/mozilla/grcov/blob/master/README.md 12 | # Ignore target/*, **test.rs 13 | grcov . --binary-path ./target/debug/ -s . -t lcov --branch --ignore-not-existing --ignore "/*" --ignore "target/*" --ignore "**tests.rs" -o lcov.info 14 | # Fix coverage 15 | # https://crates.io/crates/rust-covfix 16 | rust-covfix -o lcov_correct.info lcov.info 17 | bash <(curl -s https://codecov.io/bash) -f lcov_correct.info 18 | -------------------------------------------------------------------------------- /.maintain/update-copyright.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | SINGLE_DATES=$(grep -lr "// Copyright (C) [0-9]* Parity Technologies (UK) Ltd.") 4 | YEAR=$(date +%Y) 5 | 6 | for file in $SINGLE_DATES; do 7 | FILE_YEAR=$(cat $file | sed -n "s|// Copyright (C) \([[:digit:]][[:digit:]][[:digit:]][[:digit:]]\) Parity Technologies (UK) Ltd.|\1|p") 8 | if [ $YEAR -ne $FILE_YEAR ]; then 9 | sed -i -e "s|// Copyright (C) \([[:digit:]][[:digit:]][[:digit:]][[:digit:]]\) Parity Technologies (UK) Ltd.|// Copyright (C) \1-$YEAR Parity Technologies (UK) Ltd.|g" $file 10 | fi 11 | done 12 | 13 | grep -lr "// Copyright (C) [0-9]*-[0-9]* Parity Technologies (UK) Ltd." | 14 | xargs sed -i -e "s|// Copyright (C) \([[:digit:]][[:digit:]][[:digit:]][[:digit:]]\)-[[:digit:]][[:digit:]][[:digit:]][[:digit:]] Parity Technologies (UK) Ltd.|// Copyright (C) \1-$YEAR Parity Technologies (UK) Ltd.|g" 15 | -------------------------------------------------------------------------------- /.maintain/update-deps.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -- 2 | set -eu 3 | case $0 in 4 | (/*) dir=${0%/*}/;; 5 | (*/*) dir=./${0%/*};; 6 | (*) dir=.;; 7 | esac 8 | 9 | find "$dir/.." -name Cargo.lock -execdir cargo update \; 10 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | hard_tabs = true 3 | max_width = 100 4 | use_small_heuristics = "Max" 5 | 6 | # Imports 7 | imports_granularity = "Crate" 8 | reorder_imports = true 9 | 10 | # Consistency 11 | newline_style = "Unix" 12 | 13 | # Misc 14 | binop_separator = "Back" 15 | chain_width = 80 16 | match_arm_blocks = false 17 | match_arm_leading_pipes = "Preserve" 18 | match_block_trailing_comma = true 19 | reorder_impl_items = false 20 | spaces_around_ranges = false 21 | trailing_comma = "Vertical" 22 | trailing_semicolon = false 23 | use_field_init_shorthand = true 24 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "Run ", 8 | "type": "shell", 9 | "command": "cargo", 10 | "args": ["run", "--release", "--", "--dev"], 11 | "group": { 12 | "kind": "build", 13 | "isDefault": true 14 | }, 15 | "presentation": { 16 | "reveal": "always", 17 | "panel": "new" 18 | }, 19 | "problemMatcher": [ 20 | { 21 | "owner": "rust", 22 | "fileLocation": ["relative", "${workspaceRoot}"], 23 | "pattern": { 24 | "regexp": "^(.*):(\\d+):(\\d+):\\s+(\\d+):(\\d+)\\s+(warning|error):\\s+(.*)$", 25 | "file": 1, 26 | "line": 2, 27 | "column": 3, 28 | "endLine": 4, 29 | "endColumn": 5, 30 | "severity": 6, 31 | "message": 7 32 | } 33 | } 34 | ] 35 | } 36 | ] 37 | } -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [profile.release] 2 | # Substrate runtime requires unwinding. 3 | panic = "unwind" 4 | 5 | [workspace] 6 | resolver = "2" 7 | 8 | members = [ 9 | "node", 10 | "runtime/*", 11 | "pallets/automation-price", 12 | "pallets/automation-time", 13 | "pallets/automation-time/rpc", 14 | "pallets/automation-time/rpc/runtime-api", 15 | "pallets/xcmp-handler/rpc", 16 | "pallets/xcmp-handler/rpc/runtime-api", 17 | "pallets/valve", 18 | "pallets/vesting", 19 | ] 20 | -------------------------------------------------------------------------------- /distribution/neumann_vesting.json: -------------------------------------------------------------------------------- 1 | [ 2 | [ 3 | 1647212400, 4 | [ 5 | [ 6 | "68vqVx27xVYeCkqJTQnyXrcMCaKADUa7Rywn9TSrUZyp4NGP", 7 | 10000000000000000 8 | ], 9 | [ 10 | "68f3q4KSryfwFWTomj7DD41p9AQxAKvZNG9aJgckXBgpkvNL", 11 | 10000000000000000 12 | ] 13 | ] 14 | ], 15 | [ 16 | 1647223200, 17 | [ 18 | [ 19 | "68vqVx27xVYeCkqJTQnyXrcMCaKADUa7Rywn9TSrUZyp4NGP", 20 | 10000000000000000 21 | ], 22 | [ 23 | "68f3q4KSryfwFWTomj7DD41p9AQxAKvZNG9aJgckXBgpkvNL", 24 | 10000000000000000 25 | ] 26 | ] 27 | ], 28 | [ 29 | 1647230400, 30 | [ 31 | [ 32 | "68vqVx27xVYeCkqJTQnyXrcMCaKADUa7Rywn9TSrUZyp4NGP", 33 | 10000000000000000 34 | ], 35 | [ 36 | "68f3q4KSryfwFWTomj7DD41p9AQxAKvZNG9aJgckXBgpkvNL", 37 | 10000000000000000 38 | ] 39 | ] 40 | ], 41 | [ 42 | 1647273600, 43 | [ 44 | [ 45 | "68vqVx27xVYeCkqJTQnyXrcMCaKADUa7Rywn9TSrUZyp4NGP", 46 | 10000000000000000 47 | ], 48 | [ 49 | "68f3q4KSryfwFWTomj7DD41p9AQxAKvZNG9aJgckXBgpkvNL", 50 | 10000000000000000 51 | ] 52 | ] 53 | ], 54 | [ 55 | 1647277200, 56 | [ 57 | [ 58 | "68vqVx27xVYeCkqJTQnyXrcMCaKADUa7Rywn9TSrUZyp4NGP", 59 | 10000000000000000 60 | ], 61 | [ 62 | "68f3q4KSryfwFWTomj7DD41p9AQxAKvZNG9aJgckXBgpkvNL", 63 | 10000000000000000 64 | ] 65 | ] 66 | ] 67 | ] -------------------------------------------------------------------------------- /distribution/oak_alloc.json: -------------------------------------------------------------------------------- 1 | [ 2 | ["66MGxr9zcyJ6ka6FBQmT1VSvMqARKfwBT7589Fikii1Ci5sg", 100000000000000], 3 | ["67He8TSn5ayD2p2ZS9WDQtuVuW7Z8RXXvBx5NyszGwcEGpzS", 20010000000000000], 4 | ["6Azd1ebort6eZUDfg9f4A75fmD1JCV6ysHaFnTEqEPEuGpbP", 20010000000000000], 5 | ["6AQf3NV66CTNSsFuY1ehA1zJySYQybQwvC5Yq8ufqcZVQ3iN", 20010000000000000], 6 | ["66AJHj124JZnpKnWFoJGx41uSVqjyUz6tmVPfZWnhemBe8wG", 20010000000000000], 7 | ["69Eyxo3gFpZpcRrtx5NAFBDMcoiVQrdg7so1M9w4FWiTBLej", 10000000000000], 8 | ["67D6ecyNhnAzZqgRbxr3MdGnxB9Bw8VadMhjpLAYB3wf5Pq6", 10000000000000], 9 | ["6AxoUZEKEbaGVHsBkuJ6mvVgeMEixoroGiD1b3sBkroBqDXE", 10000000000000], 10 | ["69pKU2QpgtMBT9NsaN1diyJQ8qcvrJy8KJk5aWeAXfMGjb5F", 10000000000000], 11 | ["67ppUQ3mGfaWDEr5VQRz4QgvNzXiGLmGjwwEcnvbJofSQyMN", 10000000000000], 12 | ["68Tn1mgDo1dvctJLZCWaYJWLSWgu4GYtL5jgrrmzidAgpoJG", 10000000000000], 13 | ["67Za6G2i3BGkcTtYzU2hUzHrmy6quwWzyEMJB98oRv3GwDmb", 10000000000000], 14 | ["67nmVh57G9yo7sqiGLjgNNqtUd7H2CSESTyQgp5272aMibwS", 10000000000000], 15 | ["6871Utgdq5ycWnTzm7VEwQfg4zM81JqYv8EDzKPu3fdzsXK8", 10000000000000] 16 | ] 17 | -------------------------------------------------------------------------------- /distribution/oak_staging_alloc.json: -------------------------------------------------------------------------------- 1 | [ 2 | ["66A3Lswto3HV4ggkagQqMgP2vg5dsEhzJMYRTTJNaWLtkx6z", 9960000000000000000], 3 | ["691Fmzb8rhYmBxLvaqYEUApK22s3o6eCzC4whDY7dZZ83YYQ", 20000000000000000], 4 | ["699AH5KqTiTUsdtpQzxa3Bt3fc9yZzt4w5aYj5GPW6byUkmR", 20000000000000000] 5 | ] 6 | -------------------------------------------------------------------------------- /distribution/turing_alloc.json: -------------------------------------------------------------------------------- 1 | [ 2 | ["6AWgGe7oZuvc8542mBGwJVs1FVZoQdNH68bsaNvhzSY2xjYN", 96000000000000000], 3 | ["67ZjN7fByfR9jGex3gEdp77tgo9KR2vY7fwNyCvcWiS3w1LU", 4000000000000000], 4 | ["6BBGxHoTygiPF3GYvuUoZU9tivMZwdmkNFuQk3JjfDmGpbVC", 479810000000000000], 5 | ["66MGxr9zcyJ6ka6FBQmT1VSvMqARKfwBT7589Fikii1Ci5sg", 100000000000000], 6 | ["68eS5bmdz2nY45KxBfBFePVH88xupaPvjzExMxcnGuRBLcSK", 10000000000000], 7 | ["6BKgyjBS7exBgGKCVMGbYYcdTLHnXdJFHXD86Vr3vX4vpzPz", 10000000000000], 8 | ["67kgfmY6zpw1PRYpj3D5RtkzVZnVvn49XHGyR4v9MEsRRyet", 10000000000000], 9 | ["6A6VuGbeUwm3J2HqLduH7VFZTvrYQs8GuqzdhopLGN2JKMAe", 10000000000000], 10 | ["699YyPF2uA83zsFnQU4GCAvZXzucvyS5rx8LS9UrL9kEv8PP", 10000000000000], 11 | ["669ocRxey7vxUJs1TTRWe31zwrpGr8B13zRfAHB6yhhfcMud", 10000000000000], 12 | ["67nmVh57G9yo7sqiGLjgNNqtUd7H2CSESTyQgp5272aMibwS", 10000000000000], 13 | ["6AMsXyV1CYc3LMTk155JTDGEzbgVPvsX9aXp7VXz9heC3iuP", 10000000000000], 14 | ["67D6ecyNhnAzZqgRbxr3MdGnxB9Bw8VadMhjpLAYB3wf5Pq6", 10000000000000] 15 | ] 16 | -------------------------------------------------------------------------------- /distribution/turing_staging_alloc.json: -------------------------------------------------------------------------------- 1 | [ 2 | ["66A3Lswto3HV4ggkagQqMgP2vg5dsEhzJMYRTTJNaWLtkx6z", 9960000000000000000], 3 | ["691Fmzb8rhYmBxLvaqYEUApK22s3o6eCzC4whDY7dZZ83YYQ", 20000000000000000], 4 | ["699AH5KqTiTUsdtpQzxa3Bt3fc9yZzt4w5aYj5GPW6byUkmR", 20000000000000000] 5 | ] 6 | -------------------------------------------------------------------------------- /docker/neumann/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM docker.io/library/ubuntu:20.04 2 | 3 | ARG USERNAME=oak 4 | ARG PROFILE=release 5 | ARG BINARY=oak-collator 6 | 7 | LABEL maintainer "contact@oak.tech" 8 | LABEL description="Binary for Neumann Collator" 9 | 10 | # 1. Install curl to execute RPC call 11 | # 2. Add user 12 | # 3. Create data directory 13 | # 4. Link data directory 14 | # 5. Delete binaries except curl 15 | RUN apt-get update && apt-get install -y curl && \ 16 | useradd -m -u 1000 -U -s /bin/sh -d /$USERNAME $USERNAME && \ 17 | mkdir -p /$USERNAME/.local/share && \ 18 | mkdir /data && \ 19 | chown -R $USERNAME:$USERNAME /data && \ 20 | ln -s /data /$USERNAME/.local/share/$BINARY && \ 21 | find /usr/bin/* /usr/sbin/* | grep -v 'curl\|sh\|chmod' | xargs rm 22 | 23 | USER $USERNAME 24 | 25 | # Copy files 26 | COPY --chown=$USERNAME ./$BINARY /$USERNAME/$BINARY 27 | COPY --chown=$USERNAME ./resources /$USERNAME/resources 28 | 29 | RUN chmod uog+x /$USERNAME/$BINARY 30 | 31 | # Open network port 32 | # 30333 for parachain p2p 33 | # 30334 for relaychain p2p 34 | # 9933 for RPC call 35 | # 9944 for Websocket 36 | # 9615 for Prometheus (metrics) 37 | EXPOSE 30333 30334 9933 9944 9615 38 | 39 | # Specify volume 40 | VOLUME ["/data"] 41 | 42 | # Change work directory 43 | WORKDIR /$USERNAME 44 | 45 | ENTRYPOINT ["./oak-collator"] 46 | -------------------------------------------------------------------------------- /docker/neumann/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Please execute this script in the project root directory. 3 | set -e 4 | 5 | # The following line ensure we run from the project root 6 | PROJECT_ROOT=`git rev-parse --show-toplevel` 7 | cd $PROJECT_ROOT 8 | 9 | # Find the current version from Cargo.toml 10 | VERSION=`grep "^version" ./node/Cargo.toml | egrep -o "([0-9\.]+)"` 11 | USER=oaknetwork 12 | PROJECT=neumann 13 | 14 | # Build the image 15 | echo "Building ${USER}/${PROJECT}:latest docker image, hang on!" 16 | time docker build -f ./docker/neumann/Dockerfile -t ${USER}/${PROJECT}:latest . 17 | docker tag ${USER}/${PROJECT}:latest ${USER}/${PROJECT}:${VERSION} 18 | 19 | # Show the list of available images for this repo 20 | echo "Image is ready" 21 | docker images | grep ${PROJECT} 22 | -------------------------------------------------------------------------------- /docker/turing/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM docker.io/library/ubuntu:20.04 2 | 3 | ARG USERNAME=oak 4 | ARG PROFILE=release 5 | ARG BINARY=oak-collator 6 | 7 | LABEL maintainer "contact@oak.tech" 8 | LABEL description="Binary for Turing Collator" 9 | 10 | # 1. Install curl to execute RPC call 11 | # 2. Add user 12 | # 3. Create data directory 13 | # 4. Link data directory 14 | # 5. Delete binaries except curl 15 | RUN apt-get update && apt-get install -y curl && \ 16 | useradd -m -u 1000 -U -s /bin/sh -d /$USERNAME $USERNAME && \ 17 | mkdir -p /$USERNAME/.local/share && \ 18 | mkdir /data && \ 19 | chown -R $USERNAME:$USERNAME /data && \ 20 | ln -s /data /$USERNAME/.local/share/$BINARY && \ 21 | find /usr/bin/* /usr/sbin/* | grep -v 'curl\|sh\|chmod' | xargs rm 22 | 23 | USER $USERNAME 24 | 25 | # Copy files 26 | COPY --chown=$USERNAME ./$BINARY /$USERNAME/$BINARY 27 | COPY --chown=$USERNAME ./resources /$USERNAME/resources 28 | 29 | RUN chmod uog+x /$USERNAME/$BINARY 30 | 31 | # Open network port 32 | # 30333 for parachain p2p 33 | # 30334 for relaychain p2p 34 | # 9933 for RPC call 35 | # 9944 for Websocket 36 | # 9615 for Prometheus (metrics) 37 | EXPOSE 30333 30334 9933 9944 9615 38 | 39 | # Specify volume 40 | VOLUME ["/data"] 41 | 42 | # Change work directory 43 | WORKDIR /$USERNAME 44 | 45 | ENTRYPOINT ["./oak-collator"] 46 | -------------------------------------------------------------------------------- /docker/turing/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Please execute this script in the project root directory. 3 | set -e 4 | 5 | # The following line ensure we run from the project root 6 | PROJECT_ROOT=`git rev-parse --show-toplevel` 7 | cd $PROJECT_ROOT 8 | 9 | # Find the current version from Cargo.toml 10 | VERSION=`grep "^version" ./node/Cargo.toml | egrep -o "([0-9\.]+)"` 11 | USER=oaknetwork 12 | PROJECT=turing 13 | 14 | # Build the image 15 | echo "Building ${USER}/${PROJECT}:latest docker image, hang on!" 16 | time docker build -f ./docker/turing/Dockerfile -t ${USER}/${PROJECT}:latest . 17 | docker tag ${USER}/${PROJECT}:latest ${USER}/${PROJECT}:${VERSION} 18 | 19 | # Show the list of available images for this repo 20 | echo "Image is ready" 21 | docker images | grep ${PROJECT} 22 | -------------------------------------------------------------------------------- /media/readme-parachain-post-registration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VeteranSoftDev/OAK-blockchain/85d435d93ff4b33c1783f1797d47f064cfb96f99/media/readme-parachain-post-registration.png -------------------------------------------------------------------------------- /media/readme-parachain-registration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VeteranSoftDev/OAK-blockchain/85d435d93ff4b33c1783f1797d47f064cfb96f99/media/readme-parachain-registration.png -------------------------------------------------------------------------------- /node/build.rs: -------------------------------------------------------------------------------- 1 | use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; 2 | 3 | fn main() { 4 | generate_cargo_keys(); 5 | 6 | rerun_if_git_head_changed(); 7 | } 8 | -------------------------------------------------------------------------------- /node/src/cli.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use std::path::PathBuf; 3 | 4 | /// Sub-commands supported by the collator. 5 | #[derive(Debug, clap::Subcommand)] 6 | pub enum Subcommand { 7 | /// Build a chain specification. 8 | BuildSpec(sc_cli::BuildSpecCmd), 9 | 10 | /// Validate blocks. 11 | CheckBlock(sc_cli::CheckBlockCmd), 12 | 13 | /// Export blocks. 14 | ExportBlocks(sc_cli::ExportBlocksCmd), 15 | 16 | /// Export the state of a given block into a chain spec. 17 | ExportState(sc_cli::ExportStateCmd), 18 | 19 | /// Import blocks. 20 | ImportBlocks(sc_cli::ImportBlocksCmd), 21 | 22 | /// Revert the chain to a previous state. 23 | Revert(sc_cli::RevertCmd), 24 | 25 | /// Remove the whole chain. 26 | PurgeChain(cumulus_client_cli::PurgeChainCmd), 27 | 28 | /// Export the genesis state of the parachain. 29 | ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), 30 | 31 | /// Export the genesis wasm of the parachain. 32 | ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), 33 | 34 | /// The custom benchmark subcommmand benchmarking runtime pallets. 35 | #[clap(subcommand)] 36 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 37 | 38 | /// Try some testing command against a specified runtime state. 39 | #[cfg(feature = "try-runtime")] 40 | TryRuntime(try_runtime_cli::TryRuntimeCmd), 41 | } 42 | 43 | #[derive(Debug, clap::Parser)] 44 | #[clap( 45 | propagate_version = true, 46 | args_conflicts_with_subcommands = true, 47 | subcommand_negates_reqs = true 48 | )] 49 | pub struct Cli { 50 | #[clap(subcommand)] 51 | pub subcommand: Option, 52 | 53 | #[clap(flatten)] 54 | pub run: cumulus_client_cli::RunCmd, 55 | 56 | /// Disable automatic hardware benchmarks. 57 | /// 58 | /// By default these benchmarks are automatically ran at startup and measure 59 | /// the CPU speed, the memory bandwidth and the disk speed. 60 | /// 61 | /// The results are then printed out in the logs, and also sent as part of 62 | /// telemetry, if telemetry is enabled. 63 | #[clap(long)] 64 | pub no_hardware_benchmarks: bool, 65 | 66 | /// Relay chain arguments 67 | #[clap(raw = true)] 68 | pub relay_chain_args: Vec, 69 | } 70 | 71 | #[derive(Debug)] 72 | pub struct RelayChainCli { 73 | /// The actual relay chain cli object. 74 | pub base: polkadot_cli::RunCmd, 75 | 76 | /// Optional chain id that should be passed to the relay chain. 77 | pub chain_id: Option, 78 | 79 | /// The base path that should be used by the relay chain. 80 | pub base_path: Option, 81 | } 82 | 83 | impl RelayChainCli { 84 | /// Parse the relay chain CLI parameters using the para chain `Configuration`. 85 | pub fn new<'a>( 86 | para_config: &sc_service::Configuration, 87 | relay_chain_args: impl Iterator, 88 | ) -> Self { 89 | let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec); 90 | let chain_id = extension.map(|e| e.relay_chain.clone()); 91 | let base_path = para_config.base_path.path().join("polkadot"); 92 | Self { 93 | base: polkadot_cli::RunCmd::parse_from(relay_chain_args), 94 | chain_id, 95 | base_path: Some(base_path), 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /node/src/main.rs: -------------------------------------------------------------------------------- 1 | //! Substrate Parachain Node Template CLI 2 | 3 | #![warn(missing_docs)] 4 | 5 | mod chain_spec; 6 | #[macro_use] 7 | mod service; 8 | mod cli; 9 | mod command; 10 | mod rpc; 11 | 12 | fn main() -> sc_cli::Result<()> { 13 | command::run() 14 | } 15 | -------------------------------------------------------------------------------- /node/src/rpc.rs: -------------------------------------------------------------------------------- 1 | //! A collection of node-specific RPC methods. 2 | //! Substrate provides the `sc-rpc` crate, which defines the core RPC layer 3 | //! used by Substrate nodes. This file extends those RPC definitions with 4 | //! capabilities that are specific to this project's runtime configuration. 5 | 6 | #![warn(missing_docs)] 7 | 8 | use std::sync::Arc; 9 | 10 | use primitives::{AccountId, Balance, Block, Hash, Index as Nonce}; 11 | 12 | use sc_client_api::AuxStore; 13 | pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; 14 | use sc_transaction_pool_api::TransactionPool; 15 | use sp_api::ProvideRuntimeApi; 16 | use sp_block_builder::BlockBuilder; 17 | use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; 18 | 19 | /// A type representing all RPC extensions. 20 | pub type RpcExtension = jsonrpsee::RpcModule<()>; 21 | 22 | /// Full client dependencies 23 | pub struct FullDeps { 24 | /// The client instance to use. 25 | pub client: Arc, 26 | /// Transaction pool instance. 27 | pub pool: Arc

, 28 | /// Whether to deny unsafe calls 29 | pub deny_unsafe: DenyUnsafe, 30 | } 31 | 32 | /// Instantiate all RPC extensions. 33 | pub fn create_full( 34 | deps: FullDeps, 35 | ) -> Result> 36 | where 37 | C: ProvideRuntimeApi 38 | + HeaderBackend 39 | + AuxStore 40 | + HeaderMetadata 41 | + Send 42 | + Sync 43 | + 'static, 44 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, 45 | C::Api: substrate_frame_rpc_system::AccountNonceApi, 46 | C::Api: pallet_automation_time_rpc::AutomationTimeRuntimeApi, 47 | C::Api: pallet_automation_price_rpc::AutomationPriceRuntimeApi, 48 | C::Api: pallet_xcmp_handler_rpc::XcmpHandlerRuntimeApi, 49 | C::Api: BlockBuilder, 50 | P: TransactionPool + Sync + Send + 'static, 51 | { 52 | use pallet_automation_price_rpc::{AutomationPrice, AutomationPriceApiServer}; 53 | use pallet_automation_time_rpc::{AutomationTime, AutomationTimeApiServer}; 54 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; 55 | use pallet_xcmp_handler_rpc::{XcmpHandler, XcmpHandlerApiServer}; 56 | use substrate_frame_rpc_system::{System, SystemApiServer}; 57 | 58 | let mut module = RpcExtension::new(()); 59 | let FullDeps { client, pool, deny_unsafe } = deps; 60 | 61 | module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; 62 | module.merge(TransactionPayment::new(client.clone()).into_rpc())?; 63 | module.merge(AutomationTime::new(client.clone()).into_rpc())?; 64 | module.merge(AutomationPrice::new(client.clone()).into_rpc())?; 65 | module.merge(XcmpHandler::new(client).into_rpc())?; 66 | 67 | Ok(module) 68 | } 69 | -------------------------------------------------------------------------------- /pallets/automation-price/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-price" 3 | description = "Pallet for scheduling and running tasks in the future." 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | readme = 'README.md' 11 | 12 | [package.metadata.docs.rs] 13 | targets = ['x86_64-unknown-linux-gnu'] 14 | 15 | [dependencies] 16 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 17 | "derive", 18 | ], default-features = false } 19 | scale-info = { version = "2.1", default-features = false, features = [ 20 | "derive", 21 | ] } 22 | log = { version = "0.4.17", default-features = false } 23 | 24 | # Polkadot 25 | polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 26 | xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 27 | 28 | # Cumulus dependencies 29 | cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus', default-features = false, branch = 'polkadot-v0.9.43' } 30 | cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus', default-features = false, branch = 'polkadot-v0.9.43' } 31 | 32 | ## ORML 33 | orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 34 | orml-currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 35 | 36 | 37 | # Substrate Dependencies 38 | ## Substrate Primitive Dependencies 39 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 40 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 41 | 42 | ## Substrate FRAME Dependencies 43 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } 44 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 45 | frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 46 | 47 | ## Substrate Pallet Dependencies 48 | pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 49 | 50 | ## Polkdadot deps 51 | xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 52 | 53 | ## Local 54 | pallet-valve = { path = "../valve", default-features = false } 55 | pallet-xcmp-handler = { path = "../xcmp-handler", default-features = false } 56 | primitives = { path = "../../primitives", default-features = false } 57 | 58 | [dev-dependencies] 59 | rand = { version = "0.7.3" } 60 | serde = { version = "1.0.144" } 61 | sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 62 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 63 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 64 | 65 | pallet-xcm = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 66 | xcm-executor = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 67 | 68 | # Cumulus dependencies 69 | parachain-info = { git = 'https://github.com/paritytech/cumulus', branch = 'polkadot-v0.9.43' } 70 | 71 | orml-currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 72 | orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 73 | 74 | 75 | [features] 76 | default = ["std"] 77 | runtime-benchmarks = ["frame-benchmarking"] 78 | try-runtime = ["frame-support/try-runtime"] 79 | std = [ 80 | "codec/std", 81 | "cumulus-pallet-xcm/std", 82 | "cumulus-primitives-core/std", 83 | "frame-benchmarking/std", 84 | "frame-support/std", 85 | "frame-system/std", 86 | "orml-currencies/std", 87 | "orml-tokens/std", 88 | "orml-traits/std", 89 | "pallet-timestamp/std", 90 | "pallet-valve/std", 91 | "pallet-xcm/std", 92 | "polkadot-parachain/std", 93 | "scale-info/std", 94 | "sp-runtime/std", 95 | "sp-std/std", 96 | "xcm/std", 97 | "xcm-builder/std", 98 | "xcm-executor/std", 99 | ] 100 | dev-queue = [] 101 | -------------------------------------------------------------------------------- /pallets/automation-price/rpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-price-rpc" 3 | description = "RPC API to provide information about tasks" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3" } 16 | jsonrpsee = { version = "0.16.2", features = ["server", "macros"] } 17 | 18 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 19 | sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 20 | sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 21 | sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 22 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 23 | sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 24 | 25 | pallet-automation-price-rpc-runtime-api = { path = "./runtime-api" } 26 | -------------------------------------------------------------------------------- /pallets/automation-price/rpc/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-price-rpc-runtime-api" 3 | description = "Runtime RPC API to provide information about tasks" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3", features = ["derive", "full"], default-features = false } 16 | serde = { version = "1.0.144", features = ["derive"], optional = true } 17 | scale-info = { version = "2.1", features = ["derive"], default-features = false } 18 | 19 | sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 20 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 21 | 22 | [features] 23 | default = ["std"] 24 | std = [ 25 | "serde", 26 | "codec/std", 27 | "sp-api/std", 28 | "sp-std/std", 29 | ] 30 | 31 | -------------------------------------------------------------------------------- /pallets/automation-price/rpc/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2023 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use codec::{Codec, Decode, Encode}; 21 | use scale_info::TypeInfo; 22 | use sp_std::vec::Vec; 23 | 24 | #[cfg(feature = "std")] 25 | use serde::{Deserialize, Serialize}; 26 | 27 | #[derive(Debug, PartialEq, Encode, Decode, TypeInfo)] 28 | #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] 29 | #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] 30 | pub struct FeeDetails { 31 | pub schedule_fee: Balance, 32 | pub execution_fee: Balance, 33 | } 34 | 35 | sp_api::decl_runtime_apis! { 36 | pub trait AutomationPriceApi where 37 | AccountId: Codec, 38 | Hash: Codec, 39 | Balance: Codec, 40 | { 41 | fn query_fee_details(uxt: Block::Extrinsic) -> Result, Vec>; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /pallets/automation-price/rpc/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | use codec::{Codec, Decode}; 19 | use jsonrpsee::{ 20 | core::{async_trait, Error as JsonRpseeError, RpcResult}, 21 | proc_macros::rpc, 22 | types::error::{CallError, ErrorObject}, 23 | }; 24 | pub use pallet_automation_price_rpc_runtime_api::AutomationPriceApi as AutomationPriceRuntimeApi; 25 | use pallet_automation_price_rpc_runtime_api::FeeDetails; 26 | use sp_api::ProvideRuntimeApi; 27 | use sp_blockchain::HeaderBackend; 28 | use sp_core::Bytes; 29 | use sp_rpc::number::NumberOrHex; 30 | use sp_runtime::traits::{Block as BlockT, MaybeDisplay}; 31 | use std::sync::Arc; 32 | 33 | /// An RPC endpoint to provide information about tasks. 34 | #[rpc(client, server)] 35 | pub trait AutomationPriceApi { 36 | #[method(name = "automationPrice_queryFeeDetails")] 37 | fn query_fee_details( 38 | &self, 39 | encoded_xt: Bytes, 40 | at: Option, 41 | ) -> RpcResult>; 42 | } 43 | 44 | /// An implementation of Automation-specific RPC methods on full client. 45 | pub struct AutomationPrice { 46 | client: Arc, 47 | _marker: std::marker::PhantomData, 48 | } 49 | 50 | impl AutomationPrice { 51 | /// Create new `AutomationTaskUtility` with the given reference to the client. 52 | pub fn new(client: Arc) -> Self { 53 | Self { client, _marker: Default::default() } 54 | } 55 | } 56 | 57 | /// Error type of this RPC api. 58 | pub enum Error { 59 | /// The call to runtime failed. 60 | RuntimeError, 61 | } 62 | 63 | impl From for i32 { 64 | fn from(e: Error) -> i32 { 65 | match e { 66 | Error::RuntimeError => 1, 67 | } 68 | } 69 | } 70 | 71 | #[async_trait] 72 | impl 73 | AutomationPriceApiServer<::Hash, AccountId, Hash, Balance> 74 | for AutomationPrice 75 | where 76 | Block: BlockT, 77 | Balance: 78 | Codec + MaybeDisplay + Copy + TryInto + TryInto + Send + Sync + 'static, 79 | C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, 80 | C::Api: AutomationPriceRuntimeApi, 81 | AccountId: Codec, 82 | Hash: Codec, 83 | { 84 | fn query_fee_details( 85 | &self, 86 | encoded_xt: Bytes, 87 | at: Option, 88 | ) -> RpcResult> { 89 | let api = self.client.runtime_api(); 90 | let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); 91 | 92 | let uxt: Block::Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(|e| { 93 | CallError::Custom(ErrorObject::owned( 94 | Error::RuntimeError.into(), 95 | "Unable to decode extrinsic.".to_string(), 96 | Some(format!("{:?}", e)), 97 | )) 98 | })?; 99 | let fee_details = api 100 | .query_fee_details(at_hash, uxt) 101 | .map_err(|e| { 102 | CallError::Custom(ErrorObject::owned( 103 | Error::RuntimeError.into(), 104 | "Unable to query fee details.".to_string(), 105 | Some(format!("{:?}", e)), 106 | )) 107 | })? 108 | .map_err(|e| { 109 | JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( 110 | Error::RuntimeError.into(), 111 | "Unable to get fees.", 112 | Some(String::from_utf8(e).unwrap_or_default()), 113 | ))) 114 | })?; 115 | 116 | let try_into_rpc_balance = |value: Balance| { 117 | value.try_into().map_err(|_| { 118 | JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( 119 | Error::RuntimeError.into(), 120 | format!("{} doesn't fit in NumberOrHex representation", value), 121 | None::<()>, 122 | ))) 123 | }) 124 | }; 125 | 126 | Ok(FeeDetails { 127 | schedule_fee: try_into_rpc_balance(fee_details.schedule_fee)?, 128 | execution_fee: try_into_rpc_balance(fee_details.execution_fee)?, 129 | }) 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /pallets/automation-price/src/fees.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | /// ! Traits and default implementation for paying execution fees. 19 | use crate::{AccountOf, Action, ActionOf, Config, Error, MultiBalanceOf, Pallet}; 20 | 21 | use orml_traits::MultiCurrency; 22 | use pallet_xcmp_handler::{InstructionSequence, XcmpTransactor}; 23 | use sp_runtime::{ 24 | traits::{CheckedSub, Convert, Saturating, Zero}, 25 | DispatchError, DispatchResult, SaturatedConversion, 26 | TokenError::BelowMinimum, 27 | }; 28 | use sp_std::marker::PhantomData; 29 | use xcm::latest::prelude::*; 30 | use xcm_builder::TakeRevenue; 31 | 32 | /// Handle execution fee payments in the context of automation actions 33 | pub trait HandleFees { 34 | fn pay_checked_fees_for Result>( 35 | owner: &AccountOf, 36 | action: &ActionOf, 37 | prereq: F, 38 | ) -> Result; 39 | } 40 | pub struct FeeHandler { 41 | owner: T::AccountId, 42 | pub schedule_fee_location: MultiLocation, 43 | pub schedule_fee_amount: MultiBalanceOf, 44 | pub execution_fee_amount: MultiBalanceOf, 45 | _phantom_data: PhantomData, 46 | } 47 | 48 | impl HandleFees for FeeHandler 49 | where 50 | T: Config, 51 | TR: TakeRevenue, 52 | { 53 | fn pay_checked_fees_for Result>( 54 | owner: &AccountOf, 55 | action: &ActionOf, 56 | prereq: F, 57 | ) -> Result { 58 | let fee_handler = Self::new(owner, action)?; 59 | fee_handler.can_pay_fee().map_err(|_| Error::::InsufficientBalance)?; 60 | let outcome = prereq()?; 61 | fee_handler.pay_fees()?; 62 | Ok(outcome) 63 | } 64 | } 65 | 66 | impl FeeHandler 67 | where 68 | T: Config, 69 | TR: TakeRevenue, 70 | { 71 | /// Ensure the fee can be paid. 72 | fn can_pay_fee(&self) -> Result<(), DispatchError> { 73 | let fee = self.schedule_fee_amount.saturating_add(self.execution_fee_amount); 74 | 75 | if fee.is_zero() { 76 | return Ok(()) 77 | } 78 | 79 | // Manually check for ExistenceRequirement since MultiCurrency doesn't currently support it 80 | let currency_id = T::CurrencyIdConvert::convert(self.schedule_fee_location) 81 | .ok_or("IncoveribleMultilocation")?; 82 | let currency_id = currency_id.into(); 83 | let free_balance = T::MultiCurrency::free_balance(currency_id, &self.owner); 84 | 85 | free_balance 86 | .checked_sub(&fee) 87 | .ok_or(DispatchError::Token(BelowMinimum))? 88 | .checked_sub(&T::MultiCurrency::minimum_balance(currency_id)) 89 | .ok_or(DispatchError::Token(BelowMinimum))?; 90 | T::MultiCurrency::ensure_can_withdraw(currency_id, &self.owner, fee)?; 91 | Ok(()) 92 | } 93 | 94 | /// Withdraw the fee. 95 | fn withdraw_fee(&self) -> Result<(), DispatchError> { 96 | let fee = self.schedule_fee_amount.saturating_add(self.execution_fee_amount); 97 | 98 | if fee.is_zero() { 99 | return Ok(()) 100 | } 101 | 102 | let currency_id = T::CurrencyIdConvert::convert(self.schedule_fee_location) 103 | .ok_or("IncoveribleMultilocation")?; 104 | 105 | match T::MultiCurrency::withdraw(currency_id.into(), &self.owner, fee) { 106 | Ok(_) => { 107 | TR::take_revenue(MultiAsset { 108 | id: AssetId::Concrete(self.schedule_fee_location), 109 | fun: Fungibility::Fungible(self.schedule_fee_amount.saturated_into()), 110 | }); 111 | 112 | if self.execution_fee_amount > MultiBalanceOf::::zero() { 113 | T::XcmpTransactor::pay_xcm_fee( 114 | currency_id, 115 | self.owner.clone(), 116 | self.execution_fee_amount.saturated_into(), 117 | )?; 118 | } 119 | 120 | Ok(()) 121 | }, 122 | Err(_) => Err(DispatchError::Token(BelowMinimum)), 123 | } 124 | } 125 | 126 | /// Builds an instance of the struct 127 | pub fn new(owner: &AccountOf, action: &ActionOf) -> Result { 128 | let schedule_fee_location = action.schedule_fee_location::(); 129 | 130 | let schedule_fee_amount: u128 = 131 | Pallet::::calculate_schedule_fee_amount(action)?.saturated_into(); 132 | 133 | let execution_fee_amount = match action.clone() { 134 | Action::XCMP { execution_fee, instruction_sequence, .. } 135 | if instruction_sequence == InstructionSequence::PayThroughSovereignAccount => 136 | execution_fee.amount.saturated_into(), 137 | _ => 0u32.saturated_into(), 138 | }; 139 | 140 | Ok(Self { 141 | owner: owner.clone(), 142 | schedule_fee_location, 143 | schedule_fee_amount: schedule_fee_amount.saturated_into(), 144 | execution_fee_amount, 145 | _phantom_data: Default::default(), 146 | }) 147 | } 148 | 149 | /// Executes the fee handler 150 | fn pay_fees(self) -> DispatchResult { 151 | // This should never error if can_pay_fee passed. 152 | self.withdraw_fee().map_err(|_| Error::::LiquidityRestrictions)?; 153 | Ok(()) 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /pallets/automation-price/src/trigger.rs: -------------------------------------------------------------------------------- 1 | use crate::{Config, PriceData, Task}; 2 | 3 | use sp_std::ops::{ 4 | Bound, 5 | Bound::{Excluded, Included}, 6 | }; 7 | 8 | pub const TRIGGER_FUNC_GT: &[u8] = "gt".as_bytes(); 9 | pub const TRIGGER_FUNC_LT: &[u8] = "lt".as_bytes(); 10 | 11 | pub trait PriceConditionMatch { 12 | fn is_price_condition_match(&self, price: &PriceData) -> bool; 13 | } 14 | 15 | impl PriceConditionMatch for Task { 16 | /// check that the task has its condition match the target price of asset 17 | /// 18 | /// # Argument 19 | /// 20 | /// * `price` - the desire price of the asset to check on 21 | fn is_price_condition_match(&self, price: &PriceData) -> bool { 22 | // trigger when target price > current price of the asset 23 | // Example: 24 | // - current price: 100, the task is has target price: 50 -> runable 25 | // - current price: 100, the task is has target price: 150 -> not runable 26 | // 27 | 28 | if self.trigger_function == TRIGGER_FUNC_GT.to_vec() { 29 | price.value > self.trigger_params[0] 30 | } else { 31 | price.value < self.trigger_params[0] 32 | } 33 | } 34 | } 35 | 36 | /// Given a condition, and a target price, generate a range that match the condition 37 | pub fn range_by_trigger_func( 38 | trigger_func: &[u8], 39 | current_price: &PriceData, 40 | ) -> (Bound, Bound) { 41 | //Eg sell order, sell when price > 42 | if trigger_func == TRIGGER_FUNC_GT { 43 | (Excluded(u128::MIN), Excluded(current_price.value)) 44 | } else { 45 | // Eg buy order, buy when price < target 46 | (Included(current_price.value), Excluded(u128::MAX)) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /pallets/automation-price/src/types.rs: -------------------------------------------------------------------------------- 1 | use crate::{weights::WeightInfo, Config, InstructionSequence}; 2 | 3 | use frame_support::pallet_prelude::*; 4 | 5 | use sp_std::prelude::*; 6 | 7 | use xcm::{latest::prelude::*, VersionedMultiLocation}; 8 | 9 | /// The struct that stores execution payment for a task. 10 | #[derive(Debug, Encode, Eq, PartialEq, Decode, TypeInfo, Clone)] 11 | pub struct AssetPayment { 12 | pub asset_location: VersionedMultiLocation, 13 | pub amount: u128, 14 | } 15 | 16 | /// The enum that stores all action specific data. 17 | #[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)] 18 | #[scale_info(skip_type_params(T))] 19 | pub enum Action { 20 | XCMP { 21 | destination: MultiLocation, 22 | schedule_fee: MultiLocation, 23 | execution_fee: AssetPayment, 24 | encoded_call: Vec, 25 | encoded_call_weight: Weight, 26 | overall_weight: Weight, 27 | schedule_as: Option, 28 | instruction_sequence: InstructionSequence, 29 | }, 30 | } 31 | 32 | impl Action { 33 | pub fn execution_weight(&self) -> Result { 34 | let weight = match self { 35 | Action::XCMP { .. } => ::WeightInfo::run_xcmp_task(), 36 | }; 37 | Ok(weight.ref_time()) 38 | } 39 | 40 | pub fn schedule_fee_location(&self) -> MultiLocation { 41 | match self { 42 | Action::XCMP { schedule_fee, .. } => *schedule_fee, 43 | _ => MultiLocation::default(), 44 | } 45 | } 46 | } 47 | 48 | /// The enum represent the type of metric we track 49 | #[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)] 50 | #[scale_info(skip_type_params(T))] 51 | pub enum StatType { 52 | TotalTasksOverall, 53 | TotalTasksPerAccount, 54 | } 55 | -------------------------------------------------------------------------------- /pallets/automation-time/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-time" 3 | description = "Pallet for scheduling and running tasks in the future." 4 | version = "1.0.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | readme = 'README.md' 11 | 12 | [package.metadata.docs.rs] 13 | targets = ['x86_64-unknown-linux-gnu'] 14 | 15 | [dependencies] 16 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 17 | "derive", 18 | ], default-features = false } 19 | scale-info = { version = "2.1", default-features = false, features = [ 20 | "derive", 21 | ] } 22 | log = { version = "0.4.17", default-features = false } 23 | hex = { version = "0.4.3", default-features = false, features = [ 24 | "alloc", 25 | ] } 26 | 27 | # Polkadot 28 | polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 29 | xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 30 | 31 | # Cumulus dependencies 32 | cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus', default-features = false, branch = 'polkadot-v0.9.43' } 33 | cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus', default-features = false, branch = 'polkadot-v0.9.43' } 34 | 35 | # Substrate Dependencies 36 | ## Substrate Primitive Dependencies 37 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 38 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 39 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 40 | 41 | ## Substrate FRAME Dependencies 42 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } 43 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 44 | frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 45 | 46 | ## Substrate Pallet Dependencies 47 | pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 48 | pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 49 | 50 | ## Polkdadot deps 51 | xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 52 | 53 | ## Moonbeam Dependencies 54 | pallet-parachain-staking = { git = "https://github.com/OAK-Foundation/moonbeam", default-features = false, branch = "oak-polkadot-v0.9.43" } 55 | 56 | ## ORML 57 | orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 58 | orml-currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 59 | 60 | ## Local 61 | pallet-automation-time-rpc-runtime-api = { path = "./rpc/runtime-api", default-features = false } 62 | pallet-valve = { path = "../valve", default-features = false } 63 | pallet-xcmp-handler = { path = "../xcmp-handler", default-features = false } 64 | primitives = { path = "../../primitives", default-features = false } 65 | 66 | 67 | [dev-dependencies] 68 | rand = { version = "0.7.3" } 69 | serde = { version = "1.0.144" } 70 | sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 71 | 72 | pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 73 | pallet-xcm = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 74 | xcm-executor = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 75 | 76 | # Cumulus dependencies 77 | parachain-info = { git = 'https://github.com/paritytech/cumulus', branch = 'polkadot-v0.9.43' } 78 | 79 | orml-currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 80 | orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 81 | 82 | [features] 83 | default = ["std"] 84 | runtime-benchmarks = [ 85 | "frame-benchmarking", 86 | "pallet-parachain-staking/runtime-benchmarks", 87 | ] 88 | try-runtime = ["frame-support/try-runtime"] 89 | std = [ 90 | "codec/std", 91 | "cumulus-pallet-xcm/std", 92 | "cumulus-primitives-core/std", 93 | "frame-benchmarking/std", 94 | "frame-support/std", 95 | "frame-system/std", 96 | "orml-currencies/std", 97 | "orml-tokens/std", 98 | "orml-traits/std", 99 | "pallet-automation-time-rpc-runtime-api/std", 100 | "pallet-timestamp/std", 101 | "pallet-xcm/std", 102 | "pallet-parachain-staking/std", 103 | "pallet-valve/std", 104 | "pallet-xcmp-handler/std", 105 | "polkadot-parachain/std", 106 | "scale-info/std", 107 | "sp-runtime/std", 108 | "sp-std/std", 109 | "xcm/std", 110 | "xcm-builder/std", 111 | "xcm-executor/std", 112 | ] 113 | dev-queue = [] 114 | -------------------------------------------------------------------------------- /pallets/automation-time/rpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-time-rpc" 3 | description = "RPC API to provide information about tasks" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3" } 16 | jsonrpsee = { version = "0.16.2", features = ["server", "macros"] } 17 | 18 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 19 | sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 20 | sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 21 | sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 22 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 23 | sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 24 | 25 | pallet-automation-time-rpc-runtime-api = { path = "./runtime-api" } 26 | -------------------------------------------------------------------------------- /pallets/automation-time/rpc/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-automation-time-rpc-runtime-api" 3 | description = "Runtime RPC API to provide information about tasks" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3", features = ["derive", "full"], default-features = false } 16 | serde = { version = "1.0.144", features = ["derive"], optional = true } 17 | scale-info = { version = "2.1", default-features = false, features = [ 18 | "derive", 19 | ] } 20 | 21 | sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 22 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 23 | 24 | [features] 25 | default = ["std"] 26 | std = [ 27 | "serde", 28 | "codec/std", 29 | "sp-api/std", 30 | "sp-std/std", 31 | ] 32 | 33 | -------------------------------------------------------------------------------- /pallets/automation-time/rpc/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use codec::{Codec, Decode, Encode}; 21 | use scale_info::{prelude::string::String, TypeInfo}; 22 | use sp_std::vec::Vec; 23 | 24 | #[cfg(feature = "std")] 25 | use serde::{Deserialize, Serialize}; 26 | 27 | #[derive(PartialEq, Encode, Decode, TypeInfo)] 28 | #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] 29 | #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] 30 | #[cfg_attr(feature = "std", serde(deny_unknown_fields))] 31 | pub struct AutostakingResult { 32 | pub period: i32, 33 | pub apy: String, 34 | } 35 | 36 | #[derive(Debug, PartialEq, Encode, Decode)] 37 | #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] 38 | pub enum AutomationAction { 39 | XCMP, 40 | AutoCompoundDelegatedStake, 41 | } 42 | 43 | #[derive(Debug, PartialEq, Encode, Decode, TypeInfo)] 44 | #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] 45 | #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] 46 | pub struct FeeDetails { 47 | pub schedule_fee: Balance, 48 | pub execution_fee: Balance, 49 | } 50 | 51 | sp_api::decl_runtime_apis! { 52 | pub trait AutomationTimeApi where 53 | AccountId: Codec, 54 | Hash: Codec, 55 | Balance: Codec, 56 | { 57 | fn query_fee_details(uxt: Block::Extrinsic) -> Result, Vec>; 58 | fn calculate_optimal_autostaking( 59 | principal: i128, 60 | collator: AccountId 61 | ) -> Result>; 62 | fn get_auto_compound_delegated_stake_task_ids(account_id: AccountId) -> Vec>; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /pallets/valve/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-valve" 3 | description = "Pallet for pausing different parts of the chain." 4 | version = "0.2.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | homepage = "https://oak.tech" 8 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 9 | 10 | [package.metadata.docs.rs] 11 | targets = ['x86_64-unknown-linux-gnu'] 12 | 13 | [dependencies] 14 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 15 | "derive", 16 | ], default-features = false } 17 | scale-info = { version = "2.0.0", default-features = false, features = [ 18 | "derive", 19 | ] } 20 | 21 | # Substrate 22 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } 23 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 24 | frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 25 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 26 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 27 | 28 | 29 | [dev-dependencies] 30 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 31 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 32 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 33 | 34 | [features] 35 | default = ["std"] 36 | runtime-benchmarks = ["frame-benchmarking"] 37 | try-runtime = ["frame-support/try-runtime"] 38 | std = [ 39 | "codec/std", 40 | "frame-benchmarking/std", 41 | "frame-support/std", 42 | "frame-system/std", 43 | "pallet-balances/std", 44 | "scale-info/std", 45 | "sp-runtime/std", 46 | "sp-std/std", 47 | ] 48 | -------------------------------------------------------------------------------- /pallets/valve/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![cfg(feature = "runtime-benchmarks")] 19 | 20 | use super::*; 21 | use frame_benchmarking::benchmarks; 22 | use frame_support::traits::SortedMembers; 23 | use frame_system::RawOrigin; 24 | 25 | fn assert_last_event(generic_event: ::RuntimeEvent) { 26 | frame_system::Pallet::::assert_last_event(generic_event.into()); 27 | } 28 | 29 | fn get_caller_account_id() -> T::AccountId { 30 | T::CallAccessFilter::sorted_members().pop().unwrap() 31 | } 32 | 33 | benchmarks! { 34 | close_valve { 35 | let caller = get_caller_account_id::(); 36 | }: _(RawOrigin::Signed(caller)) 37 | verify { 38 | assert_last_event::(Event::ValveClosed.into()) 39 | } 40 | 41 | open_valve { 42 | let caller = get_caller_account_id::(); 43 | ValveClosed::::put(true); 44 | }: _(RawOrigin::Signed(caller)) 45 | verify { 46 | assert_last_event::(Event::ValveOpen.into()) 47 | } 48 | 49 | close_pallet_gate_new { 50 | let caller = get_caller_account_id::(); 51 | let pallet_name = b"System".to_vec(); 52 | }: close_pallet_gate(RawOrigin::Signed(caller), pallet_name.clone()) 53 | verify { 54 | assert_last_event::(Event::PalletGateClosed{ pallet_name_bytes: pallet_name }.into()) 55 | } 56 | 57 | close_pallet_gate_existing { 58 | let caller = get_caller_account_id::(); 59 | let pallet_name = b"System".to_vec(); 60 | ClosedPallets::::insert(pallet_name.clone(), ()); 61 | }: close_pallet_gate(RawOrigin::Signed(caller), pallet_name.to_vec()) 62 | 63 | open_pallet_gate { 64 | let caller = get_caller_account_id::(); 65 | let pallet_name = b"System".to_vec(); 66 | ClosedPallets::::insert(pallet_name.clone(), ()); 67 | }: _(RawOrigin::Signed(caller), pallet_name.clone()) 68 | verify { 69 | assert_last_event::(Event::PalletGateOpen{ pallet_name_bytes: pallet_name }.into()) 70 | } 71 | 72 | open_pallet_gates { 73 | let caller = get_caller_account_id::(); 74 | ClosedPallets::::insert(b"System".to_vec(), ()); 75 | ClosedPallets::::insert(b"Balances".to_vec(), ()); 76 | ClosedPallets::::insert(b"Bounties".to_vec(), ()); 77 | ClosedPallets::::insert(b"CollatorSelection".to_vec(), ()); 78 | ClosedPallets::::insert(b"Treasury".to_vec(), ()); 79 | ClosedPalletCount::::put(5); 80 | }: _(RawOrigin::Signed(caller)) 81 | verify { 82 | assert_last_event::(Event::PalletGatesClosed{ count: 0 }.into()) 83 | } 84 | 85 | stop_scheduled_tasks { 86 | let caller = get_caller_account_id::(); 87 | }: _(RawOrigin::Signed(caller)) 88 | verify { 89 | assert_last_event::(Event::ScheduledTasksStopped.into()) 90 | } 91 | 92 | start_scheduled_tasks { 93 | let caller = get_caller_account_id::(); 94 | T::AutomationTime::shutdown(); 95 | }: _(RawOrigin::Signed(caller)) 96 | verify { 97 | assert_last_event::(Event::ScheduledTasksResumed.into()) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /pallets/valve/src/traits.rs: -------------------------------------------------------------------------------- 1 | /// For pallets that want to be notified on shutdown events 2 | pub trait Shutdown { 3 | /// Whether or not implementer is shutdown 4 | fn is_shutdown() -> bool; 5 | /// Forwards shutdown message to implementer 6 | fn shutdown(); 7 | /// Forwards restart message to implementer 8 | fn restart(); 9 | } 10 | 11 | impl Shutdown for () { 12 | fn is_shutdown() -> bool { 13 | true 14 | } 15 | fn shutdown() {} 16 | fn restart() {} 17 | } 18 | -------------------------------------------------------------------------------- /pallets/vesting/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-vesting" 3 | description = "Pallet for minting tokens on a set schedule" 4 | version = "1.0.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ['x86_64-unknown-linux-gnu'] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 16 | "derive", 17 | ], default-features = false } 18 | scale-info = { version = "2.1", default-features = false, features = [ 19 | "derive", 20 | ] } 21 | log = { version = "0.4.17", default-features = false } 22 | 23 | # Substrate Dependencies 24 | ## Substrate Primitive Dependencies 25 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 26 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 27 | 28 | ## Substrate FRAME Dependencies 29 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } 30 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 31 | frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 32 | 33 | ## Substrate Pallet Dependencies 34 | pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 35 | 36 | ## Moonbeam dependencies 37 | pallet-parachain-staking = { git = "https://github.com/OAK-Foundation/moonbeam", default-features = false, branch = "oak-polkadot-v0.9.43" } 38 | 39 | [dev-dependencies] 40 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 41 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 42 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 43 | 44 | [features] 45 | default = ["std"] 46 | runtime-benchmarks = ["frame-benchmarking"] 47 | try-runtime = ["frame-support/try-runtime"] 48 | std = [ 49 | "codec/std", 50 | "scale-info/std", 51 | "sp-runtime/std", 52 | "sp-std/std", 53 | "frame-support/std", 54 | "frame-system/std", 55 | "pallet-timestamp/std", 56 | "pallet-parachain-staking/std", 57 | ] 58 | -------------------------------------------------------------------------------- /pallets/vesting/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use super::*; 18 | use frame_benchmarking::{account, benchmarks}; 19 | use frame_support::traits::Currency; 20 | use sp_runtime::traits::{SaturatedConversion, Saturating}; 21 | use sp_std::{vec, vec::Vec}; 22 | 23 | use crate::Pallet as Vesting; 24 | 25 | const FIRST_VEST_TIME: u64 = 3600; 26 | const ED_MULTIPLIER: u32 = 10; 27 | 28 | benchmarks! { 29 | vest { 30 | let v in 0 .. 20; 31 | 32 | if v > 0 { 33 | let mut scheduled_vests: Vec<(AccountOf, BalanceOf)> = vec![]; 34 | let amount = T::Currency::minimum_balance().saturating_mul(ED_MULTIPLIER.into()); 35 | for i in 0 .. v { 36 | let vesting_account = account("person", 0, i); 37 | scheduled_vests.push((vesting_account, amount)); 38 | } 39 | VestingSchedule::::insert(FIRST_VEST_TIME, scheduled_vests); 40 | } 41 | 42 | let pallet_time: u32 = (FIRST_VEST_TIME * 1_000).saturated_into::(); 43 | >::set_timestamp(pallet_time.into()); 44 | }: { Vesting::::vest() } 45 | } 46 | -------------------------------------------------------------------------------- /pallets/vesting/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use super::*; 18 | use crate as pallet_vesting; 19 | use frame_support::{ 20 | construct_runtime, parameter_types, 21 | traits::{ConstU32, Everything, GenesisBuild}, 22 | }; 23 | use sp_core::H256; 24 | use sp_runtime::{ 25 | testing::Header, 26 | traits::{BlakeTwo256, IdentityLookup}, 27 | }; 28 | 29 | pub type AccountId = u64; 30 | pub type BlockNumber = u64; 31 | pub type Balance = u128; 32 | 33 | pub const ALICE: AccountId = 1; 34 | pub const BOB: AccountId = 2; 35 | 36 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 37 | type Block = frame_system::mocking::MockBlock; 38 | 39 | construct_runtime!( 40 | pub enum Test where 41 | Block = Block, 42 | NodeBlock = Block, 43 | UncheckedExtrinsic = UncheckedExtrinsic, 44 | { 45 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 46 | Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, 47 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 48 | Vesting: pallet_vesting::{Pallet, Storage, Config, Event}, 49 | } 50 | ); 51 | 52 | parameter_types! { 53 | pub const BlockHashCount: u64 = 250; 54 | pub const SS58Prefix: u8 = 51; 55 | } 56 | impl frame_system::Config for Test { 57 | type BaseCallFilter = Everything; 58 | type DbWeight = (); 59 | type RuntimeOrigin = RuntimeOrigin; 60 | type Index = u64; 61 | type BlockNumber = BlockNumber; 62 | type RuntimeCall = RuntimeCall; 63 | type Hash = H256; 64 | type Hashing = BlakeTwo256; 65 | type AccountId = AccountId; 66 | type Lookup = IdentityLookup; 67 | type Header = Header; 68 | type RuntimeEvent = RuntimeEvent; 69 | type BlockHashCount = BlockHashCount; 70 | type Version = (); 71 | type PalletInfo = PalletInfo; 72 | type AccountData = pallet_balances::AccountData; 73 | type OnNewAccount = (); 74 | type OnKilledAccount = (); 75 | type SystemWeightInfo = (); 76 | type BlockWeights = (); 77 | type BlockLength = (); 78 | type SS58Prefix = SS58Prefix; 79 | type OnSetCode = (); 80 | type MaxConsumers = frame_support::traits::ConstU32<16>; 81 | } 82 | 83 | parameter_types! { 84 | pub const ExistentialDeposit: u64 = 10; 85 | pub const MaxLocks: u32 = 50; 86 | pub const MaxReserves: u32 = 50; 87 | } 88 | 89 | impl pallet_balances::Config for Test { 90 | type MaxLocks = MaxLocks; 91 | type Balance = Balance; 92 | type RuntimeEvent = RuntimeEvent; 93 | type DustRemoval = (); 94 | type ExistentialDeposit = ExistentialDeposit; 95 | type AccountStore = System; 96 | type WeightInfo = (); 97 | type MaxReserves = MaxReserves; 98 | type ReserveIdentifier = [u8; 8]; 99 | type HoldIdentifier = (); 100 | type FreezeIdentifier = (); 101 | type MaxHolds = ConstU32<0>; 102 | type MaxFreezes = ConstU32<0>; 103 | } 104 | 105 | parameter_types! { 106 | pub const MinimumPeriod: u64 = 1000; 107 | } 108 | 109 | impl pallet_timestamp::Config for Test { 110 | type Moment = u64; 111 | type OnTimestampSet = (); 112 | type MinimumPeriod = MinimumPeriod; 113 | type WeightInfo = (); 114 | } 115 | 116 | impl Config for Test { 117 | type RuntimeEvent = RuntimeEvent; 118 | type WeightInfo = (); 119 | type Currency = Balances; 120 | } 121 | 122 | #[derive(Default)] 123 | pub(crate) struct ExtBuilder { 124 | vesting_schedule: Vec<(u64, Vec<(AccountId, Balance)>)>, 125 | } 126 | 127 | impl ExtBuilder { 128 | pub(crate) fn schedule(mut self, v: Vec<(u64, Vec<(AccountId, Balance)>)>) -> Self { 129 | self.vesting_schedule = v; 130 | self 131 | } 132 | 133 | pub(crate) fn build(self) -> sp_io::TestExternalities { 134 | let mut t = frame_system::GenesisConfig::default() 135 | .build_storage::() 136 | .expect("Frame system builds valid default genesis config"); 137 | 138 | GenesisBuild::::assimilate_storage( 139 | &pallet_vesting::GenesisConfig { vesting_schedule: self.vesting_schedule }, 140 | &mut t, 141 | ) 142 | .expect("Pallet valve vesting can be assimilated"); 143 | 144 | let mut ext = sp_io::TestExternalities::new(t); 145 | ext.execute_with(|| System::set_block_number(1)); 146 | ext 147 | } 148 | } 149 | 150 | pub(crate) fn events() -> Vec> { 151 | let evt = System::events() 152 | .into_iter() 153 | .map(|r| r.event) 154 | .filter_map(|e| if let RuntimeEvent::Vesting(inner) = e { Some(inner) } else { None }) 155 | .collect::>(); 156 | 157 | System::reset_events(); 158 | evt 159 | } 160 | -------------------------------------------------------------------------------- /pallets/vesting/src/tests.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | use crate::{mock::*, Event}; 19 | use frame_support::traits::OnInitialize; 20 | use pallet_parachain_staking::AdditionalIssuance; 21 | 22 | const FIRST_VEST_TIME: u64 = 1646028000; 23 | const SECOND_VEST_TIME: u64 = FIRST_VEST_TIME + 3_600; 24 | 25 | #[test] 26 | fn genesis_default() { 27 | ExtBuilder::default().build().execute_with(|| { 28 | assert_eq!(Vesting::total_unvested_allocation(), 0); 29 | }) 30 | } 31 | 32 | #[test] 33 | #[should_panic = "Invalid time"] 34 | fn genesis_bad_time() { 35 | let mut scheduled_vests: Vec<(u64, Vec<(AccountId, Balance)>)> = vec![]; 36 | let first_vest: Vec<(AccountId, Balance)> = vec![(ALICE, 100), (BOB, 100)]; 37 | scheduled_vests.push((FIRST_VEST_TIME + 120, first_vest)); 38 | 39 | ExtBuilder::default().schedule(scheduled_vests).build().execute_with(|| {}) 40 | } 41 | 42 | #[test] 43 | #[should_panic = "Cannot vest less than the existential deposit"] 44 | fn genesis_low_amount() { 45 | let mut scheduled_vests: Vec<(u64, Vec<(AccountId, Balance)>)> = vec![]; 46 | let first_vest: Vec<(AccountId, Balance)> = vec![(ALICE, 1), (BOB, 100)]; 47 | scheduled_vests.push((FIRST_VEST_TIME, first_vest)); 48 | ExtBuilder::default().schedule(scheduled_vests).build().execute_with(|| {}) 49 | } 50 | 51 | #[test] 52 | fn genesis() { 53 | let scheduled_vests = get_schedule(); 54 | 55 | ExtBuilder::default().schedule(scheduled_vests).build().execute_with(|| { 56 | let first_vest = Vesting::get_scheduled_vest(FIRST_VEST_TIME); 57 | let second_vest = Vesting::get_scheduled_vest(SECOND_VEST_TIME); 58 | 59 | assert_eq!(first_vest.unwrap().len(), 2); 60 | assert_eq!(second_vest.unwrap().len(), 2); 61 | assert_eq!(Vesting::total_unvested_allocation(), 600); 62 | }) 63 | } 64 | 65 | #[test] 66 | fn on_initialize_with_default() { 67 | ExtBuilder::default().build().execute_with(|| { 68 | Timestamp::set_timestamp(FIRST_VEST_TIME * 1_000); 69 | 70 | assert_eq!(None, Vesting::get_scheduled_vest(FIRST_VEST_TIME)); 71 | Vesting::on_initialize(1); 72 | }) 73 | } 74 | 75 | #[test] 76 | fn on_initialize_no_time_set() { 77 | let scheduled_vests = get_schedule(); 78 | 79 | ExtBuilder::default().schedule(scheduled_vests).build().execute_with(|| { 80 | Vesting::on_initialize(1); 81 | 82 | let first_vest = Vesting::get_scheduled_vest(FIRST_VEST_TIME); 83 | let second_vest = Vesting::get_scheduled_vest(SECOND_VEST_TIME); 84 | assert_eq!(first_vest.unwrap().len(), 2); 85 | assert_eq!(second_vest.unwrap().len(), 2); 86 | 87 | assert_eq!(Vesting::total_unvested_allocation(), 600); 88 | }) 89 | } 90 | 91 | #[test] 92 | fn on_initialize() { 93 | let scheduled_vests = get_schedule(); 94 | 95 | ExtBuilder::default().schedule(scheduled_vests).build().execute_with(|| { 96 | Timestamp::set_timestamp(FIRST_VEST_TIME * 1_000); 97 | 98 | let first_vest = Vesting::get_scheduled_vest(FIRST_VEST_TIME); 99 | let vest_events = vest_to_events(first_vest.unwrap()); 100 | Vesting::on_initialize(1); 101 | 102 | let first_vest = Vesting::get_scheduled_vest(FIRST_VEST_TIME); 103 | let second_vest = Vesting::get_scheduled_vest(SECOND_VEST_TIME); 104 | assert_eq!(first_vest, None); 105 | assert_eq!(second_vest.unwrap().len(), 2); 106 | assert_eq!(events(), vest_events); 107 | assert_eq!(Balances::free_balance(ALICE), 100); 108 | assert_eq!(Balances::free_balance(BOB), 100); 109 | assert_eq!(Vesting::total_unvested_allocation(), 400); 110 | 111 | let second_vest = Vesting::get_scheduled_vest(SECOND_VEST_TIME); 112 | let vest_events = vest_to_events(second_vest.unwrap()); 113 | Timestamp::set_timestamp(SECOND_VEST_TIME * 1_000); 114 | Vesting::on_initialize(2); 115 | 116 | let second_vest = Vesting::get_scheduled_vest(SECOND_VEST_TIME); 117 | assert_eq!(second_vest, None); 118 | assert_eq!(events(), vest_events); 119 | assert_eq!(Balances::free_balance(ALICE), 300); 120 | assert_eq!(Balances::free_balance(BOB), 300); 121 | assert_eq!(Vesting::total_unvested_allocation(), 0); 122 | 123 | Timestamp::set_timestamp(SECOND_VEST_TIME * 1_000); 124 | Vesting::on_initialize(2); 125 | }) 126 | } 127 | 128 | #[test] 129 | fn additional_issuance() { 130 | ExtBuilder::default().schedule(get_schedule()).build().execute_with(|| { 131 | assert_eq!(Vesting::additional_issuance(), 600); 132 | }) 133 | } 134 | 135 | fn get_schedule() -> Vec<(u64, Vec<(AccountId, Balance)>)> { 136 | let first_vest = vec![(ALICE, 100), (BOB, 100)]; 137 | let second_vest = vec![(ALICE, 200), (BOB, 200)]; 138 | let scheduled_vests = vec![(FIRST_VEST_TIME, first_vest), (SECOND_VEST_TIME, second_vest)]; 139 | scheduled_vests 140 | } 141 | 142 | fn vest_to_events(vests: Vec<(AccountId, Balance)>) -> Vec> { 143 | let mut events: Vec> = vec![]; 144 | for (account, amount) in vests { 145 | let event = Event::Vested { account, amount }; 146 | events.push(event); 147 | } 148 | events 149 | } 150 | -------------------------------------------------------------------------------- /pallets/vesting/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK-blockchain. 2 | 3 | // Copyright (C) OAK Network Ltd. 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for pallet_vesting 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 22 | //! DATE: 2023-11-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` 23 | //! WORST CASE MAP SIZE: `1000000` 24 | //! HOSTNAME: `actions-runner-1`, CPU: `Intel(R) Xeon(R) E-2388G CPU @ 3.20GHz` 25 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("turing-dev"), DB CACHE: 1024 26 | 27 | // Executed Command: 28 | // ./oak-collator 29 | // benchmark 30 | // pallet 31 | // --header 32 | // ./.maintain/HEADER-GPL3 33 | // --chain 34 | // turing-dev 35 | // --execution 36 | // wasm 37 | // --wasm-execution 38 | // compiled 39 | // --pallet 40 | // pallet_vesting 41 | // --extrinsic 42 | // * 43 | // --repeat 44 | // 20 45 | // --steps 46 | // 50 47 | // --output 48 | // ./vesting-raw-weights.rs 49 | // --template 50 | // ./.maintain/frame-weight-template.hbs 51 | 52 | // Summary: 53 | //:vest 14_516_142,3735 54 | 55 | #![cfg_attr(rustfmt, rustfmt_skip)] 56 | #![allow(unused_parens)] 57 | #![allow(unused_imports)] 58 | #![allow(missing_docs)] 59 | 60 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 61 | use core::marker::PhantomData; 62 | 63 | /// Weight functions needed for pallet_vesting. 64 | pub trait WeightInfo { 65 | fn vest(v: u32, ) -> Weight; 66 | } 67 | 68 | /// Weights for pallet_vesting using the Substrate node and recommended hardware. 69 | pub struct SubstrateWeight(PhantomData); 70 | impl WeightInfo for SubstrateWeight { 71 | /// Storage: Timestamp Now (r:1 w:0) 72 | /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) 73 | /// Storage: Vesting VestingSchedule (r:1 w:1) 74 | /// Proof Skipped: Vesting VestingSchedule (max_values: None, max_size: None, mode: Measured) 75 | /// Storage: System Account (r:20 w:20) 76 | /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) 77 | /// Storage: Vesting TotalUnvestedAllocation (r:1 w:1) 78 | /// Proof Skipped: Vesting TotalUnvestedAllocation (max_values: Some(1), max_size: None, mode: Measured) 79 | /// The range of component `v` is `[0, 20]`. 80 | fn vest(v: u32, ) -> Weight { 81 | // Proof Size summary in bytes: 82 | // Measured: `286 + v * (55 ±0)` 83 | // Estimated: `3735 + v * (2603 ±0)` 84 | // Minimum execution time: 8_070_000 picoseconds. 85 | Weight::from_parts(14_516_142, 3735) 86 | // Standard Error: 14_066 87 | .saturating_add(Weight::from_parts(24_069_000, 0).saturating_mul(v.into())) 88 | .saturating_add(T::DbWeight::get().reads(3_u64)) 89 | .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(v.into()))) 90 | .saturating_add(T::DbWeight::get().writes(2_u64)) 91 | .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(v.into()))) 92 | .saturating_add(Weight::from_parts(0, 2603).saturating_mul(v.into())) 93 | } 94 | } 95 | 96 | // For backwards compatibility and tests 97 | impl WeightInfo for () { 98 | /// Storage: Timestamp Now (r:1 w:0) 99 | /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) 100 | /// Storage: Vesting VestingSchedule (r:1 w:1) 101 | /// Proof Skipped: Vesting VestingSchedule (max_values: None, max_size: None, mode: Measured) 102 | /// Storage: System Account (r:20 w:20) 103 | /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) 104 | /// Storage: Vesting TotalUnvestedAllocation (r:1 w:1) 105 | /// Proof Skipped: Vesting TotalUnvestedAllocation (max_values: Some(1), max_size: None, mode: Measured) 106 | /// The range of component `v` is `[0, 20]`. 107 | fn vest(v: u32, ) -> Weight { 108 | // Proof Size summary in bytes: 109 | // Measured: `286 + v * (55 ±0)` 110 | // Estimated: `3735 + v * (2603 ±0)` 111 | // Minimum execution time: 8_070_000 picoseconds. 112 | Weight::from_parts(14_516_142, 3735) 113 | // Standard Error: 14_066 114 | .saturating_add(Weight::from_parts(24_069_000, 0).saturating_mul(v.into())) 115 | .saturating_add(RocksDbWeight::get().reads(3_u64)) 116 | .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(v.into()))) 117 | .saturating_add(RocksDbWeight::get().writes(2_u64)) 118 | .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(v.into()))) 119 | .saturating_add(Weight::from_parts(0, 2603).saturating_mul(v.into())) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-xcmp-handler" 3 | description = "Pallet to handle XCMP intricacies." 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | homepage = "https://oak.tech" 8 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 9 | 10 | [package.metadata.docs.rs] 11 | targets = ['x86_64-unknown-linux-gnu'] 12 | 13 | [dependencies] 14 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 15 | "derive", 16 | ], default-features = false } 17 | scale-info = { version = "2.1", default-features = false, features = [ 18 | "derive", 19 | ] } 20 | log = { version = "0.4.17", default-features = false } 21 | serde = { version = "1.0.144" } 22 | 23 | # Substrate Dependencies 24 | ## Substrate Primitive Dependencies 25 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 26 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 27 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 28 | 29 | ## Substrate FRAME Dependencies 30 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } 31 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 32 | frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 33 | 34 | # Cumulus dependencies 35 | cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus', branch = 'polkadot-v0.9.43', default-features = false } 36 | 37 | 38 | # Polkadot Dependencies 39 | polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 40 | xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 41 | xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 42 | 43 | # ORML 44 | orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 45 | orml-currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 46 | orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 47 | 48 | [dev-dependencies] 49 | # Substrate 50 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 51 | sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 52 | 53 | # Cumulus dependencies 54 | cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus', default-features = false, branch = 'polkadot-v0.9.43' } 55 | parachain-info = { git = 'https://github.com/paritytech/cumulus', branch = 'polkadot-v0.9.43' } 56 | 57 | # Polkadot Dependencies 58 | polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 59 | pallet-xcm = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 60 | xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.43" } 61 | xcm-executor = { git = 'https://github.com/paritytech/polkadot', default-features = false, branch = "release-v0.9.43" } 62 | 63 | primitives = { path = "../../primitives", default-features = false } 64 | 65 | [features] 66 | default = ["std"] 67 | runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"] 68 | try-runtime = ["frame-support/try-runtime"] 69 | std = [ 70 | "codec/std", 71 | "cumulus-primitives-core/std", 72 | "frame-benchmarking/std", 73 | "frame-support/std", 74 | "frame-system/std", 75 | "orml-traits/std", 76 | "polkadot-parachain/std", 77 | "scale-info/std", 78 | "sp-runtime/std", 79 | "sp-std/std", 80 | "xcm/std", 81 | "xcm-builder/std", 82 | "xcm-executor/std", 83 | ] 84 | 85 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/rpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-xcmp-handler-rpc" 3 | description = "RPC API to provide information about xcmp" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3", default-features = false, features = ["derive"]} 16 | jsonrpsee = { version = "0.16.2", features = ["server", "macros"] } 17 | 18 | sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 19 | sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 20 | sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 21 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 22 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" } 23 | 24 | pallet-xcmp-handler-rpc-runtime-api = { path = "./runtime-api" } 25 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/rpc/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-xcmp-handler-rpc-runtime-api" 3 | description = "Runtime RPC API to provide information about XCMP" 4 | version = "0.1.0" 5 | edition = "2021" 6 | authors = ["OAK Developement Team"] 7 | license = "GPL-3.0" 8 | homepage = "https://oak.tech" 9 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { package = "parity-scale-codec", version = "3.1.3", features = ["derive", "full"], default-features = false } 16 | serde = { version = "1.0.144", features = ["derive"], optional = true } 17 | 18 | sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 19 | sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 20 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 21 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 22 | 23 | [features] 24 | default = ["std"] 25 | std = [ 26 | "serde", 27 | "codec/std", 28 | "sp-api/std", 29 | "sp-core/std", 30 | "sp-runtime/std", 31 | "sp-std/std", 32 | ] 33 | 34 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/rpc/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use codec::Codec; 21 | use sp_runtime::AccountId32; 22 | use sp_std::vec::Vec; 23 | 24 | sp_api::decl_runtime_apis! { 25 | pub trait XcmpHandlerApi where 26 | Balance: Codec, 27 | { 28 | fn cross_chain_account(account_id: AccountId32) -> Result>; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/rpc/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | use codec::Codec; 19 | use jsonrpsee::{ 20 | core::{async_trait, Error as JsonRpseeError, RpcResult}, 21 | proc_macros::rpc, 22 | types::error::{CallError, ErrorObject}, 23 | }; 24 | pub use pallet_xcmp_handler_rpc_runtime_api::XcmpHandlerApi as XcmpHandlerRuntimeApi; 25 | use sp_api::ProvideRuntimeApi; 26 | use sp_blockchain::HeaderBackend; 27 | use sp_runtime::{traits::Block as BlockT, AccountId32}; 28 | use std::{fmt::Debug, sync::Arc}; 29 | 30 | /// An RPC endpoint to provide information about xcmp. 31 | #[rpc(client, server)] 32 | pub trait XcmpHandlerApi { 33 | #[method(name = "xcmpHandler_crossChainAccount")] 34 | fn cross_chain_account(&self, account: AccountId32) -> RpcResult; 35 | } 36 | 37 | /// An implementation of XCMP-specific RPC methods on full client. 38 | pub struct XcmpHandler { 39 | client: Arc, 40 | _marker: std::marker::PhantomData, 41 | } 42 | 43 | impl XcmpHandler { 44 | /// Create new `XcmpHandlerUtility` with the given reference to the client. 45 | pub fn new(client: Arc) -> Self { 46 | Self { client, _marker: Default::default() } 47 | } 48 | } 49 | 50 | /// Error type of this RPC api. 51 | pub enum Error { 52 | /// The call to runtime failed. 53 | RuntimeError, 54 | } 55 | 56 | impl From for i32 { 57 | fn from(e: Error) -> i32 { 58 | match e { 59 | Error::RuntimeError => 1, 60 | } 61 | } 62 | } 63 | 64 | #[async_trait] 65 | impl XcmpHandlerApiServer<::Hash, Balance> 66 | for XcmpHandler 67 | where 68 | Block: BlockT, 69 | Balance: Codec + Copy + TryInto + Debug, 70 | C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, 71 | C::Api: XcmpHandlerRuntimeApi, 72 | { 73 | fn cross_chain_account(&self, account_id: AccountId32) -> RpcResult { 74 | let api = self.client.runtime_api(); 75 | let runtime_api_result = api.cross_chain_account(self.client.info().best_hash, account_id); 76 | let mapped_err = |message| -> JsonRpseeError { 77 | JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( 78 | Error::RuntimeError.into(), 79 | "Unable to get cross chain AccountId", 80 | Some(message), 81 | ))) 82 | }; 83 | runtime_api_result 84 | .map_err(|e| mapped_err(format!("{:?}", e))) 85 | .map(|r| r.map_err(|e| mapped_err(String::from_utf8(e).unwrap_or_default())))? 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /pallets/xcmp-handler/src/migrations/mod.rs: -------------------------------------------------------------------------------- 1 | // Migrations 2 | -------------------------------------------------------------------------------- /parachain-launch/config.yml: -------------------------------------------------------------------------------- 1 | # https://github.com/open-web3-stack/parachain-launch 2 | # Relaychain Configuration 3 | # `parachain-launch generate --config=parachain-launch/config.yml --output=parachain-launch` 4 | relaychain: 5 | image: parity/polkadot:v0.9.29 # the docker image to use 6 | chain: rococo-local # the chain to use 7 | runtimeGenesisConfig: # additonal genesis override 8 | configuration: 9 | config: 10 | validation_upgrade_cooldown: 10 11 | validation_upgrade_delay: 10 12 | env: # environment variables for all relaychain nodes 13 | RUST_LOG: parachain::candidate-backing=trace 14 | flags: # additional CLI flags for all relaychain nodes 15 | - --rpc-methods=unsafe 16 | nodes: # nodes config 17 | - name: alice # the node name and session key, this imply `--alice` 18 | wsPort: 9944 # default ws port number is `9944 + global_node_index` 19 | rpcPort: 9933 # default rpc port number is `9933 + global_node_index` 20 | port: 30333 # default libp2p port number is `30333 + global_node_index` 21 | flags: # additional CLI flags for this node 22 | - --force-authoring 23 | env: 24 | RUST_LOG: babe=debug # environment varitables for this node 25 | - name: bob 26 | - name: charlie 27 | 28 | # Parachain Configuration 29 | parachains: 30 | # Config for first parachain 31 | - image: oaknetwork/neumann:latest 32 | chain: local 33 | id: 2000 # override parachain id 34 | parachain: true # this is parachain, not parathread 35 | flags: # CLI flags for this parachain nodes 36 | - --rpc-methods=unsafe 37 | - --force-authoring 38 | - --execution=wasm 39 | relaychainFlags: # CLI flags for the relaychain port 40 | - --execution=wasm 41 | nodes: # nodes config 42 | - wsPort: 9947 43 | rpcPort: 9936 44 | port: 30336 45 | flags: # additional CLI flags for this node 46 | - --alice 47 | relaychainFlags: # additional CLI flags for relaychain part 48 | - --name=relaychain-alice 49 | - flags: 50 | - --bob 51 | -------------------------------------------------------------------------------- /parachain-launch/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | relaychain-alice: 4 | ports: 5 | - 9944:9944 6 | - 9933:9933 7 | - 30333:30333 8 | volumes: 9 | - relaychain-alice:/data 10 | build: 11 | context: . 12 | dockerfile: relaychain.Dockerfile 13 | command: 14 | - --base-path=/data 15 | - --chain=/app/rococo-local.json 16 | - --validator 17 | - --ws-external 18 | - --rpc-external 19 | - --rpc-cors=all 20 | - --name=alice 21 | - --alice 22 | - --rpc-methods=unsafe 23 | - --force-authoring 24 | environment: 25 | RUST_LOG: babe=debug 26 | ulimits: 27 | &a1 28 | nofile: 29 | soft: 65536 30 | hard: 65536 31 | relaychain-bob: 32 | ports: 33 | - 9945:9944 34 | - 9934:9933 35 | - 30334:30333 36 | volumes: 37 | - relaychain-bob:/data 38 | build: 39 | context: . 40 | dockerfile: relaychain.Dockerfile 41 | command: 42 | - --base-path=/data 43 | - --chain=/app/rococo-local.json 44 | - --validator 45 | - --ws-external 46 | - --rpc-external 47 | - --rpc-cors=all 48 | - --name=bob 49 | - --bob 50 | - --rpc-methods=unsafe 51 | environment: 52 | RUST_LOG: parachain::candidate-backing=trace 53 | ulimits: *a1 54 | relaychain-charlie: 55 | ports: 56 | - 9946:9944 57 | - 9935:9933 58 | - 30335:30333 59 | volumes: 60 | - relaychain-charlie:/data 61 | build: 62 | context: . 63 | dockerfile: relaychain.Dockerfile 64 | command: 65 | - --base-path=/data 66 | - --chain=/app/rococo-local.json 67 | - --validator 68 | - --ws-external 69 | - --rpc-external 70 | - --rpc-cors=all 71 | - --name=charlie 72 | - --charlie 73 | - --rpc-methods=unsafe 74 | environment: 75 | RUST_LOG: parachain::candidate-backing=trace 76 | ulimits: *a1 77 | parachain-2000-0: 78 | ports: 79 | - 9947:9944 80 | - 9936:9933 81 | - 30336:30333 82 | volumes: 83 | - parachain-2000-0:/data 84 | build: 85 | context: . 86 | dockerfile: parachain-2000.Dockerfile 87 | command: 88 | - --base-path=/data 89 | - --chain=/app/local-2000.json 90 | - --ws-external 91 | - --rpc-external 92 | - --rpc-cors=all 93 | - --name=parachain-2000-0 94 | - --collator 95 | - --rpc-methods=unsafe 96 | - --force-authoring 97 | - --execution=wasm 98 | - --alice 99 | - --node-key=6876ee5e966d94253b11cacf8467b4f086e0155c279740c04c48c9a8d8aed073 100 | - --listen-addr=/ip4/0.0.0.0/tcp/30333 101 | - -- 102 | - --chain=/app/rococo-local.json 103 | - --execution=wasm 104 | - --name=relaychain-alice 105 | environment: {} 106 | ulimits: *a1 107 | parachain-2000-1: 108 | ports: 109 | - 9948:9944 110 | - 9937:9933 111 | - 30337:30333 112 | volumes: 113 | - parachain-2000-1:/data 114 | build: 115 | context: . 116 | dockerfile: parachain-2000.Dockerfile 117 | command: 118 | - --base-path=/data 119 | - --chain=/app/local-2000.json 120 | - --ws-external 121 | - --rpc-external 122 | - --rpc-cors=all 123 | - --name=parachain-2000-1 124 | - --collator 125 | - --rpc-methods=unsafe 126 | - --force-authoring 127 | - --execution=wasm 128 | - --bob 129 | - >- 130 | --bootnodes=/dns/parachain-2000-0/tcp/30333/p2p/12D3KooWBPJrQ6apEPC2anmq8DXJEP7UNFa4dXxAoKM2rFpPv9gj 131 | - --listen-addr=/ip4/0.0.0.0/tcp/30333 132 | - -- 133 | - --chain=/app/rococo-local.json 134 | - --execution=wasm 135 | environment: {} 136 | ulimits: *a1 137 | volumes: 138 | relaychain-alice: null 139 | relaychain-bob: null 140 | relaychain-charlie: null 141 | parachain-2000-0: null 142 | parachain-2000-1: null 143 | -------------------------------------------------------------------------------- /parachain-launch/parachain-2000.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM oaknetwork/neumann:latest 2 | COPY . /app -------------------------------------------------------------------------------- /parachain-launch/relaychain.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM parity/polkadot:v0.9.29 2 | COPY . /app -------------------------------------------------------------------------------- /primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "primitives" 3 | version = "1.0.0" 4 | description = "Runtime primitives" 5 | authors = ["OAK Developement Team"] 6 | license = "GPL-3.0" 7 | homepage = "https://oak.tech" 8 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 9 | edition = "2021" 10 | 11 | [dependencies] 12 | impl-trait-for-tuples = "0.2.2" 13 | codec = { package = "parity-scale-codec", version = "3.0.0", features = [ 14 | "derive", 15 | ], default-features = false } 16 | scale-info = { version = "2.1", default-features = false, features = [ 17 | "derive", 18 | ] } 19 | 20 | # Substrate Dependencies 21 | ## Substrate Primitive Dependencies 22 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43", default-features = false } 23 | sp-consensus-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 24 | sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 25 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 26 | sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 27 | 28 | ## Substrate FRAME Dependencies 29 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 30 | 31 | ## Polkdadot deps 32 | xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.43", default-features = false } 33 | xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } 34 | 35 | ## ORML deps 36 | orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 37 | 38 | [features] 39 | default = ["std"] 40 | std = [ 41 | "codec/std", 42 | "scale-info/std", 43 | "sp-consensus-aura/std", 44 | "sp-core/std", 45 | "sp-runtime/std", 46 | ] 47 | -------------------------------------------------------------------------------- /primitives/src/assets.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific 16 | 17 | use codec::{Decode, Encode, MaxEncodedLen}; 18 | use scale_info::TypeInfo; 19 | 20 | #[derive( 21 | Clone, 22 | Copy, 23 | Default, 24 | PartialOrd, 25 | Ord, 26 | PartialEq, 27 | Eq, 28 | Debug, 29 | Encode, 30 | Decode, 31 | TypeInfo, 32 | MaxEncodedLen, 33 | )] 34 | pub struct ConversionRate { 35 | pub native: u32, 36 | pub foreign: u32, 37 | } 38 | 39 | /// TODO: add decimal conversion 40 | /// A type describing our custom additional metadata stored in the orml-asset-registry. 41 | #[derive( 42 | Clone, 43 | Copy, 44 | Default, 45 | PartialOrd, 46 | Ord, 47 | PartialEq, 48 | Eq, 49 | Debug, 50 | Encode, 51 | Decode, 52 | TypeInfo, 53 | MaxEncodedLen, 54 | )] 55 | pub struct CustomMetadata { 56 | /// The fee charged for every second that an XCM message takes to execute. 57 | pub fee_per_second: Option, 58 | /// The token conversion rate of Native to Foreign, ie. 1::10 59 | pub conversion_rate: Option, 60 | } 61 | -------------------------------------------------------------------------------- /resources/neumann-testnet-parachain.yaml: -------------------------------------------------------------------------------- 1 | # NOTE: This does not work on its own. This spins up the network and collators. 2 | # User will need to do the following to achieve working parachain: 3 | # 1. Manually remove the `--validator` parameter from collators. 4 | # 2. Manually create boot/full node on OnFinality and use the P2P address 5 | # for the `--bootnodes` value for the collator nodes. 6 | networkSpec: 7 | displayName: neumann-parachain-testnet-customName 8 | name: neumann-parachain-testnet-customName 9 | protocol: polkadot-parachain 10 | imageRepository: oaknetwork/neumann 11 | imageVersion: 1.2.4-rc2 12 | config: 13 | nodeTypes: 14 | full: 15 | args: 16 | - key: "--force-authoring" 17 | - key: --chain 18 | file: "neumann.json" 19 | - key: -- 20 | - key: --execution 21 | value: wasm 22 | - key: --chain 23 | file: "rococo-testnet.json" 24 | - key: --bootnodes # Relay chain p2p address 25 | value: /dns4/node-6896992096614604800-0.p2p.onfinality.io/tcp/23160/ws/p2p/12D3KooWM1vTue78y2ZjxTjZKgYEPR8gSNFtTda3KETgp3WAhCxK 26 | collator: 27 | args: 28 | - key: "--force-authoring" 29 | - key: --chain 30 | file: "neumann.json" 31 | - key: --collator 32 | - key: --bootnodes # Parachain Boot node p2p address 33 | value: FILL_ME_IN 34 | - key: -- 35 | - key: --execution 36 | value: wasm 37 | - key: --chain 38 | file: "rococo-testnet.json" 39 | - key: --bootnodes # Relay chain p2p address 40 | value: /dns4/node-6896992096614604800-0.p2p.onfinality.io/tcp/23160/ws/p2p/12D3KooWM1vTue78y2ZjxTjZKgYEPR8gSNFtTda3KETgp3WAhCxK 41 | validator: 42 | count: 2 43 | node: 44 | nodeName: neumann-parachain-testnet-collator-customName 45 | nodeType: collator 46 | clusterKey: jm 47 | nodeSpec: 48 | key: unit 49 | multiplier: 4 50 | initFromBackup: false 51 | publicPort: true 52 | useApiKey: true 53 | storage: 100Gi 54 | sessionsKey: 55 | #not needed 56 | bootNode: 57 | count: 1 58 | node: 59 | nodeName: neumann-parachain-testnet-bootnode-customName 60 | nodeType: full 61 | clusterKey: jm 62 | nodeSpec: 63 | key: unit 64 | multiplier: 4 65 | initFromBackup: false 66 | publicPort: true 67 | useApiKey: true 68 | storage: 100Gi -------------------------------------------------------------------------------- /resources/rococo-testnet-relaychain.yaml: -------------------------------------------------------------------------------- 1 | networkSpec: 2 | displayName: rococo-testnet-relaychain 3 | name: rococo-testnet 4 | protocol: substrate 5 | imageRepository: parity/polkadot 6 | imageVersion: v0.9.17 7 | config: 8 | nodeTypes: 9 | full: 10 | args: 11 | - key: "--force-authoring" 12 | - key: "--chain" 13 | file: rococo-testnet.json 14 | validator: 15 | args: 16 | - key: "--force-authoring" 17 | - key: "--chain" 18 | file: rococo-testnet.json 19 | - key: "--no-mdns" 20 | validator: 21 | count: 6 22 | sudoArgs: #sudo args is to reduce the setting of sudo users for each node. For example, there will be 3 nodes running, the first node will be assgin --alice, the second node will be assgin --bob, and the third will be assgin --charlie. 23 | - --alice 24 | - --bob 25 | node: 26 | nodeName: rococo-testnet-validator 27 | nodeType: validator 28 | clusterKey: jm 29 | nodeSpec: 30 | key: unit 31 | multiplier: 4 32 | initFromBackup: false 33 | publicPort: true 34 | useApiKey: true 35 | storage: 30Gi 36 | sessionsKey: 37 | #not needed 38 | bootNode: 39 | count: 1 40 | node: 41 | nodeName: rococo-testnet-bootnode 42 | nodeType: full 43 | clusterKey: jm 44 | nodeSpec: 45 | key: unit 46 | multiplier: 4 47 | initFromBackup: false 48 | publicPort: true 49 | useApiKey: true 50 | storage: 30Gi -------------------------------------------------------------------------------- /resources/types.json: -------------------------------------------------------------------------------- 1 | { 2 | "ProjectIndex": "u32", 3 | "ProjectOf": "Project", 4 | "RoundIndex": "u32", 5 | "RoundOf": "Round", 6 | "Round": { 7 | "start": "BlockNumber", 8 | "end": "BlockNumber", 9 | "matching_fund": "Balance", 10 | "grants": "Vec", 11 | "is_canceled": "bool", 12 | "is_finalized": "bool" 13 | }, 14 | "Grant": { 15 | "project_index": "ProjectIndex", 16 | "contributions": "Vec", 17 | "is_approved": "bool", 18 | "is_canceled": "bool", 19 | "is_withdrawn": "bool", 20 | "withdrawal_expiration": "BlockNumber", 21 | "matching_fund": "Balance" 22 | }, 23 | "Contribution": { 24 | "account_id": "AccountId", 25 | "value": "Balance" 26 | }, 27 | "Project": { 28 | "name": "Vec", 29 | "logo": "Vec", 30 | "description": "Vec", 31 | "website": "Vec", 32 | "owner": "AccountId", 33 | "create_block_number": "BlockNumber" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /runtime/common/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "common-runtime" 3 | version = "0.1.0" 4 | description = "The commonalities between runtimes" 5 | authors = ["OAK Developement Team"] 6 | license = "GPL-3.0" 7 | homepage = "https://oak.tech" 8 | repository = 'https://github.com/OAK-Foundation/OAK-blockchain' 9 | edition = "2021" 10 | 11 | [dependencies] 12 | # Substrate Dependencies 13 | ## Substrate Primitive Dependencies 14 | sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 15 | sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 16 | 17 | ## Substrate FRAME Dependencies 18 | frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 19 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43", default-features = false } 20 | 21 | ## Substrate Pallet Dependencies 22 | pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 23 | pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 24 | pallet-treasury = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } 25 | 26 | ## Polkdadot deps 27 | polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.43", default-features = false } 28 | 29 | ## ORML 30 | orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 31 | orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } 32 | 33 | # Local Dependencies 34 | primitives = { path = "../../primitives", default-features = false } 35 | 36 | [features] 37 | default = ["std"] 38 | std = [ 39 | "frame-support/std", 40 | "sp-runtime/std", 41 | "sp-std/std", 42 | "pallet-balances/std", 43 | "pallet-transaction-payment/std", 44 | "pallet-treasury/std", 45 | "primitives/std", 46 | ] 47 | -------------------------------------------------------------------------------- /runtime/common/src/constants.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod time { 19 | use primitives::BlockNumber; 20 | 21 | /// This determines the average expected block time that we are targeting. 22 | /// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. 23 | /// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked 24 | /// up by `pallet_aura` to implement `fn slot_duration()`. 25 | /// 26 | /// Change this to adjust the block time. 27 | pub const MILLISECS_PER_BLOCK: u64 = 12000; 28 | 29 | // NOTE: Currently it is not possible to change the slot duration after the chain has started. 30 | // Attempting to do so will brick block production. 31 | pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; 32 | 33 | // Time is measured by number of blocks. 34 | pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); 35 | pub const HOURS: BlockNumber = MINUTES * 60; 36 | pub const DAYS: BlockNumber = HOURS * 24; 37 | } 38 | 39 | pub mod currency { 40 | use primitives::Balance; 41 | 42 | pub const TOKEN_DECIMALS: u32 = 10; 43 | const TOKEN_BASE: u128 = 10; 44 | // Unit = the base number of indivisible units for balances 45 | pub const UNIT: Balance = TOKEN_BASE.pow(TOKEN_DECIMALS); // 10_000_000_000 46 | pub const DOLLAR: Balance = UNIT; // 10_000_000_000 47 | pub const CENT: Balance = DOLLAR / 100; // 100_000_000 48 | pub const MILLICENT: Balance = CENT / 1_000; // 100_000 49 | 50 | /// The existential deposit. Set to 1/100 of the Connected Relay Chain. 51 | pub const EXISTENTIAL_DEPOSIT: Balance = CENT; 52 | 53 | pub const fn deposit(items: u32, bytes: u32) -> Balance { 54 | items as Balance * 2_000 * CENT + (bytes as Balance) * 100 * MILLICENT 55 | } 56 | } 57 | 58 | pub mod fees { 59 | use frame_support::parameter_types; 60 | use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; 61 | use sp_runtime::{traits::Bounded, FixedPointNumber, Perquintill}; 62 | 63 | parameter_types! { 64 | /// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less 65 | /// than this will decrease the weight and more will increase. 66 | pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(1); 67 | /// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to 68 | /// change the fees more rapidly. 69 | pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000); 70 | /// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure 71 | /// that combined with `AdjustmentVariable`, we can recover from the minimum. 72 | /// See `multiplier_can_grow_from_zero`. 73 | pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128); 74 | pub MaximumMultiplier: Multiplier = Bounded::max_value(); 75 | } 76 | 77 | /// Parameterized slow adjusting fee updated based on 78 | /// https://w3f-research.readthedocs.io/en/latest/polkadot/overview/2-token-economics.html#-2.-slow-adjusting-mechanism // editorconfig-checker-disable-line 79 | /// 80 | /// The adjustment algorithm boils down to: 81 | /// 82 | /// diff = (previous_block_weight - target) / maximum_block_weight 83 | /// next_multiplier = prev_multiplier * (1 + (v * diff) + ((v * diff)^2 / 2)) 84 | /// assert(next_multiplier > min) 85 | /// where: v is AdjustmentVariable 86 | /// target is TargetBlockFullness 87 | /// min is MinimumMultiplier 88 | pub type SlowAdjustingFeeUpdate = TargetedFeeAdjustment< 89 | R, 90 | TargetBlockFullness, 91 | AdjustmentVariable, 92 | MinimumMultiplier, 93 | MaximumMultiplier, 94 | >; 95 | } 96 | 97 | pub mod weight_ratios { 98 | use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}; 99 | use sp_runtime::Perbill; 100 | 101 | /// We use at most 5% of the block weight running scheduled tasks during `on_initialize`. 102 | pub const SCHEDULED_TASKS_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5); 103 | 104 | /// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is 105 | /// used to limit the maximal weight of a single extrinsic. 106 | pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5); 107 | 108 | /// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by 109 | /// `Operational` extrinsics. 110 | pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); 111 | 112 | /// We allow for 0.5 seconds of compute with a 12 second average block time. 113 | pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( 114 | WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), 115 | polkadot_primitives::MAX_POV_SIZE as u64, 116 | ); 117 | } 118 | -------------------------------------------------------------------------------- /runtime/common/src/fees.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use frame_support::traits::{Imbalance, OnUnbalanced}; 18 | use pallet_balances::NegativeImbalance; 19 | 20 | pub struct DealWithInclusionFees(sp_std::marker::PhantomData); 21 | impl OnUnbalanced> for DealWithInclusionFees 22 | where 23 | R: pallet_balances::Config + pallet_treasury::Config, 24 | pallet_treasury::Pallet: OnUnbalanced>, 25 | { 26 | fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { 27 | if let Some(mut fees) = fees_then_tips.next() { 28 | if let Some(tips) = fees_then_tips.next() { 29 | tips.merge_into(&mut fees); 30 | } 31 | // 20% burned, 80% to the treasury 32 | let (_, to_treasury) = fees.ration(20, 80); 33 | // Balances pallet automatically burns dropped Negative Imbalances by decreasing 34 | // total_supply accordingly 35 | as OnUnbalanced<_>>::on_unbalanced(to_treasury); 36 | } 37 | } 38 | } 39 | 40 | pub struct DealWithExecutionFees(sp_std::marker::PhantomData); 41 | impl OnUnbalanced> for DealWithExecutionFees 42 | where 43 | R: pallet_balances::Config + pallet_treasury::Config, 44 | pallet_treasury::Pallet: OnUnbalanced>, 45 | { 46 | fn on_unbalanceds(mut fees: impl Iterator>) { 47 | if let Some(fees) = fees.next() { 48 | // 20% burned, 80% to the treasury 49 | let (_, to_treasury) = fees.ration(20, 80); 50 | // Balances pallet automatically burns dropped Negative Imbalances by decreasing 51 | // total_supply accordingly 52 | as OnUnbalanced<_>>::on_unbalanced(to_treasury); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /runtime/common/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | #![cfg_attr(not(feature = "std"), no_std)] 18 | use frame_support::traits::Get; 19 | use orml_traits::currency::MutationHooks; 20 | use sp_std::marker::PhantomData; 21 | 22 | pub mod constants; 23 | pub mod fees; 24 | 25 | pub struct CurrencyHooks(PhantomData, DustAccount); 26 | impl MutationHooks 27 | for CurrencyHooks 28 | where 29 | T: orml_tokens::Config, 30 | DustAccount: Get<::AccountId>, 31 | { 32 | type OnDust = orml_tokens::TransferDust; 33 | type OnSlash = (); 34 | type PreDeposit = (); 35 | type PostDeposit = (); 36 | type PreTransfer = (); 37 | type PostTransfer = (); 38 | type OnNewTokenAccount = (); 39 | type OnKilledTokenAccount = (); 40 | } 41 | -------------------------------------------------------------------------------- /runtime/neumann/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use substrate_wasm_builder::WasmBuilder; 18 | 19 | fn main() { 20 | WasmBuilder::new() 21 | .with_current_project() 22 | .export_heap_base() 23 | .import_memory() 24 | .build() 25 | } 26 | -------------------------------------------------------------------------------- /runtime/neumann/src/weights/asset_registry_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Autogenerated weights for orml_asset_registry 19 | //! 20 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 21 | //! DATE: 2022-09-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 22 | //! HOSTNAME: `Lauras-MacBook-Pro.local`, CPU: `` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("turing-dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // ./target/release/oak-collator 27 | // benchmark 28 | // pallet 29 | // --chain 30 | // turing-dev 31 | // --execution 32 | // wasm 33 | // --wasm-execution 34 | // compiled 35 | // --pallet 36 | // orml_asset_registry 37 | // --extrinsic 38 | // * 39 | // --repeat 40 | // 20 41 | // --steps 42 | // 50 43 | // --output 44 | // raw-weights.rs 45 | // --template 46 | // ./.maintain/frame-weight-template.hbs 47 | 48 | // Summary: 49 | //:register_asset 25_000_000 50 | //:update_asset 20_000_000 51 | 52 | #![cfg_attr(rustfmt, rustfmt_skip)] 53 | #![allow(unused_parens)] 54 | #![allow(unused_imports)] 55 | 56 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 57 | use sp_std::marker::PhantomData; 58 | 59 | /// Weight functions needed for orml_asset_registry. 60 | pub trait WeightInfo { 61 | fn register_asset() -> Weight; 62 | fn update_asset() -> Weight; 63 | fn set_asset_location() -> Weight; 64 | } 65 | 66 | /// Weights for orml_asset_registry using the Substrate node and recommended hardware. 67 | pub struct SubstrateWeight(PhantomData); 68 | impl orml_asset_registry::WeightInfo for SubstrateWeight { 69 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 70 | // Storage: AssetRegistry Metadata (r:1 w:1) 71 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 72 | fn register_asset() -> Weight { 73 | Weight::from_parts(25_000_000 as u64, 0u64) 74 | .saturating_add(T::DbWeight::get().reads(3 as u64)) 75 | .saturating_add(T::DbWeight::get().writes(3 as u64)) 76 | } 77 | // Storage: AssetRegistry Metadata (r:1 w:1) 78 | fn update_asset() -> Weight { 79 | Weight::from_parts(20_000_000 as u64, 0u64) 80 | .saturating_add(T::DbWeight::get().reads(1 as u64)) 81 | .saturating_add(T::DbWeight::get().writes(1 as u64)) 82 | } 83 | // Weight not used in pallet 84 | fn set_asset_location() -> Weight { 85 | Weight::zero() 86 | } 87 | } 88 | 89 | // For backwards compatibility and tests 90 | impl WeightInfo for () { 91 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 92 | // Storage: AssetRegistry Metadata (r:1 w:1) 93 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 94 | fn register_asset() -> Weight { 95 | Weight::from_parts(25_000_000 as u64, 0u64) 96 | .saturating_add(RocksDbWeight::get().reads(3 as u64)) 97 | .saturating_add(RocksDbWeight::get().writes(3 as u64)) 98 | } 99 | // Storage: AssetRegistry Metadata (r:1 w:1) 100 | fn update_asset() -> Weight { 101 | Weight::from_parts(20_000_000 as u64, 0u64) 102 | .saturating_add(RocksDbWeight::get().reads(1 as u64)) 103 | .saturating_add(RocksDbWeight::get().writes(1 as u64)) 104 | } 105 | // Weight not used in pallet 106 | fn set_asset_location() -> Weight { 107 | Weight::zero() 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /runtime/neumann/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unnecessary_cast)] 2 | 3 | pub mod asset_registry_weights; 4 | 5 | pub mod pallet_xcm; 6 | -------------------------------------------------------------------------------- /runtime/oak/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use substrate_wasm_builder::WasmBuilder; 18 | 19 | fn main() { 20 | WasmBuilder::new() 21 | .with_current_project() 22 | .export_heap_base() 23 | .import_memory() 24 | .build() 25 | } 26 | -------------------------------------------------------------------------------- /runtime/oak/src/weights/asset_registry_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Autogenerated weights for orml_asset_registry 19 | //! 20 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 21 | //! DATE: 2022-09-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 22 | //! HOSTNAME: `Lauras-MacBook-Pro.local`, CPU: `` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("turing-dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // ./target/release/oak-collator 27 | // benchmark 28 | // pallet 29 | // --chain 30 | // turing-dev 31 | // --execution 32 | // wasm 33 | // --wasm-execution 34 | // compiled 35 | // --pallet 36 | // orml_asset_registry 37 | // --extrinsic 38 | // * 39 | // --repeat 40 | // 20 41 | // --steps 42 | // 50 43 | // --output 44 | // raw-weights.rs 45 | // --template 46 | // ./.maintain/frame-weight-template.hbs 47 | 48 | // Summary: 49 | //:register_asset 25_000_000 50 | //:update_asset 20_000_000 51 | 52 | #![cfg_attr(rustfmt, rustfmt_skip)] 53 | #![allow(unused_parens)] 54 | #![allow(unused_imports)] 55 | 56 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 57 | use sp_std::marker::PhantomData; 58 | 59 | /// Weight functions needed for orml_asset_registry. 60 | pub trait WeightInfo { 61 | fn register_asset() -> Weight; 62 | fn update_asset() -> Weight; 63 | fn set_asset_location() -> Weight; 64 | } 65 | 66 | /// Weights for orml_asset_registry using the Substrate node and recommended hardware. 67 | pub struct SubstrateWeight(PhantomData); 68 | impl orml_asset_registry::WeightInfo for SubstrateWeight { 69 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 70 | // Storage: AssetRegistry Metadata (r:1 w:1) 71 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 72 | fn register_asset() -> Weight { 73 | Weight::from_parts(25_000_000 as u64, 0u64) 74 | .saturating_add(T::DbWeight::get().reads(3 as u64)) 75 | .saturating_add(T::DbWeight::get().writes(3 as u64)) 76 | } 77 | // Storage: AssetRegistry Metadata (r:1 w:1) 78 | fn update_asset() -> Weight { 79 | Weight::from_parts(20_000_000 as u64, 0u64) 80 | .saturating_add(T::DbWeight::get().reads(1 as u64)) 81 | .saturating_add(T::DbWeight::get().writes(1 as u64)) 82 | } 83 | // Weight not used in pallet 84 | fn set_asset_location() -> Weight { 85 | Weight::zero() 86 | } 87 | } 88 | 89 | // For backwards compatibility and tests 90 | impl WeightInfo for () { 91 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 92 | // Storage: AssetRegistry Metadata (r:1 w:1) 93 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 94 | fn register_asset() -> Weight { 95 | Weight::from_parts(25_000_000 as u64, 0u64) 96 | .saturating_add(RocksDbWeight::get().reads(3 as u64)) 97 | .saturating_add(RocksDbWeight::get().writes(3 as u64)) 98 | } 99 | // Storage: AssetRegistry Metadata (r:1 w:1) 100 | fn update_asset() -> Weight { 101 | Weight::from_parts(20_000_000 as u64, 0u64) 102 | .saturating_add(RocksDbWeight::get().reads(1 as u64)) 103 | .saturating_add(RocksDbWeight::get().writes(1 as u64)) 104 | } 105 | // Weight not used in pallet 106 | fn set_asset_location() -> Weight { 107 | Weight::zero() 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /runtime/oak/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unnecessary_cast)] 2 | 3 | pub mod asset_registry_weights; 4 | 5 | pub mod pallet_xcm; 6 | -------------------------------------------------------------------------------- /runtime/turing/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of OAK Blockchain. 2 | 3 | // Copyright (C) 2022 OAK Network 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | use substrate_wasm_builder::WasmBuilder; 18 | 19 | fn main() { 20 | WasmBuilder::new() 21 | .with_current_project() 22 | .export_heap_base() 23 | .import_memory() 24 | .build() 25 | } 26 | -------------------------------------------------------------------------------- /runtime/turing/src/migrations/mod.rs: -------------------------------------------------------------------------------- 1 | // Runtime Migrations 2 | -------------------------------------------------------------------------------- /runtime/turing/src/weights/asset_registry_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Autogenerated weights for orml_asset_registry 19 | //! 20 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 21 | //! DATE: 2022-09-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 22 | //! HOSTNAME: `Lauras-MacBook-Pro.local`, CPU: `` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("turing-dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // ./target/release/oak-collator 27 | // benchmark 28 | // pallet 29 | // --chain 30 | // turing-dev 31 | // --execution 32 | // wasm 33 | // --wasm-execution 34 | // compiled 35 | // --pallet 36 | // orml_asset_registry 37 | // --extrinsic 38 | // * 39 | // --repeat 40 | // 20 41 | // --steps 42 | // 50 43 | // --output 44 | // raw-weights.rs 45 | // --template 46 | // ./.maintain/frame-weight-template.hbs 47 | 48 | // Summary: 49 | //:register_asset 25_000_000 50 | //:update_asset 20_000_000 51 | 52 | #![cfg_attr(rustfmt, rustfmt_skip)] 53 | #![allow(unused_parens)] 54 | #![allow(unused_imports)] 55 | 56 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 57 | use sp_std::marker::PhantomData; 58 | 59 | /// Weight functions needed for orml_asset_registry. 60 | pub trait WeightInfo { 61 | fn register_asset() -> Weight; 62 | fn update_asset() -> Weight; 63 | fn set_asset_location() -> Weight; 64 | } 65 | 66 | /// Weights for orml_asset_registry using the Substrate node and recommended hardware. 67 | pub struct SubstrateWeight(PhantomData); 68 | impl orml_asset_registry::WeightInfo for SubstrateWeight { 69 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 70 | // Storage: AssetRegistry Metadata (r:1 w:1) 71 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 72 | fn register_asset() -> Weight { 73 | Weight::from_parts(25_000_000 as u64, 0u64) 74 | .saturating_add(T::DbWeight::get().reads(3 as u64)) 75 | .saturating_add(T::DbWeight::get().writes(3 as u64)) 76 | } 77 | // Storage: AssetRegistry Metadata (r:1 w:1) 78 | fn update_asset() -> Weight { 79 | Weight::from_parts(20_000_000 as u64, 0u64) 80 | .saturating_add(T::DbWeight::get().reads(1 as u64)) 81 | .saturating_add(T::DbWeight::get().writes(1 as u64)) 82 | } 83 | // Weight not used in pallet 84 | fn set_asset_location() -> Weight { 85 | Weight::zero() 86 | } 87 | } 88 | 89 | // For backwards compatibility and tests 90 | impl WeightInfo for () { 91 | // Storage: AssetRegistry LastAssetId (r:1 w:1) 92 | // Storage: AssetRegistry Metadata (r:1 w:1) 93 | // Storage: AssetRegistry LocationToAssetId (r:1 w:1) 94 | fn register_asset() -> Weight { 95 | Weight::from_parts(25_000_000 as u64, 0u64) 96 | .saturating_add(RocksDbWeight::get().reads(3 as u64)) 97 | .saturating_add(RocksDbWeight::get().writes(3 as u64)) 98 | } 99 | // Storage: AssetRegistry Metadata (r:1 w:1) 100 | fn update_asset() -> Weight { 101 | Weight::from_parts(20_000_000 as u64, 0u64) 102 | .saturating_add(RocksDbWeight::get().reads(1 as u64)) 103 | .saturating_add(RocksDbWeight::get().writes(1 as u64)) 104 | } 105 | // Weight not used in pallet 106 | fn set_asset_location() -> Weight { 107 | Weight::zero() 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /runtime/turing/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unnecessary_cast)] 2 | 3 | pub mod asset_registry_weights; 4 | 5 | pub mod pallet_xcm; 6 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2023-05-02" 3 | components = [ "rustfmt", "clippy" ] 4 | targets = [ "wasm32-unknown-unknown" ] 5 | profile = "minimal" 6 | -------------------------------------------------------------------------------- /scripts/run-pallet-benchmarks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PS3="Pallet name: " 4 | select pallet in $(ls pallets); do break; done 5 | 6 | pallet_name=$(echo "$pallet" | tr '-' '_') 7 | 8 | cargo run \ 9 | --release \ 10 | --features runtime-benchmarks,turing-node \ 11 | benchmark \ 12 | pallet \ 13 | --chain turing-dev \ 14 | --execution wasm \ 15 | --wasm-execution compiled \ 16 | --pallet pallet_$pallet_name \ 17 | --extrinsic '*' \ 18 | --repeat 20 \ 19 | --steps 50 \ 20 | --output ./pallets/$pallet/src/raw-weights.rs \ 21 | --template ./.maintain/frame-weight-template.hbs 22 | -------------------------------------------------------------------------------- /scripts/try-runtime.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | staging_uri=wss://rpc.turing-staging.oak.tech:443 4 | prod_uri=wss://rpc.turing.oak.tech:443 5 | 6 | PS3="Select environment: " 7 | select env in staging production 8 | do 9 | case $env in 10 | staging ) uri=$staging_uri;; 11 | production ) uri=$prod_uri;; 12 | esac 13 | 14 | break 15 | done 16 | 17 | RUST_LOG=runtime=trace,try-runtime::cli=trace,executor=trace \ 18 | cargo run \ 19 | --release \ 20 | --features=turing-node,try-runtime \ 21 | try-runtime \ 22 | --runtime ./target/release/wbuild/turing-runtime/turing_runtime.compact.compressed.wasm \ 23 | --chain turing-dev \ 24 | on-runtime-upgrade \ 25 | live \ 26 | --uri=$uri -------------------------------------------------------------------------------- /zombienets/neumann/single-chain.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | 12 | [[relaychain.nodes]] 13 | name = "bob" 14 | 15 | [[parachains]] 16 | id = 2114 17 | cumulus_based = true 18 | chain = "dev" 19 | 20 | [parachains.collator] 21 | name = "collator01" 22 | command = "./target/release/oak-collator" 23 | ws_port = 9946 24 | rpc_port = 8855 25 | -------------------------------------------------------------------------------- /zombienets/neumann/xcmp.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | 12 | [[relaychain.nodes]] 13 | name = "bob" 14 | 15 | [[parachains]] 16 | id = 2114 17 | cumulus_based = true 18 | chain = "neumann-local" 19 | 20 | [parachains.collator] 21 | name = "collator2114" 22 | command = "./target/release/oak-collator" 23 | ws_port = 9946 24 | rpc_port = 8855 25 | 26 | [[parachains]] 27 | id = 1999 28 | cumulus_based = true 29 | chain = "local" 30 | 31 | [parachains.collator] 32 | name = "collator1999" 33 | command = "../substrate-parachain-template/target/release/parachain-template-node" 34 | ws_port = 9947 35 | rpc_port = 8866 36 | 37 | [[hrmp_channels]] 38 | sender = 2114 39 | recipient = 1999 40 | max_capacity = 8 41 | max_message_size = 512 42 | 43 | [[hrmp_channels]] 44 | sender = 1999 45 | recipient = 2114 46 | max_capacity = 8 47 | max_message_size = 512 48 | -------------------------------------------------------------------------------- /zombienets/oak/single-chain.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | 12 | [[relaychain.nodes]] 13 | name = "bob" 14 | 15 | [[parachains]] 16 | id = 2114 17 | cumulus_based = true 18 | chain = "oak-dev" 19 | 20 | [parachains.collator] 21 | name = "collator01" 22 | command = "./target/release/oak-collator" 23 | ws_port = 9946 24 | rpc_port = 8855 25 | -------------------------------------------------------------------------------- /zombienets/oak/xcmp.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | 12 | [[relaychain.nodes]] 13 | name = "bob" 14 | 15 | [[parachains]] 16 | id = 2114 17 | cumulus_based = true 18 | chain = "oak-dev" 19 | 20 | [parachains.collator] 21 | name = "collator2114" 22 | command = "./target/release/oak-collator" 23 | ws_port = 9946 24 | rpc_port = 8855 25 | 26 | [[parachains]] 27 | id = 1999 28 | cumulus_based = true 29 | chain = "local" 30 | 31 | [parachains.collator] 32 | name = "collator1999" 33 | command = "../substrate-parachain-template/target/release/parachain-template-node" 34 | ws_port = 9947 35 | rpc_port = 8866 36 | 37 | [[hrmpChannels]] 38 | sender = 2114 39 | recipient = 1999 40 | maxCapacity = 8 41 | maxMessageSize = 512 42 | 43 | [[hrmpChannels]] 44 | sender = 1999 45 | recipient = 2114 46 | maxCapacity = 8 47 | maxMessageSize = 512 48 | -------------------------------------------------------------------------------- /zombienets/turing/mangata.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | ws_port = 60613 12 | rpc_port = 8850 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | ws_port = 60614 17 | rpc_port = 8851 18 | 19 | [[parachains]] 20 | id = 2114 21 | cumulus_based = true 22 | chain = "turing-dev" 23 | 24 | [parachains.collator] 25 | name = "turing-col-1" 26 | command = "./target/release/oak-collator" 27 | ws_port = 9946 28 | rpc_port = 8855 29 | 30 | [[parachains]] 31 | id = 2110 32 | cumulus_based = true 33 | chain = "rococo-local" 34 | 35 | [parachains.collator] 36 | name = "mangata-col-1" 37 | command = "../mangata-node/target/release/mangata-node" 38 | ws_port = 9947 39 | rpc_port = 8866 40 | 41 | [[hrmp_channels]] 42 | sender = 2114 43 | recipient = 2110 44 | max_capacity = 8 45 | max_message_size = 512 46 | 47 | [[hrmp_channels]] 48 | sender = 2110 49 | recipient = 2114 50 | max_capacity = 8 51 | max_message_size = 512 52 | -------------------------------------------------------------------------------- /zombienets/turing/moonbase.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | ws_port = 60613 12 | rpc_port = 8850 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | ws_port = 60614 17 | rpc_port = 8851 18 | 19 | [[parachains]] 20 | id = 2114 21 | cumulus_based = true 22 | chain = "turing-dev" 23 | 24 | [parachains.collator] 25 | name = "turing-col-1" 26 | command = "./target/release/oak-collator" 27 | ws_port = 9946 28 | rpc_port = 8855 29 | 30 | [[parachains]] 31 | id = 1000 32 | cumulus_based = true 33 | chain = "moonbase-local" 34 | 35 | [parachains.collator] 36 | name = "moonbase-local-col-1" 37 | command = "../moonbeam/target/release/moonbeam" 38 | ws_port = 9949 39 | rpc_port = 8868 40 | 41 | [[hrmp_channels]] 42 | sender = 2114 43 | recipient = 1000 44 | max_capacity = 8 45 | max_message_size = 512 46 | 47 | [[hrmp_channels]] 48 | sender = 1000 49 | recipient = 2114 50 | max_capacity = 8 51 | max_message_size = 512 52 | -------------------------------------------------------------------------------- /zombienets/turing/shibuya.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | ws_port = 60613 12 | rpc_port = 8850 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | ws_port = 60614 17 | rpc_port = 8851 18 | 19 | [[parachains]] 20 | id = 2114 21 | cumulus_based = true 22 | chain = "turing-dev" 23 | 24 | [parachains.collator] 25 | name = "turing-col-1" 26 | command = "./target/release/oak-collator" 27 | ws_port = 9946 28 | rpc_port = 8855 29 | 30 | [[parachains]] 31 | id = 2000 32 | cumulus_based = true 33 | chain = "shibuya-dev" 34 | 35 | [parachains.collator] 36 | name = "shibuya-col-1" 37 | command = "../Astar/target/release/astar-collator" 38 | args = ["--enable-evm-rpc"] # EVM RPC for Metamsk: http://localhost:9948 and Shibuya Chain Id: 81 39 | ws_port = 9948 40 | rpc_port = 8867 41 | 42 | [[hrmp_channels]] 43 | sender = 2114 44 | recipient = 2000 45 | max_capacity = 8 46 | max_message_size = 102400 47 | 48 | [[hrmp_channels]] 49 | sender = 2000 50 | recipient = 2114 51 | max_capacity = 8 52 | max_message_size = 102400 53 | -------------------------------------------------------------------------------- /zombienets/turing/turing-multi-collator.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | ws_port = 60613 12 | rpc_port = 8850 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | ws_port = 60614 17 | rpc_port = 8851 18 | 19 | [[parachains]] 20 | id = 2114 21 | cumulus_based = true 22 | chain = "turing-dev" 23 | 24 | [[parachains.collator_groups]] 25 | count = 3 26 | command = "./target/release/oak-collator" 27 | name = "collator" 28 | -------------------------------------------------------------------------------- /zombienets/turing/turing-simple.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | provider = "native" 3 | timeout = 1000 4 | 5 | [relaychain] 6 | default_command = "../polkadot/target/release/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | ws_port = 60613 12 | rpc_port = 8850 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | ws_port = 60614 17 | rpc_port = 8851 18 | 19 | [[parachains]] 20 | id = 2114 21 | cumulus_based = true 22 | chain = "turing-dev" 23 | 24 | [parachains.collator] 25 | name = "collator01" 26 | command = "./target/release/oak-collator" 27 | ws_port = 9946 28 | rpc_port = 8855 29 | --------------------------------------------------------------------------------