├── .github ├── release-template.md └── workflows │ ├── build.yml │ ├── build_pallets.yml │ ├── release-binary.yml │ ├── release.yml │ └── rustdoc_pallets.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yml ├── dockerfile ├── docs ├── collator-instructions.md └── rust-setup.md ├── invarch ├── Cargo.lock ├── Cargo.toml ├── node │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── chain_spec.rs │ │ ├── cli.rs │ │ ├── command.rs │ │ ├── lib.rs │ │ ├── main.rs │ │ ├── rpc.rs │ │ ├── service.rs │ │ └── service.rs.bkp ├── runtime │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── assets.rs │ │ ├── balances.rs │ │ ├── common_types.rs │ │ ├── dao_manager.rs │ │ ├── inflation.rs │ │ ├── lib.rs │ │ ├── staking.rs │ │ ├── weights │ │ ├── block_weights.rs │ │ ├── extrinsic_weights.rs │ │ ├── mod.rs │ │ ├── paritydb_weights.rs │ │ └── rocksdb_weights.rs │ │ └── xcm_config.rs ├── rust-toolchain.toml └── rustfmt.toml ├── new-modified-construct-runtime ├── Cargo.lock ├── Cargo.toml ├── src │ ├── construct_runtime │ │ ├── expand │ │ │ ├── call.rs │ │ │ ├── composite_helper.rs │ │ │ ├── config.rs │ │ │ ├── freeze_reason.rs │ │ │ ├── hold_reason.rs │ │ │ ├── inherent.rs │ │ │ ├── lock_id.rs │ │ │ ├── metadata.rs │ │ │ ├── mod.rs │ │ │ ├── origin.rs │ │ │ ├── outer_enums.rs │ │ │ ├── slash_reason.rs │ │ │ ├── task.rs │ │ │ └── unsigned.rs │ │ ├── mod.rs │ │ └── parse.rs │ └── lib.rs └── tools │ ├── Cargo.toml │ ├── derive │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ └── src │ ├── lib.rs │ └── syn_ext.rs ├── pallets ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── pallet-checked-inflation │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── inflation.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── test.rs │ │ └── weights.rs ├── pallet-dao-manager │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── account_derivation.rs │ │ ├── benchmarking.rs │ │ ├── dao_manager_core.rs │ │ ├── dispatch.rs │ │ ├── fee_handling.rs │ │ ├── lib.rs │ │ ├── lookup.rs │ │ ├── migrations.rs │ │ ├── multisig.rs │ │ ├── origin.rs │ │ ├── tests │ │ ├── mock.rs │ │ └── mod.rs │ │ ├── voting.rs │ │ └── weights.rs ├── pallet-dao-staking │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── migrations.rs │ │ ├── primitives.rs │ │ ├── testing │ │ ├── mock.rs │ │ ├── mod.rs │ │ └── test.rs │ │ └── weights.rs ├── pallet-rings │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── tests │ │ ├── mock.rs │ │ └── mod.rs │ │ ├── traits.rs │ │ └── weights.rs ├── primitives │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── rust-toolchain.toml └── rustfmt.toml ├── res ├── brainstorm │ ├── brainstorm2-raw.json │ └── brainstorm2.json ├── invarch │ ├── invarch-genesis-state │ ├── invarch-genesis-wasm │ ├── invarch-plain.json │ └── invarch-raw.json ├── rococo │ ├── genesis-state │ ├── genesis-state-2 │ ├── genesis-state-3 │ ├── genesis-wasm │ ├── genesis-wasm-2 │ ├── genesis-wasm-3 │ ├── tinkernet-rococo-2-raw.json │ ├── tinkernet-rococo-2.json │ ├── tinkernet-rococo-raw.json │ └── tinkernet-rococo.json └── tinker │ ├── genesis-state │ ├── genesis-wasm │ ├── tinker-raw.json │ └── tinker.json ├── testall.sh ├── tinkernet ├── Cargo.lock ├── Cargo.toml ├── node │ ├── Cargo.toml │ ├── build.rs │ ├── res │ │ ├── .gitignore │ │ ├── brainstorm-raw.json │ │ ├── brainstorm.json │ │ ├── local-tinker-para-2000-genesis │ │ ├── local-tinker-para-2000-wasm │ │ ├── rococo.json │ │ ├── tinker-raw.json │ │ ├── tinker-spec-plain-local.json │ │ ├── tinker-spec-plain.json │ │ ├── tinker-spec-raw-local.json │ │ └── tinker-spec-raw.json │ └── src │ │ ├── chain_spec.rs │ │ ├── cli.rs │ │ ├── command.rs │ │ ├── lib.rs │ │ ├── main.rs │ │ ├── rpc.rs │ │ └── service.rs ├── runtime │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── assets.rs │ │ ├── common_types.rs │ │ ├── constants.rs │ │ ├── dao_manager.rs │ │ ├── fee_handling.rs │ │ ├── inflation.rs │ │ ├── lib.rs │ │ ├── migrations.rs │ │ ├── nft.rs │ │ ├── rings │ │ ├── asset_hub.rs │ │ ├── basilisk.rs │ │ ├── bifrost.rs │ │ ├── karura.rs │ │ ├── khala.rs │ │ ├── kintsugi.rs │ │ ├── kusama.rs │ │ ├── mod.rs │ │ ├── moonriver.rs │ │ ├── picasso.rs │ │ └── shiden.rs │ │ ├── staking.rs │ │ ├── weights │ │ ├── block_weights.rs │ │ ├── extrinsic_weights.rs │ │ ├── mod.rs │ │ ├── paritydb_weights.rs │ │ └── rocksdb_weights.rs │ │ ├── xcm_config.rs │ │ └── xcm_simulator │ │ ├── mod.rs │ │ ├── parachain.rs │ │ └── relay_chain.rs ├── rust-toolchain.toml └── rustfmt.toml ├── weights-template.hbs └── zombienet ├── rococo-and-tinkernet+basilisk.toml └── rococo-and-tinkernet+tinkernet.toml /.github/release-template.md: -------------------------------------------------------------------------------- 1 | Release {{tag}} 2 | === 3 | 4 | ### New Release Details: 5 | 6 | - Network: {{network}} 7 | 8 | ### srtool details: 9 | 10 | ``` 11 | {{srtool_details}} 12 | ``` 13 | 14 | ### subwasm details: 15 | 16 | ``` 17 | {{subwasm_details}} 18 | ``` 19 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Checks 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | env: 12 | CARGO_TERM_COLOR: always 13 | 14 | jobs: 15 | get_changed_files: 16 | runs-on: ubuntu-latest 17 | name: Get Changed Files 18 | outputs: 19 | all_modified_files: ${{ steps.changed-files.outputs.all_modified_files }} 20 | steps: 21 | - uses: actions/checkout@v4 22 | 23 | - name: Changed Files 24 | id: changed-files 25 | uses: tj-actions/changed-files@v40 26 | with: 27 | fetch_depth: 0 28 | dir_names: true 29 | dir_names_max_depth: 1 30 | 31 | build_tinkernet: 32 | runs-on: ubuntu-latest 33 | name: Build Tinkernet 34 | 35 | needs: get_changed_files 36 | if: 37 | contains(needs.get_changed_files.outputs.all_modified_files, 'tinkernet') 38 | 39 | defaults: 40 | run: 41 | working-directory: ./tinkernet 42 | 43 | steps: 44 | - uses: actions/checkout@v4 45 | 46 | - name: Free disk space 47 | run: | 48 | sudo rm -rf /usr/share/dotnet 49 | sudo rm -rf /opt/ghc 50 | sudo rm -rf "/usr/local/share/boost" 51 | sudo rm -rf "$AGENT_TOOLSDIRECTORY" 52 | df -h 53 | 54 | - name: Setup for checks 55 | run: sudo apt install -y git clang curl libssl-dev llvm libudev-dev protobuf-compiler 56 | 57 | - name: Install & display rust toolchain 58 | run: rustup show 59 | 60 | - uses: Swatinem/rust-cache@v2 61 | with: 62 | workspaces: "tinkernet" 63 | 64 | - name: Build 65 | run: cargo build --verbose 66 | 67 | #- name: Run tests 68 | # run: cargo test --verbose 69 | 70 | #- name: Run clippy 71 | # run: cargo clippy -- -D warnings 72 | 73 | - name: Run cargofmt 74 | run: cargo fmt --all -- --check 75 | 76 | build_invarch: 77 | runs-on: ubuntu-latest 78 | name: Build InvArch 79 | 80 | needs: get_changed_files 81 | if: 82 | contains(needs.get_changed_files.outputs.all_modified_files, 'invarch') 83 | 84 | defaults: 85 | run: 86 | working-directory: ./invarch 87 | 88 | steps: 89 | - uses: actions/checkout@v4 90 | 91 | - name: Free disk space 92 | run: | 93 | sudo rm -rf /usr/share/dotnet 94 | sudo rm -rf /opt/ghc 95 | sudo rm -rf "/usr/local/share/boost" 96 | sudo rm -rf "$AGENT_TOOLSDIRECTORY" 97 | df -h 98 | 99 | - name: Setup for checks 100 | run: sudo apt install -y git clang curl libssl-dev llvm libudev-dev protobuf-compiler 101 | 102 | - name: Install & display rust toolchain 103 | run: rustup show 104 | 105 | - uses: Swatinem/rust-cache@v2 106 | with: 107 | workspaces: "invarch" 108 | 109 | - name: Build 110 | run: cargo build --verbose 111 | 112 | #- name: Run tests 113 | # run: cargo test --verbose 114 | 115 | #- name: Run clippy 116 | # run: cargo clippy -- -D warnings 117 | 118 | - name: Run cargofmt 119 | run: cargo fmt --all -- --check 120 | -------------------------------------------------------------------------------- /.github/workflows/build_pallets.yml: -------------------------------------------------------------------------------- 1 | name: Pallets Checks 2 | 3 | on: 4 | push: 5 | branches: [ main, development ] 6 | pull_request: 7 | branches: [ main, development ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | defaults: 16 | run: 17 | working-directory: ./pallets 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Install & display rust toolchain 21 | run: rustup show 22 | - name: Build 23 | run: cargo build --verbose 24 | 25 | test: 26 | runs-on: ubuntu-latest 27 | defaults: 28 | run: 29 | working-directory: ./pallets 30 | steps: 31 | - uses: actions/checkout@v2 32 | - name: Install & display rust toolchain 33 | run: rustup show 34 | - name: Run tests 35 | run: cargo test --verbose 36 | 37 | clippy: 38 | runs-on: ubuntu-latest 39 | defaults: 40 | run: 41 | working-directory: ./pallets 42 | steps: 43 | - uses: actions/checkout@v2 44 | - name: Install & display rust toolchain 45 | run: rustup show 46 | - name: Run clippy 47 | run: cargo clippy -- -D warnings 48 | 49 | fmt: 50 | runs-on: ubuntu-latest 51 | defaults: 52 | run: 53 | working-directory: ./pallets 54 | steps: 55 | - uses: actions/checkout@v2 56 | - name: Install & display rust toolchain 57 | run: rustup show 58 | - name: Run cargofmt 59 | run: cargo fmt --all -- --check 60 | -------------------------------------------------------------------------------- /.github/workflows/release-binary.yml: -------------------------------------------------------------------------------- 1 | name: Release binary to existing tag 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | # Get name of the chain 7 | chain: 8 | description: Chain (default = tinkernet) 9 | required: true 10 | default: tinkernet 11 | type: choice 12 | options: 13 | - tinkernet 14 | - invarch 15 | 16 | jobs: 17 | build_binary: 18 | runs-on: ubuntu-latest 19 | 20 | defaults: 21 | run: 22 | working-directory: ./${{ github.event.inputs.chain }} 23 | 24 | steps: 25 | - name: Checkout 26 | uses: actions/checkout@v3 27 | with: 28 | submodules: true 29 | 30 | - name: Free disk space 31 | run: | 32 | sudo rm -rf /usr/share/dotnet 33 | sudo rm -rf /opt/ghc 34 | sudo rm -rf "/usr/local/share/boost" 35 | sudo rm -rf "$AGENT_TOOLSDIRECTORY" 36 | df -h 37 | 38 | - name: Setup for checks 39 | run: sudo apt install -y git clang curl libssl-dev llvm libudev-dev protobuf-compiler 40 | 41 | - name: Install & display rust toolchain 42 | run: rustup show 43 | 44 | - name: Build binary 45 | run: cargo build --release 46 | 47 | - name: Add binary to release 48 | uses: djnicholson/release-action@v2.11 49 | with: 50 | token: ${{ secrets.GITHUB_TOKEN }} 51 | tag-name: ${{ github.ref_name }} 52 | asset-name: '${{ github.event.inputs.chain }}-collator' 53 | file: './${{ github.event.inputs.chain }}/target/release/${{ github.event.inputs.chain }}-collator' 54 | -------------------------------------------------------------------------------- /.github/workflows/rustdoc_pallets.yml: -------------------------------------------------------------------------------- 1 | name: Build Rust Docs 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | rustdoc: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v3 14 | 15 | - name: Install deps 16 | run: sudo apt -y install protobuf-compiler 17 | 18 | - name: Change directory to pallets 19 | run: cd ./pallets 20 | 21 | - name: Install & display rust toolchain 22 | run: rustup show 23 | 24 | - name: Check targets are installed correctly 25 | run: rustup target list --installed 26 | 27 | - name: Build Documentation 28 | run: RUSTDOCFLAGS="--enable-index-page -Zunstable-options" cargo doc --no-deps --document-private-items 29 | 30 | - name: Deploy Docs 31 | uses: peaceiris/actions-gh-pages@v3 32 | with: 33 | github_token: ${{ secrets.GITHUB_TOKEN }} 34 | publish_branch: gh-pages 35 | publish_dir: ./target/doc 36 | -------------------------------------------------------------------------------- /.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 | 15 | *.swp 16 | 17 | # Local testnet nodes storage 18 | storage 19 | 20 | # Important! 21 | *.wasm 22 | *.json 23 | *.txt 24 | 25 | # Local testing 26 | **/testing/ 27 | 28 | # The cache for local vscode data 29 | .vscode/ 30 | 31 | zombienet/binaries/* -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build-tinkernet: 2 | cd tinkernet && cargo build --release 3 | 4 | build-invarch: 5 | cd invarch && cargo build --release 6 | 7 | bindir = zombienet/binaries 8 | dir_target = $(bindir)-$(wildcard $(bindir)) 9 | dir_present = $(bindir)-$(bindir) 10 | dir_absent = $(bindir)- 11 | 12 | polkadot_target = $(bindir)/polkadot-$(wildcard $(bindir)/polkadot) 13 | polkadot_present = $(bindir)/polkadot-$(bindir)/polkadot 14 | polkadot_absent = $(bindir)/polkadot- 15 | 16 | basilisk_target = $(bindir)/basilisk-$(wildcard $(bindir)/basilisk) 17 | basilisk_present = $(bindir)/basilisk-$(bindir)/basilisk 18 | basilisk_absent = $(bindir)/basilisk- 19 | 20 | $(dir_present): 21 | $(polkadot_present): 22 | $(basilisk_present): 23 | 24 | $(dir_absent): | zombienet-create-binaries-dir 25 | 26 | $(polkadot_absent): | zombienet-download-polkadot 27 | 28 | $(basilisk_absent): | zombienet-download-basilisk 29 | 30 | zombienet-create-binaries-dir: 31 | mkdir zombienet/binaries 32 | 33 | zombienet-download-polkadot: | $(dir_target) 34 | wget -O zombienet/binaries/polkadot "https://github.com/paritytech/polkadot/releases/latest/download/polkadot" 35 | chmod +x zombienet/binaries/polkadot 36 | 37 | zombienet-download-basilisk: | $(dir_target) 38 | wget -O zombienet/binaries/basilisk "https://github.com/galacticcouncil/Basilisk-node/releases/download/v10.3.0/basilisk" 39 | chmod +x zombienet/binaries/basilisk 40 | 41 | zombienet-run-tinkernet+basilisk: | $(polkadot_target) $(basilisk_target) 42 | zombienet spawn zombienet/rococo-and-tinkernet+basilisk.toml 43 | 44 | zombienet-run-tinkernet+tinkernet: | $(polkadot_target) 45 | zombienet spawn zombienet/rococo-and-tinkernet+tinkernet.toml 46 | 47 | zombienet-run-kusama+tinkernet: 48 | zombienet spawn zombienet/kusama-and-tinkernet.toml 49 | 50 | run-tinkernet-solo-alice: 51 | cd tinkernet && ./target/release/tinkernet-collator --chain solo-dev --alice --tmp --listen-addr /ip4/0.0.0.0/tcp/53102/ws --rpc-cors=all --discover-local --collator --node-key c12b6d18942f5ee8528c8e2baf4e147b5c5c18710926ea492d09cbd9f6c9f82a 52 | 53 | run-tinkernet-solo-bob: 54 | cd tinkernet && ./target/release/tinkernet-collator --chain solo-dev --bob --tmp --listen-addr /ip4/0.0.0.0/tcp/54102/ws --rpc-cors=all --discover-local --collator --bootnodes /ip4/127.0.0.1/tcp/53102/ws/p2p/12D3KooWBmAwcd4PJNJvfV89HwE48nwkRmAgo8Vy3uQEyNNHBox2 55 | 56 | run-tinkernet-solo: ; printf "run-tinkernet-solo-alice\nrun-tinkernet-solo-bob" | parallel -u make 57 | 58 | run-invarch-solo-alice: 59 | cd invarch && ./target/release/invarch-collator --chain solo-dev --alice --tmp --listen-addr /ip4/0.0.0.0/tcp/53102/ws --rpc-cors=all --discover-local --collator --node-key c12b6d18942f5ee8528c8e2baf4e147b5c5c18710926ea492d09cbd9f6c9f82a 60 | 61 | run-invarch-solo-bob: 62 | cd invarch && ./target/release/invarch-collator --chain solo-dev --bob --tmp --listen-addr /ip4/0.0.0.0/tcp/54102/ws --rpc-cors=all --discover-local --collator --bootnodes /ip4/127.0.0.1/tcp/53102/ws/p2p/12D3KooWBmAwcd4PJNJvfV89HwE48nwkRmAgo8Vy3uQEyNNHBox2 --unsafe-force-node-key-generation 63 | 64 | run-invarch-solo: ; printf "run-invarch-solo-alice\nrun-invarch-solo-bob" | parallel -u make 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 |
6 | 7 |

DAO Infrastructure for the Polkadot Ecosystem

8 | 9 | Built using [Rust](https://github.com/rust-lang/rust) & the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk).
10 |
11 | [![Substrate version](https://img.shields.io/badge/Substrate-v3.0.0-E6007A?logo=Parity%20Substrate)](https://github.com/paritytech/substrate/releases/tag/v3.0.0) 12 | [![Medium](https://img.shields.io/badge/Medium-InvArch-E6007A?logo=medium)](https://invarch.medium.com/) 13 | [![License](https://img.shields.io/github/license/InvArch/InvArch?color=E6007A)](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE)
14 |
15 | 16 | 17 | 18 | 19 | --- 20 |
21 | 22 |

InvArch Network Overview

23 | 24 | InvArch is a public network governed by a global community, accessible to everyone, allowing
25 | people to collaborate, share ownership, & function as multichain organizations!
26 | 27 | 28 | | Protocol | Description | 29 | | -- | ----- | 30 | | `dao_manager` | Deploy DAOs controlled via fungible tokens, NFTs, or KYC (WIP). Operators can define Custom DAO governance configurations, retroactively adjust DAO members, and dynamically determine voting power & DAO permissions. Members can submit self-executing proposals to a DAO for all or some members to vote on whether to approve or reject the action(s). DAO accounts can hold a diverse treasury of assets, send/receive & bridge/transfer these tokens to other accounts, and execute transactions using these assets on accessible protocols. | WIP | 31 | | `dao_staking` | Through a system funded by network inflation: 1) DAOs can register to the network to apply for network funds through a permissionless & community-driven process. 2) Network token holders can stake their tokens towards registered DAOs to signal which they would like to see be supported by the network. 3) Stakers receive the same rate of rewards regardless of which DAO(s) they stake towards; however, the amount of rewards DAOs receive is determined by their proportional share of support throughout the entire protocol & only after attaining a minimum amount of support. | 32 | | `xvm` | A hybrid smart contract platform featuring support for both EVM & WASM smart contracts. This protocol supports both the Ethereum API & Polkadot API, in addition to various Web3 wallets from across the industry such as [MetaMask](https://metamask.io/), [Phantom](https://phantom.app/), [Coinbase](https://www.coinbase.com/wallet), [Talisman](https://www.talisman.xyz/), [SubWallet](https://www.subwallet.app/), and [Nova Wallet](https://novawallet.io/) - and more! | 33 | | `governance` | Self-executing on-chain governance controlled by network token holders. | 34 | 35 |
36 | 37 | ## How to Contribute Code 38 | 39 | Please send a [GitHub Pull Request to InvArch](https://github.com/Abstracted-Labs/InvArch/pull/new) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)) & ensure all your commits are atomic (one feature per commit). Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this:
40 | 41 | $ git commit -m "A summary of the commit." 42 | > 43 | > "A paragraph describing what changed and its impact." 44 | 45 | Also, please make sure to update tests as appropriate. 46 | 47 | ### Non-Technical Contributions 48 | 49 | If you haven't already, join the community in InvArch [Discord](https://discord.gg/VffMw5536N) and inquire about how you can get involved! Please be aware that any members who send spam, advertisements of topics unrelated to InvArch, or solicitation requests in the server will be removed and banned. 50 | 51 | ### Additional Resources 52 | • [InvArch Developer Console](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Finvarch-rpc.dwellir.com#/explorer)
53 | • [Polkadot Parachain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/parachain)
54 | 55 | ### License 56 | 57 | • [GPL](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE)
58 | 59 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | 3 | services: 4 | invarch-alice: 5 | container_name: invarch-alice 6 | image: invarch/inv4:latest 7 | build: 8 | dockerfile: dockerfile 9 | network_mode: "host" 10 | ports: 11 | - "9944:9944" 12 | command: 13 | - "--force-authoring" 14 | - "--collator" 15 | - "--unsafe-ws-external" 16 | - "--unsafe-rpc-external" 17 | - "--chain=solo-dev" 18 | - "--tmp" 19 | - "--alice" 20 | 21 | invarch-bob: 22 | container_name: invarch-bob 23 | image: invarch/inv4:latest 24 | build: 25 | dockerfile: dockerfile 26 | network_mode: "host" 27 | ports: 28 | - "9945:9944" 29 | command: 30 | - "--force-authoring" 31 | - "--collator" 32 | - "--unsafe-ws-external" 33 | - "--unsafe-rpc-external" 34 | - "--chain=solo-dev" 35 | - "--tmp" 36 | - "--bob" 37 | - "--port=30335" 38 | -------------------------------------------------------------------------------- /dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:buster as builder 2 | RUN apt-get update --fix-missing 3 | RUN apt-get install -y git && apt-get install -y curl && apt-get install -y build-essential && apt-get install -y clang && apt-get install -y jq && apt-get install -y cmake 4 | RUN git clone -b main https://github.com/Abstracted-Labs/InvArch 5 | RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \ 6 | export PATH="$PATH:$HOME/.cargo/bin" && \ 7 | cd InvArch && \ 8 | rustup toolchain install $(cat rust-toolchain.toml | grep -o -P '(?<=").*(?=")') && \ 9 | rustup default stable && \ 10 | rustup target add wasm32-unknown-unknown --toolchain $(cat rust-toolchain.toml | grep -o -P '(?<=").*(?=")') && \ 11 | cargo build --release 12 | 13 | # ↑ Build Stage | Final Stage ↓ 14 | FROM docker.io/library/ubuntu:latest 15 | COPY --from=builder /InvArch/target/release/invarch-collator /usr/local/bin 16 | COPY --from=builder /etc/ssl/certs/ /etc/ssl/certs/ 17 | COPY --from=builder /InvArch/node/res/tinker-spec-raw.json /data/tinker-spec-raw.json 18 | COPY --from=builder /InvArch/node/res/rococo.json /data/rococo.json 19 | 20 | 21 | RUN useradd -m -u 1000 -U -s /bin/sh -d /invarch-collator invarch-collator && \ 22 | mkdir -p /invarch-collator/.local/share && \ 23 | chown -R invarch-collator:invarch-collator /data && \ 24 | ln -s /data /invarch-collator/.local/share/invarch-collator && \ 25 | rm -rf /usr/bin /usr/sbin 26 | 27 | USER invarch-collator 28 | EXPOSE 30333 9933 9944 29 | VOLUME ["/data"] 30 | 31 | EXPOSE 30333 9933 9944 32 | 33 | ENTRYPOINT ["/usr/local/bin/invarch-collator"] 34 | -------------------------------------------------------------------------------- /docs/rust-setup.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Installation 3 | --- 4 | 5 | This page will guide you through the steps needed to prepare a computer for development with the 6 | InvArch Node. Since Substrate is built with 7 | [the Rust programming language](https://www.rust-lang.org/), the first thing you will need to do is 8 | prepare the computer for Rust development - these steps will vary based on the computer's operating 9 | system. Once Rust is configured, you will use its toolchains to interact with Rust projects; the 10 | commands for Rust's toolchains will be the same for all supported, Unix-based operating systems. 11 | 12 | ## Unix-Based Operating Systems 13 | 14 | Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples 15 | in the Substrate [Tutorials](https://substrate.dev/tutorials) and [Recipes](https://substrate.dev/recipes/) 16 | use Unix-style terminals to demonstrate how to interact with Substrate from the command line. 17 | 18 | ### macOS 19 | 20 | Open the Terminal application and execute the following commands: 21 | 22 | ```bash 23 | # Install Homebrew if necessary https://brew.sh/ 24 | /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 25 | 26 | # Make sure Homebrew is up-to-date, install openssl and cmake 27 | brew update 28 | brew install openssl cmake 29 | ``` 30 | 31 | ### Ubuntu/Debian 32 | 33 | Use a terminal shell to execute the following commands: 34 | 35 | ```bash 36 | sudo apt update 37 | # May prompt for location information 38 | sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libclang-dev curl 39 | ``` 40 | 41 | ### Arch Linux 42 | 43 | Run these commands from a terminal: 44 | 45 | ```bash 46 | pacman -Syu --needed --noconfirm cmake gcc openssl-1.0 pkgconf git clang 47 | export OPENSSL_LIB_DIR="/usr/lib/openssl-1.0" 48 | export OPENSSL_INCLUDE_DIR="/usr/include/openssl-1.0" 49 | ``` 50 | 51 | ### Fedora/RHEL/CentOS 52 | 53 | Use a terminal to run the following commands: 54 | 55 | ```bash 56 | # Update 57 | sudo dnf update 58 | # Install packages 59 | sudo dnf install cmake pkgconfig rocksdb rocksdb-devel llvm git libcurl libcurl-devel curl-devel clang 60 | ``` 61 | 62 | ## Rust Developer Environment 63 | 64 | This project uses [`rustup`](https://rustup.rs/) to help manage the Rust toolchain. First install 65 | and configure `rustup`: 66 | 67 | ```bash 68 | # Install 69 | curl https://sh.rustup.rs -sSf | sh 70 | # Configure 71 | source ~/.cargo/env 72 | ``` 73 | 74 | Finally, configure the Rust toolchain: 75 | 76 | ```bash 77 | rustup default stable 78 | rustup update nightly 79 | rustup update stable 80 | rustup target add wasm32-unknown-unknown --toolchain nightly 81 | ``` 82 | -------------------------------------------------------------------------------- /invarch/node/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors.workspace = true 3 | build = "build.rs" 4 | description = "A Substrate-based InvArch Node." 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | name = "invarch-node" 9 | publish = false 10 | repository.workspace = true 11 | version.workspace = true 12 | 13 | # [package.metadata.docs.rs] 14 | # targets = ["x86_64-unknown-linux-gnu"] 15 | 16 | [[bin]] 17 | name = "invarch-collator" 18 | path = "src/main.rs" 19 | 20 | [dependencies] 21 | array-bytes = { workspace = true } 22 | async-trait = { workspace = true } 23 | clap = { features = ["derive"], workspace = true } 24 | codec = { workspace = true, default-features = true } 25 | futures = { workspace = true } 26 | jsonrpsee = { features = ["server"], workspace = true } 27 | log = { workspace = true, default-features = true } 28 | serde = { features = ["derive"], workspace = true, default-features = true } 29 | 30 | # Local Dependencies 31 | invarch-runtime = { path = "../runtime" } 32 | 33 | color-print = { workspace = true } 34 | cumulus-client-cli = { workspace = true, default-features = true } 35 | cumulus-client-collator = { workspace = true, default-features = true } 36 | cumulus-client-consensus-aura = { workspace = true, default-features = true } 37 | cumulus-client-consensus-common = { workspace = true, default-features = true } 38 | cumulus-client-consensus-proposer = { workspace = true, default-features = true } 39 | cumulus-client-parachain-inherent = { workspace = true } 40 | cumulus-client-service = { workspace = true, default-features = true } 41 | cumulus-primitives-core = { workspace = true, default-features = true } 42 | cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } 43 | cumulus-relay-chain-interface = { workspace = true, default-features = true } 44 | docify = { workspace = true } 45 | frame-benchmarking = { workspace = true, default-features = true } 46 | frame-benchmarking-cli = { workspace = true, default-features = true } 47 | pallet-transaction-payment-rpc = { workspace = true, default-features = true } 48 | polkadot-cli = { features = [ 49 | "rococo-native", 50 | ], workspace = true, default-features = true } 51 | polkadot-primitives = { workspace = true, default-features = true } 52 | prometheus-endpoint = { workspace = true, default-features = true } 53 | sc-basic-authorship = { workspace = true, default-features = true } 54 | sc-chain-spec = { workspace = true, default-features = true } 55 | sc-cli = { workspace = true, default-features = true } 56 | sc-client-api = { workspace = true, default-features = true } 57 | sc-consensus = { workspace = true, default-features = true } 58 | sc-consensus-aura = { workspace = true } 59 | sc-executor = { workspace = true, default-features = true } 60 | sc-network = { workspace = true, default-features = true } 61 | sc-network-sync = { workspace = true, default-features = true } 62 | sc-offchain = { workspace = true, default-features = true } 63 | sc-rpc = { workspace = true, default-features = true } 64 | sc-service = { workspace = true, default-features = true } 65 | sc-sysinfo = { workspace = true, default-features = true } 66 | sc-telemetry = { workspace = true, default-features = true } 67 | sc-tracing = { workspace = true, default-features = true } 68 | sc-transaction-pool = { workspace = true, default-features = true } 69 | sc-transaction-pool-api = { workspace = true, default-features = true } 70 | serde_json = { workspace = true, default-features = true } 71 | sp-api = { workspace = true, default-features = true } 72 | sp-block-builder = { workspace = true, default-features = true } 73 | sp-blockchain = { workspace = true, default-features = true } 74 | sp-consensus-aura = { workspace = true, default-features = true } 75 | sp-core = { workspace = true, default-features = true } 76 | sp-io = { workspace = true, default-features = true } 77 | sp-keystore = { workspace = true, default-features = true } 78 | sp-runtime = { workspace = true, default-features = true } 79 | sp-timestamp = { workspace = true, default-features = true } 80 | substrate-frame-rpc-system = { workspace = true, default-features = true } 81 | try-runtime-cli = { workspace = true, optional = true } 82 | xcm = { workspace = true } 83 | 84 | [build-dependencies] 85 | substrate-build-script-utils = { workspace = true, default-features = true } 86 | 87 | [features] 88 | runtime-benchmarks = [ 89 | "invarch-runtime/runtime-benchmarks", 90 | "polkadot-cli/runtime-benchmarks", 91 | ] 92 | 93 | try-runtime = ["invarch-runtime/try-runtime", "try-runtime-cli", "sp-runtime/try-runtime"] 94 | -------------------------------------------------------------------------------- /invarch/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 | -------------------------------------------------------------------------------- /invarch/node/src/cli.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use std::path::PathBuf; 3 | 4 | /// Sub-commands supported by the collator. 5 | #[allow(clippy::large_enum_variant)] 6 | #[derive(Debug, clap::Subcommand)] 7 | pub enum Subcommand { 8 | /// Build a chain specification. 9 | BuildSpec(sc_cli::BuildSpecCmd), 10 | 11 | /// Validate blocks. 12 | CheckBlock(sc_cli::CheckBlockCmd), 13 | 14 | /// Export blocks. 15 | ExportBlocks(sc_cli::ExportBlocksCmd), 16 | 17 | /// Export the state of a given block into a chain spec. 18 | ExportState(sc_cli::ExportStateCmd), 19 | 20 | /// Import blocks. 21 | ImportBlocks(sc_cli::ImportBlocksCmd), 22 | 23 | /// Revert the chain to a previous state. 24 | Revert(sc_cli::RevertCmd), 25 | 26 | /// Remove the whole chain. 27 | PurgeChain(cumulus_client_cli::PurgeChainCmd), 28 | 29 | /// Export the genesis head data of the parachain. 30 | /// 31 | /// Head data is the encoded block header. 32 | #[command(alias = "export-genesis-state")] 33 | ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand), 34 | 35 | /// Export the genesis wasm of the parachain. 36 | ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), 37 | 38 | /// Sub-commands concerned with benchmarking. 39 | /// The pallet benchmarking moved to the `pallet` sub-command. 40 | #[command(subcommand)] 41 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 42 | 43 | /// Try some testing command against a specified runtime state. 44 | #[cfg(feature = "try-runtime")] 45 | TryRuntime(try_runtime_cli::TryRuntimeCmd), 46 | 47 | /// Errors since the binary was not build with `--features try-runtime`. 48 | #[cfg(not(feature = "try-runtime"))] 49 | TryRuntime, 50 | } 51 | 52 | #[derive(Debug, Parser)] 53 | #[clap( 54 | propagate_version = true, 55 | args_conflicts_with_subcommands = true, 56 | subcommand_negates_reqs = true 57 | )] 58 | pub struct Cli { 59 | #[command(subcommand)] 60 | pub subcommand: Option, 61 | 62 | #[command(flatten)] 63 | pub run: cumulus_client_cli::RunCmd, 64 | 65 | /// Disable automatic hardware benchmarks. 66 | /// 67 | /// By default these benchmarks are automatically ran at startup and measure 68 | /// the CPU speed, the memory bandwidth and the disk speed. 69 | /// 70 | /// The results are then printed out in the logs, and also sent as part of 71 | /// telemetry, if telemetry is enabled. 72 | #[arg(long)] 73 | pub no_hardware_benchmarks: bool, 74 | 75 | /// Relay chain arguments 76 | #[arg(raw = true)] 77 | pub relay_chain_args: Vec, 78 | } 79 | 80 | #[derive(Debug)] 81 | pub struct RelayChainCli { 82 | /// The actual relay chain cli object. 83 | pub base: polkadot_cli::RunCmd, 84 | 85 | /// Optional chain id that should be passed to the relay chain. 86 | pub chain_id: Option, 87 | 88 | /// The base path that should be used by the relay chain. 89 | pub base_path: Option, 90 | } 91 | 92 | impl RelayChainCli { 93 | /// Parse the relay chain CLI parameters using the para chain `Configuration`. 94 | pub fn new<'a>( 95 | para_config: &sc_service::Configuration, 96 | relay_chain_args: impl Iterator, 97 | ) -> Self { 98 | let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec); 99 | let chain_id = extension.map(|e| e.relay_chain.clone()); 100 | let base_path = para_config.base_path.path().join("polkadot"); 101 | Self { 102 | base_path: Some(base_path), 103 | chain_id, 104 | base: clap::Parser::parse_from(relay_chain_args), 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /invarch/node/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod chain_spec; 2 | pub mod rpc; 3 | pub mod service; 4 | -------------------------------------------------------------------------------- /invarch/node/src/main.rs: -------------------------------------------------------------------------------- 1 | //! Substrate Parachain Node Template CLI 2 | 3 | #![warn(missing_docs)] 4 | 5 | mod chain_spec; 6 | mod cli; 7 | mod command; 8 | mod rpc; 9 | mod service; 10 | 11 | fn main() -> sc_cli::Result<()> { 12 | command::run() 13 | } 14 | -------------------------------------------------------------------------------- /invarch/node/src/rpc.rs: -------------------------------------------------------------------------------- 1 | //! A collection of node-specific RPC methods. 2 | //! 3 | //! Substrate provides the `sc-rpc` crate, which defines the core RPC layer 4 | //! used by Substrate nodes. This file extends those RPC definitions with 5 | //! capabilities that are specific to this project's runtime configuration. 6 | 7 | #![warn(missing_docs)] 8 | 9 | use std::sync::Arc; 10 | 11 | use invarch_runtime::{opaque::Block, AccountId, Balance, Nonce}; 12 | 13 | pub use sc_rpc::DenyUnsafe; 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 | + HeaderMetadata 40 | + Send 41 | + Sync 42 | + 'static, 43 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, 44 | C::Api: substrate_frame_rpc_system::AccountNonceApi, 45 | C::Api: BlockBuilder, 46 | P: TransactionPool + Sync + Send + 'static, 47 | { 48 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; 49 | use substrate_frame_rpc_system::{System, SystemApiServer}; 50 | 51 | let mut module = RpcExtension::new(()); 52 | let FullDeps { 53 | client, 54 | pool, 55 | deny_unsafe, 56 | } = deps; 57 | 58 | module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; 59 | module.merge(TransactionPayment::new(client).into_rpc())?; 60 | Ok(module) 61 | } 62 | -------------------------------------------------------------------------------- /invarch/runtime/build.rs: -------------------------------------------------------------------------------- 1 | use substrate_wasm_builder::WasmBuilder; 2 | 3 | #[cfg(all(not(feature = "metadata-hash"), feature = "std"))] 4 | fn main() { 5 | WasmBuilder::new() 6 | .with_current_project() 7 | .export_heap_base() 8 | .import_memory() 9 | .build() 10 | } 11 | 12 | #[cfg(all(feature = "metadata-hash", feature = "std"))] 13 | fn main() { 14 | WasmBuilder::new() 15 | .with_current_project() 16 | .export_heap_base() 17 | .import_memory() 18 | .enable_metadata_hash("VARCH", 12) 19 | .build() 20 | } 21 | 22 | /// The wasm builder is deactivated when compiling 23 | /// this crate for wasm to speed up the compilation. 24 | #[cfg(not(feature = "std"))] 25 | fn main() {} 26 | -------------------------------------------------------------------------------- /invarch/runtime/src/assets.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | balances, 3 | common_types::AssetId, 4 | staking::MaxNameLength, 5 | xcm_config::{ 6 | AccountIdToMultiLocation, BaseXcmWeight, CurrencyIdConvert, MaxInstructions, 7 | ParachainMinFee, SelfLocation, UniversalLocation, XcmConfig, 8 | }, 9 | AccountId, Amount, Balance, Balances, BlockNumber, Runtime, RuntimeCall, RuntimeEvent, Tokens, 10 | }; 11 | use codec::{Decode, Encode, MaxEncodedLen}; 12 | use frame_support::{parameter_types, traits::Everything}; 13 | use frame_system::EnsureRoot; 14 | use orml_currencies::BasicCurrencyAdapter; 15 | use orml_traits2::{location::AbsoluteReserveProvider, parameter_type_with_key}; 16 | use scale_info::TypeInfo; 17 | 18 | use xcm_builder::FixedWeightBounds; 19 | 20 | pub const VARCH_ASSET_ID: AssetId = 0; 21 | 22 | parameter_types! { 23 | pub const NativeAssetId: AssetId = VARCH_ASSET_ID; 24 | } 25 | 26 | #[derive(TypeInfo, Encode, Decode, Clone, Eq, PartialEq, Debug, MaxEncodedLen)] 27 | pub struct CustomMetadata { 28 | pub fee_per_second: u128, 29 | } 30 | 31 | impl orml_asset_registry::Config for Runtime { 32 | type RuntimeEvent = RuntimeEvent; 33 | type AuthorityOrigin = EnsureRoot; 34 | type AssetId = AssetId; 35 | type Balance = Balance; 36 | type AssetProcessor = orml_asset_registry::SequentialId; 37 | type StringLimit = MaxNameLength; 38 | type CustomMetadata = CustomMetadata; 39 | type WeightInfo = (); 40 | } 41 | 42 | impl orml_currencies::Config for Runtime { 43 | type MultiCurrency = Tokens; 44 | type NativeCurrency = BasicCurrencyAdapter; 45 | type GetNativeCurrencyId = NativeAssetId; 46 | type WeightInfo = (); 47 | } 48 | 49 | parameter_type_with_key! { 50 | pub Eds: |currency_id: AssetId| -> Balance { 51 | if let Some(metadata) = orml_asset_registry::Pallet::::metadata::(*currency_id) { 52 | metadata.existential_deposit 53 | } else { 54 | // Asset does not exist - not supported 55 | Balance::MAX 56 | } 57 | }; 58 | } 59 | 60 | impl orml_tokens2::Config for Runtime { 61 | type RuntimeEvent = RuntimeEvent; 62 | type Balance = Balance; 63 | type Amount = Amount; 64 | type CurrencyId = AssetId; 65 | // Ideally we would use AssetRegistry but having multiple instances of orml pallets is causing 66 | // issues related to traits. 67 | type ExistentialDeposits = Eds; 68 | type MaxLocks = balances::MaxFreezes; 69 | type DustRemovalWhitelist = (); 70 | type MaxReserves = balances::MaxReserves; 71 | type ReserveIdentifier = [u8; 8]; 72 | type CurrencyHooks = (); 73 | type WeightInfo = (); 74 | } 75 | 76 | parameter_types! { 77 | pub const MaxAssetsForTransfer: usize = 50; 78 | } 79 | 80 | impl orml_xtokens::Config for Runtime { 81 | type RuntimeEvent = RuntimeEvent; 82 | type Balance = Balance; 83 | type CurrencyId = AssetId; 84 | type CurrencyIdConvert = CurrencyIdConvert; 85 | type SelfLocation = SelfLocation; 86 | type XcmExecutor = xcm_executor::XcmExecutor; 87 | type Weigher = FixedWeightBounds; 88 | type BaseXcmWeight = BaseXcmWeight; 89 | type MaxAssetsForTransfer = MaxAssetsForTransfer; 90 | type MinXcmFee = ParachainMinFee; 91 | type ReserveProvider = AbsoluteReserveProvider; 92 | type UniversalLocation = UniversalLocation; 93 | type AccountIdToLocation = AccountIdToMultiLocation; 94 | type LocationsFilter = Everything; 95 | type RateLimiter = (); 96 | type RateLimiterId = (); 97 | } 98 | -------------------------------------------------------------------------------- /invarch/runtime/src/common_types.rs: -------------------------------------------------------------------------------- 1 | pub type CommonId = u32; 2 | 3 | pub type AssetId = u32; 4 | -------------------------------------------------------------------------------- /invarch/runtime/src/inflation.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | balances::NegativeImbalance, Balance, Balances, BlockNumber, OcifStaking, Runtime, 3 | RuntimeEvent, DAYS, 4 | }; 5 | use frame_support::{parameter_types, traits::OnUnbalanced}; 6 | use sp_runtime::Perbill; 7 | 8 | pub const TEN_PERCENT_PER_YEAR: pallet_checked_inflation::InflationMethod = 9 | pallet_checked_inflation::InflationMethod::Rate(Perbill::from_percent(10)); 10 | 11 | const YEAR: u32 = 365; 12 | 13 | parameter_types! { 14 | pub const BlocksPerEra: BlockNumber = DAYS; 15 | pub const ErasPerYear: u32 = YEAR; 16 | pub const Inflation: pallet_checked_inflation::InflationMethod = TEN_PERCENT_PER_YEAR; 17 | } 18 | 19 | pub struct DealWithInflation; 20 | impl OnUnbalanced for DealWithInflation { 21 | fn on_unbalanced(amount: NegativeImbalance) { 22 | OcifStaking::rewards(amount); 23 | } 24 | } 25 | 26 | impl pallet_checked_inflation::Config for Runtime { 27 | type BlocksPerEra = BlocksPerEra; 28 | type Currency = Balances; 29 | type RuntimeEvent = RuntimeEvent; 30 | type ErasPerYear = ErasPerYear; 31 | type Inflation = Inflation; 32 | type DealWithInflation = DealWithInflation; 33 | type WeightInfo = pallet_checked_inflation::weights::SubstrateWeight; 34 | } 35 | -------------------------------------------------------------------------------- /invarch/runtime/src/staking.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | Balance, Balances, BlockNumber, ExistentialDeposit, MessageQueue, Runtime, RuntimeEvent, 3 | RuntimeHoldReason, DAYS, UNIT, 4 | }; 5 | use cumulus_primitives_core::AggregateMessageOrigin; 6 | use frame_support::{parameter_types, PalletId}; 7 | use pallet_dao_staking::primitives::CustomAggregateMessageOrigin; 8 | parameter_types! { 9 | pub const BlocksPerEra: BlockNumber = DAYS; 10 | pub const RegisterDeposit: Balance = 5000 * UNIT; 11 | pub const MaxStakersPerDao: u32 = 10000; 12 | // Temporarily dropping down from 50 to 5. 13 | pub const MinimumStakingAmount: Balance = 5 * UNIT; 14 | pub const MaxEraStakeValues: u32 = 5; 15 | pub const MaxUnlockingChunks: u32 = 5; 16 | pub const UnbondingPeriod: u32 = 28; 17 | pub const OcifStakingPot: PalletId = PalletId(*b"inv/stak"); 18 | pub const RewardRatio: (u32, u32) = (60, 40); 19 | pub const StakeThresholdForActiveDao: Balance = 250_000 * UNIT; 20 | pub const MaxNameLength: u32 = 20; 21 | pub const MaxDescriptionLength: u32 = 300; 22 | pub const MaxImageUrlLength: u32 = 100; 23 | pub const UnregisterOrigin: CustomAggregateMessageOrigin = CustomAggregateMessageOrigin::UnregisterMessageOrigin; 24 | } 25 | 26 | impl pallet_dao_staking::Config for Runtime { 27 | type OldCurrency = Balances; 28 | type Currency = Balances; 29 | type BlocksPerEra = BlocksPerEra; 30 | type RegisterDeposit = RegisterDeposit; 31 | type RuntimeEvent = RuntimeEvent; 32 | type MaxStakersPerDao = MaxStakersPerDao; 33 | type ExistentialDeposit = ExistentialDeposit; 34 | type PotId = OcifStakingPot; 35 | type MaxUnlocking = MaxUnlockingChunks; 36 | type UnbondingPeriod = UnbondingPeriod; 37 | type MinimumStakingAmount = MinimumStakingAmount; 38 | type MaxEraStakeValues = MaxEraStakeValues; 39 | type RewardRatio = RewardRatio; 40 | type StakeThresholdForActiveDao = StakeThresholdForActiveDao; 41 | type MaxNameLength = MaxNameLength; 42 | type MaxDescriptionLength = MaxDescriptionLength; 43 | type MaxImageUrlLength = MaxImageUrlLength; 44 | type WeightInfo = pallet_dao_staking::weights::SubstrateWeight; 45 | type StakingMessage = frame_support::traits::EnqueueWithOrigin; 46 | type WeightToFee = crate::WeightToFee; 47 | type OnUnbalanced = crate::DealWithFees; 48 | type RuntimeHoldReason = RuntimeHoldReason; 49 | } 50 | -------------------------------------------------------------------------------- /invarch/runtime/src/weights/block_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Importing a block with 0 Extrinsics. 26 | pub const BlockExecutionWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); 27 | } 28 | 29 | #[cfg(test)] 30 | mod test_weights { 31 | use frame_support::weights::constants; 32 | 33 | /// Checks that the weight exists and is sane. 34 | // NOTE: If this test fails but you are sure that the generated values are fine, 35 | // you can delete it. 36 | #[test] 37 | fn sane() { 38 | let w = super::constants::BlockExecutionWeight::get(); 39 | 40 | // At least 100 µs. 41 | assert!( 42 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 43 | "Weight should be at least 100 µs." 44 | ); 45 | // At most 50 ms. 46 | assert!( 47 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, 48 | "Weight should be at most 50 ms." 49 | ); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /invarch/runtime/src/weights/extrinsic_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Executing a NO-OP `System::remarks` Extrinsic. 26 | pub const ExtrinsicBaseWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); 27 | } 28 | 29 | #[cfg(test)] 30 | mod test_weights { 31 | use frame_support::weights::constants; 32 | 33 | /// Checks that the weight exists and is sane. 34 | // NOTE: If this test fails but you are sure that the generated values are fine, 35 | // you can delete it. 36 | #[test] 37 | fn sane() { 38 | let w = super::constants::ExtrinsicBaseWeight::get(); 39 | 40 | // At least 10 µs. 41 | assert!( 42 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 43 | "Weight should be at least 10 µs." 44 | ); 45 | // At most 1 ms. 46 | assert!( 47 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 48 | "Weight should be at most 1 ms." 49 | ); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /invarch/runtime/src/weights/mod.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 | //! Expose the auto generated weight files. 19 | 20 | pub mod block_weights; 21 | pub mod extrinsic_weights; 22 | pub mod paritydb_weights; 23 | pub mod rocksdb_weights; 24 | 25 | pub use block_weights::constants::BlockExecutionWeight; 26 | pub use extrinsic_weights::constants::ExtrinsicBaseWeight; 27 | #[allow(unused_imports)] 28 | pub use paritydb_weights::constants::ParityDbWeight; 29 | pub use rocksdb_weights::constants::RocksDbWeight; 30 | -------------------------------------------------------------------------------- /invarch/runtime/src/weights/paritydb_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights 26 | /// are available for brave runtime engineers who may want to try this out as default. 27 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use super::constants::ParityDbWeight as W; 36 | use frame_support::weights::constants; 37 | 38 | /// Checks that all weights exist and have sane values. 39 | // NOTE: If this test fails but you are sure that the generated values are fine, 40 | // you can delete it. 41 | #[test] 42 | fn sane() { 43 | // At least 1 µs. 44 | assert!( 45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 46 | "Read weight should be at least 1 µs." 47 | ); 48 | assert!( 49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 50 | "Write weight should be at least 1 µs." 51 | ); 52 | // At most 1 ms. 53 | assert!( 54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 55 | "Read weight should be at most 1 ms." 56 | ); 57 | assert!( 58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 59 | "Write weight should be at most 1 ms." 60 | ); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /invarch/runtime/src/weights/rocksdb_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout 26 | /// the runtime. 27 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use super::constants::RocksDbWeight as W; 36 | use frame_support::weights::constants; 37 | 38 | /// Checks that all weights exist and have sane values. 39 | // NOTE: If this test fails but you are sure that the generated values are fine, 40 | // you can delete it. 41 | #[test] 42 | fn sane() { 43 | // At least 1 µs. 44 | assert!( 45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 46 | "Read weight should be at least 1 µs." 47 | ); 48 | assert!( 49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 50 | "Write weight should be at least 1 µs." 51 | ); 52 | // At most 1 ms. 53 | assert!( 54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 55 | "Read weight should be at most 1 ms." 56 | ); 57 | assert!( 58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 59 | "Write weight should be at most 1 ms." 60 | ); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /invarch/rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2024-10-01" 3 | targets = ["wasm32-unknown-unknown"] 4 | components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview", "rust-src"] -------------------------------------------------------------------------------- /invarch/rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | 3 | imports_granularity = "Crate" -------------------------------------------------------------------------------- /new-modified-construct-runtime/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "new-modified-construct-runtime" 3 | version = "4.0.0-dev" 4 | authors = ["Parity Technologies "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | homepage = "https://substrate.io" 8 | repository = "https://github.com/paritytech/substrate/" 9 | description = "Proc macro of Support code for the runtime." 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [lib] 15 | proc-macro = true 16 | 17 | [dependencies] 18 | derive-syn-parse = "0.2.0" 19 | Inflector = "0.11.4" 20 | cfg-expr = "0.15.5" 21 | itertools = "0.11.0" 22 | proc-macro2 = "1.0.64" 23 | quote = "1.0.33" 24 | syn = { version = "2.0.53", features = ["full", "parsing", "visit-mut"] } 25 | frame-support-procedural-tools = { path = "./tools" } 26 | macro_magic = { version = "0.5.1", features = ["proc_support"] } 27 | proc-macro-warning = { version = "1.0.0", default-features = false } 28 | expander = "2.0.0" 29 | sp-crypto-hashing = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407" } 30 | 31 | [dev-dependencies] 32 | regex = "1.10.2" 33 | 34 | 35 | [features] 36 | default = ["std"] 37 | std = ["sp-crypto-hashing/std"] 38 | no-metadata-docs = [] 39 | # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of 40 | # pallets in a runtime grows. Does increase the compile time! 41 | tuples-96 = [] 42 | tuples-128 = [] 43 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/composite_helper.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use crate::construct_runtime::parse::PalletPath; 19 | use proc_macro2::{Ident, TokenStream}; 20 | use quote::quote; 21 | 22 | pub(crate) fn expand_conversion_fn( 23 | composite_name: &str, 24 | path: &PalletPath, 25 | instance: Option<&Ident>, 26 | variant_name: &Ident, 27 | ) -> TokenStream { 28 | let composite_name = quote::format_ident!("{}", composite_name); 29 | let runtime_composite_name = quote::format_ident!("Runtime{}", composite_name); 30 | 31 | if let Some(inst) = instance { 32 | quote! { 33 | impl From<#path::#composite_name<#path::#inst>> for #runtime_composite_name { 34 | fn from(hr: #path::#composite_name<#path::#inst>) -> Self { 35 | #runtime_composite_name::#variant_name(hr) 36 | } 37 | } 38 | } 39 | } else { 40 | quote! { 41 | impl From<#path::#composite_name> for #runtime_composite_name { 42 | fn from(hr: #path::#composite_name) -> Self { 43 | #runtime_composite_name::#variant_name(hr) 44 | } 45 | } 46 | } 47 | } 48 | } 49 | 50 | pub(crate) fn expand_variant( 51 | composite_name: &str, 52 | index: u8, 53 | path: &PalletPath, 54 | instance: Option<&Ident>, 55 | variant_name: &Ident, 56 | ) -> TokenStream { 57 | let composite_name = quote::format_ident!("{}", composite_name); 58 | 59 | if let Some(inst) = instance { 60 | quote! { 61 | #[codec(index = #index)] 62 | #variant_name(#path::#composite_name<#path::#inst>), 63 | } 64 | } else { 65 | quote! { 66 | #[codec(index = #index)] 67 | #variant_name(#path::#composite_name), 68 | } 69 | } 70 | } 71 | 72 | pub(crate) fn expand_variant_count( 73 | composite_name: &str, 74 | path: &PalletPath, 75 | instance: Option<&Ident>, 76 | ) -> TokenStream { 77 | let composite_name = quote::format_ident!("{}", composite_name); 78 | 79 | if let Some(inst) = instance { 80 | quote! { 81 | #path::#composite_name::<#path::#inst>::VARIANT_COUNT 82 | } 83 | } else { 84 | // Wrapped `<`..`>` means: use default type parameter for enum. 85 | // 86 | // This is used for pallets without instance support or pallets with instance support when 87 | // we don't specify instance: 88 | // 89 | // ``` 90 | // pub struct Pallet{..} 91 | // 92 | // #[pallet::composite_enum] 93 | // pub enum HoldReason {..} 94 | // 95 | // Pallet1: pallet_x, // <- default type parameter 96 | // ``` 97 | quote! { 98 | <#path::#composite_name>::VARIANT_COUNT 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/freeze_reason.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use super::composite_helper; 19 | use crate::construct_runtime::Pallet; 20 | use proc_macro2::TokenStream; 21 | use quote::quote; 22 | 23 | pub fn expand_outer_freeze_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream { 24 | let mut conversion_fns = Vec::new(); 25 | let mut freeze_reason_variants = Vec::new(); 26 | let mut freeze_reason_variants_count = Vec::new(); 27 | for decl in pallet_decls { 28 | if let Some(_) = decl.find_part("FreezeReason") { 29 | let variant_name = &decl.name; 30 | let path = &decl.path; 31 | let index = decl.index; 32 | let instance = decl.instance.as_ref(); 33 | 34 | conversion_fns.push(composite_helper::expand_conversion_fn( 35 | "FreezeReason", 36 | path, 37 | instance, 38 | variant_name, 39 | )); 40 | 41 | freeze_reason_variants.push(composite_helper::expand_variant( 42 | "FreezeReason", 43 | index, 44 | path, 45 | instance, 46 | variant_name, 47 | )); 48 | 49 | freeze_reason_variants_count.push(composite_helper::expand_variant_count( 50 | "FreezeReason", 51 | path, 52 | instance, 53 | )); 54 | } 55 | } 56 | 57 | quote! { 58 | /// A reason for placing a freeze on funds. 59 | #[derive( 60 | Copy, Clone, Eq, PartialEq, 61 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen, 62 | #scrate::__private::scale_info::TypeInfo, 63 | #scrate::__private::RuntimeDebug, 64 | )] 65 | pub enum RuntimeFreezeReason { 66 | #( #freeze_reason_variants )* 67 | } 68 | 69 | impl #scrate::traits::VariantCount for RuntimeFreezeReason { 70 | const VARIANT_COUNT: u32 = 0 #( + #freeze_reason_variants_count )*; 71 | } 72 | 73 | #( #conversion_fns )* 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/hold_reason.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use super::composite_helper; 19 | use crate::construct_runtime::Pallet; 20 | use proc_macro2::TokenStream; 21 | use quote::quote; 22 | 23 | pub fn expand_outer_hold_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream { 24 | let mut conversion_fns = Vec::new(); 25 | let mut hold_reason_variants = Vec::new(); 26 | let mut hold_reason_variants_count = Vec::new(); 27 | for decl in pallet_decls { 28 | if let Some(_) = decl.find_part("HoldReason") { 29 | let variant_name = &decl.name; 30 | let path = &decl.path; 31 | let index = decl.index; 32 | let instance = decl.instance.as_ref(); 33 | 34 | conversion_fns.push(composite_helper::expand_conversion_fn( 35 | "HoldReason", 36 | path, 37 | instance, 38 | variant_name, 39 | )); 40 | 41 | hold_reason_variants.push(composite_helper::expand_variant( 42 | "HoldReason", 43 | index, 44 | path, 45 | instance, 46 | variant_name, 47 | )); 48 | 49 | hold_reason_variants_count.push(composite_helper::expand_variant_count( 50 | "HoldReason", 51 | path, 52 | instance, 53 | )); 54 | } 55 | } 56 | 57 | quote! { 58 | /// A reason for placing a hold on funds. 59 | #[derive( 60 | Copy, Clone, Eq, PartialEq, 61 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen, 62 | #scrate::__private::scale_info::TypeInfo, 63 | #scrate::__private::RuntimeDebug, 64 | )] 65 | pub enum RuntimeHoldReason { 66 | #( #hold_reason_variants )* 67 | } 68 | 69 | impl #scrate::traits::VariantCount for RuntimeHoldReason { 70 | const VARIANT_COUNT: u32 = 0 #( + #hold_reason_variants_count )*; 71 | } 72 | 73 | #( #conversion_fns )* 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/lock_id.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use super::composite_helper; 19 | use crate::construct_runtime::Pallet; 20 | use proc_macro2::TokenStream; 21 | use quote::quote; 22 | 23 | pub fn expand_outer_lock_id(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream { 24 | let mut conversion_fns = Vec::new(); 25 | let mut lock_id_variants = Vec::new(); 26 | for decl in pallet_decls { 27 | if let Some(_) = decl.find_part("LockId") { 28 | let variant_name = &decl.name; 29 | let path = &decl.path; 30 | let index = decl.index; 31 | let instance = decl.instance.as_ref(); 32 | 33 | conversion_fns.push(composite_helper::expand_conversion_fn( 34 | "LockId", 35 | path, 36 | instance, 37 | variant_name, 38 | )); 39 | 40 | lock_id_variants.push(composite_helper::expand_variant( 41 | "LockId", 42 | index, 43 | path, 44 | instance, 45 | variant_name, 46 | )); 47 | } 48 | } 49 | 50 | quote! { 51 | /// An identifier for each lock placed on funds. 52 | #[derive( 53 | Copy, Clone, Eq, PartialEq, 54 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen, 55 | #scrate::__private::scale_info::TypeInfo, 56 | #scrate::__private::RuntimeDebug, 57 | )] 58 | pub enum RuntimeLockId { 59 | #( #lock_id_variants )* 60 | } 61 | 62 | #( #conversion_fns )* 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | mod call; 19 | pub mod composite_helper; 20 | mod config; 21 | mod freeze_reason; 22 | mod hold_reason; 23 | mod inherent; 24 | mod lock_id; 25 | mod metadata; 26 | mod origin; 27 | mod outer_enums; 28 | mod slash_reason; 29 | mod task; 30 | mod unsigned; 31 | 32 | pub use call::expand_outer_dispatch; 33 | pub use config::expand_outer_config; 34 | pub use freeze_reason::expand_outer_freeze_reason; 35 | pub use hold_reason::expand_outer_hold_reason; 36 | pub use inherent::expand_outer_inherent; 37 | pub use lock_id::expand_outer_lock_id; 38 | pub use metadata::expand_runtime_metadata; 39 | pub use origin::expand_outer_origin; 40 | pub use outer_enums::{expand_outer_enum, OuterEnumType}; 41 | pub use slash_reason::expand_outer_slash_reason; 42 | pub use task::expand_outer_task; 43 | pub use unsigned::expand_outer_validate_unsigned; 44 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/slash_reason.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use super::composite_helper; 19 | use crate::construct_runtime::Pallet; 20 | use proc_macro2::TokenStream; 21 | use quote::quote; 22 | 23 | pub fn expand_outer_slash_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream { 24 | let mut conversion_fns = Vec::new(); 25 | let mut slash_reason_variants = Vec::new(); 26 | for decl in pallet_decls { 27 | if let Some(_) = decl.find_part("SlashReason") { 28 | let variant_name = &decl.name; 29 | let path = &decl.path; 30 | let index = decl.index; 31 | let instance = decl.instance.as_ref(); 32 | 33 | conversion_fns.push(composite_helper::expand_conversion_fn( 34 | "SlashReason", 35 | path, 36 | instance, 37 | variant_name, 38 | )); 39 | 40 | slash_reason_variants.push(composite_helper::expand_variant( 41 | "SlashReason", 42 | index, 43 | path, 44 | instance, 45 | variant_name, 46 | )); 47 | } 48 | } 49 | 50 | quote! { 51 | /// A reason for slashing funds. 52 | #[derive( 53 | Copy, Clone, Eq, PartialEq, 54 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen, 55 | #scrate::__private::scale_info::TypeInfo, 56 | #scrate::__private::RuntimeDebug, 57 | )] 58 | pub enum RuntimeSlashReason { 59 | #( #slash_reason_variants )* 60 | } 61 | 62 | #( #conversion_fns )* 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/task.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use crate::construct_runtime::Pallet; 19 | use proc_macro2::{Ident, TokenStream as TokenStream2}; 20 | use quote::quote; 21 | 22 | /// Expands aggregate `RuntimeTask` enum. 23 | pub fn expand_outer_task( 24 | runtime_name: &Ident, 25 | pallet_decls: &[Pallet], 26 | scrate: &TokenStream2, 27 | ) -> TokenStream2 { 28 | let mut from_impls = Vec::new(); 29 | let mut task_variants = Vec::new(); 30 | let mut variant_names = Vec::new(); 31 | let mut task_paths = Vec::new(); 32 | for decl in pallet_decls { 33 | if decl.find_part("Task").is_none() { 34 | continue; 35 | } 36 | 37 | let variant_name = &decl.name; 38 | let path = &decl.path; 39 | let index = decl.index; 40 | 41 | from_impls.push(quote! { 42 | impl From<#path::Task<#runtime_name>> for RuntimeTask { 43 | fn from(hr: #path::Task<#runtime_name>) -> Self { 44 | RuntimeTask::#variant_name(hr) 45 | } 46 | } 47 | 48 | impl TryInto<#path::Task<#runtime_name>> for RuntimeTask { 49 | type Error = (); 50 | 51 | fn try_into(self) -> Result<#path::Task<#runtime_name>, Self::Error> { 52 | match self { 53 | RuntimeTask::#variant_name(hr) => Ok(hr), 54 | _ => Err(()), 55 | } 56 | } 57 | } 58 | }); 59 | 60 | task_variants.push(quote! { 61 | #[codec(index = #index)] 62 | #variant_name(#path::Task<#runtime_name>), 63 | }); 64 | 65 | variant_names.push(quote!(#variant_name)); 66 | 67 | task_paths.push(quote!(#path::Task)); 68 | } 69 | 70 | let prelude = quote!(#scrate::traits::tasks::__private); 71 | 72 | const INCOMPLETE_MATCH_QED: &'static str = 73 | "cannot have an instantiated RuntimeTask without some Task variant in the runtime. QED"; 74 | 75 | let output = quote! { 76 | /// An aggregation of all `Task` enums across all pallets included in the current runtime. 77 | #[derive( 78 | Clone, Eq, PartialEq, 79 | #scrate::__private::codec::Encode, 80 | #scrate::__private::codec::Decode, 81 | #scrate::__private::scale_info::TypeInfo, 82 | #scrate::__private::RuntimeDebug, 83 | )] 84 | pub enum RuntimeTask { 85 | #( #task_variants )* 86 | } 87 | 88 | #[automatically_derived] 89 | impl #scrate::traits::Task for RuntimeTask { 90 | type Enumeration = #prelude::IntoIter; 91 | 92 | fn is_valid(&self) -> bool { 93 | match self { 94 | #(RuntimeTask::#variant_names(val) => val.is_valid(),)* 95 | _ => unreachable!(#INCOMPLETE_MATCH_QED), 96 | } 97 | } 98 | 99 | fn run(&self) -> Result<(), #scrate::traits::tasks::__private::DispatchError> { 100 | match self { 101 | #(RuntimeTask::#variant_names(val) => val.run(),)* 102 | _ => unreachable!(#INCOMPLETE_MATCH_QED), 103 | } 104 | } 105 | 106 | fn weight(&self) -> #scrate::pallet_prelude::Weight { 107 | match self { 108 | #(RuntimeTask::#variant_names(val) => val.weight(),)* 109 | _ => unreachable!(#INCOMPLETE_MATCH_QED), 110 | } 111 | } 112 | 113 | fn task_index(&self) -> u32 { 114 | match self { 115 | #(RuntimeTask::#variant_names(val) => val.task_index(),)* 116 | _ => unreachable!(#INCOMPLETE_MATCH_QED), 117 | } 118 | } 119 | 120 | fn iter() -> Self::Enumeration { 121 | let mut all_tasks = Vec::new(); 122 | #(all_tasks.extend(#task_paths::iter().map(RuntimeTask::from).collect::>());)* 123 | all_tasks.into_iter() 124 | } 125 | } 126 | 127 | #( #from_impls )* 128 | }; 129 | 130 | output 131 | } 132 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/construct_runtime/expand/unsigned.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | use crate::construct_runtime::Pallet; 19 | use proc_macro2::TokenStream; 20 | use quote::quote; 21 | use std::str::FromStr; 22 | use syn::Ident; 23 | 24 | pub fn expand_outer_validate_unsigned( 25 | runtime: &Ident, 26 | pallet_decls: &[Pallet], 27 | scrate: &TokenStream, 28 | ) -> TokenStream { 29 | let mut pallet_names = Vec::new(); 30 | let mut pallet_attrs = Vec::new(); 31 | let mut query_validate_unsigned_part_macros = Vec::new(); 32 | 33 | for pallet_decl in pallet_decls { 34 | if pallet_decl.exists_part("ValidateUnsigned") { 35 | let name = &pallet_decl.name; 36 | let path = &pallet_decl.path; 37 | let attr = pallet_decl 38 | .cfg_pattern 39 | .iter() 40 | .fold(TokenStream::new(), |acc, pattern| { 41 | let attr = TokenStream::from_str(&format!("#[cfg({})]", pattern.original())) 42 | .expect("was successfully parsed before; qed"); 43 | quote! { 44 | #acc 45 | #attr 46 | } 47 | }); 48 | 49 | pallet_names.push(name); 50 | pallet_attrs.push(attr); 51 | query_validate_unsigned_part_macros.push(quote! { 52 | #path::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined!(#name); 53 | }); 54 | } 55 | } 56 | 57 | quote! { 58 | #( #query_validate_unsigned_part_macros )* 59 | 60 | impl #scrate::unsigned::ValidateUnsigned for #runtime { 61 | type Call = RuntimeCall; 62 | 63 | fn pre_dispatch(call: &Self::Call) -> Result<(), #scrate::unsigned::TransactionValidityError> { 64 | #[allow(unreachable_patterns)] 65 | match call { 66 | #( 67 | #pallet_attrs 68 | RuntimeCall::#pallet_names(inner_call) => #pallet_names::pre_dispatch(inner_call), 69 | )* 70 | // pre-dispatch should not stop inherent extrinsics, validation should prevent 71 | // including arbitrary (non-inherent) extrinsics to blocks. 72 | _ => Ok(()), 73 | } 74 | } 75 | 76 | fn validate_unsigned( 77 | #[allow(unused_variables)] 78 | source: #scrate::unsigned::TransactionSource, 79 | call: &Self::Call, 80 | ) -> #scrate::unsigned::TransactionValidity { 81 | #[allow(unreachable_patterns)] 82 | match call { 83 | #( 84 | #pallet_attrs 85 | RuntimeCall::#pallet_names(inner_call) => #pallet_names::validate_unsigned(source, inner_call), 86 | )* 87 | _ => #scrate::unsigned::UnknownTransaction::NoUnsignedValidator.into(), 88 | } 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) 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 | //! Proc macro of Support code for the runtime. 19 | 20 | #![recursion_limit = "512"] 21 | mod construct_runtime; 22 | 23 | use proc_macro::TokenStream; 24 | 25 | #[proc_macro] 26 | pub fn construct_runtime_modified(input: TokenStream) -> TokenStream { 27 | construct_runtime::construct_runtime_modified(input) 28 | } 29 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/tools/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "frame-support-procedural-tools" 3 | version = "4.0.0-dev" 4 | authors = ["Parity Technologies "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | homepage = "https://substrate.io" 8 | repository = "https://github.com/paritytech/substrate/" 9 | description = "Proc macro helpers for procedural macros" 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | proc-macro-crate = "3.0.0" 16 | proc-macro2 = "1.0.64" 17 | quote = "1.0.33" 18 | syn = { version = "2.0.53", features = ["full", "visit", "extra-traits"] } 19 | frame-support-procedural-tools-derive = { version = "3.0.0", path = "./derive" } 20 | -------------------------------------------------------------------------------- /new-modified-construct-runtime/tools/derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "frame-support-procedural-tools-derive" 3 | version = "3.0.0" 4 | authors = ["Parity Technologies "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | homepage = "https://substrate.io" 8 | repository = "https://github.com/paritytech/polkadot-sdk.git/" 9 | description = "Use to derive parsing for parsing struct." 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [lib] 15 | proc-macro = true 16 | 17 | [dependencies] 18 | proc-macro2 = "1.0.64" 19 | quote = { version = "1.0.33", features = ["proc-macro"] } 20 | syn = { version = "2.0.53", features = ["extra-traits", "full", "parsing", "proc-macro"] } 21 | -------------------------------------------------------------------------------- /pallets/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | **/target/ 4 | 5 | #local dependencies 6 | **/Cargo.lock 7 | .idea/vcs.xml 8 | .idea/workspace.xml 9 | -------------------------------------------------------------------------------- /pallets/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = [ 4 | "pallet-checked-inflation", 5 | "pallet-dao-manager", 6 | "pallet-dao-staking", 7 | "primitives", 8 | # "pallet-rings", 9 | ] 10 | 11 | [workspace.package] 12 | authors = ["Abstracted Labs "] 13 | edition = "2021" 14 | homepage = "https://invarch.network" 15 | license = "GPL-3.0" 16 | repository = "https://github.com/Abstracted-Labs/InvArch/" 17 | version = '0.1.0-dev' 18 | 19 | [workspace.dependencies] 20 | 21 | pallet-checked-inflation = { path = "./pallet-checked-inflation", default-features = false } 22 | pallet-dao-manager = { path = "./pallet-dao-manager", default-features = false } 23 | pallet-dao-staking = { path = "./pallet-dao-staking", default-features = false } 24 | primitives = { path = "./primitives", package = "invarch-primitives", default-features = false } 25 | 26 | # crates.io dependencies 27 | codec = { package = "parity-scale-codec", version = "3.6.12", features = [ 28 | "derive", 29 | ], default-features = false } 30 | log = { version = "0.4.20", default-features = false } 31 | num-traits = { version = "0.2", default-features = false } 32 | scale-info = { version = "2.10.0", default-features = false, features = [ 33 | "derive", 34 | ] } 35 | serde = { version = "1.0.189", features = ["derive"] } 36 | smallvec = { version = "1.6.1" } 37 | 38 | # polkadot-sdk dependencies 39 | cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 40 | frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 41 | frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 42 | frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 43 | pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 44 | pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 45 | pallet-session = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 46 | pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 47 | pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 48 | sp-api = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 49 | sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 50 | sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 51 | sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 52 | sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 53 | sp-staking = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 54 | sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false } 55 | xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" } 56 | xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" } 57 | xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" } 58 | 59 | # orml dev dependencies 60 | orml-asset-registry = { git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" } 61 | orml-tokens = { package = "orml-tokens", git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" } 62 | orml-tokens2 = { package = "orml-tokens", git = "https://github.com/Anny0nn/open-runtime-module-library.git", default-features = false, branch = "stable2407" } 63 | orml-traits = { package = "orml-traits", git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" } 64 | orml-traits2 = { package = "orml-traits", git = "https://github.com/Anny0nn/open-runtime-module-library.git", default-features = false, branch = "stable2407" } 65 | -------------------------------------------------------------------------------- /pallets/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |
4 | 5 |
6 |

InvArch FRAME Pallet Library

7 | 8 | 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2FInvArch)](https://twitter.com/InvArchNetwork) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/invarch) 11 | [![Telegram](https://img.shields.io/badge/Telegram-gray?logo=telegram)](https://t.me/InvArch) 12 | [![Knowledge Hub](https://img.shields.io/badge/🧠_Knwoledge_hub-gray)](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85) 13 |
14 | [![Polkadot SDK version](https://img.shields.io/badge/Polkadot_SDK-V1.6.0-E6007A?logo=polkadot)](https://github.com/paritytech/polkadot-sdk/releases/tag/polkadot-v1.6.0) 15 | [![Medium](https://img.shields.io/badge/Medium-InvArch-E6007A?logo=medium)](https://invarch.medium.com/) 16 | [![License](https://img.shields.io/github/license/InvArch/InvArch?color=E6007A)](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE) 17 | [![Library Docs](https://img.shields.io/badge/Library-Docs%2Ers-E6007A?logo=docsdotrs)](https://abstracted-labs.github.io/InvArch/) 18 | 19 |
20 | 21 | --- 22 | 23 | ## Intro 24 | 25 | This repository should contain the Polkadot SDK FRAME Pallets used in the InvArch blockchain, and reviews their relationships and functions. At the current stage, the goal of creating this document and repository is centered around getting feedback while we continue to write the code and develop InvArch. This is a WIP. 26 | 27 | Check out the [Knowledge Hub](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85), it is the perfect place to dive into all things InvArch 28 | 29 | ## Overview 30 | 31 | InvArch is a blockchain network & cross-consensus operating system for DAOs. InvArch revolves around on multi-party ownership & computation with a focus on non-custodial asset management, intellectual property rights facilitation, & DAO operations. 32 | 33 | Currently, InvArch features a multichain multisignature solution & DAO staking protocol. 34 | 35 | --- 36 | 37 | # Pallet Library 38 | 39 | ## [DAO Manager](./pallet-dao-manager/) 40 | - The DAO Manager pallet is designed to manage advanced virtual multisigs (DAOs), OLD: internally referred to as cores. 41 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_dao_manager/index.html) 42 | - Articles: 43 | - [`The SDK. (Old)`](https://invarch.medium.com/the-saturn-sdk-c46b4e40f46e) 44 | - [`The DAO Manager Protocol: The Core of the Creator Economy. (Old)`](https://invarch.medium.com/the-inv4-protocol-the-core-of-the-creator-economy-1af59fdbc943) 45 | - [`The Future of Multi-Party Ownership. (Old)`](https://invarch.medium.com/saturn-the-future-of-multi-party-ownership-ac7190f86a7b) 46 | 47 | ## [DAO Staking](./pallet-dao-staking) 48 | - Previously known as OCIF Staking. 49 | - The DAO Staking Staking Pallet is a pallet designed to facilitate staking towards DAOs within a blockchain network. 50 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_dao_staking/index.html) 51 | - Articles: 52 | - [`The DAO Staking Protocol: Permissionless Funding for DAOs & Creators.`](https://invarch.medium.com/the-ocif-protocol-permissionless-funding-for-daos-creators-505aa18098f1) 53 | - DAO Staking is live on [InvArch](https://portal.invarch.network/staking) and [Tinkernet](https://www.tinker.network/staking). 54 | 55 | ## [Rings](./pallet-rings) 56 | - The Rings pallet provides a cross-consensus message (XCM) abstraction layer for DAO Manager. 57 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_rings/index.html) 58 | 59 | ## [Checked Inflation](./pallet-checked-inflation) 60 | - The Checked Inflation pallet is designed to facilitate the inflationary aspect of a blockchain's economy. 61 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_checked_inflation/index.html) 62 | 63 | --- 64 | 65 | ## How to contribute 66 | 67 | We need volunteer developers to help this idea become a reality! 68 | 69 | If you haven't already, come find us on the [#InvArch Discord](https://discord.gg/invarch). We want you working on things you're excited about! 70 | 71 | ### Submitting changes 72 | 73 | Please send a [GitHub Pull Request to InvArch](https://github.com/Abstracted-Labs/InvArch/pull/new) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). Please make sure all of your commits are atomic (one feature per commit). 74 | 75 | Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: 76 | 77 | $ git commit -m "A brief summary of the commit 78 | > 79 | > A paragraph describing what changed and its impact." 80 | 81 | Please make sure to update tests as appropriate. 82 | 83 | 84 | ### License 85 | 86 | [GPLv3.0](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE) 87 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = 'pallet-checked-inflation' 3 | description = 'FRAME pallet to IP staking' 4 | authors.workspace = true 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | repository.workspace = true 9 | version.workspace = true 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { workspace = true } 16 | scale-info = { workspace = true } 17 | serde = { workspace = true, optional = true } 18 | 19 | frame-benchmarking = { workspace = true, optional = true } 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | num-traits = { workspace = true } 23 | pallet-session = { workspace = true } 24 | sp-arithmetic = { workspace = true } 25 | sp-core = { workspace = true } 26 | sp-io = { workspace = true } 27 | sp-runtime = { workspace = true } 28 | sp-staking = { workspace = true } 29 | sp-std = { workspace = true } 30 | 31 | [dev-dependencies] 32 | pallet-balances = { workspace = true } 33 | 34 | [features] 35 | default = ["std"] 36 | std = [ 37 | "codec/std", 38 | "frame-benchmarking?/std", 39 | "frame-support/std", 40 | "frame-system/std", 41 | "num-traits/std", 42 | "pallet-session/std", 43 | "scale-info/std", 44 | "serde", 45 | "sp-arithmetic/std", 46 | "sp-core/std", 47 | "sp-io/std", 48 | "sp-runtime/std", 49 | "sp-staking/std", 50 | "sp-std/std", 51 | "pallet-balances/std", 52 | ] 53 | runtime-benchmarks = [ 54 | "frame-benchmarking/runtime-benchmarks", 55 | "frame-system/runtime-benchmarks", 56 | "sp-runtime/runtime-benchmarks", 57 | "frame-support/runtime-benchmarks", 58 | "sp-staking/runtime-benchmarks", 59 | ] 60 | try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"] 61 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/README.md: -------------------------------------------------------------------------------- 1 | # Checked Inflation Pallet 2 | 3 | ## Overview 4 | 5 | The Checked Inflation Pallet is designed to facilitate the inflationary aspect of a blockchain's economy. 6 | It automatically mints new tokens at the start of every era, with the amount determined by a configurable inflation method. 7 | This functionality is crucial for maintaining a controlled expansion of the token supply, aligning with economic models or rewarding network participants. 8 | 9 | ### Key Features 10 | 11 | - **Configurable Inflation**: The amount and method of inflation can be tailored to suit the blockchain's economic model. 12 | - **Automatic Token Minting**: New tokens are minted automatically at the beginning of each era. 13 | - **Yearly and Era-Based Inflation**: Supports fixed yearly, fixed per era, or rate-based inflation calculations. 14 | 15 | ## Functionality 16 | 17 | The pallet's core functionality revolves around the `on_initialize` hook, which triggers at the beginning of each block. 18 | If conditions align (start of a new era or year), the pallet calculates the amount to mint based on the configured inflation method and mints the tokens. 19 | 20 | ## Inflation Methods 21 | 22 | Inflation can be configured in one of three ways, as defined in the `InflationMethod` enum: 23 | 24 | - **Rate**: A percentage of the current supply. 25 | - **FixedYearly**: A fixed amount distributed evenly across all eras in a year. 26 | - **FixedPerEra**: A fixed amount minted at the start of each era. 27 | 28 | The choice of method allows for flexibility in how the token supply expands over time, catering to different economic strategies. 29 | 30 | ## Dispatchable Functions 31 | 32 | ### `set_first_year_supply` 33 | 34 | Configures the initial token supply at the year's start, preparing the system for accurate inflation calculation. 35 | 36 | - **Access Control**: Root 37 | 38 | ### `halt_unhalt_pallet` 39 | 40 | Toggles the inflation process, allowing it to be halted or resumed based on network needs. 41 | 42 | - **Parameters**: 43 | - `halt`: A boolean indicating whether to halt (`true`) or resume (`false`) the inflation process. 44 | - **Access Control**: Root 45 | 46 | 47 | ## Events 48 | 49 | - **NewYear**: Marks the beginning of a new year, resetting era counts and updating the starting issuance for inflation calculations. 50 | - **NewEra**: Signifies the start of a new era, triggering token minting according to the configured inflation rate. 51 | - **InflationMinted**: Indicates that tokens have been minted due to inflation, detailing the amounts involved. 52 | - **OverInflationDetected**: Warns of excess token minting beyond expected amounts, prompting corrective measures. 53 | - **HaltChanged**: Reports changes in the inflation process's halt status. 54 | 55 | ## Errors 56 | 57 | - **NoHaltChange**: Triggered when attempting to change the halt status to its current value, indicating no action is needed. 58 | 59 | ## Conclusion 60 | 61 | The Checked Inflation Pallet offers a flexible and automated way to manage token supply expansion through inflation. 62 | By configuring the inflation method to match your blockchain's economic model, you can ensure a controlled and predictable increase in token supply, 63 | this pallet is an essential tool for managing network growth and stability through controlled inflation in response to evolving economic conditions, 64 | ensuring long-term sustainability. 65 | 66 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "runtime-benchmarks")] 2 | 3 | use super::*; 4 | use frame_benchmarking::benchmarks; 5 | use frame_system::RawOrigin as SystemOrigin; 6 | 7 | fn assert_last_event(generic_event: ::RuntimeEvent) { 8 | frame_system::Pallet::::assert_last_event(generic_event.into()); 9 | } 10 | 11 | benchmarks! { 12 | set_first_year_supply { 13 | }: _(SystemOrigin::Root) 14 | 15 | halt_unhalt_pallet { 16 | }: _(SystemOrigin::Root, true) 17 | verify { 18 | assert_last_event::(Event::::HaltChanged { 19 | is_halted: true 20 | }.into()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/src/inflation.rs: -------------------------------------------------------------------------------- 1 | //! Available inflation methods and resulting inflation amount generated per era. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This module contains the available inflation methods and the resulting inflation amount generated per era. 6 | 7 | use crate::{BalanceOf, Config}; 8 | use codec::{Decode, Encode}; 9 | use scale_info::TypeInfo; 10 | use sp_arithmetic::per_things::Perbill; 11 | 12 | /// Inflation methods. 13 | /// 14 | /// The inflation methods are used to determine the amount of inflation generated per era. 15 | #[derive(TypeInfo, Encode, Decode)] 16 | pub enum InflationMethod { 17 | /// The inflation is calculated as a percentage (`Perbill`) of the current supply. 18 | Rate(Perbill), 19 | /// The inflation is a fixed amount per year. 20 | FixedYearly(Balance), 21 | /// The inflation is a fixed amount per era. 22 | FixedPerEra(Balance), 23 | } 24 | 25 | /// Getter trait for the inflation amount to be minted in each era. 26 | pub trait GetInflation { 27 | /// Returns the inflation amount to be minted per era. 28 | fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf; 29 | } 30 | 31 | impl GetInflation for InflationMethod> 32 | where 33 | u32: Into>, 34 | { 35 | /// Returns the inflation amount to be minted per era based on the inflation method. 36 | fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf { 37 | match self { 38 | Self::Rate(rate) => (*rate * current_supply) / eras_per_year.into(), 39 | Self::FixedYearly(amount) => *amount / eras_per_year.into(), 40 | Self::FixedPerEra(amount) => *amount, 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/src/mock.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::inflation::InflationMethod; 3 | use core::convert::TryFrom; 4 | use frame_support::{ 5 | derive_impl, parameter_types, 6 | traits::{fungible, ConstU128, ConstU32, ConstU64, Hooks, OnUnbalanced}, 7 | }; 8 | use pallet_balances::AccountData; 9 | use sp_core::H256; 10 | use sp_runtime::{traits::IdentityLookup, BuildStorage, Perbill}; 11 | 12 | type Block = frame_system::mocking::MockBlock; 13 | type Balance = u128; 14 | 15 | type AccountId = u32; 16 | pub type NegativeImbalance = 17 | frame_support::traits::fungible::Credit<::AccountId, Balances>; 18 | 19 | pub const EXISTENTIAL_DEPOSIT: Balance = 1_000_000_000; 20 | 21 | pub const INFLATION_RECEIVER: AccountId = 0; 22 | pub const ALICE: AccountId = 1; 23 | 24 | frame_support::construct_runtime!( 25 | pub enum Test 26 | { 27 | System: frame_system, 28 | Balances: pallet_balances, 29 | CheckedInflation: pallet, 30 | } 31 | ); 32 | 33 | #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] 34 | impl frame_system::Config for Test { 35 | type RuntimeOrigin = RuntimeOrigin; 36 | type Nonce = u64; 37 | type Block = Block; 38 | type RuntimeCall = RuntimeCall; 39 | type Hash = H256; 40 | type Hashing = ::sp_runtime::traits::BlakeTwo256; 41 | type AccountId = AccountId; 42 | type Lookup = IdentityLookup; 43 | type RuntimeEvent = RuntimeEvent; 44 | type BlockHashCount = ConstU64<250>; 45 | type PalletInfo = PalletInfo; 46 | type AccountData = AccountData; 47 | type MaxConsumers = ConstU32<16>; 48 | } 49 | 50 | #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] 51 | impl pallet_balances::Config for Test { 52 | type MaxLocks = ConstU32<50>; 53 | type Balance = Balance; 54 | type RuntimeEvent = RuntimeEvent; 55 | type ExistentialDeposit = ConstU128; 56 | type AccountStore = System; 57 | type MaxReserves = ConstU32<50>; 58 | type ReserveIdentifier = [u8; 8]; 59 | } 60 | 61 | parameter_types! { 62 | pub const Inflation: InflationMethod> = InflationMethod::Rate(Perbill::from_percent(10)); 63 | } 64 | 65 | pub struct DealWithInflation; 66 | impl OnUnbalanced for DealWithInflation { 67 | fn on_unbalanced(amount: NegativeImbalance) { 68 | >::resolve(&INFLATION_RECEIVER, amount) 69 | .expect("should work"); 70 | } 71 | } 72 | 73 | pub const BLOCKS_PER_ERA: u64 = 4; 74 | pub const ERAS_PER_YEAR: u32 = 365; 75 | 76 | impl pallet::Config for Test { 77 | type BlocksPerEra = ConstU64; 78 | type Currency = Balances; 79 | type RuntimeEvent = RuntimeEvent; 80 | type ErasPerYear = ConstU32; 81 | type Inflation = Inflation; 82 | type DealWithInflation = DealWithInflation; 83 | type WeightInfo = weights::SubstrateWeight; 84 | } 85 | 86 | pub struct ExtBuilder; 87 | 88 | impl Default for ExtBuilder { 89 | fn default() -> Self { 90 | ExtBuilder 91 | } 92 | } 93 | 94 | pub const GENESIS_ISSUANCE: u128 = 11700000000000000000; 95 | 96 | impl ExtBuilder { 97 | pub fn build(self) -> sp_io::TestExternalities { 98 | let mut t = frame_system::GenesisConfig::::default() 99 | .build_storage() 100 | .unwrap(); 101 | 102 | pallet_balances::GenesisConfig:: { 103 | balances: vec![(INFLATION_RECEIVER, GENESIS_ISSUANCE)], 104 | } 105 | .assimilate_storage(&mut t) 106 | .unwrap(); 107 | 108 | let mut ext = sp_io::TestExternalities::new(t); 109 | ext.execute_with(|| System::set_block_number(0)); 110 | 111 | // ext.execute_with(|| YearStartIssuance::::put(Balances::total_issuance())); 112 | 113 | // ext.execute_with(|| run_to_block(1)); 114 | 115 | ext 116 | } 117 | } 118 | 119 | pub fn run_to_block(n: u64) { 120 | while System::block_number() < n { 121 | if System::block_number() > 1 { 122 | System::on_finalize(System::block_number()); 123 | } 124 | System::set_block_number(System::block_number() + 1); 125 | System::on_initialize(System::block_number()); 126 | CheckedInflation::on_initialize(System::block_number()); 127 | } 128 | } 129 | 130 | pub fn run_to_next_era() { 131 | run_to_block(CheckedInflation::next_era_starting_block()) 132 | } 133 | 134 | pub fn run_to_next_year() { 135 | // run_to_next_era(); 136 | 137 | let current_era = CheckedInflation::current_era(); 138 | 139 | run_to_block(System::block_number() + ((ERAS_PER_YEAR - current_era) as u64 * BLOCKS_PER_ERA)); 140 | 141 | run_to_next_era(); 142 | } 143 | 144 | pub fn run_to_half_year() { 145 | run_to_next_era(); 146 | 147 | let current_era = CheckedInflation::current_era(); 148 | 149 | run_to_block( 150 | System::block_number() + (((ERAS_PER_YEAR / 2) - current_era) as u64 * BLOCKS_PER_ERA), 151 | ); 152 | } 153 | -------------------------------------------------------------------------------- /pallets/pallet-checked-inflation/src/weights.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_checked_inflation` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.0 5 | //! DATE: 2024-10-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `franciscos-mbp.lan`, CPU: `` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release/invarch-collator 12 | // benchmark 13 | // pallet 14 | // --runtime 15 | // ./target/release/wbuild/invarch-runtime/invarch_runtime.compact.compressed.wasm 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_checked_inflation 18 | // --extrinsic= 19 | // --steps 20 | // 50 21 | // --repeat 22 | // 20 23 | // --output=../pallets/pallet-checked-inflation/src/weights.rs 24 | // --template=../weights-template.hbs 25 | 26 | #![cfg_attr(rustfmt, rustfmt_skip)] 27 | #![allow(unused_parens)] 28 | #![allow(unused_imports)] 29 | #![allow(missing_docs)] 30 | 31 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 32 | use core::marker::PhantomData; 33 | 34 | /// Weight functions needed for `pallet_checked_inflation`. 35 | pub trait WeightInfo { 36 | fn set_first_year_supply() -> Weight; 37 | fn halt_unhalt_pallet() -> Weight; 38 | } 39 | 40 | /// Weights for `pallet_checked_inflation` using the Substrate node and recommended hardware. 41 | pub struct SubstrateWeight(PhantomData); 42 | impl WeightInfo for SubstrateWeight { 43 | /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1) 44 | /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) 45 | fn set_first_year_supply() -> Weight { 46 | // Proof Size summary in bytes: 47 | // Measured: `0` 48 | // Estimated: `0` 49 | // Minimum execution time: 1_000_000 picoseconds. 50 | Weight::from_parts(2_000_000, 0) 51 | .saturating_add(T::DbWeight::get().writes(1_u64)) 52 | } 53 | /// Storage: `CheckedInflation::Halted` (r:1 w:1) 54 | /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) 55 | fn halt_unhalt_pallet() -> Weight { 56 | // Proof Size summary in bytes: 57 | // Measured: `0` 58 | // Estimated: `1486` 59 | // Minimum execution time: 3_000_000 picoseconds. 60 | Weight::from_parts(4_000_000, 1486) 61 | .saturating_add(T::DbWeight::get().reads(1_u64)) 62 | .saturating_add(T::DbWeight::get().writes(1_u64)) 63 | } 64 | } 65 | 66 | // For backwards compatibility and tests. 67 | impl WeightInfo for () { 68 | /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1) 69 | /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) 70 | fn set_first_year_supply() -> Weight { 71 | // Proof Size summary in bytes: 72 | // Measured: `0` 73 | // Estimated: `0` 74 | // Minimum execution time: 1_000_000 picoseconds. 75 | Weight::from_parts(2_000_000, 0) 76 | .saturating_add(RocksDbWeight::get().writes(1_u64)) 77 | } 78 | /// Storage: `CheckedInflation::Halted` (r:1 w:1) 79 | /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) 80 | fn halt_unhalt_pallet() -> Weight { 81 | // Proof Size summary in bytes: 82 | // Measured: `0` 83 | // Estimated: `1486` 84 | // Minimum execution time: 3_000_000 picoseconds. 85 | Weight::from_parts(4_000_000, 1486) 86 | .saturating_add(RocksDbWeight::get().reads(1_u64)) 87 | .saturating_add(RocksDbWeight::get().writes(1_u64)) 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = 'pallet-dao-manager' 3 | description = '' 4 | authors.workspace = true 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | repository.workspace = true 9 | version.workspace = true 10 | 11 | [dependencies] 12 | codec = { workspace = true, default-features = false, features = [ 13 | "derive", 14 | "max-encoded-len", 15 | ] } 16 | frame-support = { workspace = true } 17 | log = { workspace = true } 18 | scale-info = { workspace = true } 19 | serde = { workspace = true, optional = true } 20 | smallvec = { workspace = true } 21 | sp-arithmetic = { workspace = true } 22 | sp-runtime = { workspace = true } 23 | sp-std = { workspace = true } 24 | 25 | # InvArch dependencies 26 | primitives = { workspace = true } 27 | 28 | frame-benchmarking = { workspace = true, optional = true } 29 | frame-system = { workspace = true } # frame-benchmarking requires system 30 | pallet-balances = { workspace = true } 31 | sp-api = { workspace = true } 32 | sp-core = { workspace = true } 33 | sp-io = { workspace = true } 34 | 35 | 36 | orml-tokens2 = { workspace = true } 37 | xcm = { workspace = true } 38 | 39 | [dev-dependencies] 40 | 41 | orml-asset-registry = { workspace = true } 42 | orml-tokens = { workspace = true } 43 | orml-traits = { workspace = true } 44 | orml-traits2 = { workspace = true } 45 | 46 | 47 | [features] 48 | default = ["std"] 49 | std = [ 50 | "codec/std", 51 | "frame-benchmarking?/std", 52 | "frame-support/std", 53 | "frame-system/std", 54 | "orml-asset-registry/std", 55 | "orml-tokens/std", 56 | "orml-tokens2/std", 57 | "orml-traits/std", 58 | "orml-traits2/std", 59 | "pallet-balances/std", 60 | "primitives/std", 61 | "scale-info/std", 62 | "serde", 63 | "sp-api/std", 64 | "sp-arithmetic/std", 65 | "sp-core/std", 66 | "sp-io/std", 67 | "sp-runtime/std", 68 | "sp-std/std", 69 | "xcm/std", 70 | "log/std", 71 | ] 72 | runtime-benchmarks = [ 73 | "frame-benchmarking/runtime-benchmarks", 74 | "frame-support/runtime-benchmarks", 75 | "frame-system/runtime-benchmarks", 76 | "sp-runtime/runtime-benchmarks", 77 | ] 78 | try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"] 79 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/README.md: -------------------------------------------------------------------------------- 1 | # DAO Manager Pallet 2 | 3 | ## Introduction 4 | 5 | The DAO Manager pallet is designed to manage advanced virtual multisigs, internally referred to as DAOs. It provides the functionality to create DAOs, mint and burn the DAO's voting tokens, and manage multisig proposals. This pallet is a comprehensive solution for decentralized decision-making processes, allowing for flexible and secure management of multisig operations. 6 | 7 | ## Features 8 | 9 | - **DAO Creation**: Establish new DAOs with customizable parameters, including metadata, voting thresholds, and token freeze state. 10 | - **Token Management**: Mint and burn the DAO's voting tokens to manage the voting power within the DAO. 11 | - **Multisig Proposals**: Create, vote on, and cancel multisig proposals. Proposals automatically execute if they meet the execution threshold requirements. 12 | - **Vote Management**: Members can vote on proposals, withdraw their votes, and influence the outcome of decisions. 13 | - **Parameter Adjustment**: DAO parameters, such as voting thresholds and token freeze state, can be dynamically adjusted by DAO origins. 14 | 15 | ## Functionality Overview 16 | 17 | ### DAO Management 18 | 19 | - `create_dao`: Initialize a new DAO with specific parameters and distribute initial voting tokens to the creator. 20 | - `set_parameters`: Modify DAO parameters, including voting thresholds, metadata, and token freeze state. 21 | 22 | ### Token Operations 23 | 24 | - `token_mint`: Mint the DAO's voting tokens to a specified target, increasing their voting power within the DAO. 25 | - `token_burn`: Burn the DAO's voting tokens from a specified target, decreasing their voting power. 26 | 27 | ### Multisig Operations 28 | 29 | - `operate_multisig`: Submit a new multisig proposal. If the proposal meets execution thresholds, it is automatically executed. 30 | - `vote_multisig`: Cast a vote on an existing multisig proposal. Proposals execute automatically if they meet threshold requirements after the vote. 31 | - `withdraw_vote_multisig`: Withdraw a previously cast vote from a multisig proposal. 32 | - `cancel_multisig_proposal`: Cancel an existing multisig proposal. This action can only be performed by a DAO origin. 33 | 34 | ### Utility Functions 35 | 36 | - `DaoAccountDerivation`: Derive consistent DAO AccountIds across parachains for seamless interaction. 37 | - `DaoLookup`: Custom account lookup implementation for converting DaoIds to AccountIds. 38 | - `FeeAsset`: Define the asset used by the multisig for paying transaction fees. 39 | - `MultisigFeeHandler`: Manage fee payments for multisig operations, supporting both native and non-native assets. 40 | 41 | ## Usage 42 | 43 | To utilize the DAO Manager pallet, users must first create a DAO and receive initial voting tokens. DAOs can propose actions, vote on proposals, and execute decisions based on the collective voting power of their members. The pallet's flexible design supports a wide range of multisig use cases, from simple governance decisions to complex, conditional executions. -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/account_derivation.rs: -------------------------------------------------------------------------------- 1 | //! Dao Account Derivation. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This module defines a method for generating account addresses, and how it's implemented within this 6 | //! pallet. We use a custom derivation scheme to ensure that when a multisig is created, its AccountId 7 | //! remains consistent across different parachains, promoting seamless interaction. 8 | //! 9 | //! ### The module contains: 10 | //! - `DaoAccountDerivation` trait: The interface for our derivation method. 11 | //! - Pallet implementation: The specific logic used to derive AccountIds. 12 | 13 | use crate::{Config, Pallet}; 14 | use codec::{Compact, Encode}; 15 | use frame_support::traits::Get; 16 | use sp_io::hashing::blake2_256; 17 | use xcm::v4::{BodyId, BodyPart, Junction, Junctions}; 18 | /// Trait providing the XCM location and the derived account of a dao. 19 | pub trait DaoAccountDerivation { 20 | /// Derives the dao's AccountId. 21 | fn derive_dao_account(dao_id: T::DaoId) -> T::AccountId; 22 | /// Specifies a dao's location. 23 | fn dao_location(dao_id: T::DaoId) -> Junctions; 24 | } 25 | 26 | impl DaoAccountDerivation for Pallet 27 | where 28 | T::AccountId: From<[u8; 32]>, 29 | { 30 | /// HashedDescription of the dao location from the perspective of a sibling chain. 31 | /// This derivation allows the local account address to match the account address in other parachains. 32 | /// Reference: https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/xcm-builder/src/location_conversion.rs 33 | fn derive_dao_account(dao_id: T::DaoId) -> T::AccountId { 34 | blake2_256( 35 | &( 36 | b"SiblingChain", 37 | Compact::::from(T::ParaId::get()), 38 | (b"Body", BodyId::Index(dao_id.into()), BodyPart::Voice).encode(), 39 | ) 40 | .encode(), 41 | ) 42 | .into() 43 | } 44 | /// DAO location is defined as a plurality within the parachain. 45 | fn dao_location(dao_id: T::DaoId) -> Junctions { 46 | Junctions::X2( 47 | [ 48 | Junction::Parachain(T::ParaId::get()), 49 | Junction::Plurality { 50 | id: BodyId::Index(dao_id.into()), 51 | part: BodyPart::Voice, 52 | }, 53 | ] 54 | .into(), 55 | ) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/dispatch.rs: -------------------------------------------------------------------------------- 1 | //! Dispatches calls internally, charging fees to the multisig account. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This module employs a custom `MultisigInternalOrigin` to ensure calls originate 6 | //! from the multisig account itself, automating fee payments. The `dispatch_call` function 7 | //! includes pre and post dispatch handling for streamlined fee management within the multisig context. 8 | 9 | use crate::{ 10 | fee_handling::{FeeAsset, MultisigFeeHandler}, 11 | origin::{DaoOrigin, MultisigInternalOrigin}, 12 | Config, Error, 13 | }; 14 | use frame_support::{dispatch::GetDispatchInfo, pallet_prelude::*}; 15 | 16 | use sp_runtime::traits::Dispatchable; 17 | 18 | /// Dispatch a call executing pre/post dispatch for proper fee handling. 19 | pub fn dispatch_call( 20 | dao_id: ::DaoId, 21 | fee_asset: &FeeAsset, 22 | call: ::RuntimeCall, 23 | ) -> DispatchResultWithPostInfo 24 | where 25 | T::AccountId: From<[u8; 32]>, 26 | { 27 | // Create new custom origin as the multisig. 28 | let internal_origin = MultisigInternalOrigin::new(dao_id); 29 | let multisig_account = internal_origin.to_account_id(); 30 | let origin = DaoOrigin::Multisig(internal_origin).into(); 31 | 32 | let info = call.get_dispatch_info(); 33 | let len = call.encode().len(); 34 | 35 | // Execute pre dispatch using the multisig account instead of the extrinsic caller. 36 | let pre = >::pre_dispatch( 37 | fee_asset, 38 | &multisig_account, 39 | &call, 40 | &info, 41 | len, 42 | ) 43 | .map_err(|_| Error::::CallFeePaymentFailed)?; 44 | 45 | let dispatch_result = call.dispatch(origin); 46 | 47 | let post = match dispatch_result { 48 | Ok(p) => p, 49 | Err(e) => e.post_info, 50 | }; 51 | 52 | >::post_dispatch( 53 | fee_asset, 54 | Some(pre), 55 | &info, 56 | &post, 57 | len, 58 | &dispatch_result.map(|_| ()).map_err(|e| e.error), 59 | ) 60 | .map_err(|_| Error::::CallFeePaymentFailed)?; 61 | 62 | dispatch_result 63 | } 64 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/fee_handling.rs: -------------------------------------------------------------------------------- 1 | //! MultisigFeeHandler trait. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! Defines how transaction fees are charged to the multisig account. 6 | //! This trait requires proper runtime implementation to allow the usage of native or non-native assets. 7 | 8 | use crate::Config; 9 | use codec::{Decode, Encode, MaxEncodedLen}; 10 | use frame_support::{ 11 | traits::{fungible::Credit, fungibles::Credit as Credits}, 12 | unsigned::TransactionValidityError, 13 | }; 14 | use scale_info::TypeInfo; 15 | use sp_runtime::{ 16 | traits::{DispatchInfoOf, PostDispatchInfoOf}, 17 | DispatchResult, 18 | }; 19 | 20 | /// Represents the asset to be used by the multisig for paying transaction fees. 21 | /// 22 | /// This enum defines the assets that can be used to pay for transaction fees. 23 | #[derive(Clone, TypeInfo, Encode, Decode, MaxEncodedLen, Debug, PartialEq, Eq)] 24 | pub enum FeeAsset { 25 | Native, 26 | Relay, 27 | } 28 | 29 | /// Represents a potential negative asset balance incurred during fee payment operations 30 | /// within a multisig context. 31 | /// 32 | /// This enum handles imbalances in either the native token or 33 | /// a relay chain asset used for fees. 34 | /// 35 | /// - `Native(NativeNegativeImbalance)`: Indicates a deficit balance in the chain's native asset. 36 | /// - `Relay(RelayNegativeImbalance)`: Indicates a deficit balance in an asset originating on the relay chain. 37 | /// 38 | /// This enum plays a role in resolving deficit balances in the `MultisigFeeHandler` trait. 39 | pub enum FeeAssetNegativeImbalance { 40 | Native(NativeNegativeImbalance), 41 | Relay(RelayNegativeImbalance), 42 | } 43 | 44 | /// Fee handler trait. 45 | /// 46 | /// This should be implemented properly in the runtime to account for native and non-native assets. 47 | pub trait MultisigFeeHandler { 48 | /// Type returned by `pre_dispatch` - implementation dependent. 49 | type Pre; 50 | 51 | /// Checks if the fee can be paid using the selected asset. 52 | fn pre_dispatch( 53 | asset: &FeeAsset, 54 | who: &T::AccountId, 55 | call: &::RuntimeCall, 56 | info: &DispatchInfoOf<::RuntimeCall>, 57 | len: usize, 58 | ) -> Result; 59 | 60 | /// Charges the call dispatching fee from the multisig directly. 61 | fn post_dispatch( 62 | asset: &FeeAsset, 63 | pre: Option, 64 | info: &DispatchInfoOf<::RuntimeCall>, 65 | post_info: &PostDispatchInfoOf<::RuntimeCall>, 66 | len: usize, 67 | result: &DispatchResult, 68 | ) -> Result<(), TransactionValidityError>; 69 | 70 | /// Charges the fee for creating the dao (multisig). 71 | fn handle_creation_fee( 72 | imbalance: FeeAssetNegativeImbalance< 73 | Credit, 74 | Credits, 75 | >, 76 | ); 77 | } 78 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/lookup.rs: -------------------------------------------------------------------------------- 1 | //! Custom account lookup implementation. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! 6 | //! This module implements the [`StaticLookup`] trait allowing for convenient lookup of a DAO's 7 | //! AccountId from its DaoId. 8 | //! This implementation abstracts on top of two lower level functions: 9 | //! - `lookup_dao`: Used for accessing the storage and retrieving a DAO's AccountId. 10 | //! - `lookup_address`: Used for converting from a `MultiAddress::Index` that contains a DaoId to this DAO's AccountId. 11 | 12 | use crate::{Config, CoreByAccount, CoreStorage, Pallet}; 13 | use core::marker::PhantomData; 14 | use frame_support::error::LookupError; 15 | use sp_runtime::{traits::StaticLookup, MultiAddress}; 16 | 17 | impl Pallet { 18 | /// Queries `CoreStorage` to retrieve the AccountId of a DAO. 19 | pub fn lookup_dao(dao_id: T::DaoId) -> Option { 20 | CoreStorage::::get(dao_id).map(|dao| dao.account) 21 | } 22 | 23 | /// Matches `MultiAddress` to allow for a `MultiAddress::Index` containing a DaoId to be converted 24 | /// to it's derived AccountId. 25 | pub fn lookup_address(a: MultiAddress) -> Option { 26 | match a { 27 | MultiAddress::Id(i) => Some(i), 28 | MultiAddress::Index(i) => Self::lookup_dao(i), 29 | _ => None, 30 | } 31 | } 32 | } 33 | 34 | /// StaticLookup implementor using MultiAddress::Index for looking up DAOs by id. 35 | pub struct DaoLookup(PhantomData); 36 | 37 | impl StaticLookup for DaoLookup { 38 | type Source = MultiAddress; 39 | type Target = T::AccountId; 40 | 41 | fn lookup(a: Self::Source) -> Result { 42 | Pallet::::lookup_address(a).ok_or(LookupError) 43 | } 44 | 45 | fn unlookup(a: Self::Target) -> Self::Source { 46 | match CoreByAccount::::get(&a) { 47 | Some(dao_id) => MultiAddress::Index(dao_id), 48 | None => MultiAddress::Id(a), 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/migrations.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use frame_support::{ 3 | dispatch::GetStorageVersion, 4 | traits::{Get, OnRuntimeUpgrade}, 5 | weights::Weight, 6 | }; 7 | use log::{info, warn}; 8 | 9 | pub mod v1 { 10 | 11 | use super::*; 12 | 13 | pub fn clear_storages() { 14 | let _ = frame_support::migration::clear_storage_prefix(b"INV4", b"", b"", None, None); 15 | } 16 | 17 | pub struct MigrateToV1(sp_std::marker::PhantomData); 18 | impl OnRuntimeUpgrade for MigrateToV1 { 19 | #[cfg(feature = "try-runtime")] 20 | fn pre_upgrade() -> Result, &'static str> { 21 | frame_support::ensure!( 22 | Pallet::::current_storage_version() == 0, 23 | "Required v0 before upgrading to v1" 24 | ); 25 | 26 | Ok(Default::default()) 27 | } 28 | 29 | fn on_runtime_upgrade() -> Weight { 30 | let current = Pallet::::current_storage_version(); 31 | 32 | if current == 1 { 33 | clear_storages::(); 34 | 35 | current.put::>(); 36 | 37 | info!("v1 applied successfully"); 38 | T::DbWeight::get().reads_writes(0, 1) 39 | } else { 40 | warn!("Skipping v1, should be removed"); 41 | T::DbWeight::get().reads(1) 42 | } 43 | } 44 | 45 | #[cfg(feature = "try-runtime")] 46 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> { 47 | frame_support::ensure!( 48 | Pallet::::on_chain_storage_version() == 1, 49 | "v1 not applied" 50 | ); 51 | 52 | Ok(()) 53 | } 54 | } 55 | } 56 | 57 | pub mod v2 { 58 | use super::*; 59 | use codec::{Decode, Encode}; 60 | use frame_support::{ 61 | pallet_prelude::ValueQuery, storage_alias, Blake2_128Concat, Twox64Concat, 62 | }; 63 | 64 | #[derive(Default, Encode, Decode)] 65 | pub struct AccountData { 66 | pub free: Balance, 67 | pub reserved: Balance, 68 | pub frozen: Balance, 69 | } 70 | 71 | #[storage_alias] 72 | pub type Accounts = 73 | StorageDoubleMap< 74 | orml_tokens2::Pallet, 75 | Blake2_128Concat, 76 | ::AccountId, 77 | Twox64Concat, 78 | ::DaoId, 79 | AccountData, 80 | ValueQuery, 81 | >; 82 | 83 | pub fn fill_dao_owners() { 84 | Accounts::::iter_keys() 85 | .for_each(|(member, dao_id)| CoreMembers::::insert(dao_id, member, ())); 86 | } 87 | 88 | pub struct MigrateToV2(sp_std::marker::PhantomData); 89 | impl OnRuntimeUpgrade for MigrateToV2 { 90 | #[cfg(feature = "try-runtime")] 91 | fn pre_upgrade() -> Result, &'static str> { 92 | frame_support::ensure!( 93 | Pallet::::current_storage_version() == 1, 94 | "Required v1 before upgrading to v2" 95 | ); 96 | 97 | Ok(Default::default()) 98 | } 99 | 100 | fn on_runtime_upgrade() -> Weight { 101 | let current = Pallet::::current_storage_version(); 102 | 103 | if current == 2 { 104 | fill_dao_owners::(); 105 | 106 | current.put::>(); 107 | 108 | info!("v2 applied successfully"); 109 | T::DbWeight::get().reads_writes(0, 1) 110 | } else { 111 | warn!("Skipping v1, should be removed"); 112 | T::DbWeight::get().reads(1) 113 | } 114 | } 115 | 116 | #[cfg(feature = "try-runtime")] 117 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> { 118 | frame_support::ensure!( 119 | Pallet::::on_chain_storage_version() == 2, 120 | "v2 not applied" 121 | ); 122 | 123 | Ok(()) 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /pallets/pallet-dao-manager/src/origin.rs: -------------------------------------------------------------------------------- 1 | //! Custom Multisig Origin (`DaoOrigin`). 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This module introduces a custom origin [`DaoOrigin`], enabling self-management for DAOs and 6 | //! includes the [`ensure_multisig`] function to guarantee calls genuinely come from the multisig account. 7 | //! This is an efficient approach considering that converting from DaoId to AccountId is a one-way operation, 8 | //! so the origin brings the DaoId to dispatchable calls. 9 | //! Converting to a `RawOrigin::Signed` origin for other calls is handled in the runtime. 10 | 11 | use crate::{ 12 | account_derivation::DaoAccountDerivation, 13 | pallet::{self, Origin, Pallet}, 14 | Config, 15 | }; 16 | use codec::{Decode, Encode, MaxEncodedLen}; 17 | use frame_support::{error::BadOrigin, pallet_prelude::RuntimeDebug}; 18 | use scale_info::TypeInfo; 19 | 20 | /// Origin representing a dao by its id. 21 | #[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)] 22 | pub enum DaoOrigin { 23 | Multisig(MultisigInternalOrigin), 24 | } 25 | 26 | /// Internal origin for identifying the multisig DaoId. 27 | #[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)] 28 | pub struct MultisigInternalOrigin { 29 | pub id: T::DaoId, 30 | } 31 | 32 | impl MultisigInternalOrigin 33 | where 34 | T::AccountId: From<[u8; 32]>, 35 | { 36 | pub fn new(id: T::DaoId) -> Self { 37 | Self { id } 38 | } 39 | 40 | pub fn to_account_id(&self) -> T::AccountId { 41 | Pallet::::derive_dao_account(self.id) 42 | } 43 | } 44 | 45 | /// Ensures the passed origin is a multisig, returning [`MultisigInternalOrigin`]. 46 | pub fn ensure_multisig( 47 | o: OuterOrigin, 48 | ) -> Result, BadOrigin> 49 | where 50 | OuterOrigin: Into, OuterOrigin>>, 51 | { 52 | match o.into() { 53 | Ok(Origin::::Multisig(internal)) => Ok(internal), 54 | _ => Err(BadOrigin), 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /pallets/pallet-dao-staking/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = 'pallet-dao-staking' 3 | description = 'FRAME pallet for DAO staking' 4 | authors.workspace = true 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | repository.workspace = true 9 | version.workspace = true 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { workspace = true } 16 | log = { workspace = true } 17 | scale-info = { workspace = true } 18 | serde = { workspace = true, optional = true } 19 | 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | num-traits = { workspace = true } 23 | pallet-balances = { workspace = true, optional = true } 24 | pallet-message-queue = { workspace = true } 25 | pallet-session = { workspace = true } 26 | pallet-timestamp = { workspace = true, optional = true } 27 | sp-arithmetic = { workspace = true } 28 | sp-core = { workspace = true } 29 | sp-io = { workspace = true } 30 | sp-runtime = { workspace = true } 31 | sp-staking = { workspace = true } 32 | sp-std = { workspace = true } 33 | 34 | pallet-dao-manager = { workspace = true } 35 | 36 | cumulus-primitives-core = { workspace = true } 37 | frame-benchmarking = { workspace = true, optional = true } 38 | 39 | [dev-dependencies] 40 | orml-tokens = { workspace = true } 41 | orml-traits = { workspace = true } 42 | xcm = { workspace = true } 43 | 44 | [features] 45 | default = ["std"] 46 | std = [ 47 | "codec/std", 48 | "cumulus-primitives-core/std", 49 | "frame-benchmarking?/std", 50 | "frame-support/std", 51 | "frame-system/std", 52 | "num-traits/std", 53 | "orml-tokens/std", 54 | "orml-traits/std", 55 | "pallet-balances/std", 56 | "pallet-dao-manager/std", 57 | "pallet-message-queue/std", 58 | "pallet-session/std", 59 | "pallet-timestamp/std", 60 | "scale-info/std", 61 | "serde", 62 | "sp-arithmetic/std", 63 | "sp-core/std", 64 | "sp-io/std", 65 | "sp-runtime/std", 66 | "sp-staking/std", 67 | "sp-std/std", 68 | "xcm/std", 69 | "log/std", 70 | ] 71 | runtime-benchmarks = [ 72 | "frame-benchmarking/runtime-benchmarks", 73 | "frame-system/runtime-benchmarks", 74 | "pallet-dao-manager/runtime-benchmarks", 75 | "pallet-message-queue/runtime-benchmarks", 76 | "sp-runtime/runtime-benchmarks", 77 | "frame-support/runtime-benchmarks", 78 | "sp-staking/runtime-benchmarks", 79 | ] 80 | try-runtime = ["frame-support/try-runtime", "pallet-dao-manager/try-runtime", "sp-runtime/try-runtime"] 81 | -------------------------------------------------------------------------------- /pallets/pallet-dao-staking/README.md: -------------------------------------------------------------------------------- 1 | # DAO Staking Pallet 2 | 3 | ## Overview 4 | 5 | The DAO Staking Pallet is a pallet designed to facilitate staking towards DAOs within a blockchain network. This pallet introduces a staking mechanism that allows two distinct sets of entities, namely DAOs and Stakers, to participate in the distribution of tokens from a predefined pot. The allocation of rewards is determined based on the amount staked by each entity and the total stake towards each DAO. 6 | 7 | ### DAOs 8 | 9 | DAOs represent virtual accounts identified by unique IDs, which are responsible for registering themselves within the staking ecosystem. The primary role of DAOs is to attract Stakers to lock tokens in their favor. The rewards allocated to DAOs are proportional to the total amount staked towards them by Stakers. However, for a DAO to be eligible for rewards, it must have a total stake above a predefined threshold, thereby becoming `active`. 10 | 11 | ### Stakers 12 | 13 | Stakers are individual accounts that engage in locking tokens in favor of a DAO. Unlike DAOs, Stakers receive a fraction of the rewards based on their own stake. 14 | 15 | ## Runtime Configuration Parameters 16 | 17 | - `BlocksPerEra`: Defines the duration of an era in terms of block numbers. 18 | - `RegisterDeposit`: Specifies the deposit amount required for DAO registration. 19 | - `MaxStakersPerDao`: Limits the maximum number of Stakers that can simultaneously stake towards a single DAO. 20 | - `MinimumStakingAmount`: Sets the minimum amount required for a Staker to participate in staking. 21 | - `UnbondingPeriod`: Determines the period, in eras, required for unbonding staked tokens. 22 | - `RewardRatio`: Establishes the distribution ratio of rewards between DAOs and Stakers. 23 | - `StakeThresholdForActiveDao`: Sets the stake threshold required for a DAO to become `active`. 24 | 25 | ## Dispatchable Functions 26 | 27 | - `register_dao`: Allows DAOs to register themselves in the system. 28 | - `unregister_dao`: Enables DAOs to unregister from the system, initiating the unbonding period for Stakers. 29 | - `change_dao_metadata`: Changes the metadata associated to a DAO. 30 | - `stake`: Allows Stakers to lock tokens in favor of a DAO. 31 | - `unstake`: Unstakes tokens previously staked to a DAO, starting the unbonding period. 32 | - `withdraw_unstaked`: Allows Stakers to withdraw tokens that have completed the unbonding period. 33 | - `staker_claim_rewards`: Allows Stakers to claim available rewards. 34 | - `dao_claim_rewards`: Allows rewards to be claimed for DAOs. 35 | - `halt_unhalt_pallet`: Allows Root to trigger a halt of the system, eras will stop counting and rewards won't be distributed. 36 | 37 | ## Events 38 | 39 | The pallet emits events such as `Staked`, `Unstaked`, `DaoRegistered`, `DaoUnregistered`, and others to signal various operations and state changes within the staking ecosystem. 40 | 41 | ## Errors 42 | 43 | Errors such as `StakingNothing`, `InsufficientBalance`, `MaxStakersReached`, and others are defined to handle exceptional scenarios encountered during pallet operations. 44 | 45 | ## Example Runtime Implementation 46 | 47 | For an example runtime implementation that integrates this pallet, refer to [src/testing/mock.rs](./src/testing/mock.rs). -------------------------------------------------------------------------------- /pallets/pallet-dao-staking/src/migrations.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use frame_support::{ 3 | pallet_prelude::GetStorageVersion, 4 | traits::{Get, OnRuntimeUpgrade}, 5 | weights::Weight, 6 | }; 7 | use log::{info, warn}; 8 | 9 | pub mod v1 { 10 | 11 | use super::*; 12 | 13 | /// This will check all the info on the ledger and remove the old lock while reapplying the new lock based on the 14 | /// value of the ledger, so the wrogly locked tokens will be unlocked. 15 | pub fn migrate_locks_to_freeze() -> Weight { 16 | let mut weight = Weight::zero(); 17 | let mut count: u32 = 0; 18 | 19 | Ledger::::iter().for_each(|(account, ledger)| { 20 | if ledger.locked > Zero::zero() { 21 | ::OldCurrency::remove_lock(LOCK_ID, &account); 22 | 23 | let set_freeze_result = 24 | ::Currency::set_freeze(&LOCK_ID, &account, ledger.locked); 25 | 26 | if set_freeze_result.is_err() { 27 | warn!("set_freeze_result {:?}", set_freeze_result); 28 | } 29 | 30 | weight.saturating_accrue(T::DbWeight::get().reads_writes(3, 2)); 31 | count += 1; 32 | } 33 | }); 34 | 35 | info!("Migrated {} locks", count); 36 | weight 37 | } 38 | 39 | /// This will just remove all the holds on the enabling staking on a dao to apply the new one. 40 | pub fn migrate_holds() -> Weight { 41 | let mut count: u32 = 0; 42 | let mut weight = Weight::zero(); 43 | 44 | RegisteredCore::::iter().for_each(|(_dao_id, dao_info)| { 45 | let dao_account = dao_info.account; 46 | let dao_reserved = ::OldCurrency::reserved_balance(&dao_account); 47 | 48 | ::OldCurrency::unreserve(&dao_account, dao_reserved); 49 | 50 | let set_on_hold_result = ::Currency::set_on_hold( 51 | &HoldReason::DaoStaking.into(), 52 | &dao_account, 53 | dao_reserved, 54 | ); 55 | 56 | if set_on_hold_result.is_err() { 57 | warn!("set_on_hold_result {:?}", set_on_hold_result); 58 | } 59 | 60 | count += 1; 61 | weight.saturating_accrue(T::DbWeight::get().reads_writes(3, 2)); 62 | }); 63 | 64 | info!("Migrated {} daos", count); 65 | weight 66 | } 67 | 68 | pub struct MigrateToV1(sp_std::marker::PhantomData); 69 | impl OnRuntimeUpgrade for MigrateToV1 { 70 | #[cfg(feature = "try-runtime")] 71 | fn pre_upgrade() -> Result, sp_runtime::DispatchError> { 72 | frame_support::ensure!( 73 | Pallet::::on_chain_storage_version() <= Pallet::::in_code_storage_version(), 74 | "Required v0 before upgrading to v1" 75 | ); 76 | 77 | Ok(Default::default()) 78 | } 79 | 80 | fn on_runtime_upgrade() -> Weight { 81 | let mut weight = Weight::zero(); 82 | let current = Pallet::::in_code_storage_version(); 83 | 84 | let chain_version = Pallet::::on_chain_storage_version(); 85 | 86 | weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 0)); 87 | 88 | if current > chain_version { 89 | weight.saturating_accrue(migrate_locks_to_freeze::()); 90 | 91 | weight.saturating_accrue(migrate_holds::()); 92 | 93 | current.put::>(); 94 | 95 | info!("v1 applied successfully"); 96 | T::DbWeight::get().reads_writes(0, 1) 97 | } else { 98 | warn!("Skipping v1, should be removed"); 99 | T::DbWeight::get().reads(1) 100 | } 101 | } 102 | 103 | #[cfg(feature = "try-runtime")] 104 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::DispatchError> { 105 | frame_support::ensure!( 106 | Pallet::::on_chain_storage_version() == 1, 107 | "v1 not applied" 108 | ); 109 | 110 | Ok(()) 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /pallets/pallet-rings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = 'pallet-rings' 3 | description = '' 4 | authors.workspace = true 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | repository.workspace = true 9 | version.workspace = true 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | codec = { workspace = true } 17 | scale-info = { workspace = true } 18 | serde = { workspace = true, optional = true } 19 | 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | num-traits = { workspace = true } 23 | pallet-balances = { workspace = true } 24 | pallet-session = { workspace = true } 25 | pallet-timestamp = { workspace = true, optional = true } 26 | sp-arithmetic = { workspace = true } 27 | sp-core = { workspace = true } 28 | sp-io = { workspace = true } 29 | sp-runtime = {workspace = true} 30 | sp-staking = {workspace = true} 31 | sp-std = {workspace = true} 32 | 33 | pallet-dao-manager = { workspace = true } 34 | 35 | pallet-xcm = { workspace = true } 36 | xcm = { workspace = true } 37 | xcm-executor = { workspace = true } 38 | 39 | frame-benchmarking = { workspace = true, optional = true } 40 | 41 | [dev-dependencies] 42 | orml-traits = { workspace = true } 43 | orml-traits2 = { workspace = true } 44 | orml-tokens = { workspace = true } 45 | orml-tokens2 = { workspace = true } 46 | orml-asset-registry = { workspace = true } 47 | xcm-builder = { workspace = true } 48 | 49 | 50 | [features] 51 | default = ["std"] 52 | std = [ 53 | "serde", 54 | "codec/std", 55 | "scale-info/std", 56 | "num-traits/std", 57 | "sp-core/std", 58 | "sp-runtime/std", 59 | "sp-arithmetic/std", 60 | "sp-io/std", 61 | "sp-std/std", 62 | "frame-support/std", 63 | "frame-system/std", 64 | "pallet-balances/std", 65 | "pallet-session/std", 66 | "pallet-timestamp/std", 67 | "sp-staking/std", 68 | "pallet-dao-manager/std", 69 | "pallet-xcm/std", 70 | "xcm/std", 71 | "orml-traits2/std", 72 | "orml-traits/std", 73 | "orml-tokens/std", 74 | "orml-tokens2/std", 75 | "orml-asset-registry/std", 76 | "xcm-builder/std", 77 | "frame-benchmarking?/std", 78 | ] 79 | runtime-benchmarks = [ 80 | "frame-benchmarking/runtime-benchmarks", 81 | "sp-runtime/runtime-benchmarks", 82 | "frame-system/runtime-benchmarks", 83 | "pallet-dao-manager/runtime-benchmarks", 84 | "pallet-xcm/runtime-benchmarks", 85 | "xcm-builder/runtime-benchmarks", 86 | ] 87 | try-runtime = ["frame-support/try-runtime"] 88 | -------------------------------------------------------------------------------- /pallets/pallet-rings/README.md: -------------------------------------------------------------------------------- 1 | # Rings Pallet 2 | 3 | ## Overview 4 | 5 | The Rings pallet provides a cross-consensus message (XCM) abstraction layer for DAO Management, enabling them to manage assets effortlessly across multiple chains. It abstracts XCM complexities, facilitating easier handling of cross-chain transactions. 6 | 7 | ## Key Features 8 | 9 | - **Maintenance Mode**: Chains can be put under maintenance, restricting certain operations to ensure system integrity during upgrades or when issues are detected. 10 | - **Cross-chain Calls**: Enables sending XCM calls to other chains, allowing for a wide range of interactions. 11 | - **Asset Transfers**: Supports transferring fungible assets between accounts across different chains. 12 | - **Asset Bridging**: Facilitates the bridging of assets between chains, enhancing liquidity and asset interoperability. 13 | 14 | ## Traits Overview 15 | 16 | The pallet utilizes traits to abstract chain and asset locations: 17 | 18 | - [`ChainList`]: Provides an interface for referencing chains and retrieving their [`MultiLocation`] or main asset. 19 | - [`ChainAssetsList`]: Offers an interface for referencing chain assets and obtaining their [`MultiLocation`] or parent chain. 20 | 21 | ## Dispatchable Functions 22 | 23 | ### `set_maintenance_status` 24 | 25 | Sets the maintenance status of a chain. Requires `MaintenanceOrigin` authorization. 26 | 27 | - `chain`: The chain to modify. 28 | - `under_maintenance`: The desired maintenance status. 29 | 30 | ### `send_call` 31 | 32 | Allows sending a XCM call to another chain. Can be initiated by a DAO. 33 | 34 | - `destination`: The target chain. 35 | - `weight`: The call's weight. 36 | - `fee_asset`: The asset used for fee payment. 37 | - `fee`: The fee amount. 38 | - `call`: The call data. 39 | 40 | ### `transfer_assets` 41 | 42 | Allows transfers of fungible assets to another account in the destination chain. 43 | **Requires asset and fee_asset to be located in the same chain**. 44 | 45 | - `asset`: The asset to transfer. 46 | - `amount`: The amount to transfer. 47 | - `to`: The recipient account. 48 | - `fee_asset`: The asset used for fee payment. 49 | - `fee`: The fee amount. 50 | 51 | ### `bridge_assets` 52 | 53 | Allows bridging of assets to another chain, with either the DAO account or a third-party account as the beneficiary. 54 | 55 | - `asset`: The asset to bridge and its origin chain. 56 | - `destination`: The destination chain. 57 | - `fee`: The bridging fee. 58 | - `amount`: The amount to bridge. 59 | - `to`: Optional beneficiary account on the destination chain. (Defaults to the DAO account) 60 | 61 | ## Events 62 | 63 | - `CallSent`: Emitted when a XCM call is sent to another chain. 64 | - `AssetsTransferred`: Emitted when assets are transferred to another account on a different chain. 65 | - `AssetsBridged`: Emitted when assets are bridged to another chain. 66 | - `ChainMaintenanceStatusChanged`: Indicates a change in a chain's maintenance status. 67 | 68 | ## Errors 69 | 70 | - `SendingFailed`: Emitted when sending a XCM message fails. 71 | - `WeightTooHigh`: Emitted when the call's weight exceeds the maximum allowed. 72 | - `FailedToCalculateXcmFee`: Emitted when calculating the XCM fee fails. 73 | - `FailedToReanchorAsset`, `FailedToInvertLocation`: Errors related to asset reanchoring or location inversion. 74 | - `DifferentChains`, `ChainUnderMaintenance`: Indicate issues with the target chain or maintenance status. 75 | 76 | This pallet serves as a foundational component for building cross-chain solutions within the InvArch ecosystem, streamlining asset management and interoperability across diverse blockchain environments. -------------------------------------------------------------------------------- /pallets/pallet-rings/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "runtime-benchmarks")] 2 | 3 | use super::*; 4 | use frame_benchmarking::{benchmarks, whitelisted_caller}; 5 | use frame_support::{pallet_prelude::Weight, traits::Get, BoundedVec}; 6 | use frame_system::RawOrigin as SystemOrigin; 7 | use pallet_dao_manager::origin::{DaoOrigin, MultisigInternalOrigin}; 8 | use sp_std::{ops::Div, prelude::*, vec}; 9 | 10 | fn assert_last_event(generic_event: ::RuntimeEvent) { 11 | frame_system::Pallet::::assert_last_event(generic_event.into()); 12 | } 13 | 14 | benchmarks! { 15 | where_clause { 16 | where 17 | Result< 18 | DaoOrigin, 19 | ::RuntimeOrigin, 20 | >: From<::RuntimeOrigin>, 21 | ::RuntimeOrigin: From>, 22 | 23 | ::DaoId: Into, 24 | 25 | [u8; 32]: From<::AccountId>, 26 | 27 | T::AccountId: From<[u8; 32]>, 28 | } 29 | 30 | set_maintenance_status { 31 | let chain = T::Chains::benchmark_mock(); 32 | 33 | }: _(SystemOrigin::Root, chain.clone(), true) 34 | verify { 35 | assert_last_event::(Event::ChainMaintenanceStatusChanged { 36 | chain, 37 | under_maintenance: true 38 | }.into()); 39 | } 40 | 41 | send_call { 42 | let c in 0 .. T::MaxXCMCallLength::get(); 43 | 44 | let call: BoundedVec = vec![u8::MAX; c as usize].try_into().unwrap(); 45 | let destination = T::Chains::benchmark_mock(); 46 | let weight = Weight::from_parts(100_000_000u64, 10_000u64); 47 | let fee_asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); 48 | let fee: u128 = u128::MAX.div(4u128); 49 | 50 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), destination.clone(), weight, fee_asset, fee, call.clone()) 51 | verify { 52 | assert_last_event::(Event::CallSent { 53 | sender: 0u32.into(), 54 | destination, 55 | call: call.to_vec(), 56 | }.into()); 57 | } 58 | 59 | transfer_assets { 60 | let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); 61 | let amount: u128 = u128::MAX.div(4u128); 62 | let to: T::AccountId = whitelisted_caller(); 63 | 64 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), amount, to.clone(), asset.clone(), amount) 65 | verify { 66 | assert_last_event::(Event::AssetsTransferred { 67 | chain: asset.clone().get_chain(), 68 | asset, 69 | amount, 70 | from: 0u32.into(), 71 | to, 72 | }.into()); 73 | } 74 | 75 | bridge_assets { 76 | let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); 77 | let amount: u128 = u128::MAX.div(4u128); 78 | let fee: u128 = amount.div(5u128); 79 | let to: Option = Some(whitelisted_caller()); 80 | 81 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), asset.clone().get_chain(), fee, amount, to) 82 | verify { 83 | assert_last_event::(Event::AssetsBridged { 84 | origin_chain_asset: asset, 85 | amount, 86 | from: 0u32.into(), 87 | to: whitelisted_caller(), 88 | }.into()); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /pallets/pallet-rings/src/traits.rs: -------------------------------------------------------------------------------- 1 | //! Provides supporting traits for the rings pallet. 2 | //! 3 | //! ## Overview 4 | //! 5 | //! This module contains the traits responsible for creating an abstraction layer on top of XCM [`MultiLocation`] and allows 6 | //! easier handling of cross-chain transactions through XCM. 7 | //! 8 | //! The traits contained in this pallet require an appropriate runtime implementation. 9 | //! 10 | //! ## Traits overview: 11 | //! 12 | //! - [`ChainList`] - Trait used to opaquely refer to a chain, provides an interface to get the chain `MultiLocation` or the chain's main asset as `ChainAssetsList`. 13 | //! - [`ChainAssetsList`] - Trait used to opaquely refer to a chain's asset, provides an interface to get the chain asset `MultiLocation` or the chain as `ChainList`. 14 | 15 | use codec::MaxEncodedLen; 16 | use frame_support::Parameter; 17 | use xcm::opaque::v4::Location; 18 | 19 | /// A chain [`MultiLocation`] abstraction trait. 20 | /// 21 | /// It provides an interface for easily getting a chain's [`MultiLocation`] and to go back and forth between the chain and its assets. 22 | /// 23 | /// This should be implemented properly in the runtime. 24 | pub trait ChainList: Parameter + MaxEncodedLen { 25 | type Balance: Into; 26 | type ChainAssets: ChainAssetsList; 27 | 28 | /// Returns the chain's [`MultiLocation`]. 29 | fn get_location(&self) -> MultiLocation; 30 | 31 | /// Returns the chain's main asset as `ChainAssetsList`. 32 | fn get_main_asset(&self) -> Self::ChainAssets; 33 | 34 | #[cfg(feature = "runtime-benchmarks")] 35 | fn benchmark_mock() -> Self; 36 | } 37 | 38 | /// A chain asset [`MultiLocation`] abstraction trait. 39 | /// 40 | /// It provides an interface for easily getting a chain's asset [`MultiLocation`] and to go back and forth between the asset and its parent chain. 41 | /// 42 | /// This should be implemented properly in the runtime. 43 | pub trait ChainAssetsList: Parameter + MaxEncodedLen { 44 | type Chains: ChainList; 45 | 46 | /// Returns the asset's parent chain. 47 | fn get_chain(&self) -> Self::Chains; 48 | 49 | /// Returns the asset's [`MultiLocation`]. 50 | fn get_asset_location(&self) -> MultiLocation; 51 | } 52 | -------------------------------------------------------------------------------- /pallets/primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = 'invarch-primitives' 3 | description = 'InvArch primitives for InvArchh Pallet Library' 4 | authors.workspace = true 5 | edition.workspace = true 6 | homepage.workspace = true 7 | license.workspace = true 8 | repository.workspace = true 9 | version.workspace = true 10 | 11 | [dependencies] 12 | codec = { workspace = true } 13 | scale-info = { workspace = true } 14 | serde = { workspace = true, optional = true } 15 | 16 | frame-system = { workspace = true } 17 | sp-core = { workspace = true } 18 | sp-io = { workspace = true } 19 | sp-runtime = { workspace = true } 20 | sp-std = { workspace = true } 21 | 22 | [features] 23 | default = ["std"] 24 | std = [ 25 | "codec/std", 26 | "frame-system/std", 27 | "scale-info/std", 28 | "serde", 29 | "sp-core/std", 30 | "sp-io/std", 31 | "sp-runtime/std", 32 | "sp-std/std", 33 | ] 34 | -------------------------------------------------------------------------------- /pallets/primitives/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | use codec::{Decode, Encode, MaxEncodedLen}; 4 | use scale_info::TypeInfo; 5 | use sp_runtime::{Perbill, Percent}; 6 | 7 | /// Voting weight of an IPT 8 | #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 9 | pub enum OneOrPercent { 10 | /// Represents 100% 11 | One, 12 | /// Represents 0% - 99% inclusive 13 | ZeroPoint(Percent), 14 | } 15 | 16 | /// Entity is parent or child? 17 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 18 | pub enum Parentage { 19 | /// Parent IP (Account Id of itself) 20 | Parent(AccountId), 21 | /// Child IP (Id of the immediate parent, Account Id of the topmost parent) 22 | Child(IpsId, AccountId), 23 | } 24 | 25 | /// Normal or replica IPS 26 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 27 | pub enum IpsType { 28 | /// Normal IPS (original) 29 | Normal, 30 | /// IP Replica (Id of the original IP) 31 | Replica(IpsId), 32 | } 33 | 34 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 35 | pub enum BoolOrWasm { 36 | Bool(bool), 37 | Wasm(Wasm), 38 | } 39 | 40 | /// DAO IP Set struct 41 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 42 | pub struct DaoInfo { 43 | /// IPS parentage 44 | pub account: AccountId, 45 | /// IPS metadata 46 | pub metadata: DaoMetadataOf, 47 | 48 | /// Aye vote percentage required to execute a multisig call. 49 | /// 50 | /// Invariant: If set to `One`, 100% of tokens that have non-zero voting weight must approve 51 | pub minimum_support: Perbill, 52 | pub required_approval: Perbill, 53 | 54 | pub frozen_tokens: bool, 55 | } 56 | 57 | /// IPF Info 58 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 59 | pub struct IpfInfo { 60 | /// IPF owner 61 | pub owner: AccountId, 62 | /// Original IPF author 63 | pub author: AccountId, 64 | /// IPF metadata 65 | pub metadata: IpfMetadataOf, 66 | /// IPF data 67 | pub data: Data, 68 | } 69 | 70 | // This is a struct in preparation for having more fields in the future. 71 | #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] 72 | pub struct SubTokenInfo { 73 | pub id: IptId, 74 | pub metadata: SubAssetMetadata, 75 | } 76 | 77 | #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] 78 | pub struct CallInfo { 79 | pub pallet: Data, 80 | pub function: Data, 81 | } 82 | 83 | pub type Balance = u128; 84 | -------------------------------------------------------------------------------- /pallets/rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2024-07-15" 3 | targets = ["wasm32-unknown-unknown"] 4 | components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview"] 5 | -------------------------------------------------------------------------------- /pallets/rustfmt.toml: -------------------------------------------------------------------------------- 1 | imports_granularity = "Crate" 2 | -------------------------------------------------------------------------------- /res/invarch/invarch-genesis-state: -------------------------------------------------------------------------------- 1 | 0x00000000000000000000000000000000000000000000000000000000000000000064d77bb0ea342ea5b053fba4fd29248b1c3a5b20a8a9ef0cfc14cf45b0c5a4fb03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /res/rococo/genesis-state: -------------------------------------------------------------------------------- 1 | 0x000000000000000000000000000000000000000000000000000000000000000000ce33b242a6720e66c121d20a9ea3d1971024de922f7ad9e9662f99e972dd56d003170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /res/rococo/genesis-state-2: -------------------------------------------------------------------------------- 1 | 0x000000000000000000000000000000000000000000000000000000000000000000576f49a7a4fad0a130204494a616ccf31a3c1e16eca0630a60745ccee1a95f5103170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /res/rococo/genesis-state-3: -------------------------------------------------------------------------------- 1 | 0x0000000000000000000000000000000000000000000000000000000000000000005b664ece67e12f9c36a6480a11e7a59bd5209cb7aab7bc23182539fa45dfd3f703170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /res/tinker/genesis-state: -------------------------------------------------------------------------------- 1 | 0x000000000000000000000000000000000000000000000000000000000000000000f61fa99c7255c9fbd90dc4a55837cf79b621e99a265ebfd8712c647af1b7fdf603170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /testall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Initialize result variables 4 | pallets_result="" 5 | invarch_result="" 6 | tinkernet_result="" 7 | 8 | # Function to build and test a given directory 9 | build_and_test() { 10 | local dir=$1 11 | local result_var=$2 12 | 13 | cd ./$dir 14 | 15 | echo "$dir: 1/3 Checking format..." 16 | if RUSTFLAGS=-Awarnings cargo fmt --all -- --check > /dev/null 2>&1; then 17 | echo "$dir: 1/3 Format Check Ok" 18 | else 19 | echo "$dir: 1/3 Format Check Failed" 20 | echo "$dir: 1/3 Running cargo fmt to fix format..." 21 | if cargo fmt --all > /dev/null 2>&1; then 22 | echo "$dir: 1/3 Format Fixed" 23 | else 24 | echo "$dir: 1/3 Format Fix Failed" 25 | eval "$result_var=\"$dir: Format Failed\"" 26 | cd .. 27 | return 28 | fi 29 | fi 30 | 31 | echo "$dir: 2/3 Building..." 32 | if RUSTFLAGS=-Awarnings cargo build --quiet > /dev/null; then 33 | echo "$dir: 2/3 Build Ok" 34 | else 35 | echo "$dir: 2/3 Build Failed" 36 | eval "$result_var=\"$dir: Build Failed\"" 37 | cd .. 38 | return 39 | fi 40 | 41 | echo "$dir: 3/3 Testing..." 42 | if RUSTFLAGS=-Awarnings cargo test --quiet > /dev/null; then 43 | echo "$dir: 3/3 Test Ok" 44 | eval "$result_var=\"$dir: Ok\"" 45 | else 46 | echo "$dir: 3/3 Test Failed" 47 | eval "$result_var=\"$dir: Test Failed\"" 48 | fi 49 | 50 | cd .. 51 | } 52 | 53 | # Build and test each project 54 | build_and_test "pallets" "pallets_result" 55 | build_and_test "invarch" "invarch_result" 56 | build_and_test "tinkernet" "tinkernet_result" 57 | 58 | # Print results 59 | echo -e "\nResults:" 60 | echo $pallets_result 61 | echo $invarch_result 62 | echo $tinkernet_result -------------------------------------------------------------------------------- /tinkernet/node/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tinkernet-node" 3 | version.workspace = true 4 | authors.workspace = true 5 | license.workspace = true 6 | homepage.workspace = true 7 | publish = false 8 | repository.workspace = true 9 | edition.workspace = true 10 | 11 | build = "build.rs" 12 | 13 | [[bin]] 14 | name = "tinkernet-collator" 15 | path = "src/main.rs" 16 | 17 | [dependencies] 18 | async-trait = { workspace = true } 19 | clap = { workspace = true } 20 | codec = { workspace = true } 21 | derive_more = { workspace = true } 22 | hex-literal = { workspace = true } 23 | log = { workspace = true } 24 | scale-info = { workspace = true } 25 | serde = { workspace = true, features = ["derive"] } 26 | serde_json = { workspace = true } 27 | # RPC related Dependencies 28 | 29 | 30 | ## RPC related Dependencies 31 | jsonrpsee = { workspace = true } 32 | futures = { workspace = true } 33 | 34 | ## Local Dependencies 35 | tinkernet-runtime = { path = "../runtime" } 36 | 37 | ## Substrate Dependencies 38 | frame-benchmarking = { workspace = true, features = ["std"] } 39 | frame-benchmarking-cli = { workspace = true } 40 | pallet-transaction-payment-rpc = { workspace = true } 41 | 42 | ## Substrate Client Dependencies 43 | sc-basic-authorship = { workspace = true } 44 | sc-chain-spec = { workspace = true } 45 | sc-cli = { workspace = true } 46 | sc-client-api = { workspace = true } 47 | sc-consensus = { workspace = true } 48 | sc-consensus-aura = { workspace = true } 49 | sc-consensus-manual-seal = { workspace = true } 50 | sc-executor = { workspace = true } 51 | sc-keystore = { workspace = true } 52 | sc-network = { workspace = true } 53 | sc-network-sync = { workspace = true } 54 | sc-rpc = { workspace = true } 55 | sc-rpc-api = { workspace = true } 56 | sc-service = { workspace = true } 57 | sc-sysinfo = { workspace = true } 58 | sc-telemetry = { workspace = true } 59 | sc-tracing = { workspace = true } 60 | sc-transaction-pool = { workspace = true } 61 | sc-transaction-pool-api = { workspace = true } 62 | 63 | ## Substrate Primitive 64 | sp-api = { workspace = true, features = ["std"] } 65 | sp-io = { workspace = true, features = ["std"] } 66 | sp-block-builder = { workspace = true, features = ["std"] } 67 | sp-blockchain = { workspace = true } 68 | sp-consensus = { workspace = true } 69 | sp-consensus-aura = { workspace = true, features = ["std"] } 70 | sp-core = { workspace = true, features = ["std"] } 71 | sp-inherents = { workspace = true, features = ["std"] } 72 | sp-keystore = { workspace = true } 73 | sp-offchain = { workspace = true, features = ["std"] } 74 | sp-runtime = { workspace = true, features = ["std"] } 75 | sp-session = { workspace = true, features = ["std"] } 76 | sp-timestamp = { workspace = true } 77 | sp-transaction-pool = { workspace = true, features = ["std"] } 78 | 79 | substrate-frame-rpc-system = { workspace = true } 80 | substrate-prometheus-endpoint = { workspace = true } 81 | try-runtime-cli = { workspace = true, optional = true } 82 | 83 | ## Polkadot dependencies Dependencies 84 | polkadot-cli = { workspace = true, features = ["rococo-native"] } 85 | polkadot-parachain = { workspace = true } 86 | polkadot-primitives = { workspace = true } 87 | polkadot-service = { workspace = true } 88 | xcm = { workspace = true } 89 | 90 | ## Cumulus dependencies Dependencies 91 | cumulus-client-cli = { workspace = true } 92 | cumulus-client-collator = { workspace = true } 93 | cumulus-client-consensus-aura = { workspace = true } 94 | cumulus-client-consensus-common = { workspace = true } 95 | cumulus-client-consensus-proposer = { workspace = true } 96 | cumulus-client-network = { workspace = true } 97 | cumulus-client-service = { workspace = true } 98 | cumulus-primitives-core = { workspace = true, features = ["std"] } 99 | cumulus-primitives-parachain-inherent = { workspace = true } 100 | cumulus-relay-chain-inprocess-interface = { workspace = true } 101 | cumulus-relay-chain-minimal-node = { workspace = true } 102 | cumulus-relay-chain-interface = { workspace = true } 103 | cumulus-relay-chain-rpc-interface = { workspace = true } 104 | cumulus-client-parachain-inherent = { workspace = true } 105 | 106 | [build-dependencies] 107 | substrate-build-script-utils = { workspace = true } 108 | 109 | [features] 110 | runtime-benchmarks = [ 111 | "tinkernet-runtime/runtime-benchmarks", 112 | "polkadot-cli/runtime-benchmarks", 113 | ] 114 | 115 | try-runtime = ["tinkernet-runtime/try-runtime", "try-runtime-cli/try-runtime"] 116 | -------------------------------------------------------------------------------- /tinkernet/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 | -------------------------------------------------------------------------------- /tinkernet/node/res/.gitignore: -------------------------------------------------------------------------------- 1 | # temporary disabled for collaboration 2 | # !/*.json 3 | -------------------------------------------------------------------------------- /tinkernet/node/res/local-tinker-para-2000-genesis: -------------------------------------------------------------------------------- 1 | 0x000000000000000000000000000000000000000000000000000000000000000000b910308fc34fe87c1acd65200b97c9211314a4befea38b080b1d1eabf4b6d93603170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /tinkernet/node/src/cli.rs: -------------------------------------------------------------------------------- 1 | use crate::chain_spec; 2 | use clap::Parser; 3 | use std::path::PathBuf; 4 | 5 | /// Sub-commands supported by the collator. 6 | #[allow(clippy::large_enum_variant)] 7 | #[derive(Debug, clap::Subcommand)] 8 | pub enum Subcommand { 9 | /// Key management cli utilities 10 | #[clap(subcommand)] 11 | Key(sc_cli::KeySubcommand), 12 | 13 | /// Export the genesis state of the parachain. 14 | #[command(alias = "export-genesis-state")] 15 | ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand), 16 | 17 | /// Export the genesis wasm of the parachain. 18 | #[clap(name = "export-genesis-wasm")] 19 | ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), 20 | 21 | /// Build a chain specification. 22 | BuildSpec(sc_cli::BuildSpecCmd), 23 | 24 | /// Validate blocks. 25 | CheckBlock(sc_cli::CheckBlockCmd), 26 | 27 | /// Export blocks. 28 | ExportBlocks(sc_cli::ExportBlocksCmd), 29 | 30 | /// Export the state of a given block into a chain spec. 31 | ExportState(sc_cli::ExportStateCmd), 32 | 33 | /// Import blocks. 34 | ImportBlocks(sc_cli::ImportBlocksCmd), 35 | 36 | /// Remove the whole chain. 37 | PurgeChain(cumulus_client_cli::PurgeChainCmd), 38 | 39 | /// Revert the chain to a previous state. 40 | Revert(sc_cli::RevertCmd), 41 | 42 | /// Sub-commands concerned with benchmarking. 43 | /// The pallet benchmarking moved to the `pallet` sub-command. 44 | #[clap(subcommand)] 45 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 46 | 47 | /// Try some testing command against a specified runtime state. 48 | #[cfg(feature = "try-runtime")] 49 | TryRuntime(try_runtime_cli::TryRuntimeCmd), 50 | 51 | /// Errors since the binary was not build with `--features try-runtime`. 52 | #[cfg(not(feature = "try-runtime"))] 53 | TryRuntime, 54 | } 55 | 56 | #[derive(Debug, Parser)] 57 | #[clap( 58 | propagate_version = true, 59 | args_conflicts_with_subcommands = true, 60 | subcommand_negates_reqs = true 61 | )] 62 | pub struct Cli { 63 | #[clap(subcommand)] 64 | pub subcommand: Option, 65 | 66 | #[clap(flatten)] 67 | pub run: cumulus_client_cli::RunCmd, 68 | 69 | /// Disable automatic hardware benchmarks. 70 | /// 71 | /// By default these benchmarks are automatically ran at startup and measure 72 | /// the CPU speed, the memory bandwidth and the disk speed. 73 | /// 74 | /// The results are then printed out in the logs, and also sent as part of 75 | /// telemetry, if telemetry is enabled. 76 | #[clap(long)] 77 | pub no_hardware_benchmarks: bool, 78 | 79 | /// Relay chain arguments 80 | #[clap(raw = true)] 81 | pub relay_chain_args: Vec, 82 | } 83 | 84 | #[derive(Debug)] 85 | pub struct RelayChainCli { 86 | /// The actual relay chain cli object. 87 | pub base: polkadot_cli::RunCmd, 88 | 89 | /// Optional chain id that should be passed to the relay chain. 90 | pub chain_id: Option, 91 | 92 | /// The base path that should be used by the relay chain. 93 | pub base_path: Option, 94 | } 95 | 96 | impl RelayChainCli { 97 | /// Parse the relay chain CLI parameters using the para chain `Configuration`. 98 | pub fn new<'a>( 99 | para_config: &sc_service::Configuration, 100 | relay_chain_args: impl Iterator, 101 | ) -> Self { 102 | let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec); 103 | let chain_id = extension.map(|e| e.relay_chain.clone()); 104 | let base_path = para_config.base_path.path().join("polkadot"); 105 | Self { 106 | base_path: Some(base_path), 107 | chain_id, 108 | base: polkadot_cli::RunCmd::parse_from(relay_chain_args), 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /tinkernet/node/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod chain_spec; 2 | pub mod rpc; 3 | pub mod service; 4 | -------------------------------------------------------------------------------- /tinkernet/node/src/main.rs: -------------------------------------------------------------------------------- 1 | //! InvArch Parachain Node 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 | -------------------------------------------------------------------------------- /tinkernet/node/src/rpc.rs: -------------------------------------------------------------------------------- 1 | //! A collection of node-specific RPC methods. 2 | //! Substrate provides the `sc-rpc` crate, which defines the dao 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 tinkernet_runtime::{opaque::Block, AccountId, Balance, Hash, Nonce}; 9 | 10 | use sc_client_api::AuxStore; 11 | pub use sc_rpc::DenyUnsafe; 12 | use sc_transaction_pool_api::TransactionPool; 13 | use sp_api::ProvideRuntimeApi; 14 | use sp_block_builder::BlockBuilder; 15 | use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; 16 | use std::sync::Arc; 17 | 18 | use sc_consensus_manual_seal::rpc::EngineCommand; 19 | 20 | /// A type representing all RPC extensions. 21 | pub type RpcExtension = jsonrpsee::RpcModule<()>; 22 | 23 | /// Full client dependencies 24 | pub struct FullDeps { 25 | /// The client instance to use. 26 | pub client: Arc, 27 | /// Transaction pool instance. 28 | pub pool: Arc

, 29 | /// Whether to deny unsafe calls 30 | pub deny_unsafe: DenyUnsafe, 31 | /// Command sink used for solo-dev mode 32 | pub command_sink: Option>>, 33 | } 34 | 35 | /// Instantiate all RPC extensions. 36 | pub fn create_full( 37 | deps: FullDeps, 38 | ) -> Result> 39 | where 40 | C: ProvideRuntimeApi 41 | + HeaderBackend 42 | + AuxStore 43 | + HeaderMetadata 44 | + Send 45 | + Sync 46 | + 'static, 47 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, 48 | C::Api: substrate_frame_rpc_system::AccountNonceApi, 49 | C::Api: BlockBuilder, 50 | P: TransactionPool + Sync + Send + 'static, 51 | { 52 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; 53 | use substrate_frame_rpc_system::{System, SystemApiServer}; 54 | 55 | let mut module = RpcExtension::new(()); 56 | let FullDeps { 57 | client, 58 | pool, 59 | deny_unsafe, 60 | command_sink: _, 61 | } = deps; 62 | 63 | module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; 64 | module.merge(TransactionPayment::new(client).into_rpc())?; 65 | Ok(module) 66 | } 67 | -------------------------------------------------------------------------------- /tinkernet/runtime/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of InvArch. 2 | 3 | // Copyright (C) 2021 InvArch.io 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 | #[cfg(all(not(feature = "metadata-hash"), feature = "std"))] 20 | fn main() { 21 | substrate_wasm_builder::WasmBuilder::new() 22 | .with_current_project() 23 | .export_heap_base() 24 | .import_memory() 25 | .build() 26 | } 27 | 28 | #[cfg(all(feature = "metadata-hash", feature = "std"))] 29 | fn main() { 30 | substrate_wasm_builder::WasmBuilder::new() 31 | .with_current_project() 32 | .export_heap_base() 33 | .import_memory() 34 | .enable_metadata_hash("TNKR", 12) 35 | .build() 36 | } 37 | 38 | /// The wasm builder is deactivated when compiling 39 | /// this crate for wasm to speed up the compilation. 40 | #[cfg(not(feature = "std"))] 41 | fn main() {} 42 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/assets.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | common_types::AssetId, constants::TreasuryAccount, AccountId, Balance, Balances, BlockNumber, 3 | ExistentialDeposit, MaxLocks, MaxReserves, Runtime, RuntimeEvent, RuntimeOrigin, Tokens, 4 | }; 5 | use codec::{Decode, Encode, MaxEncodedLen}; 6 | use frame_support::{ 7 | parameter_types, 8 | traits::{Contains, EnsureOrigin, EnsureOriginWithArg}, 9 | }; 10 | use frame_system::EnsureRoot; 11 | use orml_asset_registry::ExistentialDeposits as AssetRegistryExistentialDeposits; 12 | use orml_currencies::BasicCurrencyAdapter; 13 | use orml_traits::parameter_type_with_key; 14 | use scale_info::TypeInfo; 15 | 16 | pub const CORE_ASSET_ID: AssetId = 0; 17 | pub const KSM_ASSET_ID: AssetId = 1; 18 | 19 | parameter_types! { 20 | pub const NativeAssetId: AssetId = CORE_ASSET_ID; 21 | pub const RelayAssetId: AssetId = KSM_ASSET_ID; 22 | pub const StringLimit: u32 = 255; 23 | } 24 | 25 | pub struct AssetAuthority; 26 | impl EnsureOriginWithArg> for AssetAuthority { 27 | type Success = (); 28 | 29 | fn try_origin( 30 | origin: RuntimeOrigin, 31 | _asset_id: &Option, 32 | ) -> Result { 33 | as EnsureOrigin>::try_origin(origin) 34 | } 35 | 36 | #[cfg(feature = "runtime-benchmarks")] 37 | fn try_successful_origin(_asset_id: &Option) -> Result { 38 | unimplemented!() 39 | } 40 | } 41 | 42 | #[derive(Debug, TypeInfo, Encode, Decode, PartialEq, Eq, Clone, MaxEncodedLen)] 43 | pub struct CustomAssetMetadata { 44 | pub fee_per_second: Option, 45 | } 46 | 47 | impl orml_asset_registry::Config for Runtime { 48 | type RuntimeEvent = RuntimeEvent; 49 | type AuthorityOrigin = AssetAuthority; 50 | type AssetId = AssetId; 51 | type Balance = Balance; 52 | type AssetProcessor = orml_asset_registry::SequentialId; 53 | type CustomMetadata = CustomAssetMetadata; 54 | type WeightInfo = (); 55 | type StringLimit = StringLimit; 56 | } 57 | 58 | pub struct DustRemovalWhitelist; 59 | impl Contains for DustRemovalWhitelist { 60 | fn contains(a: &AccountId) -> bool { 61 | // Always whitelists treasury account 62 | *a == TreasuryAccount::get() 63 | } 64 | } 65 | 66 | pub type Amount = i128; 67 | 68 | parameter_type_with_key! { 69 | pub ExistentialDeposits: |currency_id: AssetId| -> Balance { 70 | if currency_id == &CORE_ASSET_ID { 71 | ExistentialDeposit::get() 72 | } else { 73 | AssetRegistryExistentialDeposits::::get(currency_id) 74 | } 75 | }; 76 | } 77 | 78 | impl orml_tokens::Config for Runtime { 79 | type RuntimeEvent = RuntimeEvent; 80 | type Balance = Balance; 81 | type Amount = Amount; 82 | type CurrencyId = AssetId; 83 | type WeightInfo = (); 84 | type ExistentialDeposits = ExistentialDeposits; 85 | type MaxLocks = MaxLocks; 86 | type DustRemovalWhitelist = DustRemovalWhitelist; 87 | type MaxReserves = MaxReserves; 88 | type ReserveIdentifier = [u8; 8]; 89 | type CurrencyHooks = (); 90 | } 91 | 92 | impl orml_currencies::Config for Runtime { 93 | type MultiCurrency = Tokens; 94 | type NativeCurrency = BasicCurrencyAdapter; 95 | type GetNativeCurrencyId = NativeAssetId; 96 | type WeightInfo = (); 97 | } 98 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/common_types.rs: -------------------------------------------------------------------------------- 1 | /// The IpId 2 | pub type CommonId = u32; 3 | 4 | pub type AssetId = u32; 5 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/constants.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountId, PotId, TreasuryPalletId}; 2 | use frame_support::parameter_types; 3 | use sp_runtime::traits::AccountIdConversion; 4 | 5 | pub mod currency { 6 | use crate::Balance; 7 | 8 | pub const UNIT: Balance = 1_000_000_000_000; 9 | pub const MILLIUNIT: Balance = 1_000_000_000; 10 | pub const MICROUNIT: Balance = 1_000_000; 11 | 12 | pub const CENTS: Balance = UNIT / 10_000; 13 | pub const MILLICENTS: Balance = CENTS / 1_000; 14 | 15 | // Almost same as Kusama 16 | pub const fn deposit(items: u32, bytes: u32) -> Balance { 17 | items as Balance * 2_000 * CENTS + (bytes as Balance) * 100 * MILLICENTS 18 | } 19 | } 20 | 21 | parameter_types! { 22 | pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); 23 | pub StakingPotAccount: AccountId = PotId::get().into_account_truncating(); 24 | } 25 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/fee_handling.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | assets::RelayAssetId, 3 | common_types::AssetId, 4 | constants::{StakingPotAccount, TreasuryAccount}, 5 | AccountId, Balance, Runtime, RuntimeCall, RuntimeEvent, Tokens, 6 | }; 7 | use codec::{Decode, Encode}; 8 | use frame_support::traits::{ 9 | fungible::Inspect as FungibleInspect, 10 | fungibles::{Balanced, Credit}, 11 | tokens::{Fortitude, Precision, Preservation, WithdrawConsequence}, 12 | Contains, OnUnbalanced, 13 | }; 14 | use orml_tokens::CurrencyAdapter; 15 | use pallet_asset_tx_payment::OnChargeAssetTransaction; 16 | use scale_info::TypeInfo; 17 | use sp_runtime::{ 18 | traits::{DispatchInfoOf, One, PostDispatchInfoOf, Zero}, 19 | transaction_validity::{InvalidTransaction, TransactionValidityError}, 20 | }; 21 | 22 | pub struct KSMEnabledPallets; 23 | impl Contains for KSMEnabledPallets { 24 | fn contains(t: &RuntimeCall) -> bool { 25 | matches!( 26 | t, 27 | // We want users and DAOs to be able to operate multisigs using KSM. 28 | RuntimeCall::INV4(_) 29 | // We want DAOs to be able to operate XCMultisigs using KSM. 30 | | RuntimeCall::Rings(_) 31 | // These next 3 are needed to manage the KSM itself using KSM as the fee token. 32 | | RuntimeCall::Tokens(_) 33 | | RuntimeCall::XTokens(_) 34 | | RuntimeCall::Currencies(_) 35 | ) 36 | } 37 | } 38 | 39 | impl pallet_asset_tx_payment::Config for Runtime { 40 | type RuntimeEvent = RuntimeEvent; 41 | type Fungibles = Tokens; 42 | type OnChargeAssetTransaction = FilteredTransactionCharger; 43 | } 44 | 45 | pub struct TnkrToKsm; 46 | impl TnkrToKsm { 47 | pub fn to_asset_balance(balance: Balance) -> Balance { 48 | balance.saturating_div(20u128) 49 | } 50 | } 51 | 52 | pub struct FilteredTransactionCharger; 53 | impl OnChargeAssetTransaction for FilteredTransactionCharger { 54 | type AssetId = AssetId; 55 | type Balance = Balance; 56 | type LiquidityInfo = Credit; 57 | 58 | fn withdraw_fee( 59 | who: &AccountId, 60 | call: &RuntimeCall, 61 | _dispatch_info: &sp_runtime::traits::DispatchInfoOf, 62 | asset_id: AssetId, 63 | fee: Balance, 64 | _tip: Balance, 65 | ) -> Result, frame_support::unsigned::TransactionValidityError> { 66 | if KSMEnabledPallets::contains(call) && asset_id == 1u32 { 67 | let min_converted_fee = if fee.is_zero() { 68 | Zero::zero() 69 | } else { 70 | One::one() 71 | }; 72 | 73 | let fee = TnkrToKsm::to_asset_balance(fee).max(min_converted_fee); 74 | 75 | let can_withdraw = CurrencyAdapter::::can_withdraw(who, fee); 76 | 77 | if !matches!(can_withdraw, WithdrawConsequence::Success) { 78 | return Err(InvalidTransaction::Payment.into()); 79 | } 80 | 81 | >::withdraw( 82 | asset_id, 83 | who, 84 | fee, 85 | Precision::Exact, 86 | Preservation::Expendable, 87 | Fortitude::Force, 88 | ) 89 | .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment)) 90 | } else { 91 | Err(TransactionValidityError::from(InvalidTransaction::Payment)) 92 | } 93 | } 94 | 95 | fn correct_and_deposit_fee( 96 | who: &AccountId, 97 | _dispatch_info: &DispatchInfoOf, 98 | _post_info: &PostDispatchInfoOf, 99 | corrected_fee: Balance, 100 | _tip: Balance, 101 | paid: Credit, 102 | ) -> Result<(u128, u128), TransactionValidityError> { 103 | let min_converted_fee = if corrected_fee.is_zero() { 104 | Zero::zero() 105 | } else { 106 | One::one() 107 | }; 108 | 109 | let corrected_fee = TnkrToKsm::to_asset_balance(corrected_fee).max(min_converted_fee); 110 | 111 | let (final_fee, refund) = paid.split(corrected_fee); 112 | 113 | let _ = >::resolve(who, refund); 114 | 115 | DealWithKSMFees::on_unbalanced(final_fee); 116 | 117 | Ok((Zero::zero(), Zero::zero())) 118 | } 119 | } 120 | 121 | pub struct DealWithKSMFees; 122 | impl OnUnbalanced> for DealWithKSMFees { 123 | fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { 124 | if let Some(mut fees) = fees_then_tips.next() { 125 | if let Some(tips) = fees_then_tips.next() { 126 | // Merge with fee, for now we send everything to the treasury 127 | let _ = fees.subsume(tips); 128 | } 129 | 130 | Self::on_unbalanced(fees); 131 | } 132 | } 133 | 134 | fn on_unbalanced(amount: Credit) { 135 | let total: u128 = 100u128; 136 | let amount1 = amount.peek().saturating_mul(50u128) / total; 137 | let (to_collators, to_treasury) = amount.split(amount1); 138 | 139 | let _ = >::resolve(&TreasuryAccount::get(), to_treasury); 140 | 141 | let _ = >::resolve(&StakingPotAccount::get(), to_collators); 142 | } 143 | } 144 | 145 | #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] 146 | pub struct ChargerExtra { 147 | #[codec(compact)] 148 | pub tip: Balance, 149 | pub asset_id: Option, 150 | } 151 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/inflation.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | Balance, Balances, BlockNumber, NegativeImbalance, OcifStaking, Runtime, RuntimeEvent, DAYS, 3 | }; 4 | use frame_support::{parameter_types, traits::OnUnbalanced}; 5 | use sp_runtime::Perbill; 6 | 7 | pub const TEN_PERCENT_PER_YEAR: pallet_checked_inflation::InflationMethod = 8 | pallet_checked_inflation::InflationMethod::Rate(Perbill::from_percent(10)); 9 | 10 | const YEAR: u32 = 365; 11 | 12 | parameter_types! { 13 | pub const BlocksPerEra: BlockNumber = DAYS; 14 | pub const ErasPerYear: u32 = YEAR; 15 | pub const Inflation: pallet_checked_inflation::InflationMethod = TEN_PERCENT_PER_YEAR; 16 | } 17 | 18 | pub struct DealWithInflation; 19 | impl OnUnbalanced for DealWithInflation { 20 | fn on_unbalanced(amount: NegativeImbalance) { 21 | OcifStaking::rewards(amount); 22 | } 23 | } 24 | 25 | impl pallet_checked_inflation::Config for Runtime { 26 | type BlocksPerEra = BlocksPerEra; 27 | type Currency = Balances; 28 | type RuntimeEvent = RuntimeEvent; 29 | type ErasPerYear = ErasPerYear; 30 | type Inflation = Inflation; 31 | type DealWithInflation = DealWithInflation; 32 | type WeightInfo = pallet_checked_inflation::weights::SubstrateWeight; 33 | } 34 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/nft.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | common_types::CommonId, 3 | constants::currency::{MILLIUNIT, UNIT}, 4 | AccountId, Balance, Balances, Runtime, RuntimeEvent, 5 | }; 6 | use frame_support::{parameter_types, traits::AsEnsureOriginWithArg}; 7 | 8 | use frame_system::{EnsureRoot, EnsureSigned}; 9 | 10 | parameter_types! { 11 | pub const CollectionDeposit: Balance = UNIT; 12 | pub const ItemDeposit: Balance = UNIT / 100; 13 | pub const KeyLimit: u32 = 32; 14 | pub const ValueLimit: u32 = 256; 15 | pub const UniquesMetadataDepositBase: Balance = 10 * MILLIUNIT; 16 | pub const AttributeDepositBase: Balance = 10 * MILLIUNIT; 17 | pub const DepositPerByte: Balance = MILLIUNIT; 18 | pub const UniquesStringLimit: u32 = 128; 19 | } 20 | 21 | impl pallet_uniques::Config for Runtime { 22 | type RuntimeEvent = RuntimeEvent; 23 | type CollectionId = CommonId; 24 | type ItemId = CommonId; 25 | type Currency = Balances; 26 | type ForceOrigin = EnsureRoot; 27 | type CreateOrigin = AsEnsureOriginWithArg>; 28 | type Locker = (); 29 | type CollectionDeposit = CollectionDeposit; 30 | type ItemDeposit = ItemDeposit; 31 | type MetadataDepositBase = UniquesMetadataDepositBase; 32 | type AttributeDepositBase = AttributeDepositBase; 33 | type DepositPerByte = DepositPerByte; 34 | type StringLimit = UniquesStringLimit; 35 | type KeyLimit = KeyLimit; 36 | type ValueLimit = ValueLimit; 37 | type WeightInfo = pallet_uniques::weights::SubstrateWeight; 38 | } 39 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/asset_hub.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use scale_info::TypeInfo; 4 | use xcm::latest::{Junction, Junctions, MultiLocation}; 5 | 6 | pub struct AssetHub; 7 | 8 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 9 | pub enum AssetHubAssets { 10 | KSM, 11 | Local(u32), 12 | } 13 | 14 | impl RingsChain for AssetHub { 15 | type Assets = AssetHubAssets; 16 | 17 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 18 | use AssetHubAssets::*; 19 | match asset { 20 | KSM => MultiLocation { 21 | parents: 1, 22 | interior: Junctions::Here, 23 | }, 24 | Local(asset_id) => MultiLocation { 25 | parents: 0, 26 | interior: Junctions::X2( 27 | Junction::PalletInstance(50), 28 | Junction::GeneralIndex((*asset_id).into()), 29 | ), 30 | }, 31 | } 32 | } 33 | 34 | fn get_location() -> MultiLocation { 35 | MultiLocation { 36 | parents: 1, 37 | interior: Junctions::X1(Junction::Parachain(1000)), 38 | } 39 | } 40 | 41 | fn get_main_asset() -> Self::Assets { 42 | AssetHubAssets::KSM 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/basilisk.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::BoundedSlice; 4 | use scale_info::TypeInfo; 5 | use xcm::latest::{Junction, Junctions, MultiLocation}; 6 | 7 | pub struct Basilisk; 8 | 9 | #[allow(non_camel_case_types)] 10 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 11 | pub enum BasiliskAssets { 12 | BSX, 13 | TNKR, 14 | KSM, 15 | USDT, 16 | DAI, 17 | USDCet, 18 | XRT, 19 | aUSD, 20 | wETH, 21 | wBTC, 22 | wUSDT, 23 | } 24 | 25 | impl RingsChain for Basilisk { 26 | type Assets = BasiliskAssets; 27 | 28 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 29 | use BasiliskAssets::*; 30 | match asset { 31 | KSM => MultiLocation { 32 | parents: 1, 33 | interior: Junctions::Here, 34 | }, 35 | USDT => MultiLocation { 36 | parents: 1, 37 | interior: Junctions::X3( 38 | Junction::Parachain(1000), 39 | Junction::PalletInstance(50u8), 40 | Junction::GeneralIndex(1984u128), 41 | ), 42 | }, 43 | BSX => MultiLocation { 44 | parents: 0, 45 | interior: Junctions::X1(Junction::GeneralIndex(0u128)), 46 | }, 47 | TNKR => MultiLocation { 48 | parents: 1, 49 | interior: Junctions::X2(Junction::Parachain(2125), Junction::GeneralIndex(0u128)), 50 | }, 51 | DAI => MultiLocation { 52 | parents: 1, 53 | interior: Junctions::X2( 54 | Junction::Parachain(2000), 55 | Junction::from(BoundedSlice::truncate_from(&[ 56 | 2, 75, 182, 175, 181, 250, 43, 7, 165, 209, 196, 153, 225, 195, 221, 181, 57 | 161, 94, 112, 154, 113, 58 | ])), 59 | ), 60 | }, 61 | USDCet => MultiLocation { 62 | parents: 1, 63 | interior: Junctions::X2( 64 | Junction::Parachain(2000), 65 | Junction::from(BoundedSlice::truncate_from(&[ 66 | 2, 31, 58, 16, 88, 122, 32, 17, 78, 162, 91, 161, 179, 136, 238, 45, 212, 67 | 163, 55, 206, 39, 68 | ])), 69 | ), 70 | }, 71 | XRT => MultiLocation { 72 | parents: 1, 73 | interior: Junctions::X1(Junction::Parachain(2048)), 74 | }, 75 | aUSD => MultiLocation { 76 | parents: 1, 77 | interior: Junctions::X2( 78 | Junction::Parachain(2000), 79 | Junction::from(BoundedSlice::truncate_from(&[0, 129])), 80 | ), 81 | }, 82 | wETH => MultiLocation { 83 | parents: 1, 84 | interior: Junctions::X2( 85 | Junction::Parachain(2000), 86 | Junction::from(BoundedSlice::truncate_from(&[ 87 | 2, 236, 224, 204, 56, 2, 30, 115, 75, 239, 29, 93, 160, 113, 176, 39, 172, 88 | 47, 113, 24, 31, 89 | ])), 90 | ), 91 | }, 92 | wBTC => MultiLocation { 93 | parents: 1, 94 | interior: Junctions::X2( 95 | Junction::Parachain(2000), 96 | Junction::from(BoundedSlice::truncate_from(&[ 97 | 2, 102, 41, 28, 125, 136, 210, 237, 154, 112, 129, 71, 186, 228, 224, 129, 98 | 74, 118, 112, 94, 47, 99 | ])), 100 | ), 101 | }, 102 | wUSDT => MultiLocation { 103 | parents: 1, 104 | interior: Junctions::X2( 105 | Junction::Parachain(2000), 106 | Junction::from(BoundedSlice::truncate_from(&[ 107 | 2, 84, 225, 131, 229, 51, 253, 60, 110, 114, 222, 187, 45, 28, 171, 69, 29, 108 | 1, 127, 175, 114, 109 | ])), 110 | ), 111 | }, 112 | } 113 | } 114 | 115 | fn get_location() -> MultiLocation { 116 | MultiLocation { 117 | parents: 1, 118 | interior: Junctions::X1(Junction::Parachain(2090)), 119 | } 120 | } 121 | 122 | fn get_main_asset() -> Self::Assets { 123 | BasiliskAssets::BSX 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/bifrost.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::WeakBoundedVec; 4 | use scale_info::TypeInfo; 5 | use sp_std::vec; 6 | use xcm::latest::{Junction, Junctions, MultiLocation}; 7 | 8 | pub struct Bifrost; 9 | 10 | #[allow(non_camel_case_types)] 11 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 12 | pub enum BifrostAssets { 13 | BNC, 14 | KSM, 15 | vKSM, 16 | USDT, 17 | } 18 | 19 | impl RingsChain for Bifrost { 20 | type Assets = BifrostAssets; 21 | 22 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 23 | use BifrostAssets::*; 24 | match asset { 25 | BNC => MultiLocation { 26 | parents: 0, 27 | interior: Junctions::X1(Junction::GeneralKey(WeakBoundedVec::force_from( 28 | vec![0, 1], 29 | None, 30 | ))), 31 | }, 32 | KSM => MultiLocation { 33 | parents: 1, 34 | interior: Junctions::Here, 35 | }, 36 | vKSM => MultiLocation { 37 | parents: 0, 38 | interior: Junctions::X1(Junction::GeneralKey(WeakBoundedVec::force_from( 39 | vec![1, 4], 40 | None, 41 | ))), 42 | }, 43 | USDT => MultiLocation { 44 | parents: 1, 45 | interior: Junctions::X3( 46 | Junction::Parachain(1000), 47 | Junction::PalletInstance(50), 48 | Junction::GeneralIndex(1984), 49 | ), 50 | }, 51 | } 52 | } 53 | 54 | fn get_location() -> MultiLocation { 55 | MultiLocation { 56 | parents: 1, 57 | interior: Junctions::X1(Junction::Parachain(2030)), 58 | } 59 | } 60 | 61 | fn get_main_asset() -> Self::Assets { 62 | BifrostAssets::BNC 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/karura.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::BoundedSlice; 4 | use scale_info::TypeInfo; 5 | use xcm::latest::{Junction, Junctions, MultiLocation}; 6 | 7 | pub struct Karura; 8 | 9 | #[allow(non_camel_case_types)] 10 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 11 | pub enum KaruraAssets { 12 | KAR, 13 | LKSM, 14 | tKSM, 15 | KSM, 16 | Local([u8; 20]), 17 | } 18 | 19 | impl RingsChain for Karura { 20 | type Assets = KaruraAssets; 21 | 22 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 23 | use KaruraAssets::*; 24 | match asset { 25 | KAR => MultiLocation { 26 | parents: 0, 27 | interior: Junctions::X1(Junction::from(BoundedSlice::truncate_from( 28 | &hex_literal::hex!("0080"), 29 | ))), 30 | }, 31 | LKSM => MultiLocation { 32 | parents: 0, 33 | interior: Junctions::X1(Junction::from(BoundedSlice::truncate_from( 34 | &hex_literal::hex!("0083"), 35 | ))), 36 | }, 37 | tKSM => MultiLocation { 38 | parents: 0, 39 | interior: Junctions::X1(Junction::from(BoundedSlice::truncate_from( 40 | &hex_literal::hex!("0300000000"), 41 | ))), 42 | }, 43 | KSM => MultiLocation { 44 | parents: 1, 45 | interior: Junctions::Here, 46 | }, 47 | Local(address) => MultiLocation { 48 | parents: 0, 49 | interior: Junctions::X1(Junction::from(BoundedSlice::truncate_from(address))), 50 | }, 51 | } 52 | } 53 | 54 | fn get_location() -> MultiLocation { 55 | MultiLocation { 56 | parents: 1, 57 | interior: Junctions::X1(Junction::Parachain(2000)), 58 | } 59 | } 60 | 61 | fn get_main_asset() -> Self::Assets { 62 | KaruraAssets::KAR 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/khala.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use scale_info::TypeInfo; 4 | use xcm::latest::{Junction, Junctions, MultiLocation}; 5 | 6 | pub struct Khala; 7 | 8 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 9 | pub enum KhalaAssets { 10 | PHA, 11 | } 12 | 13 | impl RingsChain for Khala { 14 | type Assets = KhalaAssets; 15 | 16 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 17 | use KhalaAssets::*; 18 | match asset { 19 | PHA => MultiLocation { 20 | parents: 0, 21 | interior: Junctions::Here, 22 | }, 23 | } 24 | } 25 | 26 | fn get_location() -> MultiLocation { 27 | MultiLocation { 28 | parents: 1, 29 | interior: Junctions::X1(Junction::Parachain(2004)), 30 | } 31 | } 32 | 33 | fn get_main_asset() -> Self::Assets { 34 | KhalaAssets::PHA 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/kintsugi.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::WeakBoundedVec; 4 | use scale_info::TypeInfo; 5 | use sp_std::vec; 6 | use xcm::latest::{Junction, Junctions, MultiLocation}; 7 | 8 | pub struct Kintsugi; 9 | 10 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 11 | pub enum KintsugiAssets { 12 | KINT, 13 | KBTC, 14 | KSM, 15 | } 16 | 17 | impl RingsChain for Kintsugi { 18 | type Assets = KintsugiAssets; 19 | 20 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 21 | use KintsugiAssets::*; 22 | match asset { 23 | KINT => MultiLocation { 24 | parents: 0, 25 | interior: Junctions::X1(Junction::GeneralKey(WeakBoundedVec::force_from( 26 | vec![0, 12], 27 | None, 28 | ))), 29 | }, 30 | KBTC => MultiLocation { 31 | parents: 0, 32 | interior: Junctions::X1(Junction::GeneralKey(WeakBoundedVec::force_from( 33 | vec![0, 11], 34 | None, 35 | ))), 36 | }, 37 | KSM => MultiLocation { 38 | parents: 1, 39 | interior: Junctions::Here, 40 | }, 41 | } 42 | } 43 | 44 | fn get_location() -> MultiLocation { 45 | MultiLocation { 46 | parents: 1, 47 | interior: Junctions::X1(Junction::Parachain(2092)), 48 | } 49 | } 50 | 51 | fn get_main_asset() -> Self::Assets { 52 | KintsugiAssets::KINT 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/kusama.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use scale_info::TypeInfo; 4 | use xcm::latest::{Junctions, MultiLocation}; 5 | 6 | pub struct Kusama; 7 | 8 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 9 | pub enum KusamaAssets { 10 | KSM, 11 | } 12 | 13 | impl RingsChain for Kusama { 14 | type Assets = KusamaAssets; 15 | 16 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 17 | use KusamaAssets::*; 18 | match asset { 19 | KSM => MultiLocation { 20 | parents: 0, 21 | interior: Junctions::Here, 22 | }, 23 | } 24 | } 25 | 26 | fn get_location() -> MultiLocation { 27 | MultiLocation { 28 | parents: 1, 29 | interior: Junctions::Here, 30 | } 31 | } 32 | 33 | fn get_main_asset() -> Self::Assets { 34 | KusamaAssets::KSM 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountId, Balance, Runtime, RuntimeEvent}; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::parameter_types; 4 | use frame_system::EnsureRoot; 5 | use pallet_rings::{ChainAssetsList, ChainList}; 6 | use scale_info::TypeInfo; 7 | use xcm::prelude::*; 8 | 9 | mod basilisk; 10 | use basilisk::Basilisk; 11 | mod picasso; 12 | use picasso::Picasso; 13 | mod asset_hub; 14 | use asset_hub::AssetHub; 15 | mod shiden; 16 | use shiden::Shiden; 17 | mod karura; 18 | use karura::Karura; 19 | mod moonriver; 20 | use moonriver::Moonriver; 21 | mod kusama; 22 | use kusama::Kusama; 23 | 24 | parameter_types! { 25 | pub MaxXCMCallLength: u32 = 100_000; 26 | } 27 | 28 | impl pallet_rings::Config for Runtime { 29 | type RuntimeEvent = RuntimeEvent; 30 | type Chains = Chains; 31 | type MaxXCMCallLength = MaxXCMCallLength; 32 | type MaintenanceOrigin = EnsureRoot; 33 | type WeightInfo = pallet_rings::weights::SubstrateWeight; 34 | } 35 | 36 | pub trait RingsChain { 37 | type Assets; 38 | 39 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation; 40 | fn get_location() -> MultiLocation; 41 | fn get_main_asset() -> Self::Assets; 42 | } 43 | 44 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 45 | pub enum Chains { 46 | Basilisk, 47 | Picasso, 48 | AssetHub, 49 | Shiden, 50 | Karura, 51 | Moonriver, 52 | Kusama, 53 | } 54 | 55 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 56 | pub enum ChainAssets { 57 | Basilisk(::Assets), 58 | Picasso(::Assets), 59 | AssetHub(::Assets), 60 | Shiden(::Assets), 61 | Karura(::Assets), 62 | Moonriver(::Assets), 63 | Kusama(::Assets), 64 | } 65 | 66 | impl ChainAssetsList for ChainAssets { 67 | type Chains = Chains; 68 | 69 | fn get_chain(&self) -> Self::Chains { 70 | match self { 71 | Self::Basilisk(_) => Chains::Basilisk, 72 | Self::Picasso(_) => Chains::Picasso, 73 | Self::AssetHub(_) => Chains::AssetHub, 74 | Self::Shiden(_) => Chains::Shiden, 75 | Self::Karura(_) => Chains::Karura, 76 | Self::Moonriver(_) => Chains::Moonriver, 77 | Self::Kusama(_) => Chains::Kusama, 78 | } 79 | } 80 | 81 | fn get_asset_location(&self) -> MultiLocation { 82 | match self { 83 | Self::Basilisk(asset) => Basilisk::get_asset_location(asset), 84 | Self::Picasso(asset) => Picasso::get_asset_location(asset), 85 | Self::AssetHub(asset) => AssetHub::get_asset_location(asset), 86 | Self::Shiden(asset) => Shiden::get_asset_location(asset), 87 | Self::Karura(asset) => Karura::get_asset_location(asset), 88 | Self::Moonriver(asset) => Moonriver::get_asset_location(asset), 89 | Self::Kusama(asset) => Kusama::get_asset_location(asset), 90 | } 91 | } 92 | } 93 | 94 | impl ChainList for Chains { 95 | type Balance = Balance; 96 | type ChainAssets = ChainAssets; 97 | 98 | fn get_location(&self) -> MultiLocation { 99 | match self { 100 | Self::Basilisk => Basilisk::get_location(), 101 | Self::Picasso => Picasso::get_location(), 102 | Self::AssetHub => AssetHub::get_location(), 103 | Self::Shiden => Shiden::get_location(), 104 | Self::Karura => Karura::get_location(), 105 | Self::Moonriver => Moonriver::get_location(), 106 | Self::Kusama => Kusama::get_location(), 107 | } 108 | } 109 | 110 | fn get_main_asset(&self) -> Self::ChainAssets { 111 | match self { 112 | Self::Basilisk => ChainAssets::Basilisk(Basilisk::get_main_asset()), 113 | Self::Picasso => ChainAssets::Picasso(Picasso::get_main_asset()), 114 | Self::AssetHub => ChainAssets::AssetHub(AssetHub::get_main_asset()), 115 | Self::Shiden => ChainAssets::Shiden(Shiden::get_main_asset()), 116 | Self::Karura => ChainAssets::Karura(Karura::get_main_asset()), 117 | Self::Moonriver => ChainAssets::Moonriver(Moonriver::get_main_asset()), 118 | Self::Kusama => ChainAssets::Kusama(Kusama::get_main_asset()), 119 | } 120 | } 121 | 122 | #[cfg(feature = "runtime-benchmarks")] 123 | fn benchmark_mock() -> Self { 124 | Self::Basilisk 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/picasso.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use frame_support::BoundedSlice; 4 | use scale_info::TypeInfo; 5 | use xcm::latest::{Junction, Junctions, MultiLocation}; 6 | 7 | pub struct Picasso; 8 | 9 | #[allow(non_camel_case_types)] 10 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 11 | pub enum PicassoAssets { 12 | PICA, 13 | USDT, 14 | kUSD, 15 | KSM, 16 | TNKR, 17 | } 18 | 19 | impl RingsChain for Picasso { 20 | type Assets = PicassoAssets; 21 | 22 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 23 | use PicassoAssets::*; 24 | match asset { 25 | PICA => MultiLocation { 26 | parents: 0, 27 | interior: Junctions::Here, 28 | }, 29 | 30 | USDT => MultiLocation { 31 | parents: 1, 32 | interior: Junctions::X3( 33 | Junction::Parachain(1000), 34 | Junction::PalletInstance(50), 35 | Junction::GeneralIndex(1984), 36 | ), 37 | }, 38 | 39 | kUSD => MultiLocation { 40 | parents: 1, 41 | interior: Junctions::X2( 42 | Junction::Parachain(2000), 43 | Junction::from(BoundedSlice::truncate_from(&[ 44 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45 | 0, 0, 0, 0, 0, 0, 129, 46 | ])), 47 | ), 48 | }, 49 | 50 | KSM => MultiLocation { 51 | parents: 1, 52 | interior: Junctions::Here, 53 | }, 54 | 55 | TNKR => MultiLocation { 56 | parents: 1, 57 | interior: Junctions::X2(Junction::Parachain(2125), Junction::GeneralIndex(0)), 58 | }, 59 | } 60 | } 61 | 62 | fn get_location() -> MultiLocation { 63 | MultiLocation { 64 | parents: 1, 65 | interior: Junctions::X1(Junction::Parachain(2087)), 66 | } 67 | } 68 | 69 | fn get_main_asset() -> Self::Assets { 70 | PicassoAssets::PICA 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/rings/shiden.rs: -------------------------------------------------------------------------------- 1 | use super::RingsChain; 2 | use codec::{Decode, Encode, MaxEncodedLen}; 3 | use scale_info::TypeInfo; 4 | use xcm::latest::{Junction, Junctions, MultiLocation}; 5 | 6 | pub struct Shiden; 7 | 8 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] 9 | pub enum ShidenAssets { 10 | SDN, 11 | KSM, 12 | } 13 | 14 | impl RingsChain for Shiden { 15 | type Assets = ShidenAssets; 16 | 17 | fn get_asset_location(asset: &Self::Assets) -> MultiLocation { 18 | use ShidenAssets::*; 19 | match asset { 20 | SDN => MultiLocation { 21 | parents: 0, 22 | interior: Junctions::Here, 23 | }, 24 | KSM => MultiLocation { 25 | parents: 1, 26 | interior: Junctions::Here, 27 | }, 28 | } 29 | } 30 | 31 | fn get_location() -> MultiLocation { 32 | MultiLocation { 33 | parents: 1, 34 | interior: Junctions::X1(Junction::Parachain(2007)), 35 | } 36 | } 37 | 38 | fn get_main_asset() -> Self::Assets { 39 | ShidenAssets::SDN 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/staking.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | Balance, Balances, BlockNumber, ExistentialDeposit, MessageQueue, Runtime, RuntimeEvent, DAYS, 3 | UNIT, 4 | }; 5 | use cumulus_primitives_core::AggregateMessageOrigin; 6 | use frame_support::{parameter_types, PalletId}; 7 | use pallet_dao_staking::primitives::CustomAggregateMessageOrigin; 8 | parameter_types! { 9 | pub const BlocksPerEra: BlockNumber = DAYS; 10 | pub const RegisterDeposit: Balance = 500 * UNIT; 11 | pub const MaxStakersPerDao: u32 = 10000; 12 | pub const MinimumStakingAmount: Balance = 10 * UNIT; 13 | pub const MaxEraStakeValues: u32 = 5; 14 | pub const MaxUnlockingChunks: u32 = 5; 15 | pub const UnbondingPeriod: u32 = 7; 16 | pub const OcifStakingPot: PalletId = PalletId(*b"tkr/ocif"); 17 | pub const RewardRatio: (u32, u32) = (60, 40); 18 | pub const StakeThresholdForActiveDao: Balance = 25000 * UNIT; 19 | pub const MaxNameLength: u32 = 20; 20 | pub const MaxDescriptionLength: u32 = 300; 21 | pub const MaxImageUrlLength: u32 = 100; 22 | pub const UnregisterOrigin: CustomAggregateMessageOrigin = CustomAggregateMessageOrigin::UnregisterMessageOrigin; 23 | } 24 | 25 | impl pallet_dao_staking::Config for Runtime { 26 | type Currency = Balances; 27 | type BlocksPerEra = BlocksPerEra; 28 | type RegisterDeposit = RegisterDeposit; 29 | type RuntimeEvent = RuntimeEvent; 30 | type MaxStakersPerDao = MaxStakersPerDao; 31 | type ExistentialDeposit = ExistentialDeposit; 32 | type PotId = OcifStakingPot; 33 | type MaxUnlocking = MaxUnlockingChunks; 34 | type UnbondingPeriod = UnbondingPeriod; 35 | type MinimumStakingAmount = MinimumStakingAmount; 36 | type MaxEraStakeValues = MaxEraStakeValues; 37 | type RewardRatio = RewardRatio; 38 | type StakeThresholdForActiveDao = StakeThresholdForActiveDao; 39 | type MaxNameLength = MaxNameLength; 40 | type MaxDescriptionLength = MaxDescriptionLength; 41 | type MaxImageUrlLength = MaxImageUrlLength; 42 | type StakingMessage = frame_support::traits::EnqueueWithOrigin; 43 | type WeightInfo = pallet_dao_staking::weights::SubstrateWeight; 44 | type WeightToFee = crate::WeightToFee; 45 | type OnUnbalanced = crate::DealWithFees; 46 | } 47 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/weights/block_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Importing a block with 0 Extrinsics. 26 | pub const BlockExecutionWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); 27 | } 28 | 29 | #[cfg(test)] 30 | mod test_weights { 31 | use frame_support::weights::constants; 32 | 33 | /// Checks that the weight exists and is sane. 34 | // NOTE: If this test fails but you are sure that the generated values are fine, 35 | // you can delete it. 36 | #[test] 37 | fn sane() { 38 | let w = super::constants::BlockExecutionWeight::get(); 39 | 40 | // At least 100 µs. 41 | assert!( 42 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 43 | "Weight should be at least 100 µs." 44 | ); 45 | // At most 50 ms. 46 | assert!( 47 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, 48 | "Weight should be at most 50 ms." 49 | ); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/weights/extrinsic_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Executing a NO-OP `System::remarks` Extrinsic. 26 | pub const ExtrinsicBaseWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); 27 | } 28 | 29 | #[cfg(test)] 30 | mod test_weights { 31 | use frame_support::weights::constants; 32 | 33 | /// Checks that the weight exists and is sane. 34 | // NOTE: If this test fails but you are sure that the generated values are fine, 35 | // you can delete it. 36 | #[test] 37 | fn sane() { 38 | let w = super::constants::ExtrinsicBaseWeight::get(); 39 | 40 | // At least 10 µs. 41 | assert!( 42 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 43 | "Weight should be at least 10 µs." 44 | ); 45 | // At most 1 ms. 46 | assert!( 47 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 48 | "Weight should be at most 1 ms." 49 | ); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod block_weights; 2 | pub mod extrinsic_weights; 3 | pub mod paritydb_weights; 4 | pub mod rocksdb_weights; 5 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/weights/paritydb_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights 26 | /// are available for brave runtime engineers who may want to try this out as default. 27 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use super::constants::ParityDbWeight as W; 36 | use frame_support::weights::constants; 37 | 38 | /// Checks that all weights exist and have sane values. 39 | // NOTE: If this test fails but you are sure that the generated values are fine, 40 | // you can delete it. 41 | #[test] 42 | fn sane() { 43 | // At least 1 µs. 44 | assert!( 45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 46 | "Read weight should be at least 1 µs." 47 | ); 48 | assert!( 49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 50 | "Write weight should be at least 1 µs." 51 | ); 52 | // At most 1 ms. 53 | assert!( 54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 55 | "Read weight should be at most 1 ms." 56 | ); 57 | assert!( 58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 59 | "Write weight should be at most 1 ms." 60 | ); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tinkernet/runtime/src/weights/rocksdb_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 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout 26 | /// the runtime. 27 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use super::constants::RocksDbWeight as W; 36 | use frame_support::weights::constants; 37 | 38 | /// Checks that all weights exist and have sane values. 39 | // NOTE: If this test fails but you are sure that the generated values are fine, 40 | // you can delete it. 41 | #[test] 42 | fn sane() { 43 | // At least 1 µs. 44 | assert!( 45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 46 | "Read weight should be at least 1 µs." 47 | ); 48 | assert!( 49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 50 | "Write weight should be at least 1 µs." 51 | ); 52 | // At most 1 ms. 53 | assert!( 54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 55 | "Read weight should be at most 1 ms." 56 | ); 57 | assert!( 58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 59 | "Write weight should be at most 1 ms." 60 | ); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tinkernet/rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2024-07-15" 3 | targets = ["wasm32-unknown-unknown"] 4 | components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview", "rust-src"] 5 | -------------------------------------------------------------------------------- /tinkernet/rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | 3 | imports_granularity = "Crate" -------------------------------------------------------------------------------- /zombienet/rococo-and-tinkernet+basilisk.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | timeout = 1000 3 | provider = "native" 4 | 5 | [relaychain] 6 | default_command = "./zombienet/binaries/polkadot" 7 | chain = "rococo-local" 8 | default_args = ["-lxcm::barriers=trace"] 9 | 10 | [[relaychain.nodes]] 11 | name = "alice" 12 | validator = true 13 | ws_port = 9955 14 | [[env]] 15 | name = "RUST_LOG" 16 | value = "trace" 17 | 18 | [[relaychain.nodes]] 19 | name = "bob" 20 | validator = true 21 | 22 | [[parachains]] 23 | id = 2125 24 | addToGenesis = true 25 | cumulus_based = true 26 | chain = "local" 27 | 28 | [[parachains.collators]] 29 | name = "tinkernet-collator-0" 30 | command = "./tinkernet/target/release/tinkernet-collator" 31 | ws_port = 9944 32 | 33 | [[parachains.collators]] 34 | name = "tinkernet-collator-1" 35 | command = "./tinkernet/target/release/tinkernet-collator" 36 | 37 | [[parachains]] 38 | id = 2090 39 | addToGenesis = true 40 | cumulus_based = true 41 | chain = "local" 42 | 43 | [[parachains.collators]] 44 | name = "basilisk-collator-0" 45 | command = "./zombienet/binaries/basilisk" 46 | ws_port = 9933 47 | 48 | [[parachains.collators]] 49 | name = "basilisk-collator-1" 50 | command = "./zombienet/binaries/basilisk" 51 | 52 | [[hrmp_channels]] 53 | sender = 2125 54 | recipient = 2090 55 | max_capacity = 8 56 | max_message_size = 512 57 | 58 | [[hrmp_channels]] 59 | sender = 2090 60 | recipient = 2125 61 | max_capacity = 8 62 | max_message_size = 512 -------------------------------------------------------------------------------- /zombienet/rococo-and-tinkernet+tinkernet.toml: -------------------------------------------------------------------------------- 1 | [settings] 2 | timeout = 1000 3 | provider = "native" 4 | 5 | [relaychain] 6 | default_command = "./zombienet/binaries/polkadot" 7 | chain = "rococo-local" 8 | 9 | [[relaychain.nodes]] 10 | name = "alice" 11 | validator = true 12 | ws_port = 9955 13 | 14 | [[relaychain.nodes]] 15 | name = "bob" 16 | validator = true 17 | 18 | [[parachains]] 19 | id = 2125 20 | addToGenesis = true 21 | cumulus_based = true 22 | chain = "local" 23 | 24 | [[parachains.collators]] 25 | name = "tinkernet-collator-0" 26 | command = "./tinkernet/target/release/tinkernet-collator" 27 | ws_port = 2125 28 | 29 | [[parachains.collators]] 30 | name = "tinkernet-collator-1" 31 | command = "./tinkernet/target/release/tinkernet-collator" 32 | 33 | [[parachains]] 34 | id = 2126 35 | addToGenesis = true 36 | cumulus_based = true 37 | chain = "local" 38 | 39 | [[parachains.collators]] 40 | name = "tinkernet-2-collator-0" 41 | command = "./tinkernet/target/release/tinkernet-collator" 42 | ws_port = 2126 43 | 44 | [[parachains.collators]] 45 | name = "tinkernet-2-collator-1" 46 | command = "./tinkernet/target/release/tinkernet-collator" 47 | 48 | [[hrmp_channels]] 49 | sender = 2125 50 | recipient = 2126 51 | max_capacity = 8 52 | max_message_size = 512 53 | 54 | [[hrmp_channels]] 55 | sender = 2126 56 | recipient = 2125 57 | max_capacity = 8 58 | max_message_size = 512 --------------------------------------------------------------------------------