├── .dockerignore ├── .editorconfig ├── .github ├── ISSUE_TEMPLATE │ ├── ask-a-question.md │ ├── report-a-bug.md │ └── suggest-a-feature.md └── workflows │ └── rust.yml ├── .gitignore ├── .maintain └── w3g-weight-template.hbs ├── Cargo.lock ├── Cargo.toml ├── HEADER-GPL3 ├── LICENSE ├── README.md ├── chain-extensions ├── Cargo.toml ├── README.md └── src │ ├── lib.rs │ ├── token_fungible.rs │ ├── token_multi.rs │ └── token_non_fungible.rs ├── client └── README.md ├── docker-compose.yml ├── docker └── README.md ├── media └── README.md ├── node ├── Cargo.toml ├── README.md ├── build.rs └── src │ ├── chain_spec.rs │ ├── cli.rs │ ├── command.rs │ ├── command_helper.rs │ ├── main.rs │ ├── rpc.rs │ └── service.rs ├── pallets ├── README.md ├── call-switchgear │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── ethereum-chain-id │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── exchange │ ├── Cargo.toml │ ├── README.md │ ├── rpc │ │ ├── Cargo.toml │ │ ├── runtime-api │ │ │ ├── Cargo.toml │ │ │ └── src │ │ │ │ └── lib.rs │ │ └── src │ │ │ └── lib.rs │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── farming │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── launchpad │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── marketplace │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── player-id │ ├── Cargo.toml │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── proxy-pay │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── support │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── token-fungible │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── token-multi │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── token-non-fungible │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs └── wrap-currency │ ├── Cargo.toml │ └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ └── weights.rs ├── precompiles ├── Cargo.toml ├── README.md ├── src │ ├── Exchange.sol │ ├── Farming.sol │ ├── Launchpad.sol │ ├── Marketplace.sol │ ├── TokenFungible.sol │ ├── exchange.rs │ ├── farming.rs │ ├── launchpad.rs │ ├── lib.rs │ ├── marketplace.rs │ ├── token_fungible.rs │ ├── token_multi.rs │ └── token_non_fungible.rs └── utils │ ├── Cargo.toml │ ├── macro │ ├── Cargo.toml │ ├── src │ │ └── lib.rs │ └── tests │ │ └── tests.rs │ └── src │ ├── costs.rs │ ├── data │ └── mod.rs │ ├── handle.rs │ ├── lib.rs │ ├── logs.rs │ ├── modifier.rs │ ├── precompile_set.rs │ ├── substrate.rs │ ├── testing.rs │ └── tests.rs ├── primitives ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── runtime ├── README.md └── web3games │ ├── Cargo.toml │ ├── build.rs │ └── src │ ├── constants.rs │ └── lib.rs ├── rust-toolchain ├── rustfmt.toml ├── sc.json ├── sc_init.json ├── scripts ├── README.md ├── docker_run.sh ├── generate-weights.sh └── init.sh └── specs ├── README.md ├── devnet └── devnet.json └── testnet └── testnet.json /.dockerignore: -------------------------------------------------------------------------------- 1 | **/target/ 2 | Dockerfile 3 | .idea/ 4 | .vscode/ 5 | .github/ 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.rs] 4 | indent_style=tab 5 | indent_size=tab 6 | tab_width=4 7 | end_of_line=lf 8 | charset=utf-8 9 | trim_trailing_whitespace=true 10 | insert_final_newline=true 11 | 12 | [*.md] 13 | indent_style=space 14 | indent_size=2 15 | 16 | [*.toml] 17 | indent_style=tab 18 | indent_size=tab 19 | tab_width=4 20 | 21 | [*.yml] 22 | indent_style=space 23 | indent_size=2 24 | tab_width=8 25 | end_of_line=lf 26 | 27 | [*.sh] 28 | indent_style=space 29 | indent_size=2 30 | tab_width=8 31 | end_of_line=lf 32 | 33 | [*.json] 34 | indent_style=space 35 | indent_size=2 36 | 37 | [*.ts] 38 | indent_style=space 39 | indent_size=2 40 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/ask-a-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Ask a Question 3 | about: Ask a question about this project. 4 | title: "" 5 | labels: question 6 | assignees: "" 7 | --- 8 | 9 | **Question** 10 | 11 | _Please include information such as the following: is your question to clarify an existing resource 12 | or are you asking about something new? what are you trying to accomplish? where have you looked for 13 | answers?_ 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/report-a-bug.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Report a Bug 3 | about: Report a problem with this project. 4 | title: "" 5 | labels: bug 6 | assignees: "" 7 | --- 8 | 9 | **Description** 10 | 11 | _Tell us what happened. In particular, tell us how and why you are using this project, and describe 12 | the bug that you encountered. Ideally, provide a link to your project's GitHub repository. Please 13 | note that we are not able to support all conceivable use cases, but the more information you are 14 | able to provide the more equipped we will be to help._ 15 | 16 | **Steps to Reproduce** 17 | 18 | _Replace the example steps below with actual steps to reproduce the bug you're reporting._ 19 | 20 | 1. Go to '...' 21 | 2. Click on '....' 22 | 3. Scroll down to '....' 23 | 4. See error 24 | 25 | **Expected vs. Actual Behavior** 26 | 27 | _What did you expect to happen after you followed the steps you described in the last section? What 28 | actually happened?_ 29 | 30 | **Environment** 31 | 32 | _Describe the environment in which you encountered this bug. Use the list below as a starting point 33 | and add additional information if you think it's relevant._ 34 | 35 | - Operating system: 36 | - Project version/tag: 37 | - Rust version (run `rustup show`): 38 | 39 | **Logs, Errors or Screenshots** 40 | 41 | _Please provide the text of any logs or errors that you experienced; if applicable, provide 42 | screenshots to help illustrate the problem._ 43 | 44 | **Additional Information** 45 | 46 | _Please add any other details that you think may help us solve your problem._ 47 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/suggest-a-feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Suggest a Feature 3 | about: Suggest a new feature or an improvement to an existing feature for this project. 4 | title: "" 5 | labels: enhancement 6 | assignees: "" 7 | --- 8 | 9 | **Motivation** 10 | 11 | _Describe the need or frustration that motivated you to make this suggestion. Please note that the 12 | goal of this project is to provide common reusable utilities, so please take care when suggesting 13 | features that may be specific to a particular use case._ 14 | 15 | **Suggested Solution** 16 | 17 | _Describe your suggested solution to the need or frustration that you are experiencing._ 18 | 19 | **Alternatives** 20 | 21 | _Describe any alternative solutions or features you considered and why you believe your suggested 22 | solution is preferable._ 23 | 24 | **Additional Information** 25 | 26 | _Provide any additional information that you believe may help us evaluate your suggestion._ 27 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | # Controls when the action will run. 4 | on: 5 | # Triggers the workflow on push or pull request events but only for the main branch 6 | push: 7 | branches: [ main ] 8 | pull_request: 9 | branches: [ main ] 10 | 11 | # Allows you to run this workflow manually from the Actions tab 12 | workflow_dispatch: 13 | 14 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 15 | jobs: 16 | build: 17 | name: 'Run test and build' 18 | runs-on: ubuntu-20.04 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | 23 | - name: Set-Up 24 | run: sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libclang-dev curl 25 | 26 | - name: Install Rustup 27 | run: | 28 | curl https://sh.rustup.rs -sSf | sh -s -- -y 29 | source ~/.cargo/env 30 | rustup default stable 31 | rustup update nightly 32 | rustup update stable 33 | rustup target add wasm32-unknown-unknown --toolchain nightly 34 | - name: Run tests 35 | run: cargo test --all 36 | - name: Build Node 37 | run: cargo build --release 38 | 39 | lint: 40 | name: 'Run lints' 41 | runs-on: ubuntu-20.04 42 | 43 | steps: 44 | - uses: actions/checkout@v2 45 | 46 | - name: Set-Up 47 | run: sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libclang-dev curl 48 | 49 | - name: Install Rustup 50 | run: | 51 | curl https://sh.rustup.rs -sSf | sh -s -- -y 52 | source ~/.cargo/env 53 | rustup default stable 54 | rustup update nightly 55 | rustup update stable 56 | rustup target add wasm32-unknown-unknown --toolchain nightly 57 | - name: Check Rustfmt 58 | run: cargo fmt --all -- --check 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | .idea 14 | .DS_Store -------------------------------------------------------------------------------- /.maintain/w3g-weight-template.hbs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for {{pallet}} 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 22 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: {{cmd.repeat}}, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 23 | //! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} 24 | 25 | // Executed Command: 26 | {{#each args as |arg|~}} 27 | // {{arg}} 28 | {{/each}} 29 | 30 | #![cfg_attr(rustfmt, rustfmt_skip)] 31 | #![allow(unused_parens)] 32 | #![allow(unused_imports)] 33 | #![allow(clippy::unnecessary_cast)] 34 | 35 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 36 | use sp_std::marker::PhantomData; 37 | 38 | /// Weight functions needed for {{pallet}}. 39 | pub trait WeightInfo { 40 | {{#each benchmarks as |benchmark|}} 41 | fn {{benchmark.name~}} 42 | ( 43 | {{~#each benchmark.components as |c| ~}} 44 | {{c.name}}: u32, {{/each~}} 45 | ) -> Weight; 46 | {{/each}} 47 | } 48 | 49 | /// Weights for {{pallet}} using the Web3Games node and recommended hardware. 50 | pub struct W3GWeight(PhantomData); 51 | impl WeightInfo for W3GWeight { 52 | {{#each benchmarks as |benchmark|}} 53 | {{#each benchmark.comments as |comment|}} 54 | // {{comment}} 55 | {{/each}} 56 | fn {{benchmark.name~}} 57 | ( 58 | {{~#each benchmark.components as |c| ~}} 59 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 60 | ) -> Weight { 61 | ({{underscore benchmark.base_weight}} as Weight) 62 | {{#each benchmark.component_weight as |cw|}} 63 | // Standard Error: {{underscore cw.error}} 64 | .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) 65 | {{/each}} 66 | {{#if (ne benchmark.base_reads "0")}} 67 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}} as Weight)) 68 | {{/if}} 69 | {{#each benchmark.component_reads as |cr|}} 70 | .saturating_add(T::DbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) 71 | {{/each}} 72 | {{#if (ne benchmark.base_writes "0")}} 73 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}} as Weight)) 74 | {{/if}} 75 | {{#each benchmark.component_writes as |cw|}} 76 | .saturating_add(T::DbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) 77 | {{/each}} 78 | } 79 | {{/each}} 80 | } 81 | 82 | // For backwards compatibility and tests 83 | impl WeightInfo for () { 84 | {{#each benchmarks as |benchmark|}} 85 | fn {{benchmark.name~}} 86 | ( 87 | {{~#each benchmark.components as |c| ~}} 88 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 89 | ) -> Weight { 90 | ({{underscore benchmark.base_weight}} as Weight) 91 | {{#each benchmark.component_weight as |cw|}} 92 | // Standard Error: {{underscore cw.error}} 93 | .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) 94 | {{/each}} 95 | {{#if (ne benchmark.base_reads "0")}} 96 | .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}} as Weight)) 97 | {{/if}} 98 | {{#each benchmark.component_reads as |cr|}} 99 | .saturating_add(RocksDbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) 100 | {{/each}} 101 | {{#if (ne benchmark.base_writes "0")}} 102 | .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}} as Weight)) 103 | {{/if}} 104 | {{#each benchmark.component_writes as |cw|}} 105 | .saturating_add(RocksDbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) 106 | {{/each}} 107 | } 108 | {{/each}} 109 | } 110 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "pallets/*", 4 | "primitives", 5 | "chain-extensions", 6 | "precompiles", 7 | "runtime/web3games", 8 | "node", 9 | ] 10 | 11 | [profile.release] 12 | panic = "unwind" 13 | -------------------------------------------------------------------------------- /HEADER-GPL3: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | 6 | 7 | - [1. Introduction](#1-introduction) 8 | - [2. Building](#2-building) 9 | - [3. Run](#3-run) 10 | - [4. Docker](#4-run-in-docker) 11 | 12 | 13 | 14 | ## 1. Introduction 15 | 16 | Web3Games is a new generation gaming ecosystem built on Substrate. 17 | 18 | ## 2. Building 19 | 20 | Install Rust: 21 | 22 | ```bash 23 | curl https://sh.rustup.rs -sSf | sh 24 | ``` 25 | 26 | Initialize your Wasm Build environment: 27 | 28 | ```bash 29 | ./scripts/init.sh 30 | ``` 31 | 32 | Build Wasm and native code: 33 | 34 | ```bash 35 | cargo build --release 36 | ``` 37 | 38 | ## 3. Run 39 | 40 | ### Single Node Development Chain 41 | 42 | Purge any existing developer chain state: 43 | 44 | ```bash 45 | ./target/release/web3games-node purge-chain --dev 46 | ``` 47 | 48 | Start a development chain with: 49 | 50 | ```bash 51 | ./target/release/web3games-node --dev 52 | ``` 53 | 54 | Detailed logs may be shown by running the node with the following environment variables set: `RUST_LOG=debug RUST_BACKTRACE=1 cargo run -- --dev`. 55 | 56 | ### Multi-Node Local Testnet 57 | 58 | If you want to see the multi-node consensus algorithm in action locally, then you can create a local testnet with two validator nodes for Alice and Bob, who are the initial authorities of the genesis chain that have been endowed with testnet units. 59 | 60 | Optionally, give each node a name and expose them so they are listed on the Polkadot [telemetry site](https://telemetry.polkadot.io/#/Local%20Testnet). 61 | 62 | You'll need two terminal windows open. 63 | 64 | We'll start Alice's substrate node first on default TCP port 30333 with her chain database stored locally at `/tmp/alice`. The bootnode ID of her node is `QmRpheLN4JWdAnY7HGJfWFNbfkQCb6tFf4vvA6hgjMZKrR`, which is generated from the `--node-key` value that we specify below: 65 | 66 | ```bash 67 | cargo run -- \ 68 | --base-path /tmp/alice \ 69 | --chain=local \ 70 | --alice \ 71 | --node-key 0000000000000000000000000000000000000000000000000000000000000001 \ 72 | --telemetry-url 'wss://telemetry.polkadot.io/submit/ 0' \ 73 | --validator 74 | ``` 75 | 76 | In the second terminal, we'll start Bob's substrate node on a different TCP port of 30334, and with his chain database stored locally at `/tmp/bob`. We'll specify a value for the `--bootnodes` option that will connect his node to Alice's bootnode ID on TCP port 30333: 77 | 78 | ```bash 79 | cargo run -- \ 80 | --base-path /tmp/bob \ 81 | --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/QmRpheLN4JWdAnY7HGJfWFNbfkQCb6tFf4vvA6hgjMZKrR \ 82 | --chain=local \ 83 | --bob \ 84 | --port 30334 \ 85 | --telemetry-url 'wss://telemetry.polkadot.io/submit/ 0' \ 86 | --validator 87 | ``` 88 | 89 | ## 4. Run in Docker 90 | 91 | First, install [Docker](https://docs.docker.com/get-docker/) and 92 | [Docker Compose](https://docs.docker.com/compose/install/). 93 | 94 | Then run the following command to start a single node development chain. 95 | 96 | ```bash 97 | ./scripts/docker_run.sh 98 | ``` 99 | 100 | This command will firstly compile your code, and then start a local development network. You can 101 | also replace the default command 102 | (`cargo build --release && ./target/release/web3games-node --dev --ws-external`) 103 | by appending your own. A few useful ones are as follow. 104 | 105 | ```bash 106 | # Run Substrate node without re-compiling 107 | ./scripts/docker_run.sh ./target/release/web3games-node --dev --ws-external 108 | 109 | # Purge the local dev chain 110 | ./scripts/docker_run.sh ./target/release/web3games-node purge-chain --dev 111 | 112 | # Check whether the code is compilable 113 | ./scripts/docker_run.sh cargo check 114 | ``` 115 | 116 | ## License 117 | 118 | Web3Games is released under the [GPL v3.0 License](LICENSE). 119 | -------------------------------------------------------------------------------- /chain-extensions/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chain-extensions" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | serde = { version = "1.0.137", features = ["derive"], optional = true } 10 | hex = { version = "0.4.2", optional = true } 11 | log = { version = "0.4.17", default-features = false } 12 | 13 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | randomness = { package = "pallet-randomness-collective-flip", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | pallet-contracts = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 18 | 19 | primitives = {path = "../primitives", default-features = false } 20 | 21 | web3games-token-fungible = { path = "../pallets/token-fungible", default-features = false } 22 | web3games-token-non-fungible = { path = "../pallets/token-non-fungible", default-features = false } 23 | web3games-token-multi = { path = "../pallets/token-multi" ,default-features = false} 24 | 25 | [features] 26 | default = ["std"] 27 | std = [ 28 | "codec/std", 29 | "serde/std", 30 | "log/std", 31 | "sp-runtime/std", 32 | "sp-std/std", 33 | "frame-support/std", 34 | "randomness/std", 35 | "pallet-contracts/std", 36 | "primitives/std", 37 | "web3games-token-fungible/std", 38 | "web3games-token-non-fungible/std", 39 | "web3games-token-multi/std" 40 | ] 41 | -------------------------------------------------------------------------------- /chain-extensions/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games Chain extension function file for WASM Contract client node enhancement. -------------------------------------------------------------------------------- /chain-extensions/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | use codec::Encode; 22 | use frame_support::traits::Randomness; 23 | use pallet_contracts::chain_extension::{ 24 | ChainExtension, Environment, Ext, InitState, Result, RetVal, SysConfig, UncheckedFrom, 25 | }; 26 | use sp_runtime::DispatchError; 27 | use sp_std::marker::PhantomData; 28 | 29 | mod token_fungible; 30 | mod token_multi; 31 | mod token_non_fungible; 32 | 33 | pub use token_fungible::FungibleTokenExtension; 34 | pub use token_multi::MultiTokenExtension; 35 | pub use token_non_fungible::NonFungibleTokenExtension; 36 | 37 | pub struct Web3GamesChainExtensions(PhantomData); 38 | 39 | impl ChainExtension for Web3GamesChainExtensions 40 | where 41 | C: pallet_contracts::Config + web3games_token_fungible::Config, 42 | // + web3games_token_non_fungible::Config 43 | // + web3games_token_multi::Config, 44 | ::Call: From>, 45 | // ::Call: From>, 46 | // ::Call: From>, 47 | { 48 | fn call(func_id: u32, env: Environment) -> Result 49 | where 50 | E: Ext, 51 | ::AccountId: UncheckedFrom<::Hash> + AsRef<[u8]>, 52 | { 53 | match func_id { 54 | // 0x00-0x10000(0-65536): substrate pallet 55 | 1024 => { 56 | let mut env = env.buf_in_buf_out(); 57 | let random_slice = 58 | ::Randomness::random_seed().0.encode(); 59 | log::trace!( 60 | target: "runtime", 61 | "[ChainExtension]|call|func_id:{:}", 62 | func_id 63 | ); 64 | env.write(&random_slice, false, None) 65 | .map_err(|_| DispatchError::Other("ChainExtension failed to call random"))?; 66 | 67 | Ok(RetVal::Converging(0)) 68 | }, 69 | // 0x10001-0x10040(65537-65600): token-fungible 70 | id if id >= 65537 && id < 65600 => FungibleTokenExtension::call(func_id, env), 71 | 72 | // // 0x10041-0x10080(65601-65664): token-non-fungible 73 | // id if id >= 65601 && id < 65664 => NonFungibleTokenExtension::call(func_id, env), 74 | // 75 | // // 0x10081-0x100c1(65665-65729): token-multi 76 | // id if id >= 65665 && id < 65729 => MultiTokenExtension::call(func_id, env), 77 | _ => { 78 | log::error!("call an unregistered `func_id`, func_id:{:}", func_id); 79 | return Err(DispatchError::Other("Unimplemented func_id")) 80 | }, 81 | } 82 | } 83 | 84 | fn enabled() -> bool { 85 | true 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games Chain Node Client File. -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.2" 2 | 3 | services: 4 | dev: 5 | container_name: web3games-node 6 | image: paritytech/ci-linux:002c04ad-20211021 7 | working_dir: /var/www/web3games-node 8 | ports: 9 | - "9944:9944" 10 | environment: 11 | - CARGO_HOME=/var/www/web3games-node/.cargo 12 | volumes: 13 | - .:/var/www/web3games-node 14 | - type: bind 15 | source: ./.local 16 | target: /root/.local 17 | command: bash -c "cargo build --release && ./target/release/web3games-node --dev --ws-external" 18 | -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games Chain Image Container File. -------------------------------------------------------------------------------- /media/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games Chain Media Brand Resource File. -------------------------------------------------------------------------------- /node/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games Chain Node File. -------------------------------------------------------------------------------- /node/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; 20 | 21 | fn main() { 22 | generate_cargo_keys(); 23 | 24 | rerun_if_git_head_changed(); 25 | } 26 | -------------------------------------------------------------------------------- /node/src/cli.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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(feature = "manual-seal")] 20 | #[derive(Debug, Copy, Clone, clap::ArgEnum)] 21 | pub enum Sealing { 22 | // Seal using rpc method. 23 | Manual, 24 | // Seal when transaction is executed. 25 | Instant, 26 | } 27 | 28 | #[cfg(feature = "manual-seal")] 29 | impl Default for Sealing { 30 | fn default() -> Sealing { 31 | Sealing::Manual 32 | } 33 | } 34 | 35 | #[allow(missing_docs)] 36 | #[derive(Debug, clap::Parser)] 37 | pub struct RunCmd { 38 | #[allow(missing_docs)] 39 | #[clap(flatten)] 40 | pub base: sc_cli::RunCmd, 41 | 42 | /// Choose sealing method. 43 | #[cfg(feature = "manual-seal")] 44 | #[clap(long, arg_enum, ignore_case = true)] 45 | pub sealing: Sealing, 46 | 47 | #[clap(long)] 48 | pub enable_dev_signer: bool, 49 | 50 | /// Maximum number of logs in a query. 51 | #[clap(long, default_value = "10000")] 52 | pub max_past_logs: u32, 53 | 54 | /// Maximum fee history cache size. 55 | #[clap(long, default_value = "2048")] 56 | pub fee_history_limit: u64, 57 | 58 | /// The dynamic-fee pallet target gas price set by block author 59 | #[clap(long, default_value = "1")] 60 | pub target_gas_price: u64, 61 | } 62 | 63 | #[derive(Debug, clap::Parser)] 64 | pub struct Cli { 65 | #[clap(subcommand)] 66 | pub subcommand: Option, 67 | 68 | #[clap(flatten)] 69 | pub run: RunCmd, 70 | 71 | /// Disable automatic hardware benchmarks. 72 | /// 73 | /// By default these benchmarks are automatically ran at startup and measure 74 | /// the CPU speed, the memory bandwidth and the disk speed. 75 | /// 76 | /// The results are then printed out in the logs, and also sent as part of 77 | /// telemetry, if telemetry is enabled. 78 | #[clap(long)] 79 | pub no_hardware_benchmarks: bool, 80 | } 81 | 82 | #[derive(Debug, clap::Subcommand)] 83 | pub enum Subcommand { 84 | /// Key management cli utilities 85 | #[clap(subcommand)] 86 | Key(sc_cli::KeySubcommand), 87 | 88 | /// Build a chain specification. 89 | BuildSpec(sc_cli::BuildSpecCmd), 90 | 91 | /// Validate blocks. 92 | CheckBlock(sc_cli::CheckBlockCmd), 93 | 94 | /// Export blocks. 95 | ExportBlocks(sc_cli::ExportBlocksCmd), 96 | 97 | /// Export the state of a given block into a chain spec. 98 | ExportState(sc_cli::ExportStateCmd), 99 | 100 | /// Import blocks. 101 | ImportBlocks(sc_cli::ImportBlocksCmd), 102 | 103 | /// Remove the whole chain. 104 | PurgeChain(sc_cli::PurgeChainCmd), 105 | 106 | /// Revert the chain to a previous state. 107 | Revert(sc_cli::RevertCmd), 108 | 109 | /// Sub-commands concerned with benchmarking. 110 | #[clap(subcommand)] 111 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 112 | } 113 | -------------------------------------------------------------------------------- /node/src/command_helper.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | //! Contains code to setup the command invocations in [`super::command`] which would 20 | //! otherwise bloat that module. 21 | 22 | use crate::service::FullClient; 23 | 24 | use runtime::SystemCall; 25 | use sc_cli::Result; 26 | use sc_client_api::BlockBackend; 27 | use sp_core::{Encode, Pair}; 28 | use sp_inherents::{InherentData, InherentDataProvider}; 29 | use sp_keyring::Sr25519Keyring; 30 | use sp_runtime::{OpaqueExtrinsic, SaturatedConversion}; 31 | use web3games_runtime as runtime; 32 | 33 | use std::{sync::Arc, time::Duration}; 34 | 35 | /// Generates extrinsics for the `benchmark overhead` command. 36 | /// 37 | /// Note: Should only be used for benchmarking. 38 | pub struct BenchmarkExtrinsicBuilder { 39 | client: Arc, 40 | } 41 | 42 | impl BenchmarkExtrinsicBuilder { 43 | /// Creates a new [`Self`] from the given client. 44 | pub fn new(client: Arc) -> Self { 45 | Self { client } 46 | } 47 | } 48 | 49 | impl frame_benchmarking_cli::ExtrinsicBuilder for BenchmarkExtrinsicBuilder { 50 | fn remark(&self, nonce: u32) -> std::result::Result { 51 | let acc = Sr25519Keyring::Bob.pair(); 52 | let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( 53 | self.client.as_ref(), 54 | acc, 55 | SystemCall::remark { remark: vec![] }.into(), 56 | nonce, 57 | ) 58 | .into(); 59 | 60 | Ok(extrinsic) 61 | } 62 | } 63 | 64 | /// Create a transaction using the given `call`. 65 | /// 66 | /// Note: Should only be used for benchmarking. 67 | pub fn create_benchmark_extrinsic( 68 | client: &FullClient, 69 | sender: sp_core::sr25519::Pair, 70 | call: runtime::Call, 71 | nonce: u32, 72 | ) -> runtime::UncheckedExtrinsic { 73 | let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); 74 | let best_hash = client.chain_info().best_hash; 75 | let best_block = client.chain_info().best_number; 76 | 77 | let period = runtime::BlockHashCount::get() 78 | .checked_next_power_of_two() 79 | .map(|c| c / 2) 80 | .unwrap_or(2) as u64; 81 | let extra: runtime::SignedExtra = ( 82 | frame_system::CheckNonZeroSender::::new(), 83 | frame_system::CheckSpecVersion::::new(), 84 | frame_system::CheckTxVersion::::new(), 85 | frame_system::CheckGenesis::::new(), 86 | frame_system::CheckEra::::from(sp_runtime::generic::Era::mortal( 87 | period, 88 | best_block.saturated_into(), 89 | )), 90 | frame_system::CheckNonce::::from(nonce), 91 | frame_system::CheckWeight::::new(), 92 | pallet_transaction_payment::ChargeTransactionPayment::::from(0), 93 | ); 94 | 95 | let raw_payload = runtime::SignedPayload::from_raw( 96 | call.clone(), 97 | extra.clone(), 98 | ( 99 | (), 100 | runtime::VERSION.spec_version, 101 | runtime::VERSION.transaction_version, 102 | genesis_hash, 103 | best_hash, 104 | (), 105 | (), 106 | (), 107 | ), 108 | ); 109 | let signature = raw_payload.using_encoded(|e| sender.sign(e)); 110 | 111 | runtime::UncheckedExtrinsic::new_signed( 112 | call.clone(), 113 | sp_runtime::AccountId32::from(sender.public()).into(), 114 | runtime::Signature::Sr25519(signature.clone()), 115 | extra.clone(), 116 | ) 117 | } 118 | 119 | /// Generates inherent data for the `benchmark overhead` command. 120 | /// 121 | /// Note: Should only be used for benchmarking. 122 | pub fn inherent_benchmark_data() -> Result { 123 | let mut inherent_data = InherentData::new(); 124 | let d = Duration::from_millis(0); 125 | let timestamp = sp_timestamp::InherentDataProvider::new(d.into()); 126 | 127 | timestamp 128 | .provide_inherent_data(&mut inherent_data) 129 | .map_err(|e| format!("creating inherent data: {:?}", e))?; 130 | Ok(inherent_data) 131 | } 132 | -------------------------------------------------------------------------------- /node/src/main.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | //! Web3Games Node CLI library. 20 | 21 | #![warn(missing_docs)] 22 | 23 | mod chain_spec; 24 | #[macro_use] 25 | mod service; 26 | mod cli; 27 | mod command; 28 | mod command_helper; 29 | mod rpc; 30 | 31 | fn main() -> sc_cli::Result<()> { 32 | command::run() 33 | } 34 | -------------------------------------------------------------------------------- /pallets/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | 17 | The main modules of the Web3Games chain are used for the public business layer to provide open capabilities, 18 | and the production module that has passed the security audit -------------------------------------------------------------------------------- /pallets/call-switchgear/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-call-switchgear" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | serde = { version = "1.0.137", optional = true } 9 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 10 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 11 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 12 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 13 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 15 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 16 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 17 | 18 | [dev-dependencies] 19 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 20 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 21 | primitives = { path = "../../primitives"} 22 | smallvec = "1.9.0" 23 | 24 | 25 | [features] 26 | default = ["std"] 27 | std = [ 28 | "serde", 29 | "codec/std", 30 | "sp-runtime/std", 31 | "frame-support/std", 32 | "frame-system/std", 33 | "sp-io/std", 34 | "sp-std/std", 35 | "scale-info/std", 36 | ] 37 | try-runtime = ["frame-support/try-runtime"] 38 | 39 | runtime-benchmarks = [ 40 | "frame-benchmarking", 41 | "frame-support/runtime-benchmarks", 42 | "frame-system/runtime-benchmarks", 43 | ] 44 | 45 | -------------------------------------------------------------------------------- /pallets/call-switchgear/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | use crate::Pallet as CallSwitchgear; 7 | use frame_benchmarking::{account, benchmarks}; 8 | use frame_support::assert_ok; 9 | use frame_system::RawOrigin; 10 | 11 | benchmarks! { 12 | switchoff_transaction { 13 | let alice: T::AccountId = account("alice", 0, 0); 14 | }: _(RawOrigin::Root, 15 | b"Balances".to_vec(), 16 | b"transfer".to_vec() 17 | ) 18 | verify { 19 | assert_eq!(CallSwitchgear::::get_switchoff_transactions((b"Balances".to_vec(),b"transfer".to_vec())),Some(())); 20 | } 21 | 22 | switchon_transaction { 23 | let alice: T::AccountId = account("alice", 0, 0); 24 | assert_ok!(CallSwitchgear::::switchoff_transaction( 25 | RawOrigin::Root.into(), 26 | b"Balances".to_vec(), 27 | b"transfer".to_vec() 28 | )); 29 | assert_eq!( 30 | CallSwitchgear::::get_switchoff_transactions(( 31 | b"Balances".to_vec(), 32 | b"transfer".to_vec() 33 | )), 34 | Some(()) 35 | ); 36 | }: _(RawOrigin::Root, 37 | b"Balances".to_vec(), 38 | b"transfer".to_vec() 39 | ) 40 | verify { 41 | assert_eq!(CallSwitchgear::::get_switchoff_transactions((b"Balances".to_vec(),b"transfer".to_vec())),None); 42 | } 43 | 44 | 45 | impl_benchmark_test_suite!(CallSwitchgear, crate::mock::new_test_ext(), crate::mock::Test); 46 | } 47 | -------------------------------------------------------------------------------- /pallets/call-switchgear/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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(test)] 20 | 21 | use frame_support::{construct_runtime, parameter_types}; 22 | use primitives::Balance; 23 | use sp_core::H256; 24 | use sp_runtime::{testing::Header, traits::IdentityLookup}; 25 | 26 | type AccountId = u128; 27 | 28 | use super::*; 29 | 30 | use crate as web3games_call_switchgear; 31 | 32 | pub const MILLICENTS: Balance = 10_000_000_000_000; 33 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 34 | pub const DOLLARS: Balance = 100 * CENTS; 35 | 36 | parameter_types! { 37 | pub const BlockHashCount: u64 = 250; 38 | } 39 | 40 | impl frame_system::Config for Test { 41 | type Origin = Origin; 42 | type Index = u64; 43 | type BlockNumber = u64; 44 | type Call = Call; 45 | type Hash = H256; 46 | type Hashing = ::sp_runtime::traits::BlakeTwo256; 47 | type AccountId = AccountId; 48 | type Lookup = IdentityLookup; 49 | type Header = Header; 50 | type Event = Event; 51 | type BlockHashCount = BlockHashCount; 52 | type BlockWeights = (); 53 | type BlockLength = (); 54 | type Version = (); 55 | type PalletInfo = PalletInfo; 56 | type AccountData = pallet_balances::AccountData; 57 | type OnNewAccount = (); 58 | type OnKilledAccount = (); 59 | type DbWeight = (); 60 | type BaseCallFilter = frame_support::traits::Everything; 61 | type SystemWeightInfo = (); 62 | type SS58Prefix = (); 63 | type OnSetCode = (); 64 | type MaxConsumers = frame_support::traits::ConstU32<16>; 65 | } 66 | 67 | parameter_types! { 68 | pub const NativeTokenExistentialDeposit: Balance = 10; 69 | pub const MaxReserves: u32 = 50; 70 | } 71 | 72 | impl pallet_balances::Config for Test { 73 | type Balance = Balance; 74 | type DustRemoval = (); 75 | type Event = Event; 76 | type ExistentialDeposit = NativeTokenExistentialDeposit; 77 | type AccountStore = System; 78 | type MaxLocks = (); 79 | type MaxReserves = MaxReserves; 80 | type ReserveIdentifier = (); 81 | type WeightInfo = (); 82 | } 83 | 84 | impl web3games_call_switchgear::Config for Test { 85 | type Event = Event; 86 | type WeightInfo = (); 87 | } 88 | 89 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 90 | type Block = frame_system::mocking::MockBlock; 91 | 92 | construct_runtime!( 93 | pub enum Test where 94 | Block = Block, 95 | NodeBlock = Block, 96 | UncheckedExtrinsic = UncheckedExtrinsic 97 | { 98 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 99 | CallSwitchgear: web3games_call_switchgear::{Pallet, Storage, Call, Event}, 100 | Balances: pallet_balances::{Pallet, Storage, Call, Event}, 101 | } 102 | ); 103 | 104 | // Build genesis storage according to the mock runtime. 105 | pub fn new_test_ext() -> sp_io::TestExternalities { 106 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 107 | pallet_balances::GenesisConfig:: { 108 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 109 | } 110 | .assimilate_storage(&mut t) 111 | .unwrap(); 112 | let mut ext = sp_io::TestExternalities::new(t); 113 | ext.execute_with(|| System::set_block_number(1)); 114 | ext 115 | } 116 | -------------------------------------------------------------------------------- /pallets/call-switchgear/src/tests.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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(test)] 20 | 21 | use frame_support::{assert_noop, assert_ok}; 22 | use mock::{Event, *}; 23 | use sp_runtime::traits::BadOrigin; 24 | 25 | use super::*; 26 | 27 | #[test] 28 | fn switchoff_transaction_should_work() { 29 | new_test_ext().execute_with(|| { 30 | assert_noop!( 31 | CallSwitchgear::switchoff_transaction( 32 | Origin::signed(5), 33 | b"Balances".to_vec(), 34 | b"transfer".to_vec() 35 | ), 36 | BadOrigin 37 | ); 38 | 39 | assert_eq!( 40 | CallSwitchgear::get_switchoff_transactions(( 41 | b"Balances".to_vec(), 42 | b"transfer".to_vec() 43 | )), 44 | None 45 | ); 46 | assert_ok!(CallSwitchgear::switchoff_transaction( 47 | Origin::root(), 48 | b"Balances".to_vec(), 49 | b"transfer".to_vec() 50 | )); 51 | System::assert_last_event(Event::CallSwitchgear(crate::Event::TransactionSwitchedoff( 52 | b"Balances".to_vec(), 53 | b"transfer".to_vec(), 54 | ))); 55 | assert_eq!( 56 | CallSwitchgear::get_switchoff_transactions(( 57 | b"Balances".to_vec(), 58 | b"transfer".to_vec() 59 | )), 60 | Some(()) 61 | ); 62 | 63 | assert_noop!( 64 | CallSwitchgear::switchoff_transaction( 65 | Origin::root(), 66 | b"CallSwitchgear".to_vec(), 67 | b"switchoff_transaction".to_vec() 68 | ), 69 | Error::::CannotSwitchOff 70 | ); 71 | assert_noop!( 72 | CallSwitchgear::switchoff_transaction( 73 | Origin::root(), 74 | b"CallSwitchgear".to_vec(), 75 | b"some_other_call".to_vec() 76 | ), 77 | Error::::CannotSwitchOff 78 | ); 79 | assert_ok!(CallSwitchgear::switchoff_transaction( 80 | Origin::root(), 81 | b"OtherPallet".to_vec(), 82 | b"switchoff_transaction".to_vec() 83 | )); 84 | }); 85 | } 86 | 87 | #[test] 88 | fn switchon_transaction_transaction_should_work() { 89 | new_test_ext().execute_with(|| { 90 | System::set_block_number(1); 91 | 92 | assert_ok!(CallSwitchgear::switchoff_transaction( 93 | Origin::root(), 94 | b"Balances".to_vec(), 95 | b"transfer".to_vec() 96 | )); 97 | assert_eq!( 98 | CallSwitchgear::get_switchoff_transactions(( 99 | b"Balances".to_vec(), 100 | b"transfer".to_vec() 101 | )), 102 | Some(()) 103 | ); 104 | 105 | assert_noop!( 106 | CallSwitchgear::switchoff_transaction( 107 | Origin::signed(5), 108 | b"Balances".to_vec(), 109 | b"transfer".to_vec() 110 | ), 111 | BadOrigin 112 | ); 113 | 114 | assert_ok!(CallSwitchgear::switchon_transaction( 115 | Origin::root(), 116 | b"Balances".to_vec(), 117 | b"transfer".to_vec() 118 | )); 119 | System::assert_last_event(Event::CallSwitchgear(crate::Event::TransactionSwitchedOn( 120 | b"Balances".to_vec(), 121 | b"transfer".to_vec(), 122 | ))); 123 | assert_eq!( 124 | CallSwitchgear::get_switchoff_transactions(( 125 | b"Balances".to_vec(), 126 | b"transfer".to_vec() 127 | )), 128 | None 129 | ); 130 | 131 | assert_eq!(CallSwitchgear::get_overall_indicator(), false); 132 | 133 | assert_ok!(CallSwitchgear::switchoff_transaction( 134 | Origin::root(), 135 | b"All".to_vec(), 136 | b"transfer".to_vec() 137 | )); 138 | 139 | assert_eq!(CallSwitchgear::get_overall_indicator(), true); 140 | 141 | assert_ok!(CallSwitchgear::switchon_transaction( 142 | Origin::root(), 143 | b"All".to_vec(), 144 | b"transfer".to_vec() 145 | )); 146 | 147 | assert_eq!(CallSwitchgear::get_overall_indicator(), false); 148 | }); 149 | } 150 | -------------------------------------------------------------------------------- /pallets/call-switchgear/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for web3games_call_switchgear 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 22 | //! DATE: 2022-12-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // target/release/web3games-node 27 | // benchmark 28 | // pallet 29 | // --chain=dev 30 | // --steps=50 31 | // --repeat=20 32 | // --pallet=web3games_call_switchgear 33 | // --extrinsic=* 34 | // --execution=wasm 35 | // --wasm-execution=compiled 36 | // --output=./pallets/call-switchgear/src/weights.rs 37 | // --template=./.maintain/w3g-weight-template.hbs 38 | 39 | #![cfg_attr(rustfmt, rustfmt_skip)] 40 | #![allow(unused_parens)] 41 | #![allow(unused_imports)] 42 | #![allow(clippy::unnecessary_cast)] 43 | 44 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 45 | use sp_std::marker::PhantomData; 46 | 47 | /// Weight functions needed for web3games_call_switchgear. 48 | pub trait WeightInfo { 49 | fn switchoff_transaction() -> Weight; 50 | fn switchon_transaction() -> Weight; 51 | } 52 | 53 | /// Weights for web3games_call_switchgear using the Web3Games node and recommended hardware. 54 | pub struct W3GWeight(PhantomData); 55 | impl WeightInfo for W3GWeight { 56 | // Storage: CallSwitchgear SwitchedOffTransactions (r:1 w:1) 57 | fn switchoff_transaction() -> Weight { 58 | (14_000_000 as Weight) 59 | .saturating_add(T::DbWeight::get().reads(1 as Weight)) 60 | .saturating_add(T::DbWeight::get().writes(1 as Weight)) 61 | } 62 | // Storage: CallSwitchgear SwitchedOffTransactions (r:1 w:1) 63 | fn switchon_transaction() -> Weight { 64 | (14_000_000 as Weight) 65 | .saturating_add(T::DbWeight::get().reads(1 as Weight)) 66 | .saturating_add(T::DbWeight::get().writes(1 as Weight)) 67 | } 68 | } 69 | 70 | // For backwards compatibility and tests 71 | impl WeightInfo for () { 72 | fn switchoff_transaction() -> Weight { 73 | (14_000_000 as Weight) 74 | .saturating_add(RocksDbWeight::get().reads(1 as Weight)) 75 | .saturating_add(RocksDbWeight::get().writes(1 as Weight)) 76 | } 77 | fn switchon_transaction() -> Weight { 78 | (14_000_000 as Weight) 79 | .saturating_add(RocksDbWeight::get().reads(1 as Weight)) 80 | .saturating_add(RocksDbWeight::get().writes(1 as Weight)) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /pallets/ethereum-chain-id/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-ethereum-chain-id" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | serde = { version = "1.0.137", optional = true, features = [ "derive" ] } 9 | 10 | # Substrate 11 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 12 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 13 | parity-scale-codec = { version = "3.0.0", default-features = false, features = [ "derive" ] } 14 | scale-info = { version = "2.1.2", default-features = false, features = [ "derive" ] } 15 | 16 | [features] 17 | default = [ "std" ] 18 | std = [ 19 | "frame-support/std", 20 | "frame-system/std", 21 | "parity-scale-codec/std", 22 | "scale-info/std", 23 | "serde", 24 | ] 25 | try-runtime = [ "frame-support/try-runtime" ] 26 | -------------------------------------------------------------------------------- /pallets/ethereum-chain-id/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | pub use pallet::*; 22 | 23 | #[frame_support::pallet] 24 | pub mod pallet { 25 | 26 | use frame_support::pallet_prelude::*; 27 | 28 | /// The Ethereum Chain Id Pallet 29 | #[pallet::pallet] 30 | pub struct Pallet(_); 31 | 32 | /// Configuration trait of this pallet. 33 | #[pallet::config] 34 | pub trait Config: frame_system::Config {} 35 | 36 | impl Get for Pallet { 37 | fn get() -> u64 { 38 | Self::chain_id() 39 | } 40 | } 41 | 42 | #[pallet::storage] 43 | #[pallet::getter(fn chain_id)] 44 | pub type ChainId = StorageValue<_, u64, ValueQuery>; 45 | 46 | #[pallet::genesis_config] 47 | #[derive(Default)] 48 | pub struct GenesisConfig { 49 | pub chain_id: u64, 50 | } 51 | 52 | #[pallet::genesis_build] 53 | impl GenesisBuild for GenesisConfig { 54 | fn build(&self) { 55 | ChainId::::put(self.chain_id); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /pallets/exchange/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-exchange" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | 11 | log = { version = "0.4.17", default-features = false } 12 | integer-sqrt = "0.1.2" 13 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 18 | pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 19 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 20 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 21 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.26" } 22 | 23 | primitives = { path = "../../primitives", default-features = false } 24 | web3games-token-fungible = { path = "../token-fungible", default-features = false } 25 | web3games-wrap-currency = { path = "../wrap-currency", default-features = false } 26 | 27 | [dev-dependencies] 28 | pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 29 | 30 | [features] 31 | default = ["std"] 32 | std = [ 33 | "codec/std", 34 | "scale-info/std", 35 | "log/std", 36 | "frame-support/std", 37 | "frame-system/std", 38 | "frame-benchmarking/std", 39 | "sp-std/std", 40 | "sp-io/std", 41 | "sp-runtime/std", 42 | "pallet-timestamp/std", 43 | "pallet-balances/std", 44 | "sp-core/std", 45 | "primitives/std", 46 | "web3games-token-fungible/std", 47 | "web3games-wrap-currency/std", 48 | ] 49 | runtime-benchmarks = ["frame-benchmarking"] 50 | 51 | -------------------------------------------------------------------------------- /pallets/exchange/rpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-exchange-rpc" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0" } 9 | jsonrpsee = { version = "0.14.0", features = ["server", "macros"] } 10 | sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 11 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 12 | sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 13 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 14 | sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 15 | pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 16 | web3games-exchange-rpc-runtime-api = { path = "./runtime-api", default-features = false } 17 | primitives = { path = "../../../primitives", default-features = false } 18 | 19 | [features] 20 | default = ["std"] 21 | std = [ 22 | "codec/std", 23 | "sp-api/std", 24 | "sp-runtime/std", 25 | "sp-core/std", 26 | "pallet-transaction-payment-rpc-runtime-api/std", 27 | "web3games-exchange-rpc-runtime-api/std", 28 | "primitives/std", 29 | ] 30 | -------------------------------------------------------------------------------- /pallets/exchange/rpc/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-exchange-rpc-runtime-api" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 9 | sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 10 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 11 | web3games-exchange = { path = "../../../exchange", default-features = false } 12 | web3games-token-fungible = { path = "../../../token-fungible", default-features = false } 13 | primitives = { path = "../../../../primitives", default-features = false } 14 | 15 | [features] 16 | default = ["std"] 17 | std = [ 18 | "codec/std", 19 | "sp-api/std", 20 | "sp-std/std", 21 | "web3games-exchange/std", 22 | "web3games-token-fungible/std", 23 | "primitives/std", 24 | ] 25 | -------------------------------------------------------------------------------- /pallets/exchange/rpc/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | use codec::Codec; 22 | use primitives::Balance; 23 | use sp_api::decl_runtime_apis; 24 | use sp_std::vec::Vec; 25 | 26 | decl_runtime_apis! { 27 | pub trait ExchangeRuntimeApi where 28 | AccountId: Codec, 29 | { 30 | fn get_amount_in_price(supply: Balance, path: Vec) -> Option>; 31 | fn get_amount_out_price(supply: Balance, path: Vec) -> Option>; 32 | fn get_estimate_lp_token( 33 | token_0: u128, 34 | amount_0: Balance, 35 | token_1: u128, 36 | amount_1: Balance, 37 | ) -> Option; 38 | fn get_estimate_out_token(supply: Balance,token_0:u128,token_1:u128)-> Option; 39 | fn get_liquidity_to_tokens(lp_token_0:u128,lp_balance:Balance)-> Option<(Balance,Balance)>; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /pallets/farming/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-farming" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | serde = { version = "1.0.137", optional = true } 9 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 10 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 11 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 12 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 13 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 15 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 16 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 17 | 18 | web3games-token-fungible = { path = "../token-fungible", default-features = false } 19 | primitives = { path = "../../primitives", default-features = false } 20 | 21 | [dev-dependencies] 22 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 23 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 24 | smallvec = "1.9.0" 25 | 26 | 27 | [features] 28 | default = ["std"] 29 | std = [ 30 | "serde", 31 | "codec/std", 32 | "sp-runtime/std", 33 | "frame-support/std", 34 | "frame-system/std", 35 | "sp-io/std", 36 | "sp-std/std", 37 | "scale-info/std", 38 | "web3games-token-fungible/std", 39 | "primitives/std", 40 | ] 41 | try-runtime = ["frame-support/try-runtime"] 42 | 43 | runtime-benchmarks = [ 44 | "frame-benchmarking", 45 | "frame-support/runtime-benchmarks", 46 | "frame-system/runtime-benchmarks", 47 | ] 48 | 49 | -------------------------------------------------------------------------------- /pallets/farming/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | use crate::Pallet as Farming; 7 | use frame_benchmarking::{account, benchmarks}; 8 | use frame_support::assert_ok; 9 | use frame_system::{Pallet as System, RawOrigin}; 10 | use sp_runtime::traits::UniqueSaturatedFrom; 11 | use web3games_token_fungible::Pallet as TokenFungible; 12 | 13 | const W3G: u128 = 1; 14 | const USDT: u128 = 2; 15 | const W3G_DECIMALS: u128 = 1_000_000_000_000_000_000; 16 | const USDT_DECIMALS: u128 = 1_000_000; 17 | 18 | fn setup() -> DispatchResult { 19 | let alice: T::AccountId = account("alice", 0, 0); 20 | let bob: T::AccountId = account("bob", 0, 0); 21 | 22 | assert_ok!(TokenFungible::::create_token( 23 | RawOrigin::Signed(alice.clone()).into(), 24 | ::FungibleTokenId::unique_saturated_from(W3G), 25 | b"TestToken".to_vec(), 26 | b"TK".to_vec(), 27 | 18 28 | )); 29 | assert_ok!(TokenFungible::::create_token( 30 | RawOrigin::Signed(alice.clone()).into(), 31 | ::FungibleTokenId::unique_saturated_from(USDT), 32 | b"TestToken".to_vec(), 33 | b"TK".to_vec(), 34 | 18 35 | )); 36 | assert_ok!(TokenFungible::::mint( 37 | RawOrigin::Signed(alice.clone()).into(), 38 | ::FungibleTokenId::unique_saturated_from(USDT), 39 | alice.clone(), 40 | 100 * USDT_DECIMALS, 41 | )); 42 | assert_ok!(TokenFungible::::mint( 43 | RawOrigin::Signed(alice.clone()).into(), 44 | ::FungibleTokenId::unique_saturated_from(W3G), 45 | bob, 46 | 100 * W3G_DECIMALS, 47 | )); 48 | Ok(()) 49 | } 50 | 51 | benchmarks! { 52 | set_admin { 53 | let alice: T::AccountId = account("alice", 0, 0); 54 | }: _(RawOrigin::Root,alice) 55 | 56 | create_pool { 57 | let alice: T::AccountId = account("alice", 0, 0); 58 | let bob: T::AccountId = account("bob", 0, 0); 59 | setup::()?; 60 | assert_ok!(Farming::::set_admin(RawOrigin::Root.into(),alice.clone())); 61 | }: _(RawOrigin::Signed(alice),T::BlockNumber::from(1u32),T::BlockNumber::from(10u32),T::BlockNumber::from(10u32),W3G,USDT,10 * USDT_DECIMALS) 62 | 63 | staking { 64 | let alice: T::AccountId = account("alice", 0, 0); 65 | let bob: T::AccountId = account("bob", 0, 0); 66 | setup::()?; 67 | assert_ok!(Farming::::set_admin(RawOrigin::Root.into(),alice.clone())); 68 | assert_ok!(Farming::::create_pool( 69 | RawOrigin::Signed(alice.clone()).into(), 70 | T::BlockNumber::from(10u32), 71 | T::BlockNumber::from(10u32), 72 | T::BlockNumber::from(10u32), 73 | W3G, 74 | USDT, 75 | 10 * USDT_DECIMALS, 76 | )); 77 | System::::set_block_number(T::BlockNumber::from(10u32)); 78 | }: _(RawOrigin::Signed(bob),0,10 * W3G_DECIMALS) 79 | 80 | claim { 81 | let alice: T::AccountId = account("alice", 0, 0); 82 | let bob: T::AccountId = account("bob", 0, 0); 83 | setup::()?; 84 | assert_ok!(Farming::::set_admin(RawOrigin::Root.into(),alice.clone())); 85 | assert_ok!(Farming::::create_pool( 86 | RawOrigin::Signed(alice.clone()).into(), 87 | T::BlockNumber::from(10u32), 88 | T::BlockNumber::from(10u32), 89 | T::BlockNumber::from(10u32), 90 | W3G, 91 | USDT, 92 | 10 * USDT_DECIMALS, 93 | )); 94 | System::::set_block_number(T::BlockNumber::from(10u32)); 95 | assert_ok!(Farming::::staking( 96 | RawOrigin::Signed(bob.clone()).into(), 97 | 0, 98 | 10 * W3G_DECIMALS, 99 | )); 100 | System::::set_block_number(T::BlockNumber::from(30u32)); 101 | }: _(RawOrigin::Signed(bob),0) 102 | 103 | force_claim { 104 | let alice: T::AccountId = account("alice", 0, 0); 105 | let bob: T::AccountId = account("bob", 0, 0); 106 | setup::()?; 107 | assert_ok!(Farming::::set_admin(RawOrigin::Root.into(),alice.clone())); 108 | assert_ok!(Farming::::create_pool( 109 | RawOrigin::Signed(alice.clone()).into(), 110 | T::BlockNumber::from(10u32), 111 | T::BlockNumber::from(10u32), 112 | T::BlockNumber::from(10u32), 113 | W3G, 114 | USDT, 115 | 10 * USDT_DECIMALS, 116 | )); 117 | System::::set_block_number(T::BlockNumber::from(10u32)); 118 | assert_ok!(Farming::::staking( 119 | RawOrigin::Signed(bob.clone()).into(), 120 | 0, 121 | 10 * W3G_DECIMALS, 122 | )); 123 | }: _(RawOrigin::Signed(alice),bob,0) 124 | 125 | impl_benchmark_test_suite!(Farming, crate::mock::new_test_ext(), crate::mock::Test); 126 | } 127 | -------------------------------------------------------------------------------- /pallets/farming/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use crate as web3games_farming; 20 | use frame_support::{ 21 | construct_runtime, parameter_types, 22 | traits::{ConstU16, ConstU64}, 23 | PalletId, 24 | }; 25 | use primitives::Balance; 26 | use sp_core::H256; 27 | use sp_runtime::{ 28 | testing::Header, 29 | traits::{BlakeTwo256, IdentityLookup}, 30 | }; 31 | 32 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 33 | type Block = frame_system::mocking::MockBlock; 34 | 35 | pub const MILLICENTS: Balance = 10_000_000_000_000; 36 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 37 | pub const DOLLARS: Balance = 100 * CENTS; 38 | 39 | // Configure a mock runtime to test the pallet. 40 | construct_runtime!( 41 | pub enum Test where 42 | Block = Block, 43 | NodeBlock = Block, 44 | UncheckedExtrinsic = UncheckedExtrinsic, 45 | { 46 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 47 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 48 | TokenFungible: web3games_token_fungible::{Pallet, Call, Storage, Event}, 49 | Farming: web3games_farming::{Pallet, Call, Storage, Event}, 50 | } 51 | ); 52 | 53 | impl frame_system::Config for Test { 54 | type BaseCallFilter = frame_support::traits::Everything; 55 | type BlockWeights = (); 56 | type BlockLength = (); 57 | type DbWeight = (); 58 | type Origin = Origin; 59 | type Call = Call; 60 | type Index = u64; 61 | type BlockNumber = u64; 62 | type Hash = H256; 63 | type Hashing = BlakeTwo256; 64 | type AccountId = u64; 65 | type Lookup = IdentityLookup; 66 | type Header = Header; 67 | type Event = Event; 68 | type BlockHashCount = ConstU64<250>; 69 | type Version = (); 70 | type PalletInfo = PalletInfo; 71 | type AccountData = pallet_balances::AccountData; 72 | type OnNewAccount = (); 73 | type OnKilledAccount = (); 74 | type SystemWeightInfo = (); 75 | type SS58Prefix = ConstU16<42>; 76 | type OnSetCode = (); 77 | type MaxConsumers = frame_support::traits::ConstU32<16>; 78 | } 79 | 80 | parameter_types! { 81 | pub const ExistentialDeposit: Balance = 1; 82 | } 83 | 84 | impl pallet_balances::Config for Test { 85 | type Balance = Balance; 86 | type DustRemoval = (); 87 | type Event = Event; 88 | type ExistentialDeposit = ExistentialDeposit; 89 | type AccountStore = System; 90 | type WeightInfo = (); 91 | type MaxLocks = (); 92 | type MaxReserves = (); 93 | type ReserveIdentifier = [u8; 8]; 94 | } 95 | 96 | parameter_types! { 97 | pub const TokenFungiblePalletId: PalletId = PalletId(*b"w3g/tfpi"); 98 | pub const StringLimit: u32 = 50; 99 | pub const CreateTokenDeposit: Balance = 500 * MILLICENTS; 100 | } 101 | 102 | impl web3games_token_fungible::Config for Test { 103 | type Event = Event; 104 | type PalletId = TokenFungiblePalletId; 105 | type FungibleTokenId = u128; 106 | type StringLimit = StringLimit; 107 | type CreateTokenDeposit = CreateTokenDeposit; 108 | type Currency = Balances; 109 | type WeightInfo = (); 110 | } 111 | 112 | parameter_types! { 113 | pub const FarmingPalletId: PalletId = PalletId(*b"w3g/farm"); 114 | } 115 | 116 | impl web3games_farming::Config for Test { 117 | type Event = Event; 118 | type PalletId = FarmingPalletId; 119 | type WeightInfo = (); 120 | } 121 | 122 | // Build genesis storage according to the mock runtime. 123 | pub fn new_test_ext() -> sp_io::TestExternalities { 124 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 125 | pallet_balances::GenesisConfig:: { 126 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 127 | } 128 | .assimilate_storage(&mut t) 129 | .unwrap(); 130 | let mut ext = sp_io::TestExternalities::new(t); 131 | ext.execute_with(|| System::set_block_number(1)); 132 | ext 133 | } 134 | 135 | /// Run until a particular block. 136 | pub fn run_to_block(n: u64) { 137 | while System::block_number() < n { 138 | System::finalize(); 139 | System::set_block_number(System::block_number() + 1); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /pallets/launchpad/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-launchpad" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | serde = { version = "1.0.137", optional = true } 9 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 10 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 11 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 12 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 13 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 15 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 16 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 17 | 18 | web3games-token-fungible = { path = "../token-fungible", default-features = false } 19 | web3games-support = { path = "../support", default-features = false } 20 | primitives = { path = "../../primitives", default-features = false } 21 | 22 | [dev-dependencies] 23 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 24 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 25 | smallvec = "1.9.0" 26 | 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "serde", 32 | "codec/std", 33 | "sp-runtime/std", 34 | "frame-support/std", 35 | "frame-system/std", 36 | "sp-io/std", 37 | "sp-std/std", 38 | "scale-info/std", 39 | "web3games-token-fungible/std", 40 | "web3games-support/std", 41 | "primitives/std", 42 | ] 43 | try-runtime = ["frame-support/try-runtime"] 44 | 45 | runtime-benchmarks = [ 46 | "frame-benchmarking", 47 | "frame-support/runtime-benchmarks", 48 | "frame-system/runtime-benchmarks", 49 | ] 50 | 51 | -------------------------------------------------------------------------------- /pallets/launchpad/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | use crate::Pallet as Launchpad; 7 | use frame_benchmarking::{account, benchmarks}; 8 | use frame_support::assert_ok; 9 | use frame_system::{Pallet as System, RawOrigin}; 10 | use sp_runtime::traits::UniqueSaturatedFrom; 11 | use web3games_token_fungible::Pallet as TokenFungible; 12 | 13 | const W3G: u128 = 1; 14 | const USDT: u128 = 2; 15 | const W3G_DECIMALS: u128 = 1_000_000_000_000_000_000; 16 | const USDT_DECIMALS: u128 = 1_000_000; 17 | 18 | fn setup() -> DispatchResult { 19 | let alice: T::AccountId = account("alice", 0, 0); 20 | let bob: T::AccountId = account("bob", 0, 0); 21 | 22 | assert_ok!(TokenFungible::::create_token( 23 | RawOrigin::Signed(alice.clone()).into(), 24 | ::FungibleTokenId::unique_saturated_from(W3G), 25 | b"TestToken".to_vec(), 26 | b"TK".to_vec(), 27 | 18 28 | )); 29 | assert_ok!(TokenFungible::::create_token( 30 | RawOrigin::Signed(alice.clone()).into(), 31 | ::FungibleTokenId::unique_saturated_from(USDT), 32 | b"TestToken".to_vec(), 33 | b"TK".to_vec(), 34 | 6 35 | )); 36 | assert_ok!(TokenFungible::::mint( 37 | RawOrigin::Signed(alice.clone()).into(), 38 | ::FungibleTokenId::unique_saturated_from(USDT), 39 | bob.clone(), 40 | 100 * USDT_DECIMALS, 41 | )); 42 | assert_ok!(TokenFungible::::mint( 43 | RawOrigin::Signed(alice.clone()).into(), 44 | ::FungibleTokenId::unique_saturated_from(W3G), 45 | alice, 46 | 100 * W3G_DECIMALS, 47 | )); 48 | Ok(()) 49 | } 50 | 51 | benchmarks! { 52 | create_pool { 53 | let alice: T::AccountId = account("alice", 0, 0); 54 | setup::()?; 55 | }: _(RawOrigin::Signed(alice),T::BlockNumber::from(10u32),T::BlockNumber::from(10u32),W3G,USDT,10 * W3G_DECIMALS,1 * USDT_DECIMALS) 56 | 57 | buy_token { 58 | let alice: T::AccountId = account("alice", 0, 0); 59 | let bob: T::AccountId = account("bob", 0, 0); 60 | setup::()?; 61 | assert_ok!(Launchpad::::create_pool( 62 | RawOrigin::Signed(alice.clone()).into(), 63 | T::BlockNumber::from(10u32), 64 | T::BlockNumber::from(10u32), 65 | W3G, 66 | USDT, 67 | 10 * W3G_DECIMALS, 68 | 1 * USDT_DECIMALS, 69 | )); 70 | System::::set_block_number(T::BlockNumber::from(10u32)); 71 | }: _(RawOrigin::Signed(bob),0,2) 72 | 73 | claim { 74 | let alice: T::AccountId = account("alice", 0, 0); 75 | let bob: T::AccountId = account("bob", 0, 0); 76 | setup::()?; 77 | assert_ok!(Launchpad::::create_pool( 78 | RawOrigin::Signed(alice.clone()).into(), 79 | T::BlockNumber::from(10u32), 80 | T::BlockNumber::from(10u32), 81 | W3G, 82 | USDT, 83 | 10 * W3G_DECIMALS, 84 | 1 * USDT_DECIMALS, 85 | )); 86 | System::::set_block_number(T::BlockNumber::from(10u32)); 87 | assert_ok!(Launchpad::::buy_token( 88 | RawOrigin::Signed(bob.clone()).into(), 89 | 0, 90 | 2 91 | )); 92 | System::::set_block_number(T::BlockNumber::from(21u32)); 93 | }: _(RawOrigin::Signed(bob),0) 94 | 95 | owner_claim { 96 | let alice: T::AccountId = account("alice", 0, 0); 97 | let bob: T::AccountId = account("bob", 0, 0); 98 | setup::()?; 99 | assert_ok!(Launchpad::::create_pool( 100 | RawOrigin::Signed(alice.clone()).into(), 101 | T::BlockNumber::from(10u32), 102 | T::BlockNumber::from(10u32), 103 | W3G, 104 | USDT, 105 | 10 * W3G_DECIMALS, 106 | 1 * USDT_DECIMALS, 107 | )); 108 | System::::set_block_number(T::BlockNumber::from(21u32)); 109 | }: _(RawOrigin::Signed(alice),0) 110 | 111 | impl_benchmark_test_suite!(Launchpad, crate::mock::new_test_ext(), crate::mock::Test); 112 | } 113 | -------------------------------------------------------------------------------- /pallets/launchpad/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for web3games_launchpad 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 22 | //! DATE: 2022-12-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // target/release/web3games-node 27 | // benchmark 28 | // pallet 29 | // --chain=dev 30 | // --steps=50 31 | // --repeat=20 32 | // --pallet=web3games_launchpad 33 | // --extrinsic=* 34 | // --execution=wasm 35 | // --wasm-execution=compiled 36 | // --output=./pallets/launchpad/src/weights.rs 37 | // --template=./.maintain/w3g-weight-template.hbs 38 | 39 | #![cfg_attr(rustfmt, rustfmt_skip)] 40 | #![allow(unused_parens)] 41 | #![allow(unused_imports)] 42 | #![allow(clippy::unnecessary_cast)] 43 | 44 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 45 | use sp_std::marker::PhantomData; 46 | 47 | /// Weight functions needed for web3games_launchpad. 48 | pub trait WeightInfo { 49 | fn create_pool() -> Weight; 50 | fn buy_token() -> Weight; 51 | fn claim() -> Weight; 52 | fn owner_claim() -> Weight; 53 | } 54 | 55 | /// Weights for web3games_launchpad using the Web3Games node and recommended hardware. 56 | pub struct W3GWeight(PhantomData); 57 | impl WeightInfo for W3GWeight { 58 | // Storage: Launchpad NextPoolId (r:1 w:1) 59 | // Storage: TokenFungible Balances (r:2 w:2) 60 | // Storage: Launchpad Pools (r:0 w:1) 61 | fn create_pool() -> Weight { 62 | (27_000_000 as Weight) 63 | .saturating_add(T::DbWeight::get().reads(3 as Weight)) 64 | .saturating_add(T::DbWeight::get().writes(4 as Weight)) 65 | } 66 | // Storage: Launchpad Pools (r:1 w:1) 67 | // Storage: TokenFungible Balances (r:2 w:2) 68 | // Storage: TokenFungible Tokens (r:1 w:0) 69 | // Storage: Launchpad AccountPoolIdLocked (r:1 w:1) 70 | fn buy_token() -> Weight { 71 | (36_000_000 as Weight) 72 | .saturating_add(T::DbWeight::get().reads(5 as Weight)) 73 | .saturating_add(T::DbWeight::get().writes(4 as Weight)) 74 | } 75 | // Storage: Launchpad Pools (r:1 w:0) 76 | // Storage: Launchpad AccountPoolIdLocked (r:1 w:1) 77 | // Storage: TokenFungible Balances (r:2 w:2) 78 | fn claim() -> Weight { 79 | (34_000_000 as Weight) 80 | .saturating_add(T::DbWeight::get().reads(4 as Weight)) 81 | .saturating_add(T::DbWeight::get().writes(3 as Weight)) 82 | } 83 | // Storage: Launchpad Pools (r:1 w:0) 84 | // Storage: TokenFungible Balances (r:4 w:4) 85 | fn owner_claim() -> Weight { 86 | (41_000_000 as Weight) 87 | .saturating_add(T::DbWeight::get().reads(5 as Weight)) 88 | .saturating_add(T::DbWeight::get().writes(4 as Weight)) 89 | } 90 | } 91 | 92 | // For backwards compatibility and tests 93 | impl WeightInfo for () { 94 | fn create_pool() -> Weight { 95 | (27_000_000 as Weight) 96 | .saturating_add(RocksDbWeight::get().reads(3 as Weight)) 97 | .saturating_add(RocksDbWeight::get().writes(4 as Weight)) 98 | } 99 | fn buy_token() -> Weight { 100 | (36_000_000 as Weight) 101 | .saturating_add(RocksDbWeight::get().reads(5 as Weight)) 102 | .saturating_add(RocksDbWeight::get().writes(4 as Weight)) 103 | } 104 | fn claim() -> Weight { 105 | (34_000_000 as Weight) 106 | .saturating_add(RocksDbWeight::get().reads(4 as Weight)) 107 | .saturating_add(RocksDbWeight::get().writes(3 as Weight)) 108 | } 109 | fn owner_claim() -> Weight { 110 | (41_000_000 as Weight) 111 | .saturating_add(RocksDbWeight::get().reads(5 as Weight)) 112 | .saturating_add(RocksDbWeight::get().writes(4 as Weight)) 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /pallets/marketplace/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-marketplace" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | 11 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 12 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false} 15 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 18 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 19 | web3games-token-non-fungible = { path = "../token-non-fungible", default-features = false } 20 | web3games-token-multi = { path = "../token-multi", default-features = false } 21 | 22 | primitives = { path = "../../primitives", default-features = false } 23 | 24 | [dev-dependencies] 25 | pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 26 | 27 | [features] 28 | default = ["std"] 29 | std = [ 30 | "codec/std", 31 | "scale-info/std", 32 | "frame-support/std", 33 | "frame-system/std", 34 | "sp-std/std", 35 | "sp-io/std", 36 | "sp-runtime/std", 37 | "sp-core/std", 38 | "primitives/std", 39 | "web3games-token-non-fungible/std", 40 | "web3games-token-multi/std", 41 | "pallet-balances/std" 42 | ] 43 | try-runtime = ["frame-support/try-runtime"] 44 | 45 | runtime-benchmarks = [ 46 | "frame-benchmarking", 47 | "frame-support/runtime-benchmarks", 48 | "frame-system/runtime-benchmarks", 49 | ] 50 | -------------------------------------------------------------------------------- /pallets/marketplace/src/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | 3 | use super::*; 4 | use crate::mock::*; 5 | use frame_support::assert_ok; 6 | 7 | const ALICE: u64 = 1; 8 | const BOB: u64 = 2; 9 | 10 | const W3G: u128 = 1_000_000_000_000_000_000; 11 | const BLOCK: u64 = 1; 12 | 13 | fn create_non_fungible_token() { 14 | assert_ok!(TokenNonFungible::create_token( 15 | Origin::signed(ALICE), 16 | 1, 17 | b"W3G".to_vec(), 18 | b"W3G".to_vec(), 19 | b"https://web3games.com/".to_vec(), 20 | )); 21 | assert_eq!(TokenNonFungible::exists(1), true); 22 | 23 | //mint 2 to ALICE 24 | assert_ok!(TokenNonFungible::mint(Origin::signed(ALICE), 1, ALICE, 2)); 25 | assert_eq!(TokenNonFungible::owner_of(1, 2), Some(ALICE)); 26 | } 27 | 28 | #[test] 29 | fn create_order_should_work() { 30 | new_test_ext().execute_with(|| { 31 | create_non_fungible_token(); 32 | assert_ok!(Marketplace::create_order( 33 | Origin::signed(ALICE), 34 | Asset::NonFungibleToken(1, 2), 35 | 100 * W3G, 36 | 100 * BLOCK 37 | )); 38 | assert_eq!( 39 | Marketplace::orders(Asset::NonFungibleToken(1, 2)), 40 | Some(Order { 41 | creater: ALICE, 42 | price: 100 * W3G, 43 | start: 1 * BLOCK, 44 | duration: 100 * BLOCK 45 | }) 46 | ); 47 | 48 | assert_ok!( 49 | Marketplace::cancel_order(Origin::signed(ALICE), Asset::NonFungibleToken(1, 2),) 50 | ); 51 | }) 52 | } 53 | 54 | #[test] 55 | fn execute_order_should_work() { 56 | new_test_ext().execute_with(|| { 57 | create_non_fungible_token(); 58 | assert_ok!(Marketplace::create_order( 59 | Origin::signed(ALICE), 60 | Asset::NonFungibleToken(1, 2), 61 | 100 * W3G, 62 | 100 * BLOCK 63 | )); 64 | 65 | assert_ok!(Marketplace::execute_order(Origin::signed(BOB), Asset::NonFungibleToken(1, 2),)); 66 | }) 67 | } 68 | -------------------------------------------------------------------------------- /pallets/player-id/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-player-id" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | hex-literal = "0.3.4" 9 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 10 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 11 | log = { version = "0.4.17", default-features = false } 12 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false, optional = true } 13 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 18 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 19 | 20 | [dev-dependencies] 21 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 22 | 23 | [features] 24 | default = ["std"] 25 | std = [ 26 | "codec/std", 27 | "scale-info/std", 28 | "log/std", 29 | "frame-support/std", 30 | "frame-system/std", 31 | "sp-core/std", 32 | "sp-std/std", 33 | "sp-io/std", 34 | "sp-runtime/std", 35 | ] 36 | runtime-benchmarks = [ 37 | "frame-benchmarking", 38 | "frame-support/runtime-benchmarks", 39 | "frame-system/runtime-benchmarks", 40 | ] 41 | -------------------------------------------------------------------------------- /pallets/player-id/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | use crate::Pallet as PlayerIdModule; 7 | use frame_benchmarking::{account, benchmarks}; 8 | use frame_support::assert_ok; 9 | use frame_system::RawOrigin; 10 | use hex_literal::hex; 11 | 12 | benchmarks! { 13 | where_clause { 14 | where 15 | T::AccountId: AsRef<[u8]> 16 | } 17 | 18 | register { 19 | }: _(RawOrigin::Signed(account("alice", 0, 0)),"tester".as_bytes().to_vec(),account("alice", 0, 0)) 20 | 21 | add_address { 22 | let player_id_vec = "tester".as_bytes().to_vec(); 23 | let player_id: PlayerId = player_id_vec.clone().try_into().unwrap(); 24 | assert_ok!(PlayerIdModule::::register(RawOrigin::Signed(account("alice", 0, 0)).into(),player_id_vec,account("alice", 0, 0))); 25 | let eth_address = hex!["6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b"]; 26 | }: _(RawOrigin::Signed(account("alice", 0, 0)),player_id,Chains::ETH,eth_address.to_vec()) 27 | 28 | remove_address { 29 | let player_id_vec = "tester".as_bytes().to_vec(); 30 | let player_id: PlayerId = player_id_vec.clone().try_into().unwrap(); 31 | assert_ok!(PlayerIdModule::::register(RawOrigin::Signed(account("alice", 0, 0)).into(),player_id_vec,account("alice", 0, 0))); 32 | let eth_address = hex!["6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b"]; 33 | assert_ok!(PlayerIdModule::::add_address(RawOrigin::Signed(account("alice", 0, 0)).into(),player_id.clone(),Chains::ETH,eth_address.clone().to_vec())); 34 | }: _(RawOrigin::Signed(account("alice", 0, 0)),player_id.clone(),Chains::ETH,Address::try_from(eth_address.to_vec()).unwrap()) 35 | 36 | impl_benchmark_test_suite!(PlayerIdModule, crate::mock::new_test_ext(), crate::mock::Test); 37 | } 38 | -------------------------------------------------------------------------------- /pallets/player-id/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use super::*; 20 | use crate as pallet_palyer_id; 21 | use frame_support::{ 22 | construct_runtime, parameter_types, 23 | traits::{ConstU16, ConstU64}, 24 | }; 25 | use sp_core::H256; 26 | use sp_runtime::{ 27 | testing::Header, 28 | traits::{BlakeTwo256, IdentityLookup}, 29 | AccountId32, 30 | }; 31 | 32 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 33 | type Block = frame_system::mocking::MockBlock; 34 | 35 | pub type Balance = u128; 36 | 37 | pub const MILLICENTS: Balance = 10_000_000_000_000; 38 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 39 | pub const DOLLARS: Balance = 100 * CENTS; 40 | 41 | pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); 42 | pub const BOB: AccountId32 = AccountId32::new([2u8; 32]); 43 | 44 | construct_runtime!( 45 | pub enum Test where 46 | Block = Block, 47 | NodeBlock = Block, 48 | UncheckedExtrinsic = UncheckedExtrinsic, 49 | { 50 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 51 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 52 | PlayerIdModule: pallet_palyer_id::{Pallet, Call, Storage, Event}, 53 | } 54 | ); 55 | 56 | impl frame_system::Config for Test { 57 | type BaseCallFilter = frame_support::traits::Everything; 58 | type BlockWeights = (); 59 | type BlockLength = (); 60 | type DbWeight = (); 61 | type Origin = Origin; 62 | type Call = Call; 63 | type Index = u64; 64 | type BlockNumber = u64; 65 | type Hash = H256; 66 | type Hashing = BlakeTwo256; 67 | type AccountId = AccountId32; 68 | type Lookup = IdentityLookup; 69 | type Header = Header; 70 | type Event = Event; 71 | type BlockHashCount = ConstU64<250>; 72 | type Version = (); 73 | type PalletInfo = PalletInfo; 74 | type AccountData = pallet_balances::AccountData; 75 | type OnNewAccount = (); 76 | type OnKilledAccount = (); 77 | type SystemWeightInfo = (); 78 | type SS58Prefix = ConstU16<42>; 79 | type OnSetCode = (); 80 | type MaxConsumers = frame_support::traits::ConstU32<16>; 81 | } 82 | 83 | parameter_types! { 84 | pub const ExistentialDeposit: Balance = 1; 85 | } 86 | 87 | impl pallet_balances::Config for Test { 88 | type Balance = Balance; 89 | type DustRemoval = (); 90 | type Event = Event; 91 | type ExistentialDeposit = ExistentialDeposit; 92 | type AccountStore = System; 93 | type WeightInfo = (); 94 | type MaxLocks = (); 95 | type MaxReserves = (); 96 | type ReserveIdentifier = [u8; 8]; 97 | } 98 | 99 | parameter_types! { 100 | pub const MaxAddressesPerChain: u32 = 10; 101 | } 102 | 103 | impl pallet_palyer_id::Config for Test { 104 | type Event = Event; 105 | type MaxAddressesPerChain = MaxAddressesPerChain; 106 | type WeightInfo = (); 107 | } 108 | 109 | // Build genesis storage according to the mock runtime. 110 | pub fn new_test_ext() -> sp_io::TestExternalities { 111 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 112 | pallet_balances::GenesisConfig:: { 113 | balances: vec![(ALICE, 100 * DOLLARS), (BOB, 100 * DOLLARS)], 114 | } 115 | .assimilate_storage(&mut t) 116 | .unwrap(); 117 | t.into() 118 | } 119 | -------------------------------------------------------------------------------- /pallets/player-id/src/tests.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use super::*; 20 | use crate::mock::*; 21 | use frame_support::assert_ok; 22 | use hex_literal::hex; 23 | 24 | #[test] 25 | fn test_register_works() { 26 | new_test_ext().execute_with(|| { 27 | let address: Address = PlayerIdModule::account_to_address(ALICE); 28 | let player_id_vec = "tester".as_bytes().to_vec(); 29 | let player_id: PlayerId = player_id_vec.clone().try_into().unwrap(); 30 | 31 | let addresses: BoundedVec> = 32 | BoundedVec::try_from(vec![address.clone()]).unwrap(); 33 | 34 | assert_ok!(PlayerIdModule::register(Origin::signed(ALICE), player_id_vec, ALICE)); 35 | 36 | assert_eq!(PlayerIdOf::::get(address.clone(), Chains::W3G).unwrap(), player_id); 37 | assert_eq!(Addresses::::get(player_id.clone(), Chains::W3G).unwrap(), addresses); 38 | 39 | let eth_address = hex!["6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b"]; 40 | assert_ok!(PlayerIdModule::add_address( 41 | Origin::signed(ALICE), 42 | player_id.clone(), 43 | Chains::ETH, 44 | eth_address.clone().to_vec() 45 | )); 46 | 47 | assert_ok!(PlayerIdModule::remove_address( 48 | Origin::signed(ALICE), 49 | player_id, 50 | Chains::ETH, 51 | Address::try_from(eth_address.to_vec()).unwrap() 52 | )); 53 | }); 54 | } 55 | -------------------------------------------------------------------------------- /pallets/player-id/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for web3games_player_id 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 22 | //! DATE: 2022-12-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // target/release/web3games-node 27 | // benchmark 28 | // pallet 29 | // --chain=dev 30 | // --steps=50 31 | // --repeat=20 32 | // --pallet=web3games_player_id 33 | // --extrinsic=* 34 | // --execution=wasm 35 | // --wasm-execution=compiled 36 | // --output=./pallets/player-id/src/weights.rs 37 | // --template=./.maintain/w3g-weight-template.hbs 38 | 39 | #![cfg_attr(rustfmt, rustfmt_skip)] 40 | #![allow(unused_parens)] 41 | #![allow(unused_imports)] 42 | #![allow(clippy::unnecessary_cast)] 43 | 44 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 45 | use sp_std::marker::PhantomData; 46 | 47 | /// Weight functions needed for web3games_player_id. 48 | pub trait WeightInfo { 49 | fn register() -> Weight; 50 | fn add_address() -> Weight; 51 | fn remove_address() -> Weight; 52 | } 53 | 54 | /// Weights for web3games_player_id using the Web3Games node and recommended hardware. 55 | pub struct W3GWeight(PhantomData); 56 | impl WeightInfo for W3GWeight { 57 | // Storage: PlayerId Addresses (r:1 w:1) 58 | // Storage: PlayerId PlayerIdOf (r:0 w:1) 59 | fn register() -> Weight { 60 | (18_000_000 as Weight) 61 | .saturating_add(T::DbWeight::get().reads(1 as Weight)) 62 | .saturating_add(T::DbWeight::get().writes(2 as Weight)) 63 | } 64 | // Storage: PlayerId Addresses (r:2 w:1) 65 | // Storage: PlayerId PlayerIdOf (r:0 w:1) 66 | fn add_address() -> Weight { 67 | (21_000_000 as Weight) 68 | .saturating_add(T::DbWeight::get().reads(2 as Weight)) 69 | .saturating_add(T::DbWeight::get().writes(2 as Weight)) 70 | } 71 | // Storage: PlayerId Addresses (r:2 w:1) 72 | // Storage: PlayerId PlayerIdOf (r:0 w:1) 73 | fn remove_address() -> Weight { 74 | (22_000_000 as Weight) 75 | .saturating_add(T::DbWeight::get().reads(2 as Weight)) 76 | .saturating_add(T::DbWeight::get().writes(2 as Weight)) 77 | } 78 | } 79 | 80 | // For backwards compatibility and tests 81 | impl WeightInfo for () { 82 | fn register() -> Weight { 83 | (18_000_000 as Weight) 84 | .saturating_add(RocksDbWeight::get().reads(1 as Weight)) 85 | .saturating_add(RocksDbWeight::get().writes(2 as Weight)) 86 | } 87 | fn add_address() -> Weight { 88 | (21_000_000 as Weight) 89 | .saturating_add(RocksDbWeight::get().reads(2 as Weight)) 90 | .saturating_add(RocksDbWeight::get().writes(2 as Weight)) 91 | } 92 | fn remove_address() -> Weight { 93 | (22_000_000 as Weight) 94 | .saturating_add(RocksDbWeight::get().reads(2 as Weight)) 95 | .saturating_add(RocksDbWeight::get().writes(2 as Weight)) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /pallets/proxy-pay/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-proxy-pay" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ 9 | "derive", 10 | ] } 11 | scale-info = { version = "2.1.2", default-features = false, features = [ 12 | "derive", 13 | ] } 14 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 15 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 16 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 17 | pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 18 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 19 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 20 | primitives = { path = "../../primitives", default-features = false } 21 | 22 | 23 | [dev-dependencies] 24 | balances = { package = "pallet-balances", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 25 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 26 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 27 | smallvec = "1.9.0" 28 | 29 | [features] 30 | default = ["std"] 31 | std = [ 32 | "codec/std", 33 | "scale-info/std", 34 | "frame-support/std", 35 | "frame-system/std", 36 | "primitives/std", 37 | "sp-runtime/std", 38 | "sp-std/std", 39 | "pallet-transaction-payment/std", 40 | ] 41 | 42 | runtime-benchmarks = [ 43 | "frame-benchmarking", 44 | "frame-support/runtime-benchmarks", 45 | "frame-system/runtime-benchmarks", 46 | ] 47 | -------------------------------------------------------------------------------- /pallets/support/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-support" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | log = { version = "0.4.17", default-features = false } 11 | frame-support = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 12 | frame-system = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | sp-io = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-runtime = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-core = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | sp-std = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | 18 | primitives = {path = "../../primitives", default-features = false } 19 | 20 | [features] 21 | default = ["std"] 22 | std = [ 23 | "codec/std", 24 | "scale-info/std", 25 | "log/std", 26 | "frame-support/std", 27 | "frame-system/std", 28 | "sp-std/std", 29 | "sp-io/std", 30 | "sp-runtime/std", 31 | "primitives/std", 32 | "sp-core/std", 33 | ] 34 | -------------------------------------------------------------------------------- /pallets/support/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | use primitives::TokenIndex; 22 | use sp_core::H160; 23 | use sp_std::prelude::*; 24 | 25 | /// This trait ensure we can convert EVM Address to FungibleTokenId, 26 | /// NonFungibleTokenId, or MultiTokenId. 27 | /// We will require each mod to have this trait implemented 28 | pub trait TokenIdConversion { 29 | /// Try to convert an evm address into token ID. Might not succeed. 30 | fn try_from_address(address: H160) -> Option; 31 | /// Convert into an evm address. This is infallible. 32 | fn into_address(id: A) -> H160; 33 | } 34 | 35 | pub trait AccountMapping { 36 | /// Convert account ID into an evm address. 37 | fn into_evm_address(account: A) -> H160; 38 | } 39 | 40 | pub trait FungibleMetadata { 41 | type FungibleTokenId; 42 | 43 | fn token_name(id: Self::FungibleTokenId) -> Vec; 44 | fn token_symbol(id: Self::FungibleTokenId) -> Vec; 45 | fn token_decimals(id: Self::FungibleTokenId) -> u8; 46 | } 47 | 48 | pub trait NonFungibleMetadata { 49 | type NonFungibleTokenId; 50 | type TokenId; 51 | 52 | fn token_name(id: Self::NonFungibleTokenId) -> Vec; 53 | fn token_symbol(id: Self::NonFungibleTokenId) -> Vec; 54 | fn token_uri(id: Self::NonFungibleTokenId, token_id: Self::TokenId) -> Vec; 55 | } 56 | 57 | pub trait NonFungibleEnumerable { 58 | type NonFungibleTokenId; 59 | type TokenId; 60 | 61 | fn total_supply(id: Self::NonFungibleTokenId) -> u32; 62 | fn token_by_index(id: Self::NonFungibleTokenId, index: TokenIndex) -> Self::TokenId; 63 | fn token_of_owner_by_index( 64 | id: Self::NonFungibleTokenId, 65 | owner: AccountId, 66 | index: TokenIndex, 67 | ) -> Self::TokenId; 68 | } 69 | 70 | pub trait MultiMetadata { 71 | type MultiTokenId; 72 | type TokenId; 73 | 74 | fn uri(id: Self::MultiTokenId, token_id: Self::TokenId) -> Vec; 75 | } 76 | -------------------------------------------------------------------------------- /pallets/token-fungible/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-token-fungible" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | serde = { version = "1.0.137", optional = true } 11 | log = { version = "0.4.17", default-features = false } 12 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | 17 | # FRAME library 18 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.26" } 19 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 20 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 21 | 22 | primitives = {path = "../../primitives", default-features = false } 23 | web3games-support = { path = "../support", default-features = false } 24 | 25 | [dev-dependencies] 26 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "serde/std", 32 | "codec/std", 33 | "scale-info/std", 34 | "log/std", 35 | "sp-std/std", 36 | "sp-io/std", 37 | "sp-runtime/std", 38 | "primitives/std", 39 | "sp-core/std", 40 | "web3games-support/std", 41 | "frame-support/std", 42 | "frame-system/std", 43 | "frame-benchmarking/std", 44 | ] 45 | runtime-benchmarks = ["frame-benchmarking"] 46 | -------------------------------------------------------------------------------- /pallets/token-fungible/README.md: -------------------------------------------------------------------------------- 1 | # web3games-token-fungible 2 | 3 | ## call 4 | 5 | ### create_token 6 | 7 | ### approve 8 | 9 | ### transfer 10 | 11 | ### transfer_from 12 | 13 | ### mint 14 | 15 | ### burn 16 | 17 | ## storage 18 | 19 | ### Allowances 20 | 21 | FungibleTokenId<===>(T::AccountId, T::AccountId) ===>Balance 22 | 23 | Query the authorized balance 24 | 25 | ```rust 26 | #[pallet::storage] 27 | #[pallet::getter(fn allowances)] 28 | pub(super) type Allowances = StorageDoubleMap< 29 | _, 30 | Blake2_128Concat, 31 | T::FungibleTokenId, 32 | Blake2_128Concat, 33 | // (owner, operator) 34 | (T::AccountId, T::AccountId), 35 | Balance, 36 | ValueQuery, 37 | >; 38 | ``` 39 | 40 | ### Balances 41 | 42 | FungibleTokenId<===>T::AccountId ===>Balance 43 | 44 | Query account balance 45 | 46 | ```rust 47 | #[pallet::storage] 48 | #[pallet::getter(fn balance_of)] 49 | pub(super) type Balances = StorageDoubleMap< 50 | _, 51 | Blake2_128Concat, 52 | T::FungibleTokenId, 53 | Blake2_128Concat, 54 | T::AccountId, 55 | Balance, 56 | ValueQuery, 57 | >; 58 | ``` 59 | 60 | ### Tokens 61 | 62 | FungibleTokenId ===> Token 63 | 64 | Query token info 65 | 66 | ```rust 67 | #[pallet::storage] 68 | pub(super) type Tokens = StorageMap< 69 | _, 70 | Blake2_128Concat, 71 | T::FungibleTokenId, 72 | Token>, 73 | >; 74 | ``` 75 | 76 | ```rust 77 | #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] 78 | pub struct Token { 79 | owner: AccountId, 80 | name: BoundedString, 81 | symbol: BoundedString, 82 | decimals: u8, 83 | total_supply: Balance, 84 | } 85 | ``` 86 | 87 | -------------------------------------------------------------------------------- /pallets/token-fungible/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | 7 | #[allow(unused)] 8 | use crate::Pallet as TokenFungible; 9 | use codec::alloc::string::ToString; 10 | use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; 11 | use frame_system::RawOrigin; 12 | 13 | const SEED: u32 = 0; 14 | 15 | benchmarks! { 16 | create_token { 17 | let alice: T::AccountId = account("alice", 0, SEED); 18 | }: _(RawOrigin::Signed(alice), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18) 19 | 20 | mint { 21 | let alice: T::AccountId = account("alice", 0, SEED); 22 | let bob: T::AccountId = account("bob", 0, SEED); 23 | 24 | // let recipient: T::AccountId = account("recipient", 0, SEED); 25 | let _ = TokenFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18); 26 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), 100_000_000_000_000u128) 27 | 28 | approve { 29 | let alice: T::AccountId = account("alice", 0, SEED); 30 | let bob: T::AccountId = account("bob", 0, SEED); 31 | 32 | let _ = TokenFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18); 33 | let _ = TokenFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 100_000_000_000_000u128); 34 | }: _(RawOrigin::Signed(alice), 1u32.into(), bob, 100_000_000_000u128) 35 | 36 | burn { 37 | let alice: T::AccountId = account("alice", 0, SEED); 38 | let bob: T::AccountId = account("bob", 0, SEED); 39 | 40 | let _ = TokenFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18); 41 | let _ = TokenFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 100_000_000_000_000u128); 42 | }: _(RawOrigin::Signed(alice), 1u32.into(), 100_000_000_000_000u128) 43 | 44 | transfer { 45 | let alice: T::AccountId = account("alice", 0, SEED); 46 | let bob: T::AccountId = account("bob", 0, SEED); 47 | 48 | let _ = TokenFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18); 49 | let _ = TokenFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 100_000_000_000_000u128); 50 | }: _(RawOrigin::Signed(alice), 1u32.into(), bob, 100_000_000_000u128) 51 | 52 | transfer_from { 53 | let alice: T::AccountId = account("alice", 0, SEED); 54 | let bob: T::AccountId = account("bob", 0, SEED); 55 | let charlie: T::AccountId = account("charlie", 0, SEED); 56 | 57 | let _ = TokenFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), "TestToken".to_string().into(), "TK".to_string().into(), 18); 58 | let _ = TokenFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 100_000_000_000_000u128); 59 | let _ = TokenFungible::::approve(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), charlie.clone(), 100_000_000_000_000u128); 60 | }: _(RawOrigin::Signed(charlie), 1u32.into(), alice, bob, 100_000_000_000u128) 61 | } 62 | 63 | impl_benchmark_test_suite!(TokenFungible, crate::mock::new_test_ext(), crate::mock::Test,); 64 | -------------------------------------------------------------------------------- /pallets/token-fungible/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use crate as web3games_token_fungible; 20 | use frame_support::{ 21 | construct_runtime, parameter_types, 22 | traits::{ConstU16, ConstU64}, 23 | PalletId, 24 | }; 25 | pub use pallet_balances::Error as BalancesError; 26 | use primitives::Balance; 27 | use sp_core::H256; 28 | use sp_runtime::{ 29 | testing::Header, 30 | traits::{BlakeTwo256, IdentityLookup}, 31 | }; 32 | pub use web3games_token_fungible::{Error, Event as TokenFungibleEvent, Token}; 33 | 34 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 35 | type Block = frame_system::mocking::MockBlock; 36 | 37 | pub const MILLICENTS: Balance = 10_000_000_000_000; 38 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 39 | pub const DOLLARS: Balance = 100 * CENTS; 40 | 41 | construct_runtime!( 42 | pub enum Test where 43 | Block = Block, 44 | NodeBlock = Block, 45 | UncheckedExtrinsic = UncheckedExtrinsic, 46 | { 47 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 48 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 49 | TokenFungible: web3games_token_fungible::{Pallet, Call, Storage, Config, Event}, 50 | } 51 | ); 52 | 53 | impl frame_system::Config for Test { 54 | type BaseCallFilter = frame_support::traits::Everything; 55 | type BlockWeights = (); 56 | type BlockLength = (); 57 | type DbWeight = (); 58 | type Origin = Origin; 59 | type Call = Call; 60 | type Index = u64; 61 | type BlockNumber = u64; 62 | type Hash = H256; 63 | type Hashing = BlakeTwo256; 64 | type AccountId = u64; 65 | type Lookup = IdentityLookup; 66 | type Header = Header; 67 | type Event = Event; 68 | type BlockHashCount = ConstU64<250>; 69 | type Version = (); 70 | type PalletInfo = PalletInfo; 71 | type AccountData = pallet_balances::AccountData; 72 | type OnNewAccount = (); 73 | type OnKilledAccount = (); 74 | type SystemWeightInfo = (); 75 | type SS58Prefix = ConstU16<42>; 76 | type OnSetCode = (); 77 | type MaxConsumers = frame_support::traits::ConstU32<16>; 78 | } 79 | 80 | parameter_types! { 81 | pub const ExistentialDeposit: Balance = 1; 82 | } 83 | 84 | impl pallet_balances::Config for Test { 85 | type Balance = Balance; 86 | type DustRemoval = (); 87 | type Event = Event; 88 | type ExistentialDeposit = ExistentialDeposit; 89 | type AccountStore = System; 90 | type WeightInfo = (); 91 | type MaxLocks = (); 92 | type MaxReserves = (); 93 | type ReserveIdentifier = [u8; 8]; 94 | } 95 | 96 | parameter_types! { 97 | pub const TokenFungiblePalletId: PalletId = PalletId(*b"w3g/tfpi"); 98 | pub const StringLimit: u32 = 50; 99 | pub const CreateTokenDeposit: Balance = 500 * MILLICENTS; 100 | } 101 | 102 | impl web3games_token_fungible::Config for Test { 103 | type Event = Event; 104 | type PalletId = TokenFungiblePalletId; 105 | type FungibleTokenId = u32; 106 | type StringLimit = StringLimit; 107 | type CreateTokenDeposit = CreateTokenDeposit; 108 | type Currency = Balances; 109 | type WeightInfo = (); 110 | } 111 | 112 | // Build genesis storage according to the mock runtime. 113 | pub fn new_test_ext() -> sp_io::TestExternalities { 114 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 115 | pallet_balances::GenesisConfig:: { 116 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 117 | } 118 | .assimilate_storage(&mut t) 119 | .unwrap(); 120 | let mut ext = sp_io::TestExternalities::new(t); 121 | ext.execute_with(|| System::set_block_number(1)); 122 | ext 123 | } 124 | -------------------------------------------------------------------------------- /pallets/token-multi/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-token-multi" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | serde = { version = "1.0.137", optional = true } 11 | 12 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | 17 | # FRAME library 18 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.26" } 19 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 20 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 21 | 22 | primitives = {path = "../../primitives", default-features = false } 23 | web3games-support = { path = "../support", default-features = false } 24 | 25 | [dev-dependencies] 26 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "serde/std", 32 | "codec/std", 33 | "scale-info/std", 34 | "frame-support/std", 35 | "frame-system/std", 36 | "sp-io/std", 37 | "sp-runtime/std", 38 | "sp-core/std", 39 | "sp-std/std", 40 | "primitives/std", 41 | "web3games-support/std", 42 | "frame-benchmarking/std", 43 | ] 44 | runtime-benchmarks = ["frame-benchmarking"] 45 | -------------------------------------------------------------------------------- /pallets/token-multi/README.md: -------------------------------------------------------------------------------- 1 | # web3games-token-multi-fungible 2 | 3 | ## call 4 | 5 | ### create_token 6 | 7 | ### set_approve_for_all 8 | 9 | ### transfer_from 10 | 11 | ### batch_transfer_from 12 | 13 | ### mint 14 | 15 | ### mint_batch 16 | 17 | ### burn 18 | 19 | ### burn_batch 20 | 21 | ## storage 22 | 23 | ### Balances 24 | 25 | MultiTokenId<===>(T::TokenId, T::AccountId) ===> Balance 26 | 27 | Query balance based on NonFungibleTokenId 28 | 29 | ```rust 30 | #[pallet::storage] 31 | #[pallet::getter(fn balance_of)] 32 | pub(super) type Balances = StorageDoubleMap< 33 | _, 34 | Blake2_128Concat, 35 | T::MultiTokenId, 36 | Blake2_128Concat, 37 | (T::TokenId, T::AccountId), 38 | Balance, 39 | ValueQuery, 40 | >; 41 | ``` 42 | 43 | ### OperatorApprovals 44 | 45 | MultiTokenId<===>(T::AccountId, T::AccountId) ===> bool 46 | 47 | Query if it is an operator based on NonFungibleTokenId 48 | 49 | ```rust 50 | #[pallet::storage] 51 | #[pallet::getter(fn is_approved_for_all)] 52 | pub(super) type OperatorApprovals = StorageDoubleMap< 53 | _, 54 | Blake2_128Concat, 55 | T::MultiTokenId, 56 | Blake2_128Concat, 57 | // (owner, operator) 58 | (T::AccountId, T::AccountId), 59 | bool, 60 | ValueQuery, 61 | >; 62 | ``` 63 | 64 | ### Tokens 65 | 66 | NonFungibleTokenId ===> Token 67 | 68 | Query token info 69 | 70 | ```rust 71 | #[pallet::storage] 72 | pub(super) type Tokens = StorageMap< 73 | _, 74 | Blake2_128Concat, 75 | T::MultiTokenId, 76 | Token>, 77 | >; 78 | ``` 79 | 80 | ```rust 81 | #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] 82 | pub struct Token { 83 | owner: AccountId, 84 | uri: BoundedString, 85 | total_supply: Balance, 86 | } 87 | ``` 88 | -------------------------------------------------------------------------------- /pallets/token-multi/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | 7 | use crate::Pallet as TokenMulti; 8 | use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; 9 | use frame_system::RawOrigin; 10 | 11 | const SEED: u32 = 0; 12 | 13 | benchmarks! { 14 | create_token { 15 | let alice: T::AccountId = account("alice", 0, SEED); 16 | }: _(RawOrigin::Signed(alice), 1u32.into(), vec![0u8; 20]) 17 | 18 | mint { 19 | let alice: T::AccountId = account("alice", 0, SEED); 20 | 21 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 22 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), 1u32.into(), 10u128) 23 | 24 | mint_batch { 25 | let alice: T::AccountId = account("alice", 0, SEED); 26 | 27 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 28 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), vec![1u32.into(), 2u32.into(), 3u32.into(), 4u32.into(), 5u32.into()], vec![10u128; 5]) 29 | 30 | set_approval_for_all { 31 | let alice: T::AccountId = account("alice", 0, SEED); 32 | let bob: T::AccountId = account("bob", 0, SEED); 33 | 34 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 35 | let _ = TokenMulti::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into(), 10u128); 36 | }: _(RawOrigin::Signed(alice), 1u32.into(), bob, true) 37 | 38 | burn { 39 | let alice: T::AccountId = account("alice", 0, SEED); 40 | 41 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 42 | let _ = TokenMulti::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into(), 10u128); 43 | }: _(RawOrigin::Signed(alice), 1u32.into(), 1u32.into(), 5u128) 44 | 45 | burn_batch { 46 | let alice: T::AccountId = account("alice", 0, SEED); 47 | 48 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 49 | let _ = TokenMulti::::mint_batch(::Origin::from(RawOrigin::Signed(alice.clone())),1u32.into(), alice.clone(), vec![1u32.into(), 2u32.into(), 3u32.into(), 4u32.into(), 5u32.into()], vec![10u128; 5]); 50 | }: _(RawOrigin::Signed(alice), 1u32.into(), vec![1u32.into(), 2u32.into(), 3u32.into(), 4u32.into(), 5u32.into()], vec![5u128; 5]) 51 | 52 | transfer_from { 53 | let alice: T::AccountId = account("alice", 0, SEED); 54 | let bob: T::AccountId = account("bob", 0, SEED); 55 | 56 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 57 | let _ = TokenMulti::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into(), 10u128); 58 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), bob.clone(), 1u32.into(), 5u128) 59 | 60 | batch_transfer_from { 61 | let alice: T::AccountId = account("alice", 0, SEED); 62 | let bob: T::AccountId = account("bob", 0, SEED); 63 | 64 | let _ = TokenMulti::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 20]); 65 | let _ = TokenMulti::::mint_batch(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), vec![1u32.into(), 2u32.into(), 3u32.into(), 4u32.into(), 5u32.into()], vec![10u128; 5]); 66 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), bob.clone(), vec![1u32.into(), 2u32.into(), 3u32.into(), 4u32.into(), 5u32.into()], vec![5u128; 5]) 67 | } 68 | 69 | impl_benchmark_test_suite!(TokenMulti, crate::mock::new_test_ext(), crate::mock::Test,); 70 | -------------------------------------------------------------------------------- /pallets/token-multi/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use crate as web3games_token_multi; 20 | use frame_support::{ 21 | construct_runtime, parameter_types, 22 | traits::{ConstU16, ConstU64}, 23 | PalletId, 24 | }; 25 | use primitives::Balance; 26 | use sp_core::H256; 27 | use sp_runtime::{ 28 | testing::Header, 29 | traits::{BlakeTwo256, IdentityLookup}, 30 | }; 31 | 32 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 33 | type Block = frame_system::mocking::MockBlock; 34 | 35 | pub const MILLICENTS: Balance = 10_000_000_000_000; 36 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 37 | pub const DOLLARS: Balance = 100 * CENTS; 38 | 39 | // Configure a mock runtime to test the pallet. 40 | construct_runtime!( 41 | pub enum Test where 42 | Block = Block, 43 | NodeBlock = Block, 44 | UncheckedExtrinsic = UncheckedExtrinsic, 45 | { 46 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 47 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 48 | TokenMulti: web3games_token_multi::{Pallet, Call, Storage, Event}, 49 | } 50 | ); 51 | 52 | impl frame_system::Config for Test { 53 | type BaseCallFilter = frame_support::traits::Everything; 54 | type BlockWeights = (); 55 | type BlockLength = (); 56 | type DbWeight = (); 57 | type Origin = Origin; 58 | type Call = Call; 59 | type Index = u64; 60 | type BlockNumber = u64; 61 | type Hash = H256; 62 | type Hashing = BlakeTwo256; 63 | type AccountId = u64; 64 | type Lookup = IdentityLookup; 65 | type Header = Header; 66 | type Event = Event; 67 | type BlockHashCount = ConstU64<250>; 68 | type Version = (); 69 | type PalletInfo = PalletInfo; 70 | type AccountData = pallet_balances::AccountData; 71 | type OnNewAccount = (); 72 | type OnKilledAccount = (); 73 | type SystemWeightInfo = (); 74 | type SS58Prefix = ConstU16<42>; 75 | type OnSetCode = (); 76 | type MaxConsumers = frame_support::traits::ConstU32<16>; 77 | } 78 | 79 | parameter_types! { 80 | pub const ExistentialDeposit: Balance = 1; 81 | } 82 | 83 | impl pallet_balances::Config for Test { 84 | type Balance = Balance; 85 | type DustRemoval = (); 86 | type Event = Event; 87 | type ExistentialDeposit = ExistentialDeposit; 88 | type AccountStore = System; 89 | type WeightInfo = (); 90 | type MaxLocks = (); 91 | type MaxReserves = (); 92 | type ReserveIdentifier = [u8; 8]; 93 | } 94 | 95 | parameter_types! { 96 | pub const TokenMultiPalletId: PalletId = PalletId(*b"w3g/tmpi"); 97 | pub const StringLimit: u32 = 50; 98 | pub const CreateTokenDeposit: Balance = 500 * MILLICENTS; 99 | } 100 | 101 | impl web3games_token_multi::Config for Test { 102 | type Event = Event; 103 | type PalletId = TokenMultiPalletId; 104 | type MultiTokenId = u32; 105 | type TokenId = u128; 106 | type StringLimit = StringLimit; 107 | type CreateTokenDeposit = CreateTokenDeposit; 108 | type Currency = Balances; 109 | type WeightInfo = (); 110 | } 111 | 112 | pub fn new_test_ext() -> sp_io::TestExternalities { 113 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 114 | pallet_balances::GenesisConfig:: { 115 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 116 | } 117 | .assimilate_storage(&mut t) 118 | .unwrap(); 119 | t.into() 120 | } 121 | -------------------------------------------------------------------------------- /pallets/token-non-fungible/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-token-non-fungible" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | serde = { version = "1.0.137", optional = true } 11 | log = { version = "0.4.17", default-features = false } 12 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | 17 | # FRAME library 18 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.26" } 19 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 20 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 21 | 22 | primitives = {path = "../../primitives", default-features = false } 23 | web3games-support = { path = "../support", default-features = false } 24 | 25 | [dev-dependencies] 26 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "serde/std", 32 | "codec/std", 33 | "scale-info/std", 34 | "log/std", 35 | "frame-support/std", 36 | "frame-system/std", 37 | "sp-io/std", 38 | "sp-runtime/std", 39 | "sp-core/std", 40 | "sp-std/std", 41 | "primitives/std", 42 | "web3games-support/std", 43 | "frame-benchmarking/std", 44 | ] 45 | runtime-benchmarks = ["frame-benchmarking"] 46 | -------------------------------------------------------------------------------- /pallets/token-non-fungible/README.md: -------------------------------------------------------------------------------- 1 | # web3games-token-non-fungible 2 | 3 | ## call 4 | 5 | ### create_token 6 | 7 | ### approve 8 | 9 | ### set_approve_for_all 10 | 11 | ### transfer_from 12 | 13 | ### mint 14 | 15 | ### burn 16 | 17 | ## storage 18 | 19 | ### AllTokens 20 | 21 | NonFungibleTokenId<===>TokenIndex ===>TokenId 22 | 23 | Query TokenId based on TokenIndex 24 | 25 | ```rust 26 | #[pallet::storage] 27 | pub(super) type AllTokens = StorageDoubleMap< 28 | _, 29 | Blake2_128Concat, 30 | T::NonFungibleTokenId, 31 | Blake2_128Concat, 32 | TokenIndex, 33 | T::TokenId, 34 | ValueQuery, 35 | >; 36 | ``` 37 | 38 | ### AllTokensIndex 39 | 40 | NonFungibleTokenId<===>TokenId ===> TokenIndex 41 | 42 | Query TokenIndex based on TokenId 43 | 44 | ```rust 45 | #[pallet::storage] 46 | pub(super) type AllTokensIndex = StorageDoubleMap< 47 | _, 48 | Blake2_128Concat, 49 | T::NonFungibleTokenId, 50 | Blake2_128Concat, 51 | T::TokenId, 52 | TokenIndex, 53 | ValueQuery, 54 | >; 55 | ``` 56 | 57 | ### Balances 58 | 59 | NonFungibleTokenId<===>AccountId ===> u32 60 | 61 | Query balance based on NonFungibleTokenId 62 | 63 | ```rust 64 | #[pallet::storage] 65 | #[pallet::getter(fn balance_of)] 66 | pub(super) type Balances = StorageDoubleMap< 67 | _, 68 | Blake2_128Concat, 69 | T::NonFungibleTokenId, 70 | Blake2_128Concat, 71 | T::AccountId, 72 | u32, 73 | ValueQuery, 74 | >; 75 | ``` 76 | 77 | ### OperatorApprovals 78 | 79 | NonFungibleTokenId<===>(T::AccountId, T::AccountId) ===> bool 80 | 81 | Query if it is an operator based on NonFungibleTokenId 82 | 83 | ```rust 84 | #[pallet::storage] 85 | #[pallet::getter(fn is_approved_for_all)] 86 | pub(super) type OperatorApprovals = StorageDoubleMap< 87 | _, 88 | Blake2_128Concat, 89 | T::NonFungibleTokenId, 90 | Blake2_128Concat, 91 | // (owner, operator) 92 | (T::AccountId, T::AccountId), 93 | bool, 94 | ValueQuery, 95 | >; 96 | ``` 97 | 98 | ### OwnedTokens 99 | 100 | NonFungibleTokenId<===>(T::AccountId, TokenIndex) ===> TokenId 101 | 102 | Query the user's tokenId based on TokenIndex 103 | 104 | ```rust 105 | #[pallet::storage] 106 | pub(super) type OwnedTokens = StorageDoubleMap< 107 | _, 108 | Blake2_128Concat, 109 | T::NonFungibleTokenId, 110 | Blake2_128Concat, 111 | (T::AccountId, TokenIndex), 112 | T::TokenId, 113 | ValueQuery, 114 | >; 115 | ``` 116 | 117 | ### OwnedTokensIndex 118 | 119 | NonFungibleTokenId<===>(T::AccountId, TokenId) ===> TokenIndex 120 | 121 | Query the user's TokenIndex based on TokenId 122 | 123 | ```rust 124 | #[pallet::storage] 125 | pub(super) type OwnedTokensIndex = StorageDoubleMap< 126 | _, 127 | Blake2_128Concat, 128 | T::NonFungibleTokenId, 129 | Blake2_128Concat, 130 | (T::AccountId, T::TokenId), 131 | TokenIndex, 132 | ValueQuery, 133 | >; 134 | ``` 135 | 136 | ### owners 137 | 138 | NonFungibleTokenId<===>TokenId , ===> AccountId 139 | 140 | Query the TokenId's owner 141 | 142 | ```rust 143 | #[pallet::storage] 144 | #[pallet::getter(fn owner_of)] 145 | pub(super) type Owners = StorageDoubleMap< 146 | _, 147 | Blake2_128Concat, 148 | T::NonFungibleTokenId, 149 | Blake2_128Concat, 150 | T::TokenId, 151 | T::AccountId, 152 | OptionQuery, 153 | GetDefault, 154 | ConstU32<300_000>, 155 | >; 156 | ``` 157 | 158 | ### TokenApprovals 159 | 160 | NonFungibleTokenId<===>TokenId , ===> AccountId 161 | 162 | Query the TokenId's approver 163 | 164 | ```rust 165 | #[pallet::storage] 166 | #[pallet::getter(fn get_approved)] 167 | pub(super) type TokenApprovals = StorageDoubleMap< 168 | _, 169 | Blake2_128Concat, 170 | T::NonFungibleTokenId, 171 | Blake2_128Concat, 172 | T::TokenId, 173 | T::AccountId, 174 | OptionQuery, 175 | GetDefault, 176 | ConstU32<300_000>, 177 | >; 178 | ``` 179 | 180 | ### Tokens 181 | 182 | NonFungibleTokenId ===> Token 183 | 184 | Query token info 185 | 186 | ```rust 187 | #[pallet::storage] 188 | pub(super) type Tokens = StorageMap< 189 | _, 190 | Blake2_128Concat, 191 | T::NonFungibleTokenId, 192 | Token>, 193 | >; 194 | ``` 195 | 196 | ```rust 197 | #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] 198 | pub struct Token { 199 | owner: AccountId, 200 | name: BoundedString, 201 | symbol: BoundedString, 202 | base_uri: BoundedString, 203 | } 204 | ``` 205 | 206 | ### TotalSupply 207 | 208 | NonFungibleTokenId ===> u32 209 | 210 | Query token totalSupply 211 | 212 | ```rust 213 | #[pallet::storage] 214 | pub(super) type TotalSupply = 215 | StorageMap<_, Blake2_128Concat, T::NonFungibleTokenId, u32, ValueQuery>; 216 | ``` 217 | -------------------------------------------------------------------------------- /pallets/token-non-fungible/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-template 2 | 3 | #![cfg(feature = "runtime-benchmarks")] 4 | 5 | use super::*; 6 | 7 | use crate::Pallet as TokenNonFungible; 8 | use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; 9 | use frame_system::RawOrigin; 10 | 11 | const SEED: u32 = 0; 12 | 13 | benchmarks! { 14 | create_token { 15 | let alice: T::AccountId = account("alice", 0, SEED); 16 | }: _(RawOrigin::Signed(alice), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]) 17 | 18 | mint { 19 | let alice: T::AccountId = account("alice", 0, SEED); 20 | // let bob: T::AccountId = account("bob", 0, SEED); 21 | 22 | let _ = TokenNonFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]); 23 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), 1u32.into()) 24 | 25 | burn { 26 | let alice: T::AccountId = account("alice", 0, SEED); 27 | 28 | let _ = TokenNonFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]); 29 | let _ = TokenNonFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into()); 30 | }: _(RawOrigin::Signed(alice), 1u32.into(), 1u32.into()) 31 | 32 | approve { 33 | let alice: T::AccountId = account("alice", 0, SEED); 34 | let bob: T::AccountId = account("bob", 0, SEED); 35 | 36 | let _ = TokenNonFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]); 37 | let _ = TokenNonFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into()); 38 | }: _(RawOrigin::Signed(alice), 1u32.into(), bob, 1u32.into()) 39 | 40 | set_approve_for_all { 41 | let alice: T::AccountId = account("alice", 0, SEED); 42 | let bob: T::AccountId = account("bob", 0, SEED); 43 | 44 | let _ = TokenNonFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]); 45 | let _ = TokenNonFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into()); 46 | }: _(RawOrigin::Signed(alice), 1u32.into(), bob, true) 47 | 48 | transfer_from { 49 | let alice: T::AccountId = account("alice", 0, SEED); 50 | let bob: T::AccountId = account("bob", 0, SEED); 51 | 52 | let _ = TokenNonFungible::::create_token(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), vec![0u8; 10], vec![0u8; 10], vec![0u8; 20]); 53 | let _ = TokenNonFungible::::mint(::Origin::from(RawOrigin::Signed(alice.clone())), 1u32.into(), alice.clone(), 1u32.into()); 54 | }: _(RawOrigin::Signed(alice.clone()), 1u32.into(), alice.clone(), bob, 1u32.into()) 55 | } 56 | 57 | impl_benchmark_test_suite!(TokenNonFungible, crate::mock::new_test_ext(), crate::mock::Test,); 58 | -------------------------------------------------------------------------------- /pallets/token-non-fungible/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use crate as web3games_token_non_fungible; 20 | use frame_support::{ 21 | construct_runtime, parameter_types, 22 | traits::{ConstU16, ConstU64}, 23 | PalletId, 24 | }; 25 | use primitives::Balance; 26 | use sp_core::H256; 27 | use sp_runtime::{ 28 | testing::Header, 29 | traits::{BlakeTwo256, IdentityLookup}, 30 | }; 31 | pub use web3games_token_non_fungible::{Error, Event as TokenFungibleEvent}; 32 | 33 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 34 | type Block = frame_system::mocking::MockBlock; 35 | 36 | pub const MILLICENTS: Balance = 10_000_000_000_000; 37 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 38 | pub const DOLLARS: Balance = 100 * CENTS; 39 | 40 | // Configure a mock runtime to test the pallet. 41 | construct_runtime!( 42 | pub enum Test where 43 | Block = Block, 44 | NodeBlock = Block, 45 | UncheckedExtrinsic = UncheckedExtrinsic, 46 | { 47 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 48 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 49 | TokenNonFungible: web3games_token_non_fungible::{Pallet, Call, Storage, Event}, 50 | } 51 | ); 52 | 53 | impl frame_system::Config for Test { 54 | type BaseCallFilter = frame_support::traits::Everything; 55 | type BlockWeights = (); 56 | type BlockLength = (); 57 | type DbWeight = (); 58 | type Origin = Origin; 59 | type Call = Call; 60 | type Index = u64; 61 | type BlockNumber = u64; 62 | type Hash = H256; 63 | type Hashing = BlakeTwo256; 64 | type AccountId = u64; 65 | type Lookup = IdentityLookup; 66 | type Header = Header; 67 | type Event = Event; 68 | type BlockHashCount = ConstU64<250>; 69 | type Version = (); 70 | type PalletInfo = PalletInfo; 71 | type AccountData = pallet_balances::AccountData; 72 | type OnNewAccount = (); 73 | type OnKilledAccount = (); 74 | type SystemWeightInfo = (); 75 | type SS58Prefix = ConstU16<42>; 76 | type OnSetCode = (); 77 | type MaxConsumers = frame_support::traits::ConstU32<16>; 78 | } 79 | 80 | parameter_types! { 81 | pub const ExistentialDeposit: Balance = 1; 82 | } 83 | 84 | impl pallet_balances::Config for Test { 85 | type Balance = Balance; 86 | type DustRemoval = (); 87 | type Event = Event; 88 | type ExistentialDeposit = ExistentialDeposit; 89 | type AccountStore = System; 90 | type WeightInfo = (); 91 | type MaxLocks = (); 92 | type MaxReserves = (); 93 | type ReserveIdentifier = [u8; 8]; 94 | } 95 | 96 | parameter_types! { 97 | pub const TokenNonFungiblePalletId: PalletId = PalletId(*b"w3g/tnfp"); 98 | pub const StringLimit: u32 = 50; 99 | pub const CreateTokenDeposit: Balance = 500 * MILLICENTS; 100 | } 101 | 102 | impl web3games_token_non_fungible::Config for Test { 103 | type Event = Event; 104 | type PalletId = TokenNonFungiblePalletId; 105 | type NonFungibleTokenId = u32; 106 | type TokenId = u128; 107 | type StringLimit = StringLimit; 108 | type CreateTokenDeposit = CreateTokenDeposit; 109 | type Currency = Balances; 110 | type WeightInfo = (); 111 | } 112 | 113 | // Build genesis storage according to the mock runtime. 114 | pub fn new_test_ext() -> sp_io::TestExternalities { 115 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 116 | pallet_balances::GenesisConfig:: { 117 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 118 | } 119 | .assimilate_storage(&mut t) 120 | .unwrap(); 121 | let mut ext = sp_io::TestExternalities::new(t); 122 | ext.execute_with(|| System::set_block_number(1)); 123 | ext 124 | } 125 | -------------------------------------------------------------------------------- /pallets/wrap-currency/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web3games-wrap-currency" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | serde = { version = "1.0.137", optional = true } 9 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 10 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 11 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 12 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 13 | frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false, optional = true } 14 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 15 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 16 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 17 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 18 | 19 | web3games-token-fungible = { path = "../token-fungible", default-features = false } 20 | primitives = { path = "../../primitives", default-features = false } 21 | 22 | [dev-dependencies] 23 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" } 24 | pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26"} 25 | smallvec = "1.9.0" 26 | 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "serde", 32 | "codec/std", 33 | "sp-runtime/std", 34 | "frame-support/std", 35 | "frame-system/std", 36 | "sp-io/std", 37 | "sp-std/std", 38 | "scale-info/std", 39 | "web3games-token-fungible/std", 40 | "primitives/std", 41 | ] 42 | try-runtime = ["frame-support/try-runtime"] 43 | 44 | runtime-benchmarks = [ 45 | "frame-benchmarking", 46 | "frame-support/runtime-benchmarks", 47 | "frame-system/runtime-benchmarks", 48 | ] 49 | 50 | -------------------------------------------------------------------------------- /pallets/wrap-currency/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "runtime-benchmarks")] 2 | 3 | use super::*; 4 | use crate::Pallet as WrapCurrency; 5 | use frame_benchmarking::{account, benchmarks}; 6 | use frame_support::assert_ok; 7 | use frame_system::RawOrigin; 8 | use pallet_balances::Pallet as Balances; 9 | use sp_runtime::traits::StaticLookup; 10 | 11 | const W3G_DECIMALS: u128 = 1_000_000_000_000_000_000; 12 | 13 | pub fn lookup_of_account( 14 | who: T::AccountId, 15 | ) -> <::Lookup as StaticLookup>::Source { 16 | ::Lookup::unlookup(who) 17 | } 18 | 19 | benchmarks! { 20 | where_clause { 21 | where 22 | T: Config + pallet_balances::Config 23 | } 24 | deposit { 25 | let alice: T::AccountId = account("alice", 0, 0); 26 | let bob: T::AccountId = account("bob", 0, 0); 27 | // assert_ok!(TokenFungible::::create_token( 28 | // RawOrigin::Signed(WrapCurrency::::account_id()).into(), 29 | // ::FungibleTokenId::unique_saturated_from(W3G), 30 | // b"W3G".to_vec(), 31 | // b"W3G".to_vec(), 32 | // 18 33 | // )); 34 | assert_ok!(Balances::::set_balance( 35 | RawOrigin::Root.into(), 36 | lookup_of_account::(alice.clone()), 37 | 100 * W3G_DECIMALS, 38 | 0, 39 | )); 40 | 41 | }: _(RawOrigin::Signed(alice), 10 * W3G_DECIMALS) 42 | 43 | withdraw { 44 | let alice: T::AccountId = account("alice", 0, 0); 45 | let bob: T::AccountId = account("bob", 0, 0); 46 | // assert_ok!(TokenFungible::::create_token( 47 | // RawOrigin::Signed(WrapCurrency::::account_id()).into(), 48 | // ::FungibleTokenId::unique_saturated_from(W3G), 49 | // b"W3G".to_vec(), 50 | // b"W3G".to_vec(), 51 | // 18 52 | // )); 53 | assert_ok!(Balances::::set_balance( 54 | RawOrigin::Root.into(), 55 | lookup_of_account::(alice.clone()), 56 | 100 * W3G_DECIMALS, 57 | 0, 58 | )); 59 | assert_ok!(WrapCurrency::::deposit( 60 | RawOrigin::Signed(alice.clone()).into(), 61 | 10 * W3G_DECIMALS, 62 | )); 63 | }: _(RawOrigin::Signed(alice), 5 * W3G_DECIMALS) 64 | 65 | impl_benchmark_test_suite!(WrapCurrency, crate::mock::new_test_ext(), crate::mock::Test); 66 | } 67 | -------------------------------------------------------------------------------- /pallets/wrap-currency/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | use frame_support::{ 22 | dispatch::DispatchResult, 23 | traits::{Currency, ExistenceRequirement::KeepAlive, Get}, 24 | PalletId, 25 | }; 26 | use sp_runtime::traits::{AccountIdConversion, UniqueSaturatedFrom}; 27 | 28 | use sp_std::prelude::*; 29 | 30 | pub use pallet::*; 31 | use primitives::Balance; 32 | 33 | pub mod weights; 34 | pub use weights::WeightInfo; 35 | 36 | #[cfg(feature = "runtime-benchmarks")] 37 | mod benchmarking; 38 | 39 | #[cfg(test)] 40 | mod mock; 41 | 42 | #[cfg(test)] 43 | mod tests; 44 | 45 | type BalanceOf = 46 | <::Currency as Currency<::AccountId>>::Balance; 47 | type FungibleTokenIdOf = ::FungibleTokenId; 48 | 49 | #[frame_support::pallet] 50 | pub mod pallet { 51 | use super::*; 52 | use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; 53 | use frame_system::pallet_prelude::*; 54 | 55 | #[pallet::config] 56 | pub trait Config: frame_system::Config + web3games_token_fungible::Config { 57 | type Event: From> + IsType<::Event>; 58 | // #[pallet::constant] 59 | type PalletId: Get; 60 | /// Weight information for the extrinsics in this module. 61 | type WeightInfo: WeightInfo; 62 | type Currency: Currency; 63 | #[pallet::constant] 64 | type W3GFungibleTokenId: Get>; 65 | } 66 | 67 | #[pallet::pallet] 68 | #[pallet::generate_store(pub(super) trait Store)] 69 | pub struct Pallet(_); 70 | 71 | #[pallet::event] 72 | #[pallet::generate_deposit(pub(super) fn deposit_event)] 73 | pub enum Event { 74 | Deposited(T::AccountId, Balance), 75 | Withdrawn(T::AccountId, Balance), 76 | } 77 | 78 | #[pallet::hooks] 79 | impl Hooks> for Pallet {} 80 | 81 | #[pallet::call] 82 | impl Pallet { 83 | #[pallet::weight(::WeightInfo::deposit())] 84 | pub fn deposit(origin: OriginFor, amount: Balance) -> DispatchResult { 85 | let who = ensure_signed(origin)?; 86 | Self::do_deposit(who.clone(), amount)?; 87 | Ok(()) 88 | } 89 | 90 | #[pallet::weight(::WeightInfo::withdraw())] 91 | pub fn withdraw(origin: OriginFor, amount: Balance) -> DispatchResult { 92 | let who = ensure_signed(origin)?; 93 | Self::do_withdraw(who.clone(), amount)?; 94 | Ok(()) 95 | } 96 | } 97 | } 98 | 99 | impl Pallet { 100 | pub fn account_id() -> T::AccountId { 101 | ::PalletId::get().into_account_truncating() 102 | } 103 | 104 | pub fn do_deposit(who: T::AccountId, amount: Balance) -> DispatchResult { 105 | let vault_account = Self::account_id(); 106 | 107 | ::Currency::transfer( 108 | &who, 109 | &vault_account, 110 | BalanceOf::::unique_saturated_from(amount), 111 | KeepAlive, 112 | )?; 113 | 114 | web3games_token_fungible::Pallet::::do_mint( 115 | T::W3GFungibleTokenId::get(), 116 | &vault_account, 117 | who.clone(), 118 | amount, 119 | )?; 120 | Self::deposit_event(Event::Deposited(who, amount)); 121 | Ok(()) 122 | } 123 | 124 | pub fn do_withdraw(who: T::AccountId, amount: Balance) -> DispatchResult { 125 | ::Currency::transfer( 126 | &Self::account_id(), 127 | &who, 128 | BalanceOf::::unique_saturated_from(amount), 129 | KeepAlive, 130 | )?; 131 | 132 | web3games_token_fungible::Pallet::::do_burn(T::W3GFungibleTokenId::get(), &who, amount)?; 133 | Self::deposit_event(Event::Withdrawn(who, amount)); 134 | Ok(()) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /pallets/wrap-currency/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | // 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use crate as web3games_wrap_currency; 20 | use frame_support::{ 21 | parameter_types, 22 | traits::{ConstU16, ConstU64}, 23 | PalletId, 24 | }; 25 | use primitives::Balance; 26 | use sp_core::H256; 27 | use sp_runtime::{ 28 | testing::Header, 29 | traits::{BlakeTwo256, IdentityLookup}, 30 | }; 31 | 32 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 33 | type Block = frame_system::mocking::MockBlock; 34 | 35 | pub const MILLICENTS: Balance = 10_000_000_000_000; 36 | pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent. 37 | pub const DOLLARS: Balance = 100 * CENTS; 38 | 39 | // Configure a mock runtime to test the pallet. 40 | frame_support::construct_runtime!( 41 | pub enum Test where 42 | Block = Block, 43 | NodeBlock = Block, 44 | UncheckedExtrinsic = UncheckedExtrinsic, 45 | { 46 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 47 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 48 | TokenFungible: web3games_token_fungible::{Pallet, Call, Storage, Event}, 49 | WrapCurrency: web3games_wrap_currency::{Pallet, Call, Storage, Event}, 50 | } 51 | ); 52 | 53 | impl frame_system::Config for Test { 54 | type BaseCallFilter = frame_support::traits::Everything; 55 | type BlockWeights = (); 56 | type BlockLength = (); 57 | type DbWeight = (); 58 | type Origin = Origin; 59 | type Call = Call; 60 | type Index = u64; 61 | type BlockNumber = u64; 62 | type Hash = H256; 63 | type Hashing = BlakeTwo256; 64 | type AccountId = u64; 65 | type Lookup = IdentityLookup; 66 | type Header = Header; 67 | type Event = Event; 68 | type BlockHashCount = ConstU64<250>; 69 | type Version = (); 70 | type PalletInfo = PalletInfo; 71 | type AccountData = pallet_balances::AccountData; 72 | type OnNewAccount = (); 73 | type OnKilledAccount = (); 74 | type SystemWeightInfo = (); 75 | type SS58Prefix = ConstU16<42>; 76 | type OnSetCode = (); 77 | type MaxConsumers = frame_support::traits::ConstU32<16>; 78 | } 79 | 80 | parameter_types! { 81 | pub const ExistentialDeposit: Balance = 1; 82 | } 83 | 84 | impl pallet_balances::Config for Test { 85 | type Balance = Balance; 86 | type DustRemoval = (); 87 | type Event = Event; 88 | type ExistentialDeposit = ExistentialDeposit; 89 | type AccountStore = System; 90 | type WeightInfo = (); 91 | type MaxLocks = (); 92 | type MaxReserves = (); 93 | type ReserveIdentifier = [u8; 8]; 94 | } 95 | 96 | parameter_types! { 97 | pub const TokenFungiblePalletId: PalletId = PalletId(*b"w3g/tfpi"); 98 | pub const StringLimit: u32 = 50; 99 | pub const CreateTokenDeposit: Balance = 500 * MILLICENTS; 100 | } 101 | 102 | impl web3games_token_fungible::Config for Test { 103 | type Event = Event; 104 | type PalletId = TokenFungiblePalletId; 105 | type FungibleTokenId = u128; 106 | type StringLimit = StringLimit; 107 | type CreateTokenDeposit = CreateTokenDeposit; 108 | type Currency = Balances; 109 | type WeightInfo = (); 110 | } 111 | 112 | parameter_types! { 113 | pub const WrapCurrencyPalletId: PalletId = PalletId(*b"w3g/wrap"); 114 | pub const W3GFungibleTokenId: u128 = 0; 115 | } 116 | 117 | impl web3games_wrap_currency::Config for Test { 118 | type Event = Event; 119 | type PalletId = WrapCurrencyPalletId; 120 | type WeightInfo = (); 121 | type Currency = Balances; 122 | type W3GFungibleTokenId = W3GFungibleTokenId; 123 | } 124 | 125 | // Build genesis storage according to the mock runtime. 126 | pub fn new_test_ext() -> sp_io::TestExternalities { 127 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 128 | pallet_balances::GenesisConfig:: { 129 | balances: vec![(1, 100 * DOLLARS), (2, 100 * DOLLARS)], 130 | } 131 | .assimilate_storage(&mut t) 132 | .unwrap(); 133 | 134 | let mut ext = sp_io::TestExternalities::new(t); 135 | ext.execute_with(|| System::set_block_number(1)); 136 | ext 137 | } 138 | -------------------------------------------------------------------------------- /pallets/wrap-currency/src/tests.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | // 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | pub use crate::mock::*; 20 | use frame_support::assert_ok; 21 | 22 | #[test] 23 | fn wrap_currency_tests() { 24 | new_test_ext().execute_with(|| { 25 | assert_ok!(TokenFungible::create_token( 26 | Origin::signed(WrapCurrency::account_id()), 27 | 0, 28 | b"W3G".to_vec(), 29 | b"W3G".to_vec(), 30 | 18 31 | )); 32 | assert_eq!(TokenFungible::exists(0), true); 33 | assert_ok!(WrapCurrency::deposit(Origin::signed(1), 10 * DOLLARS)); 34 | assert_eq!(Balances::free_balance(1), 100 * DOLLARS - 10 * DOLLARS); 35 | assert_eq!(TokenFungible::balance_of(0, 1), 10 * DOLLARS); 36 | 37 | assert_ok!(WrapCurrency::withdraw(Origin::signed(1), 5 * DOLLARS)); 38 | assert_eq!(Balances::free_balance(1), 100 * DOLLARS - 10 * DOLLARS + 5 * DOLLARS); 39 | assert_eq!(TokenFungible::balance_of(0, 1), 5 * DOLLARS); 40 | }); 41 | } 42 | -------------------------------------------------------------------------------- /pallets/wrap-currency/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Autogenerated weights for web3games_wrap_currency 20 | //! 21 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 22 | //! DATE: 2022-12-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` 23 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 24 | 25 | // Executed Command: 26 | // target/release/web3games-node 27 | // benchmark 28 | // pallet 29 | // --chain=dev 30 | // --steps=50 31 | // --repeat=20 32 | // --pallet=web3games_wrap_currency 33 | // --extrinsic=* 34 | // --execution=wasm 35 | // --wasm-execution=compiled 36 | // --output=./pallets/wrap-currency/src/weights.rs 37 | // --template=./.maintain/w3g-weight-template.hbs 38 | 39 | #![cfg_attr(rustfmt, rustfmt_skip)] 40 | #![allow(unused_parens)] 41 | #![allow(unused_imports)] 42 | #![allow(clippy::unnecessary_cast)] 43 | 44 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 45 | use sp_std::marker::PhantomData; 46 | 47 | /// Weight functions needed for web3games_wrap_currency. 48 | pub trait WeightInfo { 49 | fn deposit() -> Weight; 50 | fn withdraw() -> Weight; 51 | } 52 | 53 | /// Weights for web3games_wrap_currency using the Web3Games node and recommended hardware. 54 | pub struct W3GWeight(PhantomData); 55 | impl WeightInfo for W3GWeight { 56 | // Storage: System Account (r:2 w:2) 57 | // Storage: TokenFungible Tokens (r:1 w:1) 58 | // Storage: TokenFungible Balances (r:1 w:1) 59 | fn deposit() -> Weight { 60 | (44_000_000 as Weight) 61 | .saturating_add(T::DbWeight::get().reads(4 as Weight)) 62 | .saturating_add(T::DbWeight::get().writes(4 as Weight)) 63 | } 64 | // Storage: System Account (r:2 w:2) 65 | // Storage: TokenFungible Tokens (r:1 w:1) 66 | // Storage: TokenFungible Balances (r:1 w:1) 67 | fn withdraw() -> Weight { 68 | (37_000_000 as Weight) 69 | .saturating_add(T::DbWeight::get().reads(4 as Weight)) 70 | .saturating_add(T::DbWeight::get().writes(4 as Weight)) 71 | } 72 | } 73 | 74 | // For backwards compatibility and tests 75 | impl WeightInfo for () { 76 | fn deposit() -> Weight { 77 | (44_000_000 as Weight) 78 | .saturating_add(RocksDbWeight::get().reads(4 as Weight)) 79 | .saturating_add(RocksDbWeight::get().writes(4 as Weight)) 80 | } 81 | fn withdraw() -> Weight { 82 | (37_000_000 as Weight) 83 | .saturating_add(RocksDbWeight::get().reads(4 as Weight)) 84 | .saturating_add(RocksDbWeight::get().writes(4 as Weight)) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /precompiles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "precompiles" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } 9 | log = { version = "0.4.17", default-features = false } 10 | rustc-hex = { version = "2.0.1", default-features = false } 11 | num_enum = { version = "0.5.3", default-features = false } 12 | 13 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false} 16 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 17 | fp-evm = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 18 | pallet-evm = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 19 | pallet-evm-precompile-modexp = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 20 | pallet-evm-precompile-bn128 = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 21 | pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 22 | pallet-evm-precompile-sha3fips = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 23 | pallet-evm-precompile-dispatch = { default-features = false, git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26" } 24 | 25 | web3games-token-fungible = { path = "../pallets/token-fungible", default-features = false } 26 | web3games-token-non-fungible = { path = "../pallets/token-non-fungible", default-features = false } 27 | web3games-token-multi = { path = "../pallets/token-multi", default-features = false } 28 | web3games-exchange = { path = "../pallets/exchange", default-features = false } 29 | web3games-marketplace = { path = "../pallets/marketplace", default-features = false } 30 | web3games-farming = { path = "../pallets/farming", default-features = false } 31 | web3games-launchpad = { path = "../pallets/launchpad", default-features = false } 32 | web3games-support = { path = "../pallets/support", default-features = false } 33 | primitives = {path = "../primitives", default-features = false } 34 | precompile-utils = { path = "./utils", default-features = false } 35 | 36 | [features] 37 | default = [ "std" ] 38 | std = [ 39 | "codec/std", 40 | "log/std", 41 | "frame-system/std", 42 | "frame-support/std", 43 | "sp-std/std", 44 | "sp-core/std", 45 | "fp-evm/std", 46 | "pallet-evm/std", 47 | "pallet-evm-precompile-modexp/std", 48 | "pallet-evm-precompile-bn128/std", 49 | "pallet-evm-precompile-simple/std", 50 | "pallet-evm-precompile-sha3fips/std", 51 | "pallet-evm-precompile-dispatch/std", 52 | # "evm/std", 53 | "web3games-token-fungible/std", 54 | "web3games-token-non-fungible/std", 55 | "web3games-token-multi/std", 56 | "web3games-exchange/std", 57 | "web3games-marketplace/std", 58 | "web3games-farming/std", 59 | "web3games-launchpad/std", 60 | "web3games-support/std", 61 | "primitives/std", 62 | "precompile-utils/std", 63 | ] 64 | -------------------------------------------------------------------------------- /precompiles/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | Web3Games precompiled contract files for the contract layer client to provide enhancements. -------------------------------------------------------------------------------- /precompiles/src/Exchange.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // @custom:address 0x0000000000000000000000000000000000000403 3 | pragma solidity ^0.8.0; 4 | 5 | interface Exchange { 6 | function create_pool(uint256 token_a,uint256 token_b) external; 7 | function add_liquidity(uint256 token_a,uint256 token_b,uint256 amount_a_desired,uint256 amount_b_desired,uint256 amount_a_min,uint256 amount_b_min,address to,uint256 deadline) external; 8 | function add_liquidity_w3g(uint256 token,uint256 amount_w3g_desired,uint256 amount_desired,uint256 amount_w3g_min,uint256 amount_min,address to,uint256 deadline) external; 9 | function remove_liquidity(uint256 token_a,uint256 token_b,uint256 liquidity,uint256 amount_a_min,uint256 amount_b_min,address to,uint256 deadline) external; 10 | function remove_liquidity_w3g(uint256 token,uint256 liquidity,uint256 amount_w3g_min,uint256 amount_min,address to,uint256 deadline) external; 11 | function swap_exact_tokens_for_tokens(uint256 amount_in,uint256 amount_out_min,uint256[] memory path,address to,uint256 deadline) external; 12 | function swap_exact_w3g_for_tokens(uint256 amount_in_w3g,uint256 amount_out_min,uint256[] memory path,address to,uint256 deadline) external; 13 | function swap_tokens_for_exact_tokens(uint256 amount_out,uint256 amount_in_max,uint256[] memory path,address to,uint256 deadline) external; 14 | function swap_tokens_for_exact_w3g(uint256 amount_out_w3g,uint256 amount_in_max,uint256[] memory path,address to,uint256 deadline) external; 15 | } 16 | -------------------------------------------------------------------------------- /precompiles/src/Farming.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // @custom:address 0x0000000000000000000000000000000000000405 3 | pragma solidity ^0.8.0; 4 | 5 | interface Farming { 6 | function staking(uint256 pool_id,uint256 amount) external; 7 | function claim(uint256 pool_id) external; 8 | } 9 | -------------------------------------------------------------------------------- /precompiles/src/Launchpad.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // @custom:address 0x0000000000000000000000000000000000000406 3 | pragma solidity ^0.8.0; 4 | 5 | interface Launchpad { 6 | function create_pool(uint256 sale_start,uint256 sale_duration,uint256 sale_token_id,uint256 buy_token_id,uint256 total_sale_amount,uint256 token_price) external; 7 | function buy_token(uint256 pool_id,uint256 amount) external; 8 | function owner_claim(uint256 pool_id) external; 9 | function claim(uint256 pool_id) external; 10 | } 11 | -------------------------------------------------------------------------------- /precompiles/src/Marketplace.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // @custom:address 0x0000000000000000000000000000000000000404 3 | pragma solidity ^0.8.0; 4 | 5 | interface Marketplace { 6 | function create_order(uint256 group_id,uint256 token_id,uint256 asset_type,uint256 price,uint256 duration) external; 7 | function cancel_order(uint256 group_id,uint256 token_id,uint256 asset_type) external; 8 | function execute_order(uint256 group_id,uint256 token_id,uint256 asset_type) external; 9 | function place_bid(uint256 group_id,uint256 token_id,uint256 asset_type,uint256 price,uint256 duration) external; 10 | function cancel_bid(uint256 group_id,uint256 token_id,uint256 asset_type) external; 11 | function accept_bid(uint256 group_id,uint256 token_id,uint256 asset_type) external; 12 | } 13 | -------------------------------------------------------------------------------- /precompiles/src/TokenFungible.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // @custom:address 0xFFFFFFFF00000000000000000000000000000000 3 | pragma solidity ^0.8.0; 4 | 5 | interface TokenFungible { 6 | function create(bytes memory name,bytes memory symbol,uint8 decimals) external; 7 | function name() external view returns (string memory); 8 | function symbol() external view returns (string memory); 9 | function decimals() external view returns (uint256); 10 | function totalSupply() external view returns (uint256); 11 | function balanceOf(address account) external view returns (uint256); 12 | function transfer(address to, uint256 amount) external; 13 | function transferFrom(address from,address to, uint256 amount) external; 14 | function mint(address account, uint256 amount) external; 15 | function burn(uint256 amount) external; 16 | } 17 | -------------------------------------------------------------------------------- /precompiles/src/farming.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use fp_evm::{PrecompileHandle, PrecompileOutput}; 20 | use frame_support::dispatch::{Dispatchable, GetDispatchInfo, PostDispatchInfo}; 21 | use pallet_evm::{AddressMapping, PrecompileSet}; 22 | use precompile_utils::prelude::*; 23 | use sp_core::H160; 24 | use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; 25 | 26 | #[generate_function_selector] 27 | #[derive(Debug, PartialEq)] 28 | enum Action { 29 | Staking = "staking(uint256,uint256)", 30 | Claim = "claim(uint256)", 31 | } 32 | 33 | pub struct FarmingExtension(PhantomData); 34 | 35 | impl PrecompileSet for FarmingExtension 36 | where 37 | Runtime: web3games_farming::Config + pallet_evm::Config, 38 | Runtime::Call: Dispatchable + GetDispatchInfo, 39 | ::Origin: From>, 40 | Runtime::Call: From>, 41 | { 42 | fn execute(&self, handle: &mut impl PrecompileHandle) -> Option> { 43 | let result = { 44 | let selector = match handle.read_selector() { 45 | Ok(selector) => selector, 46 | Err(e) => return Some(Err(e)), 47 | }; 48 | if let Err(err) = handle.check_function_modifier(match selector { 49 | Action::Staking | Action::Claim => FunctionModifier::NonPayable, 50 | }) { 51 | return Some(Err(err)) 52 | } 53 | match selector { 54 | Action::Staking => Self::staking(handle), 55 | Action::Claim => Self::claim(handle), 56 | } 57 | }; 58 | Some(result) 59 | } 60 | fn is_precompile(&self, _address: H160) -> bool { 61 | true 62 | } 63 | } 64 | 65 | impl FarmingExtension { 66 | pub fn new() -> Self { 67 | Self(PhantomData) 68 | } 69 | } 70 | 71 | impl FarmingExtension 72 | where 73 | Runtime: web3games_farming::Config + pallet_evm::Config, 74 | Runtime::Call: Dispatchable + GetDispatchInfo, 75 | ::Origin: From>, 76 | Runtime::Call: From>, 77 | { 78 | fn staking(handle: &mut impl PrecompileHandle) -> EvmResult { 79 | let mut input = handle.read_input()?; 80 | input.expect_arguments(2)?; 81 | 82 | let pool_id = input.read::()?.into(); 83 | let amount = input.read::()?.into(); 84 | 85 | { 86 | let caller: Runtime::AccountId = 87 | Runtime::AddressMapping::into_account_id(handle.context().caller); 88 | 89 | // Dispatch call (if enough gas). 90 | RuntimeHelper::::try_dispatch( 91 | handle, 92 | Some(caller).into(), 93 | web3games_farming::Call::::staking { pool_id, amount }, 94 | )?; 95 | } 96 | 97 | // Return call information 98 | Ok(succeed(EvmDataWriter::new().write(true).build())) 99 | } 100 | 101 | fn claim(handle: &mut impl PrecompileHandle) -> EvmResult { 102 | let mut input = handle.read_input()?; 103 | input.expect_arguments(1)?; 104 | 105 | let pool_id = input.read::()?.into(); 106 | 107 | { 108 | let caller: Runtime::AccountId = 109 | Runtime::AddressMapping::into_account_id(handle.context().caller); 110 | 111 | // Dispatch call (if enough gas). 112 | RuntimeHelper::::try_dispatch( 113 | handle, 114 | Some(caller).into(), 115 | web3games_farming::Call::::claim { pool_id }, 116 | )?; 117 | } 118 | 119 | // Return call information 120 | Ok(succeed(EvmDataWriter::new().write(true).build())) 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /precompiles/utils/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "precompile-utils" 3 | authors = [ "PureStake" ] 4 | description = "Utils to write EVM precompiles." 5 | edition = "2021" 6 | version = "0.1.0" 7 | 8 | [dependencies] 9 | impl-trait-for-tuples = "0.2.2" 10 | log = "0.4" 11 | num_enum = { version = "0.5.3", default-features = false } 12 | sha3 = { version = "0.9", default-features = false } 13 | similar-asserts = { version = "1.1.0", optional = true } 14 | 15 | # Moonbeam 16 | precompile-utils-macro = { path = "macro" } 17 | 18 | # Substrate 19 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } 20 | frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 21 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 22 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 23 | sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 24 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26", default-features = false } 25 | 26 | # Frontier 27 | evm = { git = "https://github.com/rust-blockchain/evm", rev = "51b8c2ce3104265e1fd5bb0fe5cdfd2e0938239c", default-features = false, features = [ "with-codec"]} 28 | fp-evm = { git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26", default-features = false } 29 | pallet-evm = { git = "https://github.com/web3gamesofficial/frontier", branch = "polkadot-v0.9.26", default-features = false } 30 | 31 | [dev-dependencies] 32 | hex-literal = "0.3.1" 33 | 34 | [features] 35 | default = [ "std" ] 36 | std = [ 37 | "codec/std", 38 | "fp-evm/std", 39 | "frame-support/std", 40 | "frame-system/std", 41 | "pallet-evm/std", 42 | "sp-core/std", 43 | "sp-io/std", 44 | "sp-std/std", 45 | ] 46 | testing = [ "similar-asserts", "std" ] 47 | -------------------------------------------------------------------------------- /precompiles/utils/macro/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "precompile-utils-macro" 3 | authors = [ "PureStake" ] 4 | description = "" 5 | edition = "2021" 6 | version = "0.1.0" 7 | 8 | [lib] 9 | proc-macro = true 10 | 11 | [[test]] 12 | name = "tests" 13 | path = "tests/tests.rs" 14 | 15 | [dependencies] 16 | num_enum = { version = "0.5.3", default-features = false } 17 | proc-macro2 = "1.0" 18 | quote = "1.0" 19 | sha3 = "0.8" 20 | syn = { version = "1.0.98", features = [ "extra-traits", "fold", "full", "visit" ] } 21 | -------------------------------------------------------------------------------- /precompiles/utils/macro/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | #![crate_type = "proc-macro"] 15 | extern crate proc_macro; 16 | 17 | use proc_macro::TokenStream; 18 | use proc_macro2::Literal; 19 | use quote::{quote, quote_spanned}; 20 | use sha3::{Digest, Keccak256}; 21 | use syn::{ 22 | parse_macro_input, spanned::Spanned, Attribute, Expr, ExprLit, Ident, ItemEnum, Lit, LitStr, 23 | }; 24 | 25 | struct Bytes(Vec); 26 | 27 | impl ::std::fmt::Debug for Bytes { 28 | #[inline] 29 | fn fmt(&self, f: &mut std::fmt::Formatter) -> ::std::fmt::Result { 30 | let data = &self.0; 31 | write!(f, "[")?; 32 | if !data.is_empty() { 33 | write!(f, "{:#04x}u8", data[0])?; 34 | for unit in data.iter().skip(1) { 35 | write!(f, ", {:#04x}", unit)?; 36 | } 37 | } 38 | write!(f, "]") 39 | } 40 | } 41 | 42 | #[proc_macro] 43 | pub fn keccak256(input: TokenStream) -> TokenStream { 44 | let lit_str = parse_macro_input!(input as LitStr); 45 | 46 | let hash = Keccak256::digest(lit_str.value().as_ref()); 47 | 48 | let bytes = Bytes(hash.to_vec()); 49 | let eval_str = format!("{:?}", bytes); 50 | let eval_ts: proc_macro2::TokenStream = eval_str.parse().unwrap_or_else(|_| { 51 | panic!("Failed to parse the string \"{}\" to TokenStream.", eval_str); 52 | }); 53 | quote!(#eval_ts).into() 54 | } 55 | 56 | /// This macro allows to associate to each variant of an enumeration a discriminant (of type u32 57 | /// whose value corresponds to the first 4 bytes of the Hash Keccak256 of the character string 58 | ///indicated by the user of this macro. 59 | /// 60 | /// Usage: 61 | /// 62 | /// ```ignore 63 | /// #[generate_function_selector] 64 | /// enum Action { 65 | /// Toto = "toto()", 66 | /// Tata = "tata()", 67 | /// } 68 | /// ``` 69 | /// 70 | /// Extended to: 71 | /// 72 | /// ```rust 73 | /// #[repr(u32)] 74 | /// enum Action { 75 | /// Toto = 119097542u32, 76 | /// Tata = 1414311903u32, 77 | /// } 78 | /// ``` 79 | #[proc_macro_attribute] 80 | pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenStream { 81 | let item = parse_macro_input!(input as ItemEnum); 82 | 83 | let ItemEnum { attrs, vis, enum_token, ident, variants, .. } = item; 84 | 85 | let mut ident_expressions: Vec = vec![]; 86 | let mut variant_expressions: Vec = vec![]; 87 | let mut variant_attrs: Vec> = vec![]; 88 | for variant in variants { 89 | match variant.discriminant { 90 | Some((_, Expr::Lit(ExprLit { lit, .. }))) => 91 | if let Lit::Str(lit_str) = lit { 92 | let digest = Keccak256::digest(lit_str.value().as_ref()); 93 | let selector = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]); 94 | ident_expressions.push(variant.ident); 95 | variant_expressions.push(Expr::Lit(ExprLit { 96 | lit: Lit::Verbatim(Literal::u32_suffixed(selector)), 97 | attrs: Default::default(), 98 | })); 99 | variant_attrs.push(variant.attrs); 100 | } else { 101 | return quote_spanned! { 102 | lit.span() => compile_error("Expected literal string"); 103 | } 104 | .into() 105 | }, 106 | Some((_eg, expr)) => 107 | return quote_spanned! { 108 | expr.span() => compile_error("Expected literal"); 109 | } 110 | .into(), 111 | None => 112 | return quote_spanned! { 113 | variant.span() => compile_error("Each variant must have a discriminant"); 114 | } 115 | .into(), 116 | } 117 | } 118 | 119 | (quote! { 120 | #(#attrs)* 121 | #[derive(num_enum::TryFromPrimitive, num_enum::IntoPrimitive)] 122 | #[repr(u32)] 123 | #vis #enum_token #ident { 124 | #( 125 | #(#variant_attrs)* 126 | #ident_expressions = #variant_expressions, 127 | )* 128 | } 129 | }) 130 | .into() 131 | } 132 | -------------------------------------------------------------------------------- /precompiles/utils/macro/tests/tests.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | use sha3::{Digest, Keccak256}; 15 | 16 | #[precompile_utils_macro::generate_function_selector] 17 | pub enum Action { 18 | Toto = "toto()", 19 | Tata = "tata()", 20 | } 21 | 22 | #[test] 23 | fn test_keccak256() { 24 | assert_eq!(&precompile_utils_macro::keccak256!(""), Keccak256::digest(b"").as_ref(),); 25 | assert_eq!( 26 | &precompile_utils_macro::keccak256!("toto()"), 27 | Keccak256::digest(b"toto()").as_ref(), 28 | ); 29 | assert_ne!( 30 | &precompile_utils_macro::keccak256!("toto()"), 31 | Keccak256::digest(b"tata()").as_ref(), 32 | ); 33 | } 34 | 35 | #[test] 36 | fn test_generate_function_selector() { 37 | assert_eq!(&(Action::Toto as u32).to_be_bytes()[..], &Keccak256::digest(b"toto()")[0..4],); 38 | assert_eq!(&(Action::Tata as u32).to_be_bytes()[..], &Keccak256::digest(b"tata()")[0..4],); 39 | assert_ne!(Action::Toto as u32, Action::Tata as u32); 40 | } 41 | -------------------------------------------------------------------------------- /precompiles/utils/src/costs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | //! Cost calculations. 18 | //! TODO: PR EVM to make those cost calculations public. 19 | 20 | use crate::EvmResult; 21 | use fp_evm::{ExitError, PrecompileFailure}; 22 | use sp_core::U256; 23 | 24 | pub fn log_costs(topics: usize, data_len: usize) -> EvmResult { 25 | // Cost calculation is copied from EVM code that is not publicly exposed by the crates. 26 | // https://github.com/rust-blockchain/evm/blob/master/gasometer/src/costs.rs#L148 27 | 28 | const G_LOG: u64 = 375; 29 | const G_LOGDATA: u64 = 8; 30 | const G_LOGTOPIC: u64 = 375; 31 | 32 | let topic_cost = G_LOGTOPIC 33 | .checked_mul(topics as u64) 34 | .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })?; 35 | 36 | let data_cost = G_LOGDATA 37 | .checked_mul(data_len as u64) 38 | .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })?; 39 | 40 | G_LOG 41 | .checked_add(topic_cost) 42 | .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas })? 43 | .checked_add(data_cost) 44 | .ok_or(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) 45 | } 46 | 47 | // Compute the cost of doing a subcall. 48 | // Some parameters cannot be known in advance, so we estimate the worst possible cost. 49 | pub fn call_cost(value: U256, config: &evm::Config) -> u64 { 50 | // Copied from EVM code since not public. 51 | pub const G_CALLVALUE: u64 = 9000; 52 | pub const G_NEWACCOUNT: u64 = 25000; 53 | 54 | fn address_access_cost(is_cold: bool, regular_value: u64, config: &evm::Config) -> u64 { 55 | if config.increase_state_access_gas { 56 | if is_cold { 57 | config.gas_account_access_cold 58 | } else { 59 | config.gas_storage_read_warm 60 | } 61 | } else { 62 | regular_value 63 | } 64 | } 65 | 66 | fn xfer_cost(is_call_or_callcode: bool, transfers_value: bool) -> u64 { 67 | if is_call_or_callcode && transfers_value { 68 | G_CALLVALUE 69 | } else { 70 | 0 71 | } 72 | } 73 | 74 | fn new_cost( 75 | is_call_or_staticcall: bool, 76 | new_account: bool, 77 | transfers_value: bool, 78 | config: &evm::Config, 79 | ) -> u64 { 80 | let eip161 = !config.empty_considered_exists; 81 | if is_call_or_staticcall { 82 | if eip161 { 83 | if transfers_value && new_account { 84 | G_NEWACCOUNT 85 | } else { 86 | 0 87 | } 88 | } else if new_account { 89 | G_NEWACCOUNT 90 | } else { 91 | 0 92 | } 93 | } else { 94 | 0 95 | } 96 | } 97 | 98 | let transfers_value = value != U256::default(); 99 | let is_cold = true; 100 | let is_call_or_callcode = true; 101 | let is_call_or_staticcall = true; 102 | let new_account = true; 103 | 104 | address_access_cost(is_cold, config.gas_call, config) + 105 | xfer_cost(is_call_or_callcode, transfers_value) + 106 | new_cost(is_call_or_staticcall, new_account, transfers_value, config) 107 | } 108 | -------------------------------------------------------------------------------- /precompiles/utils/src/handle.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | use crate::{data::EvmDataReader, modifier::FunctionModifier, EvmResult}; 18 | use fp_evm::{Log, PrecompileHandle}; 19 | 20 | pub trait PrecompileHandleExt: PrecompileHandle { 21 | /// Record cost of a log manually. 22 | /// This can be useful to record log costs early when their content have static size. 23 | #[must_use] 24 | fn record_log_costs_manual(&mut self, topics: usize, data_len: usize) -> EvmResult; 25 | 26 | /// Record cost of logs. 27 | #[must_use] 28 | fn record_log_costs(&mut self, logs: &[&Log]) -> EvmResult; 29 | 30 | #[must_use] 31 | /// Check that a function call is compatible with the context it is 32 | /// called into. 33 | fn check_function_modifier(&self, modifier: FunctionModifier) -> EvmResult; 34 | 35 | #[must_use] 36 | /// Read the selector from the input data. 37 | fn read_selector(&self) -> EvmResult 38 | where 39 | T: num_enum::TryFromPrimitive; 40 | 41 | #[must_use] 42 | /// Returns a reader of the input, skipping the selector. 43 | fn read_input(&self) -> EvmResult; 44 | } 45 | 46 | impl PrecompileHandleExt for T { 47 | /// Record cost of a log manualy. 48 | /// This can be useful to record log costs early when their content have static size. 49 | #[must_use] 50 | fn record_log_costs_manual(&mut self, topics: usize, data_len: usize) -> EvmResult { 51 | self.record_cost(crate::costs::log_costs(topics, data_len)?)?; 52 | 53 | Ok(()) 54 | } 55 | 56 | /// Record cost of logs. 57 | #[must_use] 58 | fn record_log_costs(&mut self, logs: &[&Log]) -> EvmResult { 59 | for log in logs { 60 | self.record_log_costs_manual(log.topics.len(), log.data.len())?; 61 | } 62 | 63 | Ok(()) 64 | } 65 | 66 | #[must_use] 67 | /// Check that a function call is compatible with the context it is 68 | /// called into. 69 | fn check_function_modifier(&self, modifier: FunctionModifier) -> EvmResult { 70 | crate::modifier::check_function_modifier(self.context(), self.is_static(), modifier) 71 | } 72 | 73 | #[must_use] 74 | /// Read the selector from the input data. 75 | fn read_selector(&self) -> EvmResult 76 | where 77 | S: num_enum::TryFromPrimitive, 78 | { 79 | EvmDataReader::read_selector(self.input()) 80 | } 81 | 82 | #[must_use] 83 | /// Returns a reader of the input, skipping the selector. 84 | fn read_input(&self) -> EvmResult { 85 | EvmDataReader::new_skip_selector(self.input()) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /precompiles/utils/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | #![cfg_attr(not(feature = "std"), no_std)] 18 | #![feature(assert_matches)] 19 | 20 | extern crate alloc; 21 | 22 | pub mod costs; 23 | pub mod handle; 24 | pub mod logs; 25 | pub mod modifier; 26 | pub mod precompile_set; 27 | pub mod substrate; 28 | 29 | #[cfg(feature = "testing")] 30 | pub mod testing; 31 | 32 | #[cfg(test)] 33 | mod tests; 34 | 35 | use crate::alloc::borrow::ToOwned; 36 | use fp_evm::{ 37 | ExitError, ExitRevert, ExitSucceed, PrecompileFailure, PrecompileHandle, PrecompileOutput, 38 | }; 39 | 40 | pub mod data; 41 | 42 | // pub use data::{Address, Bytes, EvmData, EvmDataReader, EvmDataWriter}; 43 | // pub use fp_evm::Precompile; 44 | // pub use precompile_utils_macro::{generate_function_selector, keccak256}; 45 | 46 | /// Return an error with provided (static) text. 47 | /// Using the `revert` function of `Gasometer` is preferred as erroring 48 | /// consumed all the gas limit and the error message is not easily 49 | /// retrievable. 50 | #[must_use] 51 | pub fn error>>(text: T) -> PrecompileFailure { 52 | PrecompileFailure::Error { exit_status: ExitError::Other(text.into()) } 53 | } 54 | 55 | #[must_use] 56 | pub fn revert(output: impl AsRef<[u8]>) -> PrecompileFailure { 57 | PrecompileFailure::Revert { 58 | exit_status: ExitRevert::Reverted, 59 | output: output.as_ref().to_owned(), 60 | } 61 | } 62 | 63 | #[must_use] 64 | pub fn succeed(output: impl AsRef<[u8]>) -> PrecompileOutput { 65 | PrecompileOutput { exit_status: ExitSucceed::Returned, output: output.as_ref().to_owned() } 66 | } 67 | 68 | /// Alias for Result returning an EVM precompile error. 69 | pub type EvmResult = Result; 70 | 71 | /// Trait similar to `fp_evm::Precompile` but with a `&self` parameter to manage some 72 | /// state (this state is only kept in a single transaction and is lost afterward). 73 | pub trait StatefulPrecompile { 74 | /// Instanciate the precompile. 75 | /// Will be called once when building the PrecompileSet at the start of each 76 | /// Ethereum transaction. 77 | fn new() -> Self; 78 | 79 | /// Execute the precompile with a reference to its state. 80 | fn execute(&self, handle: &mut impl PrecompileHandle) -> EvmResult; 81 | } 82 | 83 | pub mod prelude { 84 | pub use crate::{ 85 | data::{Address, Bytes, EvmData, EvmDataReader, EvmDataWriter}, 86 | error, 87 | handle::PrecompileHandleExt, 88 | logs::{log0, log1, log2, log3, log4, LogExt}, 89 | modifier::{check_function_modifier, FunctionModifier}, 90 | revert, 91 | substrate::RuntimeHelper, 92 | succeed, EvmResult, StatefulPrecompile, 93 | }; 94 | pub use pallet_evm::PrecompileHandle; 95 | pub use precompile_utils_macro::{generate_function_selector, keccak256}; 96 | } 97 | -------------------------------------------------------------------------------- /precompiles/utils/src/logs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | use crate::EvmResult; 18 | use pallet_evm::{Log, PrecompileHandle}; 19 | use sp_core::{H160, H256}; 20 | use sp_std::{vec, vec::Vec}; 21 | 22 | /// Create a 0-topic log. 23 | #[must_use] 24 | pub fn log0(address: impl Into, data: impl Into>) -> Log { 25 | Log { address: address.into(), topics: vec![], data: data.into() } 26 | } 27 | 28 | /// Create a 1-topic log. 29 | #[must_use] 30 | pub fn log1(address: impl Into, topic0: impl Into, data: impl Into>) -> Log { 31 | Log { address: address.into(), topics: vec![topic0.into()], data: data.into() } 32 | } 33 | 34 | /// Create a 2-topics log. 35 | #[must_use] 36 | pub fn log2( 37 | address: impl Into, 38 | topic0: impl Into, 39 | topic1: impl Into, 40 | data: impl Into>, 41 | ) -> Log { 42 | Log { address: address.into(), topics: vec![topic0.into(), topic1.into()], data: data.into() } 43 | } 44 | 45 | /// Create a 3-topics log. 46 | #[must_use] 47 | pub fn log3( 48 | address: impl Into, 49 | topic0: impl Into, 50 | topic1: impl Into, 51 | topic2: impl Into, 52 | data: impl Into>, 53 | ) -> Log { 54 | Log { 55 | address: address.into(), 56 | topics: vec![topic0.into(), topic1.into(), topic2.into()], 57 | data: data.into(), 58 | } 59 | } 60 | 61 | /// Create a 4-topics log. 62 | #[must_use] 63 | pub fn log4( 64 | address: impl Into, 65 | topic0: impl Into, 66 | topic1: impl Into, 67 | topic2: impl Into, 68 | topic3: impl Into, 69 | data: impl Into>, 70 | ) -> Log { 71 | Log { 72 | address: address.into(), 73 | topics: vec![topic0.into(), topic1.into(), topic2.into(), topic3.into()], 74 | data: data.into(), 75 | } 76 | } 77 | 78 | /// Extension trait allowing to record logs into a PrecompileHandle. 79 | pub trait LogExt { 80 | fn record(self, handle: &mut impl PrecompileHandle) -> EvmResult; 81 | 82 | fn compute_cost(&self) -> EvmResult; 83 | } 84 | 85 | impl LogExt for Log { 86 | fn record(self, handle: &mut impl PrecompileHandle) -> EvmResult { 87 | handle.log(self.address, self.topics, self.data)?; 88 | Ok(()) 89 | } 90 | 91 | fn compute_cost(&self) -> EvmResult { 92 | crate::costs::log_costs(self.topics.len(), self.data.len()) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /precompiles/utils/src/modifier.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | //! Provide checks related to function modifiers (view/payable). 18 | 19 | use crate::{revert, EvmResult}; 20 | use fp_evm::Context; 21 | use sp_core::U256; 22 | 23 | /// Represents modifiers a Solidity function can be annotated with. 24 | #[derive(Copy, Clone, PartialEq, Eq)] 25 | pub enum FunctionModifier { 26 | /// Function that doesn't modify the state. 27 | View, 28 | /// Function that modifies the state but refuse receiving funds. 29 | /// Correspond to a Solidity function with no modifiers. 30 | NonPayable, 31 | /// Function that modifies the state and accept funds. 32 | Payable, 33 | } 34 | 35 | #[must_use] 36 | /// Check that a function call is compatible with the context it is 37 | /// called into. 38 | pub fn check_function_modifier( 39 | context: &Context, 40 | is_static: bool, 41 | modifier: FunctionModifier, 42 | ) -> EvmResult { 43 | if is_static && modifier != FunctionModifier::View { 44 | return Err(revert("can't call non-static function in static context")) 45 | } 46 | 47 | if modifier != FunctionModifier::Payable && context.apparent_value > U256::zero() { 48 | return Err(revert("function is not payable")) 49 | } 50 | 51 | Ok(()) 52 | } 53 | -------------------------------------------------------------------------------- /precompiles/utils/src/substrate.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2022 PureStake Inc. 2 | // This file is part of Moonbeam. 3 | 4 | // Moonbeam is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Moonbeam is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Moonbeam. If not, see . 16 | 17 | //! Utils related to Substrate features: 18 | //! - Substrate call dispatch. 19 | //! - Substrate DB read and write costs 20 | 21 | use crate::{revert, EvmResult}; 22 | use core::marker::PhantomData; 23 | use fp_evm::{ExitError, PrecompileFailure, PrecompileHandle}; 24 | use frame_support::{ 25 | dispatch::{Dispatchable, GetDispatchInfo, PostDispatchInfo}, 26 | traits::Get, 27 | }; 28 | use pallet_evm::GasWeightMapping; 29 | 30 | /// Helper functions requiring a Substrate runtime. 31 | /// This runtime must of course implement `pallet_evm::Config`. 32 | #[derive(Clone, Copy, Debug)] 33 | pub struct RuntimeHelper(PhantomData); 34 | 35 | impl RuntimeHelper 36 | where 37 | Runtime: pallet_evm::Config, 38 | Runtime::Call: Dispatchable + GetDispatchInfo, 39 | { 40 | /// Try to dispatch a Substrate call. 41 | /// Return an error if there are not enough gas, or if the call fails. 42 | /// If successful returns the used gas using the Runtime GasWeightMapping. 43 | pub fn try_dispatch( 44 | handle: &mut impl PrecompileHandle, 45 | origin: ::Origin, 46 | call: Call, 47 | ) -> EvmResult<()> 48 | where 49 | Runtime::Call: From, 50 | { 51 | let call = Runtime::Call::from(call); 52 | let dispatch_info = call.get_dispatch_info(); 53 | 54 | // Make sure there is enough gas. 55 | let remaining_gas = handle.remaining_gas(); 56 | let required_gas = Runtime::GasWeightMapping::weight_to_gas(dispatch_info.weight); 57 | if required_gas > remaining_gas { 58 | return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) 59 | } 60 | 61 | // Dispatch call. 62 | // It may be possible to not record gas cost if the call returns Pays::No. 63 | // However while Substrate handle checking weight while not making the sender pay for it, 64 | // the EVM doesn't. It seems this safer to always record the costs to avoid unmetered 65 | // computations. 66 | let used_weight = call 67 | .dispatch(origin) 68 | .map_err(|e| revert(alloc::format!("Dispatched call failed with error: {:?}", e)))? 69 | .actual_weight; 70 | 71 | let used_gas = 72 | Runtime::GasWeightMapping::weight_to_gas(used_weight.unwrap_or(dispatch_info.weight)); 73 | 74 | handle.record_cost(used_gas)?; 75 | 76 | Ok(()) 77 | } 78 | } 79 | 80 | impl RuntimeHelper 81 | where 82 | Runtime: pallet_evm::Config, 83 | { 84 | /// Cost of a Substrate DB write in gas. 85 | pub fn db_write_gas_cost() -> u64 { 86 | ::GasWeightMapping::weight_to_gas( 87 | ::DbWeight::get().write, 88 | ) 89 | } 90 | 91 | /// Cost of a Substrate DB read in gas. 92 | pub fn db_read_gas_cost() -> u64 { 93 | ::GasWeightMapping::weight_to_gas( 94 | ::DbWeight::get().read, 95 | ) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "primitives" 3 | version = "0.1.0" 4 | authors = ["Web3Games Developers"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } 9 | scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } 10 | serde = { version = "1.0.137", optional = true } 11 | frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 12 | sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 13 | sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 14 | sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 15 | sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.26" , default-features = false } 16 | 17 | [features] 18 | default = ["std"] 19 | std = [ 20 | "codec/std", 21 | "scale-info/std", 22 | "serde", 23 | "frame-system/std", 24 | "sp-application-crypto/std", 25 | "sp-core/std", 26 | "sp-runtime/std", 27 | "sp-std/std", 28 | ] 29 | -------------------------------------------------------------------------------- /primitives/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | 17 | Web3Games Important Profile Definition Folder. -------------------------------------------------------------------------------- /primitives/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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_attr(not(feature = "std"), no_std)] 20 | 21 | use sp_runtime::{ 22 | generic, 23 | traits::{BlakeTwo256, IdentifyAccount, Verify}, 24 | MultiSignature, OpaqueExtrinsic, 25 | }; 26 | 27 | /// An index to a block. 28 | pub type BlockNumber = u32; 29 | 30 | /// Alias to 512-bit hash when used in the context of a transaction signature on the chain. 31 | pub type Signature = MultiSignature; 32 | 33 | /// Some way of identifying an account on the chain. We intentionally make it equivalent 34 | /// to the public key of our transaction signing scheme. 35 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 36 | 37 | /// The type for looking up accounts. We don't expect more than 4 billion of them. 38 | pub type AccountIndex = u32; 39 | 40 | /// Balance of an account. 41 | pub type Balance = u128; 42 | 43 | /// Type used for expressing timestamp. 44 | pub type Moment = u64; 45 | 46 | /// Index of a transaction in the chain. 47 | pub type Index = u32; 48 | 49 | /// A hash of some data used by the chain. 50 | pub type Hash = sp_core::H256; 51 | 52 | /// A timestamp: milliseconds since the unix epoch. 53 | /// `u64` is enough to represent a duration of half a billion years, when the 54 | /// time scale is milliseconds. 55 | pub type Timestamp = u64; 56 | 57 | /// Header type. 58 | pub type Header = generic::Header; 59 | /// Block type. 60 | pub type Block = generic::Block; 61 | /// Block ID. 62 | pub type BlockId = generic::BlockId; 63 | 64 | /// Signed version of Balance 65 | pub type Amount = i128; 66 | 67 | // ID of fungible token or non fungible token or multi token 68 | pub type TokenAssetId = u128; 69 | 70 | /// Token ID 71 | pub type TokenId = u128; 72 | 73 | /// Index of token created 74 | pub type TokenIndex = u32; 75 | -------------------------------------------------------------------------------- /runtime/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | 17 | Web3Games chain runtime environment,On-chain runtime main file. -------------------------------------------------------------------------------- /runtime/web3games/build.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | use substrate_wasm_builder::WasmBuilder; 20 | 21 | fn main() { 22 | WasmBuilder::new() 23 | .with_current_project() 24 | .export_heap_base() 25 | .import_memory() 26 | .build() 27 | } 28 | -------------------------------------------------------------------------------- /runtime/web3games/src/constants.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Web3Games. 2 | 3 | // Copyright (C) 2021-2022 Web3Games https://web3games.org 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 | //! A set of constant values used in substrate runtime. 20 | 21 | /// Money matters. 22 | pub mod currency { 23 | use crate::Balance; 24 | 25 | pub const WEI: Balance = 1; 26 | pub const KILOWEI: Balance = 1_000; 27 | pub const MEGAWEI: Balance = 1_000_000; 28 | pub const GIGAWEI: Balance = 1_000_000_000; 29 | pub const MICROW3G: Balance = 1_000_000_000_000; 30 | pub const MILLIW3G: Balance = 1_000_000_000_000_000; 31 | pub const W3G: Balance = 1_000_000_000_000_000_000; 32 | pub const KILOW3G: Balance = 1_000_000_000_000_000_000_000; 33 | 34 | pub const DOLLARS: Balance = W3G; 35 | pub const CENTS: Balance = DOLLARS / 100; 36 | pub const MILLICENTS: Balance = CENTS / 1_000; 37 | 38 | pub const fn deposit(items: u32, bytes: u32) -> Balance { 39 | items as Balance * 1_000 * CENTS + (bytes as Balance) * 100 * MILLICENTS 40 | } 41 | } 42 | 43 | /// Time. 44 | pub mod time { 45 | use crate::{BlockNumber, Moment}; 46 | 47 | /// Since BABE is probabilistic this is the average expected block time that 48 | /// we are targetting. Blocks will be produced at a minimum duration defined 49 | /// by `SLOT_DURATION`, but some slots will not be allocated to any 50 | /// authority and hence no block will be produced. We expect to have this 51 | /// block time on average following the defined slot duration and the value 52 | /// of `c` configured for BABE (where `1 - c` represents the probability of 53 | /// a slot being empty). 54 | /// This value is only used indirectly to define the unit constants below 55 | /// that are expressed in blocks. The rest of the code should use 56 | /// `SLOT_DURATION` instead (like the Timestamp pallet for calculating the 57 | /// minimum period). 58 | /// 59 | /// If using BABE with secondary slots (default) then all of the slots will 60 | /// always be assigned, in which case `MILLISECS_PER_BLOCK` and 61 | /// `SLOT_DURATION` should have the same value. 62 | /// 63 | /// 64 | pub const MILLISECS_PER_BLOCK: Moment = 6000; 65 | pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000; 66 | 67 | pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; 68 | 69 | // 1 in 4 blocks (on average, not counting collisions) will be primary BABE blocks. 70 | pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); 71 | 72 | pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 10 * MINUTES; 73 | pub const EPOCH_DURATION_IN_SLOTS: u64 = { 74 | const SLOT_FILL_RATE: f64 = MILLISECS_PER_BLOCK as f64 / SLOT_DURATION as f64; 75 | 76 | (EPOCH_DURATION_IN_BLOCKS as f64 * SLOT_FILL_RATE) as u64 77 | }; 78 | 79 | // These time units are defined in number of blocks. 80 | pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber); 81 | pub const HOURS: BlockNumber = MINUTES * 60; 82 | pub const DAYS: BlockNumber = HOURS * 24; 83 | } 84 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2022-05-11" 3 | components = [ "rustfmt" ] 4 | targets = [ "wasm32-unknown-unknown"] 5 | profile = "minimal" 6 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | hard_tabs = true 3 | max_width = 100 4 | use_small_heuristics = "Max" 5 | # Imports 6 | imports_granularity = "Crate" 7 | reorder_imports = true 8 | # Consistency 9 | newline_style = "Unix" 10 | # Format comments 11 | comment_width = 100 12 | wrap_comments = true 13 | # Misc 14 | chain_width = 80 15 | spaces_around_ranges = false 16 | binop_separator = "Back" 17 | reorder_impl_items = false 18 | match_arm_leading_pipes = "Preserve" 19 | match_arm_blocks = false 20 | match_block_trailing_comma = true 21 | trailing_comma = "Vertical" 22 | trailing_semicolon = false 23 | use_field_init_shorthand = true 24 | -------------------------------------------------------------------------------- /scripts/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | 17 | This folder contains a list of script useful to develop/test the Web3Games Chain Node -------------------------------------------------------------------------------- /scripts/docker_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # This script is meant to be run on Unix/Linux based systems 3 | set -e 4 | 5 | echo "*** Start Substrate node template ***" 6 | 7 | cd $(dirname ${BASH_SOURCE[0]})/.. 8 | 9 | docker-compose down --remove-orphans 10 | docker-compose run --rm --service-ports dev $@ 11 | -------------------------------------------------------------------------------- /scripts/generate-weights.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cargo build --release --features="runtime-benchmarks" 4 | 5 | target/release/web3games-node benchmark pallet --chain=$1 --list | sed -n '2,$p' | grep -Eio "^\w+" | uniq | 6 | while IFS= read -r line 7 | do 8 | pallet=$line 9 | temp=${pallet/web3games_/} 10 | pallet_dir=${temp//_/-} 11 | if [ "$pallet" != "frame_system" -a "$pallet" != "pallet_balances" -a "$pallet" != "pallet_timestamp" ]; then 12 | echo "benchmark ${pallet}" 13 | echo "benchmark ${pallet_dir}" 14 | target/release/web3games-node benchmark pallet --chain=$1 \ 15 | --steps=50 \ 16 | --repeat=20 \ 17 | --pallet=$pallet \ 18 | --extrinsic="*" \ 19 | --execution=wasm \ 20 | --wasm-execution=compiled \ 21 | --output="./pallets/${pallet_dir}/src/weights.rs" \ 22 | --template="./.maintain/w3g-weight-template.hbs"; 23 | fi 24 | done 25 | -------------------------------------------------------------------------------- /scripts/init.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # This script is meant to be run on Unix/Linux based systems 3 | set -e 4 | 5 | echo "*** Initializing WASM build environment" 6 | 7 | if [ -z $CI_PROJECT_NAME ] ; then 8 | rustup update nightly 9 | rustup update stable 10 | fi 11 | 12 | rustup target add wasm32-unknown-unknown --toolchain nightly 13 | -------------------------------------------------------------------------------- /specs/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |
6 | 7 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/web3gamesofficial/web3games-blockchain/Rust)](https://github.com/web3gamesofficial/web3games-blockchain/actions) 8 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/web3gamesofficial/web3games-blockchain/blob/main/LICENSE) 9 | [![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fweb3games)](https://twitter.com/web3games) 10 | [![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/web3games) 11 | [![Medium](https://img.shields.io/badge/Medium-gray?logo=medium)](https://blog.web3games.com/) 12 | 13 |
14 | 15 | ## 1. Introduction 16 | 17 | This directory contains chain specs for well-known public networks. 18 | --------------------------------------------------------------------------------