From fc09bdc626218820d5cbc477263850afc6100773 Mon Sep 17 00:00:00 2001 From: Luiz Carvalho Date: Sat, 3 Feb 2024 16:59:01 -0300 Subject: [PATCH] refac: run clippy for entire codebase This PR runs clippy and formatter to the entire PR. Also updates the GH action to ensure it is formatted. --- .cargo/config.toml | 13 + .github/workflows/check.yml | 59 +- .gitignore | 6 - Cargo.lock | 255 ++-- Cargo.toml | 6 +- node/src/chain_spec.rs | 42 +- node/src/command.rs | 2 +- node/src/rpc.rs | 4 +- pallets/subspace/rpc/Cargo.toml | 2 +- pallets/subspace/rpc/src/lib.rs | 45 +- .../subspace/{rpc => }/runtime-api/Cargo.toml | 0 .../subspace/{rpc => }/runtime-api/src/lib.rs | 26 +- pallets/subspace/src/benchmarking.rs | 1053 ++++++++--------- pallets/subspace/src/global.rs | 90 +- pallets/subspace/src/lib.rs | 437 ++++--- pallets/subspace/src/math.rs | 34 +- pallets/subspace/src/migration.rs | 394 +++--- pallets/subspace/src/mock.rs | 20 +- pallets/subspace/src/module.rs | 103 +- pallets/subspace/src/profit_share.rs | 165 ++- pallets/subspace/src/registration.rs | 114 +- pallets/subspace/src/staking.rs | 145 ++- pallets/subspace/src/step.rs | 290 +++-- pallets/subspace/src/subnet.rs | 413 +++---- pallets/subspace/src/utils.rs | 30 - pallets/subspace/src/voting.rs | 734 ++++++------ pallets/subspace/src/weights.rs | 58 +- pallets/subspace/tests/test_burn.rs | 202 ++-- .../subspace/tests/test_delegate_staking.rs | 140 ++- pallets/subspace/tests/test_mock.rs | 17 +- pallets/subspace/tests/test_profit_share.rs | 60 +- pallets/subspace/tests/test_registration.rs | 3 +- pallets/subspace/tests/test_staking.rs | 11 +- pallets/subspace/tests/test_step.rs | 360 +++--- pallets/subspace/tests/test_subnets.rs | 122 +- pallets/subspace/tests/test_voting.rs | 362 +++--- pallets/subspace/tests/weights.rs | 2 - runtime/Cargo.toml | 2 +- runtime/src/lib.rs | 43 +- runtime/src/precompiles.rs | 14 +- 40 files changed, 2786 insertions(+), 3092 deletions(-) create mode 100644 .cargo/config.toml rename pallets/subspace/{rpc => }/runtime-api/Cargo.toml (100%) rename pallets/subspace/{rpc => }/runtime-api/src/lib.rs (84%) delete mode 100644 pallets/subspace/src/utils.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..cafb38f79 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,13 @@ +[target.'cfg(all())'] +# Enable global lints +rustflags = [ + # TODO: remove once we refactor the code + "-Aclippy::too_many_arguments", + "-Aclippy::type_complexity", +] + +[registries.crates-io] +protocol = "sparse" + +[build] +rustflags = ["-Z", "threads=8"] diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 02ef91097..8465c7f38 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -15,34 +15,57 @@ on: jobs: check: # The type of runner that the job will run on - runs-on: ubuntu-20.04 + runs-on: ubuntu-22.04 # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v4 - - name: Set-Up - run: sudo apt install -y git clang curl libssl-dev llvm libudev-dev protobuf-compiler + - name: Install Protoc + uses: arduino/setup-protoc@v1 + with: + version: 3.20.1 + repo-token: ${{ secrets.GITHUB_TOKEN }} - - name: Install Rustup - run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y - source ~/.cargo/env - rustup default stable - rustup update nightly - rustup update stable - rustup target add wasm32-unknown-unknown --toolchain nightly - - - name: Check Build + - name: Set-up Rust cache + uses: Swatinem/rust-cache@v2 + with: + prefix-key: registry-main-cache + cache-targets: false + cache-all-crates: false + cache-on-failure: true + save-if: ${{ github.ref_name == 'main' }} + + - name: Install Rust toolchain run: | - SKIP_WASM_BUILD=1 cargo check --release + rustup set profile minimal + rustup show + + - name: Ensure Rust formatting + id: rust-formatter + uses: actions-rs/cargo@v1 + with: + command: fmt + args: -- --check + + - name: Check code errors + id: rust-clippy + uses: actions-rs/clippy-check@v1 + env: + SKIP_WASM_BUILD: 1 + with: + args: >- + --color=always --timings -- -D warnings + token: ${{ secrets.GITHUB_TOKEN }} - name: Run tests - run: | - cargo test + id: rust-test + env: + SKIP_WASM_BUILD: 1 + run: cargo test - name: Check Build for Benchmarking - run: > - pushd node && + run: | + pushd node cargo check --features=runtime-benchmarks --release diff --git a/.gitignore b/.gitignore index 6be40a655..68da9e136 100644 --- a/.gitignore +++ b/.gitignore @@ -8,12 +8,6 @@ .DS_Store -# The cache for docker container dependency -.cargo - -# The cache for chain data in container -.local - # direnv cache .direnv diff --git a/Cargo.lock b/Cargo.lock index 8c5ebe095..53c896689 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -130,9 +130,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.5" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d664a92ecae85fd0a7392615844904654d1d5f5514837f471ddef4a057aba1b6" +checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5" dependencies = [ "anstyle", "anstyle-parse", @@ -144,9 +144,9 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +checksum = "2faccea4cc4ab4a667ce676a30e8ec13922a692c99bb8f5b11f1502c72e04220" [[package]] name = "anstyle-parse" @@ -267,11 +267,11 @@ dependencies = [ [[package]] name = "async-io" -version = "2.2.2" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6afaa937395a620e33dc6a742c593c01aced20aa376ffb0f628121198578ccc7" +checksum = "8f97ab0c5b00a7cdbe5a371b9a782ee7be1316095885c8a4ea1daf490eb0ef65" dependencies = [ - "async-lock 3.2.0", + "async-lock 3.3.0", "cfg-if", "concurrent-queue", "futures-io", @@ -295,11 +295,11 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7125e42787d53db9dd54261812ef17e937c95a51e4d291373b670342fa44310c" +checksum = "d034b430882f8381900d3fe6f0aaa3ad94f2cb4ac519b429692a1bc2dda4ae7b" dependencies = [ - "event-listener 4.0.1", + "event-listener 4.0.3", "event-listener-strategy", "pin-project-lite 0.2.13", ] @@ -352,14 +352,13 @@ dependencies = [ [[package]] name = "auto_impl" -version = "1.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fee3da8ef1276b0bee5dd1c7258010d8fffd31801447323115a25560e1327b89" +checksum = "823b8bb275161044e2ac7a25879cb3e2480cb403e3943022c7c769c599b756aa" dependencies = [ - "proc-macro-error", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.48", ] [[package]] @@ -403,9 +402,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.5" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" [[package]] name = "base64ct" @@ -443,7 +442,7 @@ dependencies = [ "lazy_static", "lazycell", "peeking_take_while", - "prettyplease 0.2.15", + "prettyplease 0.2.16", "proc-macro2", "quote", "regex", @@ -654,9 +653,9 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e34637b3140142bdf929fb439e8aa4ebad7651ebf7b1080b3930aa16ac1459ff" +checksum = "ceed8ef69d8518a5dda55c07425450b58a4e1946f4951eab6d7191ee86c2443d" dependencies = [ "serde", ] @@ -669,7 +668,7 @@ checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a" dependencies = [ "camino", "cargo-platform", - "semver 1.0.20", + "semver 1.0.21", "serde", "serde_json", "thiserror", @@ -779,9 +778,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.6.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" +checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" dependencies = [ "glob", "libc", @@ -790,9 +789,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.11" +version = "4.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfaff671f6b22ca62406885ece523383b9b64022e341e53e009a62ebc47a45f2" +checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c" dependencies = [ "clap_builder", "clap_derive", @@ -800,9 +799,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.11" +version = "4.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a216b506622bb1d316cd51328dce24e07bdff4a6128a47c7e7fad11878d5adbb" +checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7" dependencies = [ "anstream", "anstyle", @@ -866,15 +865,15 @@ dependencies = [ [[package]] name = "console" -version = "0.15.7" +version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c926e00cc70edefdc64d3a5ff31cc65bb97a3460097762bd23afb4d8145fccf8" +checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" dependencies = [ "encode_unicode", "lazy_static", "libc", "unicode-width", - "windows-sys 0.45.0", + "windows-sys 0.52.0", ] [[package]] @@ -1061,34 +1060,28 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fca89a0e215bab21874660c67903c5f143333cab1da83d041c7ded6053774751" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" dependencies = [ - "cfg-if", "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.9.17" +version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e3681d554572a651dda4186cd47240627c3d0114d45a95f6ad27f2f22e7548d" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ - "autocfg", - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.18" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3a430a770ebd84726f584a90ee7f020d28db52c6d02138900f22341f866d39c" -dependencies = [ - "cfg-if", -] +checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" [[package]] name = "crunchy" @@ -1204,9 +1197,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9fc0c733f71e58dedf4f034cd2a266f80b94cc9ed512729e1798651b68c2cba" +checksum = "8de00f15a6fa069c99b88c5c78c4541d0e7899a33b86f7480e23df2431fce0bc" dependencies = [ "cc", "cxxbridge-flags", @@ -1216,9 +1209,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bc81d2664db24cf1d35405f66e18a85cffd4d49ab930c71a5c6342a410f38c" +checksum = "0a71e1e631fa2f2f5f92e8b0d860a00c198c6771623a6cefcc863e3554f0d8d6" dependencies = [ "cc", "codespan-reporting", @@ -1231,15 +1224,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8511afbe34ea242697784da5cb2c5d4a0afb224ca8b136bdf93bfe180cbe5884" +checksum = "6f3fed61d56ba497c4efef9144dfdbaa25aa58f2f6b3a7cf441d4591c583745c" [[package]] name = "cxxbridge-macro" -version = "1.0.111" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6888cd161769d65134846d4d4981d5a6654307cc46ec83fb917e530aea5f84" +checksum = "8908e380a8efd42150c017b0cfa31509fc49b6d47f7cb6b33e93ffb8f4e3661e" dependencies = [ "proc-macro2", "quote", @@ -1333,9 +1326,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb30d70a07a3b04884d2677f06bec33509dc67ca60d92949e5535352d3191dc" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", ] @@ -1608,9 +1601,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b3f3e67048839cb0d0781f445682a35113da7121f7c949db0e2be96a4fbece" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" dependencies = [ "humantime", "is-terminal", @@ -1725,9 +1718,9 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" -version = "4.0.1" +version = "4.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84f2cdcf274580f2d63697192d744727b3198894b1bf02923643bf59e2c26712" +checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" dependencies = [ "concurrent-queue", "parking", @@ -1740,7 +1733,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3" dependencies = [ - "event-listener 4.0.1", + "event-listener 4.0.3", "pin-project-lite 0.2.13", ] @@ -2406,9 +2399,9 @@ checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeee267a1883f7ebef3700f262d2d54de95dfaf38189015a74fdc4e0c7ad8143" +checksum = "445ba825b27408685aaecefd65178908c36c6e96aaf6d8599419d46e624192ba" dependencies = [ "futures-core", "pin-project-lite 0.2.13", @@ -2592,9 +2585,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.3.22" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" +checksum = "bb2c4422095b67ee78da96fbb51a4cc413b3b25883c7717ff7ca1ab31022c9c9" dependencies = [ "bytes", "fnv", @@ -2845,7 +2838,7 @@ dependencies = [ "rustls-native-certs", "tokio", "tokio-rustls", - "webpki-roots 0.25.3", + "webpki-roots 0.25.4", ] [[package]] @@ -3072,13 +3065,13 @@ checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455" dependencies = [ "hermit-abi 0.3.3", "rustix 0.38.28", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -3147,7 +3140,7 @@ dependencies = [ "tokio-rustls", "tokio-util", "tracing", - "webpki-roots 0.25.3", + "webpki-roots 0.25.4", ] [[package]] @@ -3333,12 +3326,12 @@ checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "libloading" -version = "0.7.4" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161" dependencies = [ "cfg-if", - "winapi", + "windows-sys 0.48.0", ] [[package]] @@ -3810,9 +3803,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.12" +version = "1.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" +checksum = "037731f5d3aaa87a5675e895b63ddff1a87624bc29f77004ea829809654e48f6" dependencies = [ "cc", "pkg-config", @@ -4045,6 +4038,15 @@ dependencies = [ "libc", ] +[[package]] +name = "memmap2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe751422e4a8caa417e13c3ea66452215d7d63e19e604f4980461212f3ae1322" +dependencies = [ + "libc", +] + [[package]] name = "memoffset" version = "0.8.0" @@ -4346,7 +4348,7 @@ dependencies = [ "frame-system", "futures", "jsonrpsee", - "memmap2", + "memmap2 0.9.4", "node-subspace-runtime", "pallet-transaction-payment", "pallet-transaction-payment-rpc", @@ -4494,6 +4496,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-format" version = "0.4.4" @@ -4966,9 +4974,9 @@ dependencies = [ [[package]] name = "parity-db" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59e9ab494af9e6e813c72170f0d3c1de1500990d62c97cc05cc7576f91aa402f" +checksum = "592a28a24b09c9dc20ac8afaa6839abc417c720afe42c12e1e4a9d6aa2508d2e" dependencies = [ "blake2", "crc32fast", @@ -4977,11 +4985,12 @@ dependencies = [ "libc", "log", "lz4", - "memmap2", + "memmap2 0.5.10", "parking_lot 0.12.1", "rand 0.8.5", "siphasher", "snap", + "winapi", ] [[package]] @@ -5159,9 +5168,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +checksum = "1f200d8d83c44a45b21764d1916299752ca035d15ecd46faca3e9a2a2bf6ad06" dependencies = [ "memchr", "thiserror", @@ -5170,9 +5179,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81d78524685f5ef2a3b3bd1cafbc9fcabb036253d9b1463e726a91cd16e2dfc2" +checksum = "bcd6ab1236bbdb3a49027e920e693192ebfe8913f6d60e294de57463a493cfde" dependencies = [ "pest", "pest_generator", @@ -5180,9 +5189,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68bd1206e71118b5356dae5ddc61c8b11e28b09ef6a31acbd15ea48a28e0c227" +checksum = "2a31940305ffc96863a735bef7c7994a00b325a7138fdbc5bda0f1a0476d3275" dependencies = [ "pest", "pest_meta", @@ -5193,9 +5202,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c747191d4ad9e4a4ab9c8798f1e82a39affe7ef9648390b7e5548d18e099de6" +checksum = "a7ff62f5259e53b78d1af898941cdcdccfae7385cf7d793a6e55de5d05bb4b7d" dependencies = [ "once_cell", "pest", @@ -5214,18 +5223,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +checksum = "0302c4a0442c456bd56f841aee5c3bfd17967563f6fadc9ceb9f9c23cf3807e0" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", @@ -5262,21 +5271,21 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d3587f8a9e599cc7ec2c00e331f71c4e69a5f9a4b8a6efd5b07466b9736f9a" +checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb" [[package]] name = "platforms" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14e6ab3f592e6fb464fc9712d8d6e6912de6473954635fd76a589d832cffcbb0" +checksum = "626dec3cac7cc0e1577a2ec3fc496277ec2baa084bebad95bb6fdbfae235f84c" [[package]] name = "polling" -version = "3.3.1" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf63fa624ab313c11656b4cda960bfc46c410187ad493c41f6ba2d8c1e991c9e" +checksum = "545c980a3880efd47b2e262f6a4bb6daad6555cf3367aa9c4e52895f69537a41" dependencies = [ "cfg-if", "concurrent-queue", @@ -5369,9 +5378,9 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae005bd773ab59b4725093fd7df83fd7892f7d8eafb48dbd7de6e024e4215f9d" +checksum = "a41cf62165e97c7f814d2221421dbb9afcbcdb0a88068e5ea206e19951c2cbb5" dependencies = [ "proc-macro2", "syn 2.0.48", @@ -5728,9 +5737,9 @@ checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" [[package]] name = "rayon" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" +checksum = "fa7237101a77a10773db45d62004a272517633fbcc3df19d96455ede1122e051" dependencies = [ "either", "rayon-core", @@ -5738,9 +5747,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.12.0" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" dependencies = [ "crossbeam-deque", "crossbeam-utils", @@ -6022,7 +6031,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.20", + "semver 1.0.21", ] [[package]] @@ -6103,7 +6112,7 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", ] [[package]] @@ -6220,7 +6229,7 @@ name = "sc-chain-spec" version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate?branch=polkadot-v1.0.0#948fbd2fd1233dc26dbb9f9bbc1d2cca2c03945d" dependencies = [ - "memmap2", + "memmap2 0.5.10", "sc-chain-spec-derive", "sc-client-api", "sc-executor", @@ -7076,11 +7085,11 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -7218,9 +7227,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.20" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" +checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" dependencies = [ "serde", ] @@ -7381,9 +7390,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" @@ -7458,9 +7467,9 @@ checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" [[package]] name = "snow" -version = "0.9.4" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58021967fd0a5eeeb23b08df6cc244a4d4a5b4aec1d27c9e02fad1a58b4cd74e" +checksum = "850948bee068e713b8ab860fe1adc4d109676ab4c3b621fd8147f06b261f2f85" dependencies = [ "aes-gcm", "blake2", @@ -8486,22 +8495,22 @@ checksum = "14c39fd04924ca3a864207c66fc2cd7d22d7c016007f9ce846cbb9326331930a" [[package]] name = "tempfile" -version = "3.8.1" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" dependencies = [ "cfg-if", "fastrand", "redox_syscall 0.4.1", "rustix 0.38.28", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "termcolor" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] @@ -8569,12 +8578,13 @@ dependencies = [ [[package]] name = "time" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f657ba42c3f86e7680e53c8cd3af8abbe56b5491790b46e22e19c0d57463583e" +checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" dependencies = [ "deranged", "itoa", + "num-conv", "powerfmt", "serde", "time-core", @@ -8589,10 +8599,11 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26197e33420244aeb70c3e8c78376ca46571bc4e701e4791c2cd9f57dcb3a43f" +checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" dependencies = [ + "num-conv", "time-core", ] @@ -9393,7 +9404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c86437fa68626fe896e5afc69234bb2b5894949083586535f200385adfd71213" dependencies = [ "anyhow", - "base64 0.21.5", + "base64 0.21.7", "bincode", "directories-next", "file-per-thread-logger", @@ -9575,9 +9586,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.25.3" +version = "0.25.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1778a42e8b3b90bff8d0f5032bf22250792889a5cdc752aa0020c84abe3aaf10" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" [[package]] name = "which" diff --git a/Cargo.toml b/Cargo.toml index c73396120..762172fbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["node", "pallets/subspace", "runtime"] +members = ["node", "pallets/*", "runtime"] [profile.release] panic = "unwind" @@ -9,12 +9,12 @@ panic = "unwind" opt-level = 3 [workspace.dependencies] -clap = "4.4.6" +clap = "4.4.18" futures = { version = "0.3.21", default-features = false } jsonrpsee = "0.16.2" lazy_static = "1.4.0" log = { version = "0.4.14", default-features = false } -memmap2 = "0.5.0" +memmap2 = "0.9.4" ndarray = { version = "0.15.0", default-features = false } rand = "0.8" scale-info = { version = "2.10.0", default-features = false, features = [ diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 26c44a4a4..299acc1d8 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -1,6 +1,6 @@ use node_subspace_runtime::{ - AccountId, AuraConfig, BalancesConfig, GrandpaConfig, Signature, - SubspaceModuleConfig, SudoConfig, SystemConfig, WASM_BINARY, Precompiles, RuntimeGenesisConfig + AccountId, AuraConfig, BalancesConfig, GrandpaConfig, Precompiles, RuntimeGenesisConfig, + Signature, SubspaceModuleConfig, SudoConfig, SystemConfig, WASM_BINARY, }; use sc_service::ChainType; use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -74,8 +74,8 @@ struct SubspaceJSONState { version: u32, } -pub fn generate_config(network: String) -> Result { - let path: PathBuf = std::path::PathBuf::from(format!("./snapshots/{}.json", network)); +pub fn generate_config(network: &str) -> Result { + let path: PathBuf = std::path::PathBuf::from(format!("./snapshots/{network}.json")); let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; // We mmap the file into memory first, as this is *a lot* faster than using @@ -119,9 +119,9 @@ pub fn generate_config(network: String) -> Result { ), )); - // Add modules + // Add modules modules.push(Vec::new()); - for (_uid, module) in state.modules[netuid].iter().enumerate() { + for module in state.modules[netuid].iter() { modules[netuid].push(( sp_runtime::AccountId32::from( // module_key @@ -136,14 +136,14 @@ pub fn generate_config(network: String) -> Result { for (key_str, key_stake_to) in state.stake_to[netuid].iter() { stake_to[netuid].push(( sp_runtime::AccountId32::from( - ::from_ss58check(&key_str).unwrap(), + ::from_ss58check(key_str).unwrap(), ), key_stake_to .iter() .map(|(a, b)| { ( sp_runtime::AccountId32::from( - ::from_ss58check(&a).unwrap(), + ::from_ss58check(a).unwrap(), ), *b, ) @@ -155,7 +155,7 @@ pub fn generate_config(network: String) -> Result { let mut processed_balances: Vec<(sp_runtime::AccountId32, u64)> = Vec::new(); for (key_str, amount) in state.balances.iter() { - let key = ::from_ss58check(&key_str).unwrap(); + let key = ::from_ss58check(key_str).unwrap(); let key_account = sp_runtime::AccountId32::from(key); processed_balances.push((key_account, *amount)); @@ -209,14 +209,14 @@ pub fn generate_config(network: String) -> Result { } pub fn mainnet_config() -> Result { - return generate_config("main".to_string()) + generate_config("main") } pub fn devnet_config() -> Result { - return generate_config("dev".to_string()) + generate_config("dev") } pub fn testnet_config() -> Result { - return generate_config("test".to_string()) + generate_config("test") } // Configure initial storage state for FRAME modules. @@ -231,7 +231,11 @@ fn network_genesis( block: u32, ) -> RuntimeGenesisConfig { use node_subspace_runtime::EVMConfig; - + + let (aura_authorities, grandpa_authorities): (Vec<_>, Vec<_>) = + initial_authorities.into_iter().unzip(); + let grandpa_authorities = grandpa_authorities.into_iter().map(|a| (a, 1)).collect(); + RuntimeGenesisConfig { system: SystemConfig { // Add Wasm runtime to storage. @@ -240,16 +244,10 @@ fn network_genesis( }, balances: BalancesConfig { // Configure endowed accounts with initial balance of 1 << 60. - //balances: balances.iter().cloned().map(|k| k).collect(), - balances: balances.iter().cloned().map(|(k, balance)| (k, balance)).collect(), - }, - aura: AuraConfig { - authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), - }, - grandpa: GrandpaConfig { - authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), - ..Default::default() + balances, }, + aura: AuraConfig { authorities: aura_authorities }, + grandpa: GrandpaConfig { authorities: grandpa_authorities, ..Default::default() }, sudo: SudoConfig { // Assign network admin rights. key: Some(root_key), diff --git a/node/src/command.rs b/node/src/command.rs index 8c4cd551b..45cfdba3e 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -107,7 +107,7 @@ pub fn run() -> sc_cli::Result<()> { runner.sync_run(|config| { use sp_io::SubstrateHostFunctions; - + // This switch needs to be in the client, since the client decides // which sub-commands it wants to support. match cmd { diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 67b1dbf96..ddc5f25dd 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -41,9 +41,9 @@ where P: TransactionPool + 'static, { use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use subspace_rpc::{SubspaceApiServer, SubspacePallet}; use substrate_frame_rpc_system::{System, SystemApiServer}; - use subspace_rpc::{SubspacePallet, SubspaceApiServer}; - + let mut module = RpcModule::new(()); let FullDeps { client, pool, deny_unsafe } = deps; diff --git a/pallets/subspace/rpc/Cargo.toml b/pallets/subspace/rpc/Cargo.toml index aafd3c37c..a888833d6 100644 --- a/pallets/subspace/rpc/Cargo.toml +++ b/pallets/subspace/rpc/Cargo.toml @@ -24,7 +24,7 @@ sp-blockchain.workspace = true sp-runtime.workspace = true # local packages -subspace-runtime-api = { path = "./runtime-api", default-features = false } +subspace-runtime-api = { path = "../runtime-api", default-features = false } [features] default = ["std"] diff --git a/pallets/subspace/rpc/src/lib.rs b/pallets/subspace/rpc/src/lib.rs index ba62dd41f..ea048255b 100644 --- a/pallets/subspace/rpc/src/lib.rs +++ b/pallets/subspace/rpc/src/lib.rs @@ -1,38 +1,30 @@ -use subspace_runtime_api::ModuleInfo; -pub use subspace_runtime_api::SubspaceRuntimeApi; use jsonrpsee::{ - core::{ - Error as JsonRpseeError, - RpcResult, - }, + core::{Error as JsonRpseeError, RpcResult}, proc_macros::rpc, - types::error::{ - CallError, - ErrorObject, - }, + types::error::{CallError, ErrorObject}, }; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_runtime::traits::Block as BlockT; -use std::sync::Arc; use sp_runtime::{ + traits::{Block as BlockT, IdentifyAccount, Verify}, MultiSignature, - traits::{ - Verify, - IdentifyAccount, - } }; +use std::sync::Arc; +use subspace_runtime_api::ModuleInfo; +pub use subspace_runtime_api::SubspaceRuntimeApi; type Signature = MultiSignature; type AccountId = <::Signer as IdentifyAccount>::AccountId; #[rpc(client, server)] -pub trait SubspaceApi -{ +pub trait SubspaceApi { #[method(name = "subspace_getModuleInfo")] - fn get_module_info(&self, key: AccountId, netuid: u16, at: Option) -> RpcResult; - - + fn get_module_info( + &self, + key: AccountId, + netuid: u16, + at: Option, + ) -> RpcResult; } pub struct SubspacePallet { @@ -52,11 +44,16 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: SubspaceRuntimeApi, { - fn get_module_info(&self, key: AccountId, netuid: u16, at: Option<::Hash>) -> RpcResult { + fn get_module_info( + &self, + key: AccountId, + netuid: u16, + at: Option<::Hash>, + ) -> RpcResult { let api = self.client.runtime_api(); let at = at.unwrap_or_else(|| self.client.info().best_hash); - let value = api.get_module_info(at, key, netuid, ).map_err(runtime_error_into_rpc_err); + let value = api.get_module_info(at, key, netuid).map_err(runtime_error_into_rpc_err); Ok(value.unwrap()) } } @@ -71,4 +68,4 @@ fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError { Some(format!("{:?}", err)), )) .into() -} \ No newline at end of file +} diff --git a/pallets/subspace/rpc/runtime-api/Cargo.toml b/pallets/subspace/runtime-api/Cargo.toml similarity index 100% rename from pallets/subspace/rpc/runtime-api/Cargo.toml rename to pallets/subspace/runtime-api/Cargo.toml diff --git a/pallets/subspace/rpc/runtime-api/src/lib.rs b/pallets/subspace/runtime-api/src/lib.rs similarity index 84% rename from pallets/subspace/rpc/runtime-api/src/lib.rs rename to pallets/subspace/runtime-api/src/lib.rs index 17a43e6ce..da5ded60f 100644 --- a/pallets/subspace/rpc/runtime-api/src/lib.rs +++ b/pallets/subspace/runtime-api/src/lib.rs @@ -1,33 +1,25 @@ #![cfg_attr(not(feature = "std"), no_std)] +use sp_arithmetic::per_things::Percent; use sp_runtime::{ - MultiSignature, sp_std::prelude::Vec, - traits::{ - Verify, - IdentifyAccount - }, + traits::{IdentifyAccount, Verify}, + MultiSignature, }; -use sp_arithmetic::per_things::Percent; -use codec::{ - Decode, - Encode, -}; +use codec::{Decode, Encode}; use scale_info::TypeInfo; -use serde::{ - Deserialize, - Serialize -}; +use serde::{Deserialize, Serialize}; type Signature = MultiSignature; pub type AccountId = <::Signer as IdentifyAccount>::AccountId; #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo, Serialize, Deserialize)] -pub struct ModuleStats{ +pub struct ModuleStats { pub last_update: u64, pub registration_block: u64, - pub stake_from: Vec<(AccountId, u64)>, /* map of key to stake on this module/key * (includes delegations) */ + pub stake_from: Vec<(AccountId, u64)>, /* map of key to stake on this module/key * (includes + * delegations) */ pub emission: u64, pub incentive: u16, pub dividends: u16, @@ -53,4 +45,4 @@ sp_api::decl_runtime_apis! { { fn get_module_info(key: AccountId, netuid: u16) -> ModuleInfo; } -} \ No newline at end of file +} diff --git a/pallets/subspace/src/benchmarking.rs b/pallets/subspace/src/benchmarking.rs index ae0dc392b..461ba6df4 100644 --- a/pallets/subspace/src/benchmarking.rs +++ b/pallets/subspace/src/benchmarking.rs @@ -1,4 +1,3 @@ - #![cfg(feature = "runtime-benchmarks")] use super::*; @@ -15,653 +14,625 @@ const MIN_STAKE: u64 = 1_00_000_000_000; const BATCH: u64 = 250; fn set_user_balance(user: &T::AccountId) { - T::Currency::deposit_creating(user, >::u64_to_balance(BALANCE).unwrap()); + T::Currency::deposit_creating(user, >::u64_to_balance(BALANCE).unwrap()); } -fn single_register_helper() -> ( - Vec, - Vec, - Vec, - T::AccountId, - u16 -) { - let network: Vec = b"network".to_vec(); - let name: Vec = b"name".to_vec(); - let address: Vec = b"address".to_vec(); - let module_key: T::AccountId = account("module_key", 0, SEED); - - set_user_balance::(&module_key); - - let netuid = register_helper::( - network.clone(), - name.clone(), - address.clone(), - MIN_STAKE, - module_key.clone() - ); - - (network, name, address, module_key, netuid) +fn single_register_helper() -> (Vec, Vec, Vec, T::AccountId, u16) { + let network: Vec = b"network".to_vec(); + let name: Vec = b"name".to_vec(); + let address: Vec = b"address".to_vec(); + let module_key: T::AccountId = account("module_key", 0, SEED); + + set_user_balance::(&module_key); + + let netuid = register_helper::( + network.clone(), + name.clone(), + address.clone(), + MIN_STAKE, + module_key.clone(), + ); + + (network, name, address, module_key, netuid) } -fn multiple_register_helper() -> ( - u16, - Vec, - Vec -) { - let network: Vec = b"network".to_vec(); - - let module_keys: Vec = (0..BATCH).map(|i| account("module_key", i as u32, SEED)).collect(); - let amounts: Vec = (0..BATCH).map(|i| MIN_STAKE).collect(); - - let mut netuid: u16 = 0; - - for (index, module_key) in module_keys.iter().enumerate() { - let mut address: Vec = b"address".to_vec(); - let mut name: Vec = b"name".to_vec(); - - address.extend(vec![index as u8]); - name.extend(vec![index as u8]); - - set_user_balance::(&module_key); - - netuid = register_helper::( - network.clone(), - name, - address, - MIN_STAKE, - module_key.clone() - ); - } - - (netuid, module_keys, amounts) +fn multiple_register_helper() -> (u16, Vec, Vec) { + let network: Vec = b"network".to_vec(); + + let module_keys: Vec = + (0..BATCH).map(|i| account("module_key", i as u32, SEED)).collect(); + let amounts: Vec = (0..BATCH).map(|i| MIN_STAKE).collect(); + + let mut netuid: u16 = 0; + + for (index, module_key) in module_keys.iter().enumerate() { + let mut address: Vec = b"address".to_vec(); + let mut name: Vec = b"name".to_vec(); + + address.extend(vec![index as u8]); + name.extend(vec![index as u8]); + + set_user_balance::(&module_key); + + netuid = + register_helper::(network.clone(), name, address, MIN_STAKE, module_key.clone()); + } + + (netuid, module_keys, amounts) } fn register_helper( - network: Vec, - name: Vec, - address: Vec, - stake: u64, - module_key: T::AccountId, + network: Vec, + name: Vec, + address: Vec, + stake: u64, + module_key: T::AccountId, ) -> u16 { - >::register( - RawOrigin::Signed(module_key.clone()).into(), - network.clone(), - name.clone(), - address.clone(), - stake, - module_key.clone(), - ); - - let netuid = >::get_netuid_for_name(network.clone()); - - netuid + >::register( + RawOrigin::Signed(module_key.clone()).into(), + network.clone(), + name.clone(), + address.clone(), + stake, + module_key.clone(), + ); + + let netuid = >::get_netuid_for_name(network.clone()); + + netuid } fn add_stake_helper( - caller: T::AccountId, - network: Vec, - name: Vec, - address: Vec, - module_key: T::AccountId, - stake: u64, + caller: T::AccountId, + network: Vec, + name: Vec, + address: Vec, + module_key: T::AccountId, + stake: u64, ) -> u16 { - let netuid = register_helper::( - network, - name.clone(), - address.clone(), - MIN_STAKE, - module_key.clone() - ); - - >::add_stake( - RawOrigin::Signed(caller).into(), - netuid, - module_key, - stake, - ); - - netuid + let netuid = + register_helper::(network, name.clone(), address.clone(), MIN_STAKE, module_key.clone()); + + >::add_stake(RawOrigin::Signed(caller).into(), netuid, module_key, stake); + + netuid } fn add_stake_multiple_helper( - caller: T::AccountId, -) -> ( - u16, - Vec, - Vec -) { - let (netuid, module_keys, amounts) = multiple_register_helper::(); - - >::add_stake_multiple( - RawOrigin::Signed(caller).into(), - netuid, - module_keys.clone(), - amounts.clone(), - ); - - (netuid, module_keys, amounts) + caller: T::AccountId, +) -> (u16, Vec, Vec) { + let (netuid, module_keys, amounts) = multiple_register_helper::(); + + >::add_stake_multiple( + RawOrigin::Signed(caller).into(), + netuid, + module_keys.clone(), + amounts.clone(), + ); + + (netuid, module_keys, amounts) } #[benchmarks] mod benchmarks { - use super::*; + use super::*; - // #[benchmark] - // fn set_weights() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - // let network: Vec = b"network".to_vec(); - // let address: Vec = b"address".to_vec(); - // let name: Vec = b"name".to_vec(); + // #[benchmark] + // fn set_weights() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); + // let network: Vec = b"network".to_vec(); + // let address: Vec = b"address".to_vec(); + // let name: Vec = b"name".to_vec(); - // set_user_balance::(&caller); + // set_user_balance::(&caller); - // let _netuid = register_helper::( - // network.clone(), - // name.clone(), - // address.clone(), - // MIN_STAKE * BATCH, - // caller.clone(), - // ); + // let _netuid = register_helper::( + // network.clone(), + // name.clone(), + // address.clone(), + // MIN_STAKE * BATCH, + // caller.clone(), + // ); - // let (netuid, _module_keys, _amounts) = multiple_register_helper::(); + // let (netuid, _module_keys, _amounts) = multiple_register_helper::(); - // let uids = >::get_uids(netuid); + // let uids = >::get_uids(netuid); - // #[extrinsic_call] + // #[extrinsic_call] // set_weights( - // RawOrigin::Signed(caller.clone()), - // netuid, - // uids[1..].to_vec(), - // vec![1u16;uids.len() - 1] - // ); + // RawOrigin::Signed(caller.clone()), + // netuid, + // uids[1..].to_vec(), + // vec![1u16;uids.len() - 1] + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn add_stake() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); + // #[benchmark] + // fn add_stake() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); - // let (network, name, address, module_key, netuid) = single_register_helper::(); + // let (network, name, address, module_key, netuid) = single_register_helper::(); - // set_user_balance::(&caller); + // set_user_balance::(&caller); - // #[extrinsic_call] + // #[extrinsic_call] // add_stake( - // RawOrigin::Signed(caller), + // RawOrigin::Signed(caller), // netuid, // module_key, - // MIN_STAKE, - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn add_stake_multiple() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - - // let network: Vec = b"network".to_vec(); - - // let module_keys: Vec = (0..BATCH).map(|i| account("module_key", i as u32, SEED)).collect(); - // let amounts: Vec = (0..BATCH).map(|i| MIN_STAKE).collect(); - - // let mut netuid: u16 = 0; - - // set_user_balance::(&caller); - - // for (index, module_key) in module_keys.iter().enumerate() { - // let mut address: Vec = b"address".to_vec(); - // let mut name: Vec = b"name".to_vec(); - - // address.extend(vec![index as u8]); - // name.extend(vec![index as u8]); - - // set_user_balance::(&module_key); - - // netuid = register_helper::( - // network.clone(), - // name, - // address, - // MIN_STAKE, - // module_key.clone() - // ); - // } - - // #[extrinsic_call] + // MIN_STAKE, + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn add_stake_multiple() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); + + // let network: Vec = b"network".to_vec(); + + // let module_keys: Vec = (0..BATCH).map(|i| account("module_key", i as u32, + // SEED)).collect(); let amounts: Vec = (0..BATCH).map(|i| MIN_STAKE).collect(); + + // let mut netuid: u16 = 0; + + // set_user_balance::(&caller); + + // for (index, module_key) in module_keys.iter().enumerate() { + // let mut address: Vec = b"address".to_vec(); + // let mut name: Vec = b"name".to_vec(); + + // address.extend(vec![index as u8]); + // name.extend(vec![index as u8]); + + // set_user_balance::(&module_key); + + // netuid = register_helper::( + // network.clone(), + // name, + // address, + // MIN_STAKE, + // module_key.clone() + // ); + // } + + // #[extrinsic_call] // add_stake_multiple( - // RawOrigin::Signed(caller), + // RawOrigin::Signed(caller), // netuid, // module_keys, - // amounts, - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn remove_stake() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - // let network: Vec = b"network".to_vec(); - // let name: Vec = b"name".to_vec(); - // let address: Vec = b"address".to_vec(); - // let module_key: T::AccountId = account("module_key", 0, SEED); - - // set_user_balance::(&caller); - // set_user_balance::(&module_key); - - // let netuid = add_stake_helper::( - // caller.clone(), - // network.clone(), - // name.clone(), - // address.clone(), - // module_key.clone(), - // MIN_STAKE - // ); - - // #[extrinsic_call] + // amounts, + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn remove_stake() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); + // let network: Vec = b"network".to_vec(); + // let name: Vec = b"name".to_vec(); + // let address: Vec = b"address".to_vec(); + // let module_key: T::AccountId = account("module_key", 0, SEED); + + // set_user_balance::(&caller); + // set_user_balance::(&module_key); + + // let netuid = add_stake_helper::( + // caller.clone(), + // network.clone(), + // name.clone(), + // address.clone(), + // module_key.clone(), + // MIN_STAKE + // ); + + // #[extrinsic_call] // remove_stake( - // RawOrigin::Signed(caller.clone()), + // RawOrigin::Signed(caller.clone()), // netuid, // module_key.clone(), - // MIN_STAKE, - // ); + // MIN_STAKE, + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn remove_stake_multiple() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); + // #[benchmark] + // fn remove_stake_multiple() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); - // set_user_balance::(&caller); + // set_user_balance::(&caller); - // let (netuid, module_keys, amounts) = add_stake_multiple_helper::(caller.clone()); + // let (netuid, module_keys, amounts) = add_stake_multiple_helper::(caller.clone()); - // #[extrinsic_call] + // #[extrinsic_call] // remove_stake_multiple( - // RawOrigin::Signed(caller.clone()), + // RawOrigin::Signed(caller.clone()), // netuid, // module_keys, - // amounts, - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn transfer_stake() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - // let network: Vec = b"network".to_vec(); - - // let old_name: Vec = b"old_name".to_vec(); - // let old_address: Vec = b"old_address".to_vec(); - // let old_module_key: T::AccountId = account("old_key", 0, SEED); - - // let new_name: Vec = b"new_name".to_vec(); - // let new_address: Vec = b"new_address".to_vec(); - // let new_module_key: T::AccountId = account("new_key", 0, SEED); - - // set_user_balance::(&caller); - // set_user_balance::(&old_module_key); - // set_user_balance::(&new_module_key); - - // let _ = add_stake_helper::( - // caller.clone(), - // network.clone(), - // old_name.clone(), - // old_address.clone(), - // old_module_key.clone(), - // MIN_STAKE - // ); - - // let netuid = register_helper::( - // network.clone(), - // new_name, - // new_address, - // MIN_STAKE, - // new_module_key.clone() - // ); - - // #[extrinsic_call] + // amounts, + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn transfer_stake() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); + // let network: Vec = b"network".to_vec(); + + // let old_name: Vec = b"old_name".to_vec(); + // let old_address: Vec = b"old_address".to_vec(); + // let old_module_key: T::AccountId = account("old_key", 0, SEED); + + // let new_name: Vec = b"new_name".to_vec(); + // let new_address: Vec = b"new_address".to_vec(); + // let new_module_key: T::AccountId = account("new_key", 0, SEED); + + // set_user_balance::(&caller); + // set_user_balance::(&old_module_key); + // set_user_balance::(&new_module_key); + + // let _ = add_stake_helper::( + // caller.clone(), + // network.clone(), + // old_name.clone(), + // old_address.clone(), + // old_module_key.clone(), + // MIN_STAKE + // ); + + // let netuid = register_helper::( + // network.clone(), + // new_name, + // new_address, + // MIN_STAKE, + // new_module_key.clone() + // ); + + // #[extrinsic_call] // transfer_stake( - // RawOrigin::Signed(caller.clone()), + // RawOrigin::Signed(caller.clone()), // netuid, // old_module_key.clone(), - // new_module_key.clone(), - // MIN_STAKE, - // ); + // new_module_key.clone(), + // MIN_STAKE, + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn transfer_multiple() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - - // set_user_balance::(&caller); + // #[benchmark] + // fn transfer_multiple() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); - // let (netuid, module_keys, amounts) = multiple_register_helper::(); + // set_user_balance::(&caller); - // #[extrinsic_call] + // let (netuid, module_keys, amounts) = multiple_register_helper::(); + + // #[extrinsic_call] // transfer_multiple( - // RawOrigin::Signed(caller), + // RawOrigin::Signed(caller), // module_keys, - // amounts, - // ); + // amounts, + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn update_module() -> Result<(), BenchmarkError> { - // let (network, name, address, module_key, netuid) = single_register_helper::(); + // #[benchmark] + // fn update_module() -> Result<(), BenchmarkError> { + // let (network, name, address, module_key, netuid) = single_register_helper::(); - // let mut new_name = name.clone(); - // new_name.extend(vec![1u8]); + // let mut new_name = name.clone(); + // new_name.extend(vec![1u8]); - // #[extrinsic_call] + // #[extrinsic_call] // update_module( - // RawOrigin::Signed(module_key.clone()), + // RawOrigin::Signed(module_key.clone()), // netuid, - // new_name, - // address, - // Option::None - // ); - - // Ok(()) - // } - - #[benchmark] - fn register() -> Result<(), BenchmarkError> { - let network: Vec = b"network".to_vec(); - let name: Vec = b"name".to_vec(); - let address: Vec = b"address".to_vec(); - let module_key: T::AccountId = account("key", 0, SEED); - - set_user_balance::(&module_key); - - #[extrinsic_call] + // new_name, + // address, + // Option::None + // ); + + // Ok(()) + // } + + #[benchmark] + fn register() -> Result<(), BenchmarkError> { + let network: Vec = b"network".to_vec(); + let name: Vec = b"name".to_vec(); + let address: Vec = b"address".to_vec(); + let module_key: T::AccountId = account("key", 0, SEED); + + set_user_balance::(&module_key); + + #[extrinsic_call] register( - RawOrigin::Signed(module_key.clone()), + RawOrigin::Signed(module_key.clone()), network.clone(), - name, - address, - MIN_STAKE, + name, + address, + MIN_STAKE, module_key.clone(), - ); + ); - Ok(()) - } + Ok(()) + } - // #[benchmark] - // fn deregister() -> Result<(), BenchmarkError> { - // let (_, _, _, module_key, netuid) = single_register_helper::(); + // #[benchmark] + // fn deregister() -> Result<(), BenchmarkError> { + // let (_, _, _, module_key, netuid) = single_register_helper::(); - // #[extrinsic_call] + // #[extrinsic_call] // deregister( - // RawOrigin::Signed(module_key.clone()), + // RawOrigin::Signed(module_key.clone()), // netuid - // ); + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn add_profit_shares() -> Result<(), BenchmarkError> { - // let (_, _, _, module_key, netuid) = single_register_helper::(); + // #[benchmark] + // fn add_profit_shares() -> Result<(), BenchmarkError> { + // let (_, _, _, module_key, netuid) = single_register_helper::(); - // let keys: Vec = (0..BATCH).map(|i| account("key", i as u32, SEED)).collect(); - // let shares: Vec = (0..BATCH).map(|i| i as u16 + 1).collect(); + // let keys: Vec = (0..BATCH).map(|i| account("key", i as u32, + // SEED)).collect(); let shares: Vec = (0..BATCH).map(|i| i as u16 + 1).collect(); - // #[extrinsic_call] + // #[extrinsic_call] // add_profit_shares( - // RawOrigin::Signed(module_key.clone()), + // RawOrigin::Signed(module_key.clone()), // keys, - // shares - // ); + // shares + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn update_global() -> Result<(), BenchmarkError> { - // #[extrinsic_call] + // #[benchmark] + // fn update_global() -> Result<(), BenchmarkError> { + // #[extrinsic_call] // update_global( - // RawOrigin::Root, + // RawOrigin::Root, // 1, // burn_rate - // 1, // max_allowed_modules - // 1, // max_allowed_subnets - // 1, // max_name_length - // 1, // max_proposals - // 1, // max_registrations_per_block - // 0, // min_burn - // 0, // min_stake - // 0, // min_weight_stake - // 1, // tx_rate_limit - // 1, // unit_emission - // b"stake".to_vec(), // vote_mode - // 1, // vote_threshold - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn add_global_proposal() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("caller", 0, SEED); - - // #[extrinsic_call] + // 1, // max_allowed_modules + // 1, // max_allowed_subnets + // 1, // max_name_length + // 1, // max_proposals + // 1, // max_registrations_per_block + // 0, // min_burn + // 0, // min_stake + // 0, // min_weight_stake + // 1, // tx_rate_limit + // 1, // unit_emission + // b"stake".to_vec(), // vote_mode + // 1, // vote_threshold + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn add_global_proposal() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("caller", 0, SEED); + + // #[extrinsic_call] // add_global_proposal( - // RawOrigin::Signed(caller), + // RawOrigin::Signed(caller), // 1, // burn_rate - // 1, // max_allowed_modules - // 1, // max_allowed_subnets - // 1, // max_name_length - // 1, // max_proposals - // 1, // max_registrations_per_block - // 0, // min_burn - // 0, // min_stake - // 0, // min_weight_stake - // 1, // unit_emission - // 1, // tx_rate_limit - // 1, // vote_threshold - // b"stake".to_vec(), // vote_mode - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn update_subnet() -> Result<(), BenchmarkError> { - // let (network, name, address, module_key, netuid) = single_register_helper::(); - - // let subnet_params = >::subnet_params(netuid); - - // #[extrinsic_call] + // 1, // max_allowed_modules + // 1, // max_allowed_subnets + // 1, // max_name_length + // 1, // max_proposals + // 1, // max_registrations_per_block + // 0, // min_burn + // 0, // min_stake + // 0, // min_weight_stake + // 1, // unit_emission + // 1, // tx_rate_limit + // 1, // vote_threshold + // b"stake".to_vec(), // vote_mode + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn update_subnet() -> Result<(), BenchmarkError> { + // let (network, name, address, module_key, netuid) = single_register_helper::(); + + // let subnet_params = >::subnet_params(netuid); + + // #[extrinsic_call] // update_subnet( - // RawOrigin::Signed(module_key.clone()), + // RawOrigin::Signed(module_key.clone()), // netuid, // subnet_params.founder, - // subnet_params.founder_share, + // subnet_params.founder_share, // subnet_params.immunity_period, - // subnet_params.incentive_ratio, - // subnet_params.max_allowed_uids, - // subnet_params.max_allowed_weights, - // subnet_params.max_stake, - // subnet_params.min_allowed_weights, - // subnet_params.min_stake, + // subnet_params.incentive_ratio, + // subnet_params.max_allowed_uids, + // subnet_params.max_allowed_weights, + // subnet_params.max_stake, + // subnet_params.min_allowed_weights, + // subnet_params.min_stake, // b"new_name".to_vec(), - // subnet_params.self_vote, - // subnet_params.tempo, - // subnet_params.trust_ratio, - // subnet_params.vote_mode, - // subnet_params.vote_threshold, - // ); + // subnet_params.self_vote, + // subnet_params.tempo, + // subnet_params.trust_ratio, + // subnet_params.vote_mode, + // subnet_params.vote_threshold, + // ); - // Ok(()) - // } + // Ok(()) + // } - // #[benchmark] - // fn add_subnet_proposal() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("key", 0, SEED); + // #[benchmark] + // fn add_subnet_proposal() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("key", 0, SEED); - // let (_, _, _, _, netuid) = single_register_helper::(); + // let (_, _, _, _, netuid) = single_register_helper::(); - // #[extrinsic_call] + // #[extrinsic_call] // add_subnet_proposal( - // RawOrigin::Signed(caller.clone()), + // RawOrigin::Signed(caller.clone()), // netuid, - // caller.clone(), // founder - // 1, // founder_share - // 1, // immunity_period - // 1, // incentive_ratio - // u16::MAX, // max_allowed_uids - // 1, // max_allowed_weights - // u64::MAX, // max_stake - // 1, // min_allowed_weights - // 0, // min_stake - // b"new_name".to_vec(), // name - // true, // self_vote - // 1, // tempo - // 1, // trust_ratio - // b"stake".to_vec(), // vote_mode - // 1, // vote_threshold - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn add_custom_proposal() -> Result<(), BenchmarkError> { - // let caller: T::AccountId = account("key", 0, SEED); - - // #[extrinsic_call] + // caller.clone(), // founder + // 1, // founder_share + // 1, // immunity_period + // 1, // incentive_ratio + // u16::MAX, // max_allowed_uids + // 1, // max_allowed_weights + // u64::MAX, // max_stake + // 1, // min_allowed_weights + // 0, // min_stake + // b"new_name".to_vec(), // name + // true, // self_vote + // 1, // tempo + // 1, // trust_ratio + // b"stake".to_vec(), // vote_mode + // 1, // vote_threshold + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn add_custom_proposal() -> Result<(), BenchmarkError> { + // let caller: T::AccountId = account("key", 0, SEED); + + // #[extrinsic_call] // add_custom_proposal( - // RawOrigin::Signed(caller.clone()), - // b"custom_proposal_data".to_vec(), // data - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn vote_proposal() -> Result<(), BenchmarkError> { - // let proposer: T::AccountId = account("proposer", 0, SEED); - // let voter: T::AccountId = account("voter", 0, SEED); - - // set_user_balance::(&proposer); - // set_user_balance::(&voter); - - // let (network, name, address, module_key, netuid) = single_register_helper::(); - - // let _ = add_stake_helper::( - // proposer.clone(), - // network.clone(), - // name.clone(), - // address.clone(), - // module_key.clone(), - // MIN_STAKE - // ); - - // let _ = add_stake_helper::( - // voter.clone(), - // network.clone(), - // name.clone(), - // address.clone(), - // module_key.clone(), - // MIN_STAKE - // ); + // RawOrigin::Signed(caller.clone()), + // b"custom_proposal_data".to_vec(), // data + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn vote_proposal() -> Result<(), BenchmarkError> { + // let proposer: T::AccountId = account("proposer", 0, SEED); + // let voter: T::AccountId = account("voter", 0, SEED); + + // set_user_balance::(&proposer); + // set_user_balance::(&voter); + + // let (network, name, address, module_key, netuid) = single_register_helper::(); + + // let _ = add_stake_helper::( + // proposer.clone(), + // network.clone(), + // name.clone(), + // address.clone(), + // module_key.clone(), + // MIN_STAKE + // ); + + // let _ = add_stake_helper::( + // voter.clone(), + // network.clone(), + // name.clone(), + // address.clone(), + // module_key.clone(), + // MIN_STAKE + // ); // >::add_subnet_proposal( - // RawOrigin::Signed(proposer.clone()).into(), + // RawOrigin::Signed(proposer.clone()).into(), // netuid, - // proposer.clone(), // founder - // 1, // founder_share - // 1, // immunity_period - // 1, // incentive_ratio - // u16::MAX, // max_allowed_uids - // 1, // max_allowed_weights - // u64::MAX, // max_stake - // 1, // min_allowed_weights - // 0, // min_stake - // b"new_name".to_vec(), // name - // true, // self_vote - // 1, // tempo - // 1, // trust_ratio - // b"stake".to_vec(), // vote_mode - // 1, // vote_threshold - // ); - - // #[extrinsic_call] + // proposer.clone(), // founder + // 1, // founder_share + // 1, // immunity_period + // 1, // incentive_ratio + // u16::MAX, // max_allowed_uids + // 1, // max_allowed_weights + // u64::MAX, // max_stake + // 1, // min_allowed_weights + // 0, // min_stake + // b"new_name".to_vec(), // name + // true, // self_vote + // 1, // tempo + // 1, // trust_ratio + // b"stake".to_vec(), // vote_mode + // 1, // vote_threshold + // ); + + // #[extrinsic_call] // vote_proposal( - // RawOrigin::Signed(voter.clone()), + // RawOrigin::Signed(voter.clone()), // 0 - // ); - - // Ok(()) - // } - - // #[benchmark] - // fn unvote_proposal() -> Result<(), BenchmarkError> { - // let proposer: T::AccountId = account("proposer", 0, SEED); - // let voter: T::AccountId = account("voter", 0, SEED); - - // set_user_balance::(&proposer); - // set_user_balance::(&voter); - - // let (network, name, address, module_key, netuid) = single_register_helper::(); - - // let _ = add_stake_helper::( - // proposer.clone(), - // network.clone(), - // name.clone(), - // address.clone(), - // module_key.clone(), - // MIN_STAKE - // ); - - // let _ = add_stake_helper::( - // voter.clone(), - // network.clone(), - // name.clone(), - // address.clone(), - // module_key.clone(), - // MIN_STAKE - // ); + // ); + + // Ok(()) + // } + + // #[benchmark] + // fn unvote_proposal() -> Result<(), BenchmarkError> { + // let proposer: T::AccountId = account("proposer", 0, SEED); + // let voter: T::AccountId = account("voter", 0, SEED); + + // set_user_balance::(&proposer); + // set_user_balance::(&voter); + + // let (network, name, address, module_key, netuid) = single_register_helper::(); + + // let _ = add_stake_helper::( + // proposer.clone(), + // network.clone(), + // name.clone(), + // address.clone(), + // module_key.clone(), + // MIN_STAKE + // ); + + // let _ = add_stake_helper::( + // voter.clone(), + // network.clone(), + // name.clone(), + // address.clone(), + // module_key.clone(), + // MIN_STAKE + // ); // >::add_subnet_proposal( - // RawOrigin::Signed(proposer.clone()).into(), + // RawOrigin::Signed(proposer.clone()).into(), // netuid, - // proposer.clone(), // founder - // 1, // founder_share - // 1, // immunity_period - // 1, // incentive_ratio - // u16::MAX, // max_allowed_uids - // 1, // max_allowed_weights - // u64::MAX, // max_stake - // 1, // min_allowed_weights - // 0, // min_stake - // b"new_name".to_vec(), // name - // true, // self_vote - // 1, // tempo - // 1, // trust_ratio - // b"stake".to_vec(), // vote_mode - // 100, // vote_threshold - // ); + // proposer.clone(), // founder + // 1, // founder_share + // 1, // immunity_period + // 1, // incentive_ratio + // u16::MAX, // max_allowed_uids + // 1, // max_allowed_weights + // u64::MAX, // max_stake + // 1, // min_allowed_weights + // 0, // min_stake + // b"new_name".to_vec(), // name + // true, // self_vote + // 1, // tempo + // 1, // trust_ratio + // b"stake".to_vec(), // vote_mode + // 100, // vote_threshold + // ); // >::vote_proposal( - // RawOrigin::Signed(voter.clone()).into(), + // RawOrigin::Signed(voter.clone()).into(), // 0 - // ); + // ); - // #[extrinsic_call] - // unvote_proposal( - // RawOrigin::Signed(voter.clone()), - // ); + // #[extrinsic_call] + // unvote_proposal( + // RawOrigin::Signed(voter.clone()), + // ); - // Ok(()) - // } + // Ok(()) + // } - impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); } diff --git a/pallets/subspace/src/global.rs b/pallets/subspace/src/global.rs index ca98ef32d..7e8799715 100644 --- a/pallets/subspace/src/global.rs +++ b/pallets/subspace/src/global.rs @@ -1,12 +1,9 @@ use super::*; use frame_support::pallet_prelude::DispatchResult; -use sp_runtime::DispatchError; -use system::ensure_root; -use crate::utils::is_vec_str; use sp_runtime::BoundedVec; +use system::ensure_root; impl Pallet { - pub fn global_params() -> GlobalParams { GlobalParams { max_name_length: Self::get_global_max_name_length(), @@ -26,18 +23,21 @@ impl Pallet { } } - pub fn check_global_params(params: GlobalParams) -> DispatchResult{ - // checks if params are valid + pub fn check_global_params(params: GlobalParams) -> DispatchResult { + // checks if params are valid let og_params = Self::global_params(); - // check if the name already exists - ensure!(params.max_name_length > 0, Error::::InvalidMaxNameLength); - - ensure!(params.max_allowed_subnets > 0, Error::::InvalidMaxAllowedSubnets); + // check if the name already exists + ensure!(params.max_name_length > 0, Error::::InvalidMaxNameLength); + + ensure!(params.max_allowed_subnets > 0, Error::::InvalidMaxAllowedSubnets); ensure!(params.max_allowed_modules > 0, Error::::InvalidMaxAllowedModules); - ensure!(params.max_registrations_per_block > 0, Error::::InvalidMaxRegistrationsPerBlock); + ensure!( + params.max_registrations_per_block > 0, + Error::::InvalidMaxRegistrationsPerBlock + ); ensure!(params.vote_threshold < 100, Error::::InvalidVoteThreshold); @@ -48,17 +48,13 @@ impl Pallet { ensure!(params.tx_rate_limit > 0, Error::::InvalidTxRateLimit); ensure!(params.burn_rate <= 100, Error::::InvalidBurnRate); - - ensure!(params.min_burn <= 100, Error::::InvalidMinBurn); - - - Ok(()) - } + ensure!(params.min_burn <= 100, Error::::InvalidMinBurn); + Ok(()) + } pub fn set_global_params(params: GlobalParams) { - Self::set_global_max_name_length(params.max_name_length); Self::set_global_max_allowed_subnets(params.max_allowed_subnets); Self::set_max_allowed_modules(params.max_allowed_modules); @@ -69,7 +65,7 @@ impl Pallet { Self::set_max_proposals(params.max_proposals); Self::set_vote_mode_global(params.vote_mode); Self::set_burn_rate(params.burn_rate); - Self::set_min_burn( params.min_burn); + Self::set_min_burn(params.min_burn); Self::set_min_weight_stake(params.min_weight_stake); Self::set_min_stake_global(params.min_stake); } @@ -77,7 +73,7 @@ impl Pallet { pub fn get_min_weight_stake() -> u64 { GlobalStateStorage::::get().min_weight_stake } - pub fn set_min_weight_stake(min_weight_stake: u64) { + pub fn set_min_weight_stake(min_weight_stake: u64) { let mut global_state = GlobalStateStorage::::get(); global_state.min_weight_stake = min_weight_stake; @@ -111,11 +107,12 @@ impl Pallet { pub fn set_vote_mode_global(vote_mode: Vec) { let mut global_state = GlobalStateStorage::::get(); - global_state.vote_mode = BoundedVec::>::try_from(vote_mode).expect("too long vote mode"); + global_state.vote_mode = + BoundedVec::>::try_from(vote_mode).expect("too long vote mode"); GlobalStateStorage::::put(global_state) } - + pub fn get_vote_mode_global() -> Vec { GlobalStateStorage::::get().vote_mode.into_inner() } @@ -123,14 +120,13 @@ impl Pallet { GlobalStateStorage::::get().burn_rate } - pub fn set_burn_rate(mut burn_rate: u16) { + pub fn set_burn_rate(burn_rate: u16) { let mut global_state = GlobalStateStorage::::get(); - global_state.burn_rate = burn_rate.min(100); GlobalStateStorage::::put(global_state) } - + pub fn set_max_proposals(max_proposals: u64) { let mut global_state = GlobalStateStorage::::get(); @@ -168,44 +164,34 @@ impl Pallet { GlobalStateStorage::::put(global_state) } - pub fn do_update_global( - origin: T::RuntimeOrigin, - params: GlobalParams, - ) -> DispatchResult { + pub fn do_update_global(origin: T::RuntimeOrigin, params: GlobalParams) -> DispatchResult { ensure_root(origin)?; - ensure!(is_vec_str(Self::get_vote_mode_global(),"authority"), Error::::InvalidVoteMode); - + ensure!(Self::get_vote_mode_global() == b"authority", Error::::InvalidVoteMode); + Self::set_global_params(params.clone()); - + Ok(()) } pub fn global_n() -> u16 { - let mut global_n : u16 = 0; - - for netuid in Self::netuids() { - global_n += SubnetStateStorage::::get(netuid).n; - } - - return global_n + Self::netuids() + .iter() + .map(|netuid| SubnetStateStorage::::get(netuid).n) + .sum() } - - pub fn get_global_stake_to( - key: &T::AccountId, - ) -> u64 { + pub fn get_global_stake_to(key: &T::AccountId) -> u64 { // get all of the stake to - let total_networks: u16 = GlobalStateStorage::::get().total_subnets; - let mut total_stake_to = 0; - - for netuid in 0..total_networks { - total_stake_to += Self::get_total_stake_to(netuid, key); - } + let total_networks: u16 = GlobalStateStorage::::get().total_subnets; + let mut total_stake_to = 0; - total_stake_to - } + for netuid in 0..total_networks { + total_stake_to += Self::get_total_stake_to(netuid, key); + } + total_stake_to + } // Configure tx rate limiting pub fn get_tx_rate_limit() -> u64 { @@ -219,7 +205,7 @@ impl Pallet { GlobalStateStorage::::put(global_state) } - pub fn set_min_burn( min_burn: u64) { + pub fn set_min_burn(min_burn: u64) { let mut global_state = GlobalStateStorage::::get(); global_state.min_burn = min_burn; diff --git a/pallets/subspace/src/lib.rs b/pallets/subspace/src/lib.rs index 9235b7f3f..30fbab435 100644 --- a/pallets/subspace/src/lib.rs +++ b/pallets/subspace/src/lib.rs @@ -1,5 +1,4 @@ -// disable all warnings -#![allow(warnings)] +#![allow(deprecated)] #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "512"] use frame_system::{self as system, ensure_signed}; @@ -15,12 +14,12 @@ use frame_support::{ use codec::{Decode, Encode}; use frame_support::sp_runtime::transaction_validity::ValidTransaction; use scale_info::TypeInfo; +use sp_core::ConstU32; use sp_runtime::{ traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SignedExtension}, transaction_validity::{TransactionValidity, TransactionValidityError}, }; use sp_std::marker::PhantomData; -use sp_core::ConstU32; // ============================ // ==== Benchmark Imports ===== @@ -39,25 +38,24 @@ mod mock; // ========================= mod global; mod math; -mod utils; +mod migration; pub mod module; -mod subnet; +mod profit_share; mod registration; mod staking; mod step; -mod weights; +mod subnet; mod voting; -mod profit_share; -mod migration; +mod weights; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{pallet_prelude::{ValueQuery, *}, traits::Currency}; + use frame_support::{ + pallet_prelude::{ValueQuery, *}, + traits::Currency, + }; use frame_system::pallet_prelude::*; - use scale_info::prelude::string::String; - use serde::{Deserialize, Serialize}; - use serde_with::{serde_as, DisplayFromStr}; use sp_arithmetic::per_things::Percent; pub use sp_std::{vec, vec::Vec}; @@ -89,7 +87,6 @@ pub mod pallet { // ==== Defaults ==== // ======================================= - #[pallet::type_value] pub fn EmptyU16Vec() -> Vec { vec![] @@ -107,9 +104,12 @@ pub mod pallet { // ==== Global Variables ==== // ============================ #[pallet::type_value] - pub fn DefaultLastTxBlock() -> u64 { 0 } + pub fn DefaultLastTxBlock() -> u64 { + 0 + } #[pallet::storage] // --- MAP ( key ) --> last_block - pub(super) type LastTxBlock = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; + pub(super) type LastTxBlock = + StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; #[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen, PartialEqNoBound, RuntimeDebug)] #[scale_info(skip_type_params(T))] @@ -120,18 +120,18 @@ pub mod pallet { pub total_subnets: u16, // max - pub max_name_length: u16, // max length of a network name - pub max_allowed_subnets: u16, // max number of subnets allowed - pub max_allowed_modules: u16, // max number of modules allowed per subnet + pub max_name_length: u16, // max length of a network name + pub max_allowed_subnets: u16, // max number of subnets allowed + pub max_allowed_modules: u16, // max number of modules allowed per subnet pub max_registrations_per_block: u16, // max number of registrations per block - pub max_allowed_weights: u16, // max number of weights per module + pub max_allowed_weights: u16, // max number of weights per module pub max_proposals: u64, - + // min - pub min_burn: u64, // min burn required - pub min_stake: u64, // min stake required + pub min_burn: u64, // min burn required + pub min_stake: u64, // min stake required pub min_weight_stake: u64, // min weight stake required - + // other pub unit_emission: u64, // emission per block pub tx_rate_limit: u64, // tx rate limit @@ -147,21 +147,21 @@ pub mod pallet { GlobalState { registrations_per_block: 0, total_subnets: 0, - max_name_length: 32, // max length of a network name - max_allowed_subnets: 256, // max number of subnets allowed - max_allowed_modules: 10_000, // max number of modules allowed per subnet + max_name_length: 32, // max length of a network name + max_allowed_subnets: 256, // max number of subnets allowed + max_allowed_modules: 10_000, // max number of modules allowed per subnet max_registrations_per_block: 10, // max number of registrations per block - max_allowed_weights: 512, // max number of weights per module + max_allowed_weights: 512, // max number of weights per module max_proposals: 128, - + // min - min_burn: 0, // min burn required - min_stake: 0, // min stake required - min_weight_stake: 0,// min weight stake required - + min_burn: 0, // min burn required + min_stake: 0, // min stake required + min_weight_stake: 0, // min weight stake required + // other unit_emission: 23148148148, // emission per block - tx_rate_limit: 1, // tx rate limit + tx_rate_limit: 1, // tx rate limit burn_rate: 0, // vote @@ -171,7 +171,8 @@ pub mod pallet { } #[pallet::storage] #[pallet::getter(fn global_state)] - pub(super) type GlobalStateStorage = StorageValue<_, GlobalState, ValueQuery, DefaultGlobalState>; + pub(super) type GlobalStateStorage = + StorageValue<_, GlobalState, ValueQuery, DefaultGlobalState>; #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] #[scale_info(skip_type_params(T))] @@ -187,23 +188,23 @@ pub mod pallet { pub struct GlobalParams { pub burn_rate: u16, // max - pub max_name_length: u16, // max length of a network name - pub max_allowed_subnets: u16, // max number of subnets allowed - pub max_allowed_modules: u16, // max number of modules allowed per subnet + pub max_name_length: u16, // max length of a network name + pub max_allowed_subnets: u16, // max number of subnets allowed + pub max_allowed_modules: u16, // max number of modules allowed per subnet pub max_registrations_per_block: u16, // max number of registrations per block - pub max_allowed_weights: u16, // max number of weights per module - pub max_proposals: u64, // max number of proposals per block + pub max_allowed_weights: u16, // max number of weights per module + pub max_proposals: u64, // max number of proposals per block // mins - pub min_burn: u64, // min burn required - pub min_stake: u64, // min stake required + pub min_burn: u64, // min burn required + pub min_stake: u64, // min stake required pub min_weight_stake: u64, // min weight stake required // other - pub unit_emission: u64, // emission per block - pub tx_rate_limit: u64, // tx rate limit + pub unit_emission: u64, // emission per block + pub tx_rate_limit: u64, // tx rate limit pub vote_threshold: u16, // out of 100 - pub vote_mode: Vec, // out of 100 + pub vote_mode: Vec, // out of 100 } #[pallet::type_value] @@ -220,14 +221,13 @@ pub mod pallet { min_burn: 0, min_stake: 100, min_weight_stake: 0, - unit_emission: 23148148148, + unit_emission: 23148148148, tx_rate_limit: 1, vote_threshold: 50, vote_mode: b"authority".to_vec(), } } - // ========================= // ==== Subnet PARAMS ==== // ========================= @@ -236,17 +236,18 @@ pub mod pallet { #[codec(mel_bound())] pub struct SubnetState { pub founder: T::AccountId, - pub founder_share: u16, // out of 100 - pub incentive_ratio : u16, // out of 100 - pub immunity_period: u16, // immunity period - pub max_allowed_uids: u16, // max number of weights allowed to be registered in this + pub founder_share: u16, // out of 100 + pub incentive_ratio: u16, // out of 100 + pub immunity_period: u16, // immunity period + pub max_allowed_uids: u16, // max number of weights allowed to be registered in this pub max_allowed_weights: u16, // max number of weights allowed to be registered in this pub min_allowed_weights: u16, // min number of weights allowed to be registered in this - pub max_stake: u64, // max stake allowed - pub max_weight_age: u64, // max age of a weightpub max_weight_age: u64, // max age of a weight - pub min_stake: u64, // min stake required - pub self_vote: bool, // - pub tempo: u16, // how many blocks to wait before rewarding models + pub max_stake: u64, // max stake allowed + pub max_weight_age: u64, /* max age of a weightpub max_weight_age: u64, // max age + * of a weight */ + pub min_stake: u64, // min stake required + pub self_vote: bool, // + pub tempo: u16, // how many blocks to wait before rewarding models pub trust_ratio: u16, pub quadratic_voting: bool, pub pending_deregister_uids: BoundedVec>, @@ -271,18 +272,20 @@ pub mod pallet { #[pallet::type_value] pub fn DefaultSubnetState() -> SubnetState { SubnetState { - founder: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap(), - founder_share: 0, // out of 100 - incentive_ratio : 50, // out of 100 - immunity_period: 40, // immunity period - max_allowed_uids: 4096, // max number of weights allowed to be registered in this + founder: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) + .unwrap(), + founder_share: 0, // out of 100 + incentive_ratio: 50, // out of 100 + immunity_period: 40, // immunity period + max_allowed_uids: 4096, // max number of weights allowed to be registered in this max_allowed_weights: 420, // max number of weights allowed to be registered in this - min_allowed_weights: 1, // min number of weights allowed to be registered in this - max_stake: u64::MAX, // max stake allowed - max_weight_age: u64::MAX, // max age of a weightmax_weight_age: u64, // max age of a weight - min_stake: 0, // min stake required - self_vote: true, // - tempo: 1, // how many blocks to wait before rewarding models + min_allowed_weights: 1, // min number of weights allowed to be registered in this + max_stake: u64::MAX, // max stake allowed + max_weight_age: u64::MAX, /* max age of a weightmax_weight_age: u64, // max age of a + * weight */ + min_stake: 0, // min stake required + self_vote: true, // + tempo: 1, // how many blocks to wait before rewarding models trust_ratio: 0, quadratic_voting: false, pending_deregister_uids: BoundedVec::>::default(), @@ -300,30 +303,31 @@ pub mod pallet { trusts: BoundedVec::>::default(), dividends: BoundedVec::>::default(), emissions: BoundedVec::>::default(), - last_updates: BoundedVec::>::default() + last_updates: BoundedVec::>::default(), } } #[pallet::storage] #[pallet::getter(fn subnet_state)] - pub(super) type SubnetStateStorage = StorageMap<_, Identity, u16, SubnetState, ValueQuery, DefaultSubnetState>; + pub(super) type SubnetStateStorage = + StorageMap<_, Identity, u16, SubnetState, ValueQuery, DefaultSubnetState>; #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct SubnetParams { // --- parameters pub founder: T::AccountId, - pub founder_share: u16, // out of 100 - pub immunity_period: u16, // immunity period - pub incentive_ratio : u16, // out of 100 - pub max_allowed_uids: u16, // max number of weights allowed to be registered in this + pub founder_share: u16, // out of 100 + pub immunity_period: u16, // immunity period + pub incentive_ratio: u16, // out of 100 + pub max_allowed_uids: u16, // max number of weights allowed to be registered in this pub max_allowed_weights: u16, // max number of weights allowed to be registered in this pub min_allowed_weights: u16, // min number of weights allowed to be registered in this - pub max_stake: u64, // max stake allowed - pub max_weight_age: u64, // max age of a weight - pub min_stake: u64, // min stake required + pub max_stake: u64, // max stake allowed + pub max_weight_age: u64, // max age of a weight + pub min_stake: u64, // min stake required pub name: Vec, - pub self_vote: bool, // - pub tempo: u16, // how many blocks to wait before rewarding models + pub self_vote: bool, // + pub tempo: u16, // how many blocks to wait before rewarding models pub trust_ratio: u16, pub vote_threshold: u16, // out of 100 pub vote_mode: Vec, @@ -345,9 +349,10 @@ pub mod pallet { trust_ratio: 0, self_vote: true, founder_share: 0, - incentive_ratio : 50, - min_stake : 0, - founder: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap(), + incentive_ratio: 50, + min_stake: 0, + founder: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) + .unwrap(), } } @@ -364,20 +369,17 @@ pub mod pallet { } #[pallet::type_value] - pub fn DefaultVoterInfo() -> VoterInfo { - VoterInfo { - proposal_id: u64::MAX, - votes: 0, - participant_index: u16::MAX, - } + pub fn DefaultVoterInfo() -> VoterInfo { + VoterInfo { proposal_id: u64::MAX, votes: 0, participant_index: u16::MAX } } #[pallet::storage] // --- MAP ( netuid ) --> epoch - pub type Voter2Info =StorageMap<_, Identity, T::AccountId, VoterInfo, ValueQuery, DefaultVoterInfo>; + pub type Voter2Info = + StorageMap<_, Identity, T::AccountId, VoterInfo, ValueQuery, DefaultVoterInfo>; #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetInfo { // --- parameters - pub params: SubnetParams , + pub params: SubnetParams, pub netuid: u16, // --- unique id of the network pub n: u16, pub stake: u64, @@ -389,42 +391,60 @@ pub mod pallet { // ==== Module Variables ==== // ======================================= - #[pallet::storage] // --- DMAP ( netuid, module_key ) --> uid pub(super) type Uids = StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, u16, OptionQuery>; - #[pallet::storage] // --- DMAP ( netuid, module_key ) --> uid - pub(super) type Key2Controller = - StorageDoubleMap<_, Identity, T::AccountId, Blake2_128Concat, T::AccountId, u16, OptionQuery>; + pub(super) type Key2Controller = StorageDoubleMap< + _, + Identity, + T::AccountId, + Blake2_128Concat, + T::AccountId, + u16, + OptionQuery, + >; #[pallet::storage] // --- DMAP ( netuid, module_key ) --> uid - pub(super) type Controller2Keys = - StorageDoubleMap<_, Identity, T::AccountId, Blake2_128Concat, Vec, u16, OptionQuery>; + pub(super) type Controller2Keys = StorageDoubleMap< + _, + Identity, + T::AccountId, + Blake2_128Concat, + Vec, + u16, + OptionQuery, + >; - - #[pallet::type_value] pub fn DefaultKey() -> T::AccountId { T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap() } #[pallet::storage] // --- DMAP ( netuid, uid ) --> module_key - pub(super) type Keys = StorageDoubleMap<_, Identity, u16, Identity, u16, T::AccountId, ValueQuery, DefaultKey>; + pub(super) type Keys = + StorageDoubleMap<_, Identity, u16, Identity, u16, T::AccountId, ValueQuery, DefaultKey>; #[pallet::type_value] - pub fn DefaultName() -> Vec {vec![]} + pub fn DefaultName() -> Vec { + vec![] + } #[pallet::storage] // --- DMAP ( netuid, uid ) --> module_name - pub type Name =StorageDoubleMap<_, Twox64Concat, u16, Twox64Concat, u16, Vec, ValueQuery>; + pub type Name = + StorageDoubleMap<_, Twox64Concat, u16, Twox64Concat, u16, Vec, ValueQuery>; #[pallet::type_value] - pub fn DefaultAddress() -> Vec {vec![]} + pub fn DefaultAddress() -> Vec { + vec![] + } #[pallet::storage] // --- DMAP ( netuid, uid ) --> module_address - pub type Address = StorageDoubleMap<_, Twox64Concat, u16, Twox64Concat, u16, Vec, ValueQuery>; - + pub type Address = + StorageDoubleMap<_, Twox64Concat, u16, Twox64Concat, u16, Vec, ValueQuery>; #[pallet::type_value] - pub fn DefaultDelegationFee() -> Percent { Percent::from_percent(20u8)} + pub fn DefaultDelegationFee() -> Percent { + Percent::from_percent(20u8) + } #[pallet::storage] // -- DMAP(netuid, module_key) -> delegation_fee pub(super) type DelegationFee = StorageDoubleMap< _, @@ -440,7 +460,9 @@ pub mod pallet { // STATE OF THE MODULE #[pallet::type_value] - pub fn DefaultBlockAtRegistration() -> u64 { 0 } + pub fn DefaultBlockAtRegistration() -> u64 { + 0 + } #[pallet::storage] // --- DMAP ( netuid, uid ) --> block number that the module is registered pub type RegistrationBlock = StorageDoubleMap< _, @@ -458,7 +480,9 @@ pub mod pallet { // ======================================= #[pallet::type_value] - pub fn DefaultStake() -> u64 { 0 } + pub fn DefaultStake() -> u64 { + 0 + } #[pallet::storage] // --- DMAP ( netuid, module_key ) --> stake | Returns the stake under a module. pub type Stake = StorageDoubleMap< @@ -497,42 +521,38 @@ pub mod pallet { // LOAN VARIABLES #[pallet::storage] // --- DMAP ( netuid, module_key ) --> Vec<(delegater, stake )> | Returns the list of delegates - pub type LoanTo = StorageMap< - _, - Identity, - T::AccountId, - Vec<(T::AccountId, u64)>, - ValueQuery, - >; + pub type LoanTo = + StorageMap<_, Identity, T::AccountId, Vec<(T::AccountId, u64)>, ValueQuery>; #[pallet::storage] // --- DMAP ( netuid, module_key ) --> Vec<(delegater, stake )> | Returns the list of delegates - pub type LoanFrom = StorageMap< + pub type LoanFrom = + StorageMap<_, Identity, T::AccountId, Vec<(T::AccountId, u64)>, ValueQuery>; + + // PROFIT SHARE VARIABLES + + #[pallet::type_value] + pub fn DefaultProfitShares() -> Vec<(T::AccountId, u16)> { + vec![] + } + + #[pallet::storage] // --- DMAP ( netuid, account_id ) --> Vec<(module_key, stake )> | Returns the list of the + pub type ProfitShares = StorageMap< _, Identity, T::AccountId, - Vec<(T::AccountId, u64)>, + Vec<(T::AccountId, u16)>, ValueQuery, + DefaultProfitShares, >; - // PROFIT SHARE VARIABLES - - #[pallet::type_value] - pub fn DefaultProfitShares() -> Vec<(T::AccountId, u16)> {vec![]} - - #[pallet::storage] // --- DMAP ( netuid, account_id ) --> Vec<(module_key, stake )> | Returns the list of the - pub type ProfitShares = StorageMap<_, - Identity, - T::AccountId, - Vec<(T::AccountId, u16)>, - ValueQuery, - DefaultProfitShares>; - // ======================================= // ==== Module Consensus Variables ==== // ======================================= #[pallet::type_value] - pub fn DefaultWeights() -> Vec<(u16, u16)> {vec![]} + pub fn DefaultWeights() -> Vec<(u16, u16)> { + vec![] + } #[pallet::storage] // --- DMAP ( netuid, uid ) --> weights pub(super) type Weights = StorageDoubleMap< _, @@ -545,7 +565,6 @@ pub mod pallet { DefaultWeights, >; - #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { @@ -581,8 +600,8 @@ pub mod pallet { MaxAllowedModulesSet(u16), // --- Event created when setting the maximum allowed modules MaxRegistrationsPerBlockSet(u16), // --- Event created when we set max registrations per block GlobalUpdate(u16, u16, u16, u16, u64, u64), - GlobalProposalAccepted(u64), // (id) - CustomProposalAccepted(u64), // (id) + GlobalProposalAccepted(u64), // (id) + CustomProposalAccepted(u64), // (id) SubnetProposalAccepted(u64, u16), // (id, netuid) } @@ -592,10 +611,10 @@ pub mod pallet { ModuleNameAlreadyExists, // --- Thrown when a module name already exists. NetworkDoesNotExist, // --- Thrown when the network does not exist. TooFewVotesForNewProposal, - ModuleAddressTooLong, - NetworkExist, // --- Thrown when the network already exist. - InvalidIpType, /* ---- Thrown when the user tries to serve an module which - * is not of type 4 (IPv4) or 6 (IPv6). */ + ModuleAddressTooLong, + NetworkExist, // --- Thrown when the network already exist. + InvalidIpType, /* ---- Thrown when the user tries to serve an module which + * is not of type 4 (IPv4) or 6 (IPv6). */ InvalidIpAddress, /* --- Thrown when an invalid IP address is passed to the serve * function. */ NotRegistered, /* ---- Thrown when the caller requests setting or removing data from a @@ -674,8 +693,8 @@ pub mod pallet { NotEnoughVotesToAccept, NotEnoughBalanceToTransfer, NotAuthorityMode, - InvalidTrustRatio, - InvalidMinAllowedWeights, + InvalidTrustRatio, + InvalidMinAllowedWeights, InvalidMaxAllowedWeights, InvalidMinStake, @@ -701,14 +720,9 @@ pub mod pallet { InvalidVoteMode, InvalidMaxWeightAge, InvalidMaxStake, - - AlreadyControlled, - AlreadyController - - - - + AlreadyControlled, + AlreadyController, } // ================== @@ -757,13 +771,13 @@ pub mod pallet { vote_mode: default_params.vote_mode.clone(), trust_ratio: default_params.trust_ratio, self_vote: default_params.self_vote, - founder_share: default_params.founder_share, + founder_share: default_params.founder_share, incentive_ratio: default_params.incentive_ratio, max_weight_age: default_params.max_weight_age, }; - + self::Pallet::::add_subnet(params.clone()); - + for (uid_usize, (key, name, address, weights)) in self.modules[subnet_idx].iter().enumerate() { @@ -772,7 +786,7 @@ pub mod pallet { } } // Now we can add the stake to the network - for (subnet_idx, subnet) in self.subnets.iter().enumerate() { + for (subnet_idx, _) in self.subnets.iter().enumerate() { let netuid: u16 = subnet_idx as u16; for (key, stake_to) in self.stake_to[netuid as usize].iter() { @@ -801,9 +815,6 @@ pub mod pallet { pub mode: Vec, // "global", "subnet", "custom" } - - - #[pallet::type_value] pub fn DefaultProposal() -> Proposal { Proposal { @@ -814,7 +825,7 @@ pub mod pallet { participants: vec![], accepted: false, mode: vec![], - data: vec![] + data: vec![], } } #[pallet::storage] // --- MAP ( global_proposal_id ) --> global_update_proposal @@ -835,8 +846,7 @@ pub mod pallet { // - The number of the block we are initializing. fn on_initialize(_block_number: BlockNumberFor) -> Weight { Self::block_step(); - - return Weight::zero() + Weight::zero() } fn on_runtime_upgrade() -> frame_support::weights::Weight { @@ -899,7 +909,6 @@ pub mod pallet { Self::do_remove_stake_multiple(origin, netuid, module_keys, amounts) } - #[pallet::weight(T::WeightInfo::transfer_stake())] pub fn transfer_stake( origin: OriginFor, // --- The account that is calling this function. @@ -920,7 +929,6 @@ pub mod pallet { Self::do_transfer_multiple(origin, destinations, amounts) } - #[pallet::weight(T::WeightInfo::update_module())] pub fn update_module( origin: OriginFor, @@ -931,7 +939,7 @@ pub mod pallet { ) -> DispatchResult { let key = ensure_signed(origin.clone())?; ensure!(Self::is_registered(netuid, &key), Error::::NotRegistered); - let uid : u16 = Self::get_uid_for_key(netuid, &key); + let uid: u16 = Self::get_uid_for_key(netuid, &key); let mut params = Self::module_params(netuid, uid); params.name = name; params.address = address; @@ -954,10 +962,7 @@ pub mod pallet { } #[pallet::weight(T::WeightInfo::deregister())] - pub fn deregister( - origin: OriginFor, - netuid : u16, - ) -> DispatchResult { + pub fn deregister(origin: OriginFor, netuid: u16) -> DispatchResult { Self::do_deregister(origin, netuid) } @@ -965,7 +970,7 @@ pub mod pallet { pub fn add_profit_shares( origin: OriginFor, keys: Vec, - shares: Vec + shares: Vec, ) -> DispatchResult { Self::do_add_profit_shares(origin, keys, shares) } @@ -983,8 +988,8 @@ pub mod pallet { min_stake: u64, min_weight_stake: u64, tx_rate_limit: u64, - unit_emission: u64, - vote_mode: Vec, + unit_emission: u64, + vote_mode: Vec, vote_threshold: u16, ) -> DispatchResult { let mut params = Self::global_params(); @@ -1002,14 +1007,13 @@ pub mod pallet { params.unit_emission = unit_emission; params.vote_mode = vote_mode; params.vote_threshold = vote_threshold; - Self::do_update_global(origin, params) } #[pallet::weight(T::WeightInfo::add_global_proposal())] - pub fn add_global_proposal( - origin: OriginFor, + pub fn add_global_proposal( + origin: OriginFor, // params burn_rate: u16, max_name_length: u16, @@ -1020,13 +1024,13 @@ pub mod pallet { min_burn: u64, min_stake: u64, min_weight_stake: u64, - unit_emission: u64, + unit_emission: u64, tx_rate_limit: u64, vote_threshold: u16, vote_mode: Vec, ) -> DispatchResult { let mut params = Self::global_params(); - + params.burn_rate = burn_rate; params.max_allowed_modules = max_allowed_modules; params.max_allowed_subnets = max_allowed_subnets; @@ -1039,11 +1043,10 @@ pub mod pallet { params.tx_rate_limit = tx_rate_limit; params.unit_emission = unit_emission; params.vote_mode = vote_mode; - params.vote_threshold = vote_threshold; - - Self::do_add_global_proposal(origin, params) - } + params.vote_threshold = vote_threshold; + Self::do_add_global_proposal(origin, params) + } #[pallet::weight(T::WeightInfo::update_subnet())] pub fn update_subnet( @@ -1059,12 +1062,12 @@ pub mod pallet { max_stake: u64, max_weight_age: u64, min_allowed_weights: u16, - min_stake : u64, + min_stake: u64, name: Vec, self_vote: bool, tempo: u16, trust_ratio: u16, - vote_mode: Vec, + vote_mode: Vec, vote_threshold: u16, ) -> DispatchResult { let mut params = Self::subnet_params(netuid); @@ -1084,14 +1087,13 @@ pub mod pallet { params.trust_ratio = trust_ratio; params.vote_mode = vote_mode; params.vote_threshold = vote_threshold; - - Self::do_update_subnet(origin,netuid,params) - } + Self::do_update_subnet(origin, netuid, params) + } #[pallet::weight(T::WeightInfo::add_subnet_proposal())] - pub fn add_subnet_proposal( - origin: OriginFor, + pub fn add_subnet_proposal( + origin: OriginFor, netuid: u16, // FOR SUBNET PROPOSAL ONLY founder: T::AccountId, founder_share: u16, @@ -1102,12 +1104,12 @@ pub mod pallet { max_stake: u64, max_weight_age: u64, min_allowed_weights: u16, - min_stake : u64, + min_stake: u64, name: Vec, self_vote: bool, tempo: u16, trust_ratio: u16, - vote_mode: Vec, + vote_mode: Vec, vote_threshold: u16, ) -> DispatchResult { let mut params = Self::subnet_params(netuid); @@ -1128,59 +1130,47 @@ pub mod pallet { params.vote_mode = vote_mode; params.vote_threshold = vote_threshold; - Self::do_add_subnet_proposal(origin, netuid, params) - } + Self::do_add_subnet_proposal(origin, netuid, params) + } #[pallet::weight(T::WeightInfo::add_custom_proposal())] - pub fn add_custom_proposal( - origin: OriginFor, - data: Vec, - ) -> DispatchResult { - Self::do_add_custom_proposal(origin, data) - } + pub fn add_custom_proposal(origin: OriginFor, data: Vec) -> DispatchResult { + Self::do_add_custom_proposal(origin, data) + } #[pallet::weight(T::WeightInfo::vote_proposal())] - pub fn vote_proposal( - origin: OriginFor, - proposal_id: u64 - ) -> DispatchResult { - Self::do_vote_proposal( - origin, - proposal_id - ) - } + pub fn vote_proposal(origin: OriginFor, proposal_id: u64) -> DispatchResult { + Self::do_vote_proposal(origin, proposal_id) + } #[pallet::weight(T::WeightInfo::unvote_proposal())] - pub fn unvote_proposal( - origin: OriginFor, - ) -> DispatchResult { - Self::do_unregister_voter( - origin - ) - } - + pub fn unvote_proposal(origin: OriginFor) -> DispatchResult { + Self::do_unregister_voter(origin) + } } // ---- Subspace helper functions. impl Pallet { // --- Returns the transaction priority for setting weights. pub fn get_priority_set_weights(key: &T::AccountId, netuid: u16) -> u64 { - if Uids::::contains_key(netuid, &key) { - let uid: u16 = Self::get_uid_for_key(netuid, &key.clone()); - let current_block_number: u64 = Self::get_current_block_as_u64(); - return current_block_number - Self::get_last_update_for_uid(netuid, uid as u16) + if Uids::::contains_key(netuid, key) { + let uid = Self::get_uid_for_key(netuid, key); + let current_block_number = Self::get_current_block_as_u64(); + current_block_number - Self::get_last_update_for_uid(netuid, uid as u16) + } else { + 0 } - return 0 } // --- Returns the transaction priority for setting weights. pub fn get_priority_stake(key: &T::AccountId, netuid: u16) -> u64 { - if Uids::::contains_key(netuid, &key) { - return Self::get_stake(netuid, key) + if Uids::::contains_key(netuid, key) { + Self::get_stake(netuid, key) + } else { + 0 } - return 0 } pub fn get_priority_balance(key: &T::AccountId) -> u64 { - return Self::get_balance_u64(key) + Self::get_balance_u64(key) } } @@ -1189,7 +1179,7 @@ pub mod pallet { ************************************************************/ } -#[derive(Debug, PartialEq)] +#[derive(Debug, Default, PartialEq)] pub enum CallType { SetWeights, AddStake, @@ -1203,13 +1193,9 @@ pub enum CallType { Register, AddNetwork, Serve, + #[default] Other, } -impl Default for CallType { - fn default() -> Self { - CallType::Other - } -} #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] pub struct SubspaceSignedExtension(pub PhantomData); @@ -1229,16 +1215,13 @@ where // get the current block number let current_block_number: u64 = Pallet::::get_current_block_as_u64(); let balance = Pallet::::get_balance_u64(who); - let priority = current_block_number + balance; // proriorty is the current block number minus the last update block number - - return priority + current_block_number + balance } pub fn get_priority_set_weights(who: &T::AccountId, netuid: u16) -> u64 { // Return the non vanilla priority for a set weights call. - - return Pallet::::get_priority_set_weights(who, netuid) + Pallet::::get_priority_set_weights(who, netuid) } pub fn u64_to_balance( diff --git a/pallets/subspace/src/math.rs b/pallets/subspace/src/math.rs index 40c4f2ea5..793dec7a3 100644 --- a/pallets/subspace/src/math.rs +++ b/pallets/subspace/src/math.rs @@ -1,8 +1,8 @@ +use sp_std::{vec, vec::Vec}; use substrate_fixed::{ transcendental::exp, types::{I32F32, I64F64}, }; -use sp_std::{vec, vec::Vec}; #[allow(dead_code)] pub fn bottom_k_u16(vector: &Vec, k: usize) -> Vec { @@ -146,7 +146,7 @@ pub fn is_topk(vector: &Vec, k: usize) -> Vec { let n: usize = vector.len(); let mut result: Vec = vec![true; n]; if n < k { - return result + return result; } let mut idxs: Vec = (0..n).collect(); idxs.sort_by_key(|&idx| &vector[idx]); // ascending stable sort @@ -547,7 +547,6 @@ pub fn matmul_sparse( // Compute trust scores: t_j = SUM(i) w_ij * s_i // result_j = SUM(i) vector_i * matrix_ij result[*j as usize] += vector[i] * value; - } } result @@ -728,27 +727,14 @@ pub fn weighted_median( } } if (partition_lo + lo_stake <= minority) && (minority < partition_hi - hi_stake) { - return pivot + pivot } else if (minority < partition_lo + lo_stake) && (lower.len() > 0) { - return weighted_median( - stake, - score, - &lower, - minority, - partition_lo, - partition_lo + lo_stake, - ) + weighted_median(stake, score, &lower, minority, partition_lo, partition_lo + lo_stake) } else if (partition_hi - hi_stake <= minority) && (upper.len() > 0) { - return weighted_median( - stake, - score, - &upper, - minority, - partition_hi - hi_stake, - partition_hi, - ) - } - pivot + weighted_median(stake, score, &upper, minority, partition_hi - hi_stake, partition_hi) + } else { + pivot + } } /// Column-wise weighted median, e.g. stake-weighted median scores per server (column) over all @@ -949,7 +935,7 @@ mod tests { use rand::{seq::SliceRandom, thread_rng, Rng}; use substrate_fixed::{ transcendental::exp, - types::{I110F18, I32F32, I64F64, I96F32}, + types::{I32F32, I64F64, I96F32}, }; fn assert_float_compare(a: I32F32, b: I32F32, epsilon: I32F32) { @@ -2501,6 +2487,4 @@ mod tests { epsilon, ); } - - } diff --git a/pallets/subspace/src/migration.rs b/pallets/subspace/src/migration.rs index 665b19dbc..17df7217a 100644 --- a/pallets/subspace/src/migration.rs +++ b/pallets/subspace/src/migration.rs @@ -1,33 +1,35 @@ use super::*; -use log::info; use frame_support::{ - traits::{Get, StorageVersion, GetStorageVersion}, - weights::Weight, storage_alias, Identity, BoundedVec + storage_alias, + traits::{Get, GetStorageVersion, StorageVersion}, + weights::Weight, + BoundedVec, Identity, }; +use log::info; const LOG_TARGET: &str = "subspace"; // only contains V1 storage format pub mod v1 { - use super::*; - - /////////////////////////////// - /// GLOBAL STORAGE - /////////////////////////////// - - #[storage_alias] + use super::*; + + /////////////////////////////// + /// GLOBAL STORAGE + /////////////////////////////// + + #[storage_alias] pub(super) type UnitEmissionPallet = StorageValue, u64>; #[storage_alias] pub(super) type TxRateLimit = StorageValue, u64>; - + #[storage_alias] - pub(super) type BurnRate = StorageValue , u16>; + pub(super) type BurnRate = StorageValue, u16>; #[storage_alias] pub(super) type MinBurn = StorageValue, u64>; - #[storage_alias] + #[storage_alias] pub(super) type MaxNameLength = StorageValue, u16>; #[storage_alias] @@ -35,244 +37,270 @@ pub mod v1 { #[storage_alias] pub(super) type MaxAllowedModules = StorageValue, u16>; - + #[storage_alias] pub(super) type RegistrationsPerBlock = StorageValue, u16>; - - #[storage_alias] + + #[storage_alias] pub(super) type MaxRegistrationsPerBlock = StorageValue, u16>; - #[storage_alias] + #[storage_alias] pub(super) type MinStakeGlobal = StorageValue, u64>; - - #[storage_alias] + + #[storage_alias] pub(super) type MinWeightStake = StorageValue, u64>; - - #[storage_alias] + + #[storage_alias] pub(super) type MaxAllowedWeightsGlobal = StorageValue, u16>; - #[storage_alias] + #[storage_alias] pub(super) type TotalSubnets = StorageValue, u16>; - #[storage_alias] + #[storage_alias] pub(super) type GlobalVoteThreshold = StorageValue, u16>; - #[storage_alias] + #[storage_alias] pub(super) type VoteModeGlobal = StorageValue, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type MaxProposals = StorageValue, u64>; - /////////////////////////////// - /// SUBNET STORAGE - /////////////////////////////// - - #[storage_alias] + /////////////////////////////// + /// SUBNET STORAGE + /////////////////////////////// + + #[storage_alias] pub(super) type MaxAllowedUids = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type ImmunityPeriod = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type MinAllowedWeights = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type SelfVote = StorageMap, Identity, u16, bool>; - #[storage_alias] + #[storage_alias] pub(super) type MinStake = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type MaxStake = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type MaxWeightAge = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type MaxAllowedWeights = StorageMap, Identity, u16, u16>; - #[storage_alias] - pub(super) type PendingDeregisterUids = StorageMap, Identity, u16, Vec>; + #[storage_alias] + pub(super) type PendingDeregisterUids = + StorageMap, Identity, u16, Vec>; - #[storage_alias] - pub(super) type Founder = StorageMap, Identity, u16, ::AccountId>; + #[storage_alias] + pub(super) type Founder = + StorageMap, Identity, u16, ::AccountId>; - #[storage_alias] + #[storage_alias] pub(super) type FounderShare = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type IncentiveRatio = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type Tempo = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type TrustRatio = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type QuadraticVoting = StorageMap, Identity, u16, bool>; - #[storage_alias] + #[storage_alias] pub(super) type VoteThresholdSubnet = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type VoteModeSubnet = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type SubnetEmission = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type N = StorageMap, Identity, u16, u16>; - #[storage_alias] + #[storage_alias] pub(super) type PendingEmission = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type SubnetNames = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type TotalStake = StorageMap, Identity, u16, u64>; - #[storage_alias] + #[storage_alias] pub(super) type Incentive = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type Trust = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type Dividends = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type Emission = StorageMap, Identity, u16, Vec>; - #[storage_alias] + #[storage_alias] pub(super) type LastUpdate = StorageMap, Identity, u16, Vec>; -} - +} // contains checks and transforms storage to V2 format pub fn migrate_to_v2() -> Weight { - let onchain_version = Pallet::::on_chain_storage_version(); - - if onchain_version < 2 { - info!(target: LOG_TARGET, " >>> Updating Global storage..."); - - let unit_emission = v1::UnitEmissionPallet::::get().unwrap(); - let tx_rate_limit = v1::TxRateLimit::::get().unwrap(); - let burn_rate = v1::BurnRate::::get().unwrap(); - let min_burn = v1::MinBurn::::get().unwrap(); - let max_name_length = v1::MaxNameLength::::get().unwrap(); - let max_allowed_subnets = v1::MaxAllowedSubnets::::get().unwrap(); - let max_allowed_modules = v1::MaxAllowedModules::::get().unwrap(); - let registrations_per_block = v1::RegistrationsPerBlock::::get().unwrap(); - let max_registrations_per_block = v1::MaxRegistrationsPerBlock::::get().unwrap(); - let min_stake = v1::MinStakeGlobal::::get().unwrap(); - let min_weight_stake = v1::MinWeightStake::::get().unwrap(); - let max_allowed_weights = v1::MaxAllowedWeightsGlobal::::get().unwrap(); - let total_subnets = v1::TotalSubnets::::get().unwrap(); - let vote_threshold = v1::GlobalVoteThreshold::::get().unwrap(); - let vote_mode = BoundedVec::>::try_from(v1::VoteModeGlobal::::get().unwrap()).expect("too long vote mode"); - let max_proposals = v1::MaxProposals::::get().unwrap(); - - let global_state = GlobalState { - registrations_per_block, - max_name_length, - max_allowed_subnets, - max_allowed_modules, - max_registrations_per_block, - max_allowed_weights, - min_burn, - min_stake, - min_weight_stake, - unit_emission, - tx_rate_limit, - burn_rate, - total_subnets, - vote_threshold, - vote_mode, - max_proposals - }; - - GlobalStateStorage::::put(global_state); - - info!(target: LOG_TARGET, " >>> Updated Global storage..."); - - info!(target: LOG_TARGET, " >>> Updating Subnet storage..."); - - let mut count = 0; - - for netuid in v1::MaxAllowedUids::::iter_keys() { - let max_allowed_uids = v1::MaxAllowedUids::::get(netuid).unwrap(); - let immunity_period = v1::ImmunityPeriod::::get(netuid).unwrap(); - let min_allowed_weights = v1::MinAllowedWeights::::get(netuid).unwrap(); - let self_vote = v1::SelfVote::::get(netuid).unwrap(); - let min_stake = v1::MinStake::::get(netuid).unwrap(); - let max_stake = v1::MaxStake::::get(netuid).unwrap(); - let max_weight_age = v1::MaxWeightAge::::get(netuid).unwrap(); - let max_allowed_weights = v1::MaxAllowedWeights::::get(netuid).unwrap(); - let pending_deregister_uids = BoundedVec::>::try_from(v1::PendingDeregisterUids::::get(netuid).unwrap()).expect("subnets exceed 10000"); - let founder = v1::Founder::::get(netuid).unwrap(); - let founder_share = v1::FounderShare::::get(netuid).unwrap(); - let incentive_ratio = v1::IncentiveRatio::::get(netuid).unwrap(); - let tempo = v1::Tempo::::get(netuid).unwrap(); - let trust_ratio = v1::TrustRatio::::get(netuid).unwrap(); - let quadratic_voting = v1::QuadraticVoting::::get(netuid).unwrap(); - let vote_threshold = v1::VoteThresholdSubnet::::get(netuid).unwrap(); - let vote_mode = BoundedVec::>::try_from(v1::VoteModeSubnet::::get(netuid).unwrap()).expect("too long vote mode"); - let emission = v1::SubnetEmission::::get(netuid).unwrap(); - let n = v1::N::::get(netuid).unwrap(); - let pending_emission = v1::PendingEmission::::get(netuid).unwrap(); - let name = BoundedVec::>::try_from(v1::SubnetNames::::get(netuid).unwrap()).expect("too long vote mode"); - let total_stake = v1::TotalStake::::get(netuid).unwrap(); - let incentives = BoundedVec::>::try_from(v1::Incentive::::get(netuid).unwrap()).expect("module count exceed 10000"); - let trusts = BoundedVec::>::try_from(v1::Trust::::get(netuid).unwrap()).expect("module count exceed 10000"); - let dividends = BoundedVec::>::try_from(v1::Dividends::::get(netuid).unwrap()).expect("module count exceed 10000"); - let emissions = BoundedVec::>::try_from(v1::Emission::::get(netuid).unwrap()).expect("module count exceed 10000"); - let last_updates = BoundedVec::>::try_from(v1::LastUpdate::::get(netuid).unwrap()).expect("module count exceed 10000"); - - let subnet_state = SubnetState { - founder, - founder_share, - incentive_ratio, - immunity_period, - max_allowed_uids, - max_allowed_weights, - min_allowed_weights, - max_stake, - max_weight_age, - min_stake, - self_vote, - tempo, - trust_ratio, - quadratic_voting, - pending_deregister_uids, - vote_threshold, - vote_mode, - emission, - n, - pending_emission, - name, - total_stake, - incentives, - trusts, - dividends, - emissions, - last_updates - }; - - SubnetStateStorage::::insert(netuid, subnet_state); - - count += 1; - } - - info!(target: LOG_TARGET, " >>> Updated Subnet storage..."); - - StorageVersion::new(2).put::>(); - - T::DbWeight::get().reads_writes(13 + count * 17 + 1, 13 + count * 17 + 1) - } else { - info!(target: LOG_TARGET, " >>> Skipped migration!"); - - Weight::zero() - } + let onchain_version = Pallet::::on_chain_storage_version(); + + if onchain_version < 2 { + info!(target: LOG_TARGET, " >>> Updating Global storage..."); + + let unit_emission = v1::UnitEmissionPallet::::get().unwrap(); + let tx_rate_limit = v1::TxRateLimit::::get().unwrap(); + let burn_rate = v1::BurnRate::::get().unwrap(); + let min_burn = v1::MinBurn::::get().unwrap(); + let max_name_length = v1::MaxNameLength::::get().unwrap(); + let max_allowed_subnets = v1::MaxAllowedSubnets::::get().unwrap(); + let max_allowed_modules = v1::MaxAllowedModules::::get().unwrap(); + let registrations_per_block = v1::RegistrationsPerBlock::::get().unwrap(); + let max_registrations_per_block = v1::MaxRegistrationsPerBlock::::get().unwrap(); + let min_stake = v1::MinStakeGlobal::::get().unwrap(); + let min_weight_stake = v1::MinWeightStake::::get().unwrap(); + let max_allowed_weights = v1::MaxAllowedWeightsGlobal::::get().unwrap(); + let total_subnets = v1::TotalSubnets::::get().unwrap(); + let vote_threshold = v1::GlobalVoteThreshold::::get().unwrap(); + let vote_mode = + BoundedVec::>::try_from(v1::VoteModeGlobal::::get().unwrap()) + .expect("too long vote mode"); + let max_proposals = v1::MaxProposals::::get().unwrap(); + + let global_state = GlobalState { + registrations_per_block, + max_name_length, + max_allowed_subnets, + max_allowed_modules, + max_registrations_per_block, + max_allowed_weights, + min_burn, + min_stake, + min_weight_stake, + unit_emission, + tx_rate_limit, + burn_rate, + total_subnets, + vote_threshold, + vote_mode, + max_proposals, + }; + + GlobalStateStorage::::put(global_state); + + info!(target: LOG_TARGET, " >>> Updated Global storage..."); + + info!(target: LOG_TARGET, " >>> Updating Subnet storage..."); + + let mut count = 0; + + for netuid in v1::MaxAllowedUids::::iter_keys() { + let max_allowed_uids = v1::MaxAllowedUids::::get(netuid).unwrap(); + let immunity_period = v1::ImmunityPeriod::::get(netuid).unwrap(); + let min_allowed_weights = v1::MinAllowedWeights::::get(netuid).unwrap(); + let self_vote = v1::SelfVote::::get(netuid).unwrap(); + let min_stake = v1::MinStake::::get(netuid).unwrap(); + let max_stake = v1::MaxStake::::get(netuid).unwrap(); + let max_weight_age = v1::MaxWeightAge::::get(netuid).unwrap(); + let max_allowed_weights = v1::MaxAllowedWeights::::get(netuid).unwrap(); + let pending_deregister_uids = BoundedVec::>::try_from( + v1::PendingDeregisterUids::::get(netuid).unwrap(), + ) + .expect("subnets exceed 10000"); + let founder = v1::Founder::::get(netuid).unwrap(); + let founder_share = v1::FounderShare::::get(netuid).unwrap(); + let incentive_ratio = v1::IncentiveRatio::::get(netuid).unwrap(); + let tempo = v1::Tempo::::get(netuid).unwrap(); + let trust_ratio = v1::TrustRatio::::get(netuid).unwrap(); + let quadratic_voting = v1::QuadraticVoting::::get(netuid).unwrap(); + let vote_threshold = v1::VoteThresholdSubnet::::get(netuid).unwrap(); + let vote_mode = BoundedVec::>::try_from( + v1::VoteModeSubnet::::get(netuid).unwrap(), + ) + .expect("too long vote mode"); + let emission = v1::SubnetEmission::::get(netuid).unwrap(); + let n = v1::N::::get(netuid).unwrap(); + let pending_emission = v1::PendingEmission::::get(netuid).unwrap(); + let name = BoundedVec::>::try_from( + v1::SubnetNames::::get(netuid).unwrap(), + ) + .expect("too long vote mode"); + let total_stake = v1::TotalStake::::get(netuid).unwrap(); + let incentives = BoundedVec::>::try_from( + v1::Incentive::::get(netuid).unwrap(), + ) + .expect("module count exceed 10000"); + let trusts = + BoundedVec::>::try_from(v1::Trust::::get(netuid).unwrap()) + .expect("module count exceed 10000"); + let dividends = BoundedVec::>::try_from( + v1::Dividends::::get(netuid).unwrap(), + ) + .expect("module count exceed 10000"); + let emissions = BoundedVec::>::try_from( + v1::Emission::::get(netuid).unwrap(), + ) + .expect("module count exceed 10000"); + let last_updates = BoundedVec::>::try_from( + v1::LastUpdate::::get(netuid).unwrap(), + ) + .expect("module count exceed 10000"); + + let subnet_state = SubnetState { + founder, + founder_share, + incentive_ratio, + immunity_period, + max_allowed_uids, + max_allowed_weights, + min_allowed_weights, + max_stake, + max_weight_age, + min_stake, + self_vote, + tempo, + trust_ratio, + quadratic_voting, + pending_deregister_uids, + vote_threshold, + vote_mode, + emission, + n, + pending_emission, + name, + total_stake, + incentives, + trusts, + dividends, + emissions, + last_updates, + }; + + SubnetStateStorage::::insert(netuid, subnet_state); + + count += 1; + } + + info!(target: LOG_TARGET, " >>> Updated Subnet storage..."); + + StorageVersion::new(2).put::>(); + + T::DbWeight::get().reads_writes(13 + count * 17 + 1, 13 + count * 17 + 1) + } else { + info!(target: LOG_TARGET, " >>> Skipped migration!"); + + Weight::zero() + } } diff --git a/pallets/subspace/src/mock.rs b/pallets/subspace/src/mock.rs index fec0b4264..bbdfc2dc9 100644 --- a/pallets/subspace/src/mock.rs +++ b/pallets/subspace/src/mock.rs @@ -2,17 +2,17 @@ #![allow(warnings)] use crate as pallet_subspace; use frame_support::{ - assert_ok, parameter_types, + assert_ok, parameter_types, traits::{Everything, Hash, Hooks, StorageMapShim}, weights, }; use frame_system as system; use frame_system::{limits, Config, EnsureNever, EnsureRoot, RawOrigin}; -use sp_core::{Get, H256, U256, ConstU32}; +use sp_core::{ConstU32, Get, H256, U256}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - DispatchResult, BuildStorage, + BuildStorage, DispatchResult, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -67,21 +67,21 @@ impl pallet_balances::Config for Test { type WeightInfo = (); type MaxReserves = MaxReserves; type ReserveIdentifier = (); - type RuntimeHoldReason = (); - type FreezeIdentifier = (); - type MaxHolds = frame_support::traits::ConstU32<16>; + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxHolds = frame_support::traits::ConstU32<16>; type MaxFreezes = frame_support::traits::ConstU32<16>; } impl system::Config for Test { type BaseCallFilter = Everything; - type Block = Block; + type Block = Block; type BlockWeights = (); type BlockLength = (); type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Nonce = u32; + type Nonce = u32; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = U256; @@ -102,12 +102,12 @@ impl system::Config for Test { impl pallet_subspace::Config for Test { type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type WeightInfo = (); + type WeightInfo = (); } // Build genesis storage according to the mock runtime. #[allow(dead_code)] pub fn new_test_ext() -> sp_io::TestExternalities { sp_tracing::try_init_simple(); - >::default().build_storage().unwrap().into() + >::default().build_storage().unwrap().into() } diff --git a/pallets/subspace/src/module.rs b/pallets/subspace/src/module.rs index a813cf5d0..3c7165a4c 100644 --- a/pallets/subspace/src/module.rs +++ b/pallets/subspace/src/module.rs @@ -1,20 +1,16 @@ use super::*; -use frame_support::{ - pallet_prelude::{Decode, Encode, DispatchResult}, - storage::IterableStorageMap, -}; +use frame_support::pallet_prelude::{Decode, DispatchResult, Encode}; extern crate alloc; use alloc::vec::Vec; -use codec::Compact; -use sp_std::vec; use sp_arithmetic::per_things::Percent; #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug)] pub struct ModuleStats { pub last_update: u64, pub registration_block: u64, - pub stake_from: Vec<(T::AccountId, u64)>, /* map of key to stake on this module/key * (includes delegations) */ + pub stake_from: Vec<(T::AccountId, u64)>, /* map of key to stake on this module/key * + * (includes delegations) */ pub emission: u64, pub incentive: u16, pub dividends: u16, @@ -27,10 +23,7 @@ pub struct ModuleInfo { stats: ModuleStats, } - impl Pallet { - - pub fn do_update_module( origin: T::RuntimeOrigin, netuid: u16, @@ -39,58 +32,58 @@ impl Pallet { // --- 1. We check the callers (key) signature. let key = ensure_signed(origin)?; let uid: u16 = Self::get_uid_for_key(netuid, &key); - Self::check_module_params(netuid, params.clone())?; + Self::check_module_params(¶ms)?; Self::set_module_params(netuid, uid, params); // --- 8. Return is successful dispatch. Ok(()) } - - - pub fn check_module_params(netuid: u16, params: ModuleParams) -> DispatchResult { - + pub fn check_module_params(params: &ModuleParams) -> DispatchResult { // if len(name) > 0, then we update the name. assert!(params.name.len() > 0); - ensure!(params.name.len() <= Self::get_global_max_name_length() as usize, Error::::ModuleNameTooLong); + ensure!( + params.name.len() <= Self::get_global_max_name_length() as usize, + Error::::ModuleNameTooLong + ); assert!(params.address.len() > 0); - ensure!(params.address.len() <= Self::get_global_max_name_length() as usize, Error::::ModuleAddressTooLong); + ensure!( + params.address.len() <= Self::get_global_max_name_length() as usize, + Error::::ModuleAddressTooLong + ); // delegation fee is a percent Ok(()) } - pub fn module_params(netuid: u16, uid:u16) -> ModuleParams { - let module_params : ModuleParams = ModuleParams { + pub fn module_params(netuid: u16, uid: u16) -> ModuleParams { + ModuleParams { name: Self::get_module_name(netuid, uid), address: Self::get_module_address(netuid, uid), delegation_fee: Self::get_module_delegation_fee(netuid, uid), controller: Self::get_key_for_uid(netuid, uid), - }; - return module_params + } } pub fn set_module_params(netuid: u16, uid: u16, module_params: ModuleParams) { Self::set_module_name(netuid, uid, module_params.name); Self::set_module_address(netuid, uid, module_params.address); - Self::set_module_delegation_fee( netuid, uid, module_params.delegation_fee); + Self::set_module_delegation_fee(netuid, uid, module_params.delegation_fee); } - pub fn get_module_address(netuid: u16, uid: u16) -> Vec { return Address::::get(netuid, uid) } - - pub fn set_module_address( netuid: u16, uid: u16, address: Vec) { + pub fn set_module_address(netuid: u16, uid: u16, address: Vec) { Address::::insert(netuid, uid, address); } - + pub fn get_module_delegation_fee(netuid: u16, uid: u16) -> Percent { let key = Self::get_key_for_uid(netuid, uid); - let mut delegation_fee: Percent = DelegationFee::::get(netuid, key); - return delegation_fee + let delegation_fee: Percent = DelegationFee::::get(netuid, key); + delegation_fee } - pub fn set_module_delegation_fee( netuid: u16, uid: u16, delegation_fee: Percent) { + pub fn set_module_delegation_fee(netuid: u16, uid: u16, delegation_fee: Percent) { let key = Self::get_key_for_uid(netuid, uid); DelegationFee::::insert(netuid, key, delegation_fee); } @@ -99,7 +92,7 @@ impl Pallet { return Name::::get(netuid, uid) } - pub fn set_module_name( netuid: u16, uid: u16, name: Vec) { + pub fn set_module_name(netuid: u16, uid: u16, name: Vec) { Name::::insert(netuid, uid, name.clone()); } @@ -108,8 +101,8 @@ impl Pallet { // 1. Get the old key under this position. let n = Self::get_subnet_n(netuid); if n == 0 { - /// No modules in the network. - return + // No modules in the network. + return; } let uid_key: T::AccountId = Keys::::get(netuid, uid); let replace_uid = n - 1; @@ -129,10 +122,10 @@ impl Pallet { Keys::::remove(netuid, replace_uid); // Remove key - uid association. // let mut delegation_fee: Percent = DelegationFee::::get(netuid, uid_key.clone()); - + // swap consensus vectors let mut subnet_state = SubnetStateStorage::::get(netuid); - + subnet_state.incentives[uid as usize] = subnet_state.incentives[replace_uid as usize]; subnet_state.dividends[uid as usize] = subnet_state.dividends[replace_uid as usize]; subnet_state.emissions[uid as usize] = subnet_state.emissions[replace_uid as usize]; @@ -151,7 +144,11 @@ impl Pallet { Weights::::remove(netuid, replace_uid); // Make uid - key association. // HANDLE THE REGISTRATION BLOCK - RegistrationBlock::::insert(netuid,uid,RegistrationBlock::::get(netuid, replace_uid),); // Fill block at registration. + RegistrationBlock::::insert( + netuid, + uid, + RegistrationBlock::::get(netuid, replace_uid), + ); // Fill block at registration. RegistrationBlock::::remove(netuid, replace_uid); // Fill block at registration. // HANDLE THE ADDRESS @@ -163,17 +160,20 @@ impl Pallet { Name::::remove(netuid, replace_uid); // Fill module namespace. // HANDLE THE DELEGATION FEE - DelegationFee::::insert(netuid,replace_key.clone(),DelegationFee::::get(netuid, uid_key.clone())); // Make uid - key association. + DelegationFee::::insert( + netuid, + replace_key.clone(), + DelegationFee::::get(netuid, uid_key.clone()), + ); // Make uid - key association. DelegationFee::::remove(netuid, uid_key.clone()); // Make uid - key association. // 3. Remove the network if it is empty. let mut subnet_state = SubnetStateStorage::::get(netuid); - if(subnet_state.n > 0) { + if subnet_state.n > 0 { subnet_state.n -= 1; } - SubnetStateStorage::::insert(netuid, subnet_state); // remove the network if it is empty @@ -183,7 +183,6 @@ impl Pallet { // remove stake from old key and add to new key Self::remove_stake_from_storage(netuid, &uid_key); - } // Appends the uid to the network. @@ -195,10 +194,11 @@ impl Pallet { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.incentives.try_push(0); - subnet_state.dividends.try_push(0); - subnet_state.emissions.try_push(0); - subnet_state.last_updates.try_push(block_number); + // TODO: handle errors + let _ = subnet_state.incentives.try_push(0); + let _ = subnet_state.dividends.try_push(0); + let _ = subnet_state.emissions.try_push(0); + let _ = subnet_state.last_updates.try_push(block_number); SubnetStateStorage::::insert(netuid, subnet_state); @@ -220,7 +220,7 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state); - return uid + uid } pub fn get_modules_stats(netuid: u16) -> Vec> { @@ -231,14 +231,11 @@ impl Pallet { let mut modules = Vec::new(); let n = Self::get_subnet_n(netuid); for uid in 0..n { - let uid = uid; - let netuid = netuid; - let module = Self::get_module_stats(netuid, uid); - modules.push(module); } - return modules + + modules } pub fn get_module_stats(netuid: u16, uid: u16) -> ModuleStats { @@ -246,7 +243,6 @@ impl Pallet { let incentive = Self::get_incentive_for_uid(netuid, uid as u16); let dividends = Self::get_dividends_for_uid(netuid, uid as u16); let last_update = Self::get_last_update_for_uid(netuid, uid as u16); - let registration_block = Self::get_registration_block_for_uid(netuid, uid as u16); let weights = >::get(netuid, uid) .iter() .filter_map(|(i, w)| if *w > 0 { Some(((*i).into(), (*w).into())) } else { None }) @@ -257,16 +253,15 @@ impl Pallet { let registration_block = Self::get_registration_block_for_uid(netuid, uid as u16); let module_stats = ModuleStats { - stake_from: stake_from, + stake_from, emission: emission.into(), incentive: incentive.into(), dividends: dividends.into(), last_update: last_update.into(), registration_block: registration_block.into(), - weights: weights, + weights, }; - return module_stats + module_stats } - } diff --git a/pallets/subspace/src/profit_share.rs b/pallets/subspace/src/profit_share.rs index 81226af5a..c3345d1dc 100644 --- a/pallets/subspace/src/profit_share.rs +++ b/pallets/subspace/src/profit_share.rs @@ -1,94 +1,83 @@ - use frame_support::pallet_prelude::DispatchResult; -use substrate_fixed::types::{I110F18, I32F32, I64F64, I96F32}; +use substrate_fixed::types::{I64F64, I96F32}; use super::*; impl Pallet { - pub fn do_add_profit_shares( - origin: T::RuntimeOrigin, - keys: Vec, - shares: Vec - ) -> DispatchResult { - - let key = ensure_signed(origin)?; - - // needs to be registered as a network - ensure!( - Self::is_key_registered_on_any_network(&key), - Error::::NotRegistered - ); - assert!(keys.len() > 0); // ensure non empty keys - assert!(keys.len() == shares.len()); // make sure the keys and shares are the same length - let mut total_shares: u32 = shares.iter().map(|x| *x as u32).sum(); - assert!(total_shares > 0); - - let mut normalized_shares_float: Vec = Vec::new(); - // normalize shares - let mut total_normalized_length: u32 = 0; - for share in shares.iter() { - - let normalized_share = (I64F64::from(*share) / I64F64::from(total_shares as u16))* I64F64::from(u16::MAX); - total_normalized_length = total_normalized_length + normalized_share.to_num::(); - normalized_shares_float.push(normalized_share ); - } - // make sure the normalized shares add up to the unit - // convert the normalized shares to u16 - let mut normalize_shares: Vec = normalized_shares_float.iter().map(|x| x.to_num::()).collect::>(); - - let mut total_normalized_shares: u16 = normalize_shares.iter().sum::(); - // ensure the profit shares add up to the unit - if total_normalized_shares < u16::MAX { - if normalize_shares.len() > 0 { - normalize_shares[0] = normalize_shares[0].saturating_add(u16::MAX.saturating_sub(total_normalized_shares)); - } - total_normalized_shares = normalize_shares.iter().sum::(); - } - - assert!(total_normalized_shares == u16::MAX, "normalized shares {} vs {} do not add up to the unit", total_normalized_shares, u16::MAX); - - // check tssat the normalized shares add up to the unit - let total_normalized_shares: u16 = normalize_shares.iter().sum::(); - - // now send the normalized shares to the profit share pallet - let profit_share_tuples : Vec<(T::AccountId, u16)> = keys.iter().zip(normalize_shares.iter()).map(|(x, y)| (x.clone(), *y)).collect(); - - ProfitShares::::insert(&key, profit_share_tuples.clone()); - - - Ok(()) - - - } - - pub fn get_profit_share_emissions( - key: T::AccountId, - emission: u64, - ) -> Vec<(T::AccountId, u64)> { - - let profit_shares = ProfitShares::::get(&key); - let mut emission_shares: Vec<(T::AccountId, u64)> = Vec::new(); - for (share_key, share_ratio) in profit_shares.iter() { - let share_emission_float: I96F32 = I96F32::from(emission) * (I96F32::from(*share_ratio) / I96F32::from(u16::MAX)); - let share_emission: u64 = share_emission_float.to_num::(); - emission_shares.push((share_key.clone(), share_emission)); - } - - return emission_shares; - - - } - - - - - pub fn get_profit_shares( - key: T::AccountId, - ) -> Vec<(T::AccountId, u16)> { - return ProfitShares::::get(&key);; - - } - + pub fn do_add_profit_shares( + origin: T::RuntimeOrigin, + keys: Vec, + shares: Vec, + ) -> DispatchResult { + let key = ensure_signed(origin)?; + + // needs to be registered as a network + ensure!(Self::is_key_registered_on_any_network(&key), Error::::NotRegistered); + assert!(keys.len() > 0); // ensure non empty keys + assert!(keys.len() == shares.len()); // make sure the keys and shares are the same length + let total_shares: u32 = shares.iter().map(|x| *x as u32).sum(); + assert!(total_shares > 0); + + let mut normalized_shares_float: Vec = Vec::new(); + // normalize shares + let mut total_normalized_length: u32 = 0; + for share in shares.iter() { + let normalized_share = + (I64F64::from(*share) / I64F64::from(total_shares as u16)) * I64F64::from(u16::MAX); + total_normalized_length = total_normalized_length + normalized_share.to_num::(); + normalized_shares_float.push(normalized_share); + } + // make sure the normalized shares add up to the unit + // convert the normalized shares to u16 + let mut normalize_shares: Vec = + normalized_shares_float.iter().map(|x| x.to_num::()).collect::>(); + + let mut total_normalized_shares: u16 = normalize_shares.iter().sum::(); + // ensure the profit shares add up to the unit + if total_normalized_shares < u16::MAX { + if normalize_shares.len() > 0 { + normalize_shares[0] = normalize_shares[0] + .saturating_add(u16::MAX.saturating_sub(total_normalized_shares)); + } + total_normalized_shares = normalize_shares.iter().sum::(); + } + + assert!( + total_normalized_shares == u16::MAX, + "normalized shares {} vs {} do not add up to the unit", + total_normalized_shares, + u16::MAX + ); + + // TODO: check tssat the normalized shares add up to the unit + let _total_normalized_shares: u16 = normalize_shares.iter().sum::(); + + // now send the normalized shares to the profit share pallet + let profit_share_tuples: Vec<(T::AccountId, u16)> = + keys.iter().zip(normalize_shares.iter()).map(|(x, y)| (x.clone(), *y)).collect(); + + ProfitShares::::insert(&key, profit_share_tuples.clone()); + + Ok(()) + } + + pub fn get_profit_share_emissions( + key: T::AccountId, + emission: u64, + ) -> Vec<(T::AccountId, u64)> { + let profit_shares = ProfitShares::::get(&key); + let mut emission_shares: Vec<(T::AccountId, u64)> = Vec::new(); + for (share_key, share_ratio) in profit_shares.iter() { + let share_emission_float: I96F32 = + I96F32::from(emission) * (I96F32::from(*share_ratio) / I96F32::from(u16::MAX)); + let share_emission: u64 = share_emission_float.to_num::(); + emission_shares.push((share_key.clone(), share_emission)); + } + + return emission_shares; + } + + pub fn get_profit_shares(key: T::AccountId) -> Vec<(T::AccountId, u16)> { + return ProfitShares::::get(&key); + } } - - diff --git a/pallets/subspace/src/registration.rs b/pallets/subspace/src/registration.rs index f443beebd..9ee4e8aea 100644 --- a/pallets/subspace/src/registration.rs +++ b/pallets/subspace/src/registration.rs @@ -1,19 +1,14 @@ use super::*; -use crate::system::ensure_root; use frame_support::pallet_prelude::DispatchResult; use frame_system::ensure_signed; -use sp_arithmetic::per_things::Percent; -use sp_core::{H256, U256}; -use sp_io::hashing::{keccak_256, sha2_256}; +use sp_core::H256; use sp_std::{convert::TryInto, vec::Vec}; use substrate_fixed::types::I32F32; -use sp_std::vec; use system::pallet_prelude::BlockNumberFor; // IterableStorageMap use frame_support::storage::IterableStorageMap; - -const LOG_TARGET: &'static str = "runtime::subspace::registration"; +const LOG_TARGET: &str = "runtime::subspace::registration"; impl Pallet { pub fn do_register( @@ -27,7 +22,6 @@ impl Pallet { // --- 1. Check that the caller has signed the transaction. let key = ensure_signed(origin.clone())?; - // --- 2. Ensure we are not exceeding the max allowed registrations per block. ensure!( @@ -35,9 +29,6 @@ impl Pallet { Error::::NotEnoughBalanceToRegister ); - - - // -- 3. resolve the network in case it doesnt exisst if !Self::if_subnet_name_exists(network.clone()) { Self::add_subnet_from_registration(network.clone(), stake_amount, &key)?; @@ -45,14 +36,15 @@ impl Pallet { // get the netuid let netuid = Self::get_netuid_for_name(network.clone()); - - ensure!( Self::enough_stake_to_register(netuid, stake_amount), Error::::NotEnoughStakeToRegister ); ensure!(!Self::is_key_registered(netuid, &key), Error::::KeyAlreadyRegistered); - ensure!(!Self::if_module_name_exists(netuid, name.clone()),Error::::NameAlreadyRegistered); + ensure!( + !Self::if_module_name_exists(netuid, name.clone()), + Error::::NameAlreadyRegistered + ); let min_burn: u64 = Self::get_min_burn(); @@ -62,28 +54,26 @@ impl Pallet { GlobalStateStorage::::put(global_state); - let mut uid: u16; - let n: u16 = Self::get_subnet_n(netuid); - let global_n = Self::global_n(); + let global_n = Self::global_n(); // replace a node if we reach the max allowed modules if global_n >= Self::get_max_allowed_modules() { // get random netuid let mut netuid_n = 0; let mut random_netuid = Self::random_netuid(); - while netuid_n == 0 { + while netuid_n == 0 { random_netuid = Self::random_netuid(); netuid_n = Self::get_subnet_n(random_netuid); } - - Self::remove_module(netuid, Self::get_lowest_uid(random_netuid)); - } else if n >= Self::get_max_allowed_uids(netuid){ - // if we reach the max allowed modules for this network, then we replace the lowest priority node + Self::remove_module(netuid, Self::get_lowest_uid(random_netuid)); + } else if n >= Self::get_max_allowed_uids(netuid) { + // if we reach the max allowed modules for this network, then we replace the lowest + // priority node Self::remove_module(netuid, Self::get_lowest_uid(netuid)); } - uid = Self::append_module(netuid, &module_key, name.clone(), address.clone()); + let uid = Self::append_module(netuid, &module_key, name.clone(), address.clone()); Self::increase_stake(netuid, &module_key, &module_key, 0); if stake_amount > 0 { @@ -95,7 +85,10 @@ impl Pallet { Self::decrease_stake(netuid, &key, &module_key, min_burn); let min_stake = Self::get_min_stake(netuid); let current_stake = Self::get_total_stake_to(netuid, &key); - ensure!(current_stake == stake_amount.saturating_sub(min_burn), Error::::NotEnoughStakeToRegister); + ensure!( + current_stake == stake_amount.saturating_sub(min_burn), + Error::::NotEnoughStakeToRegister + ); ensure!(current_stake >= min_stake, Error::::NotEnoughStakeToRegister); } // ---Deposit successful event. @@ -106,27 +99,17 @@ impl Pallet { Ok(()) } - - pub fn do_deregister( - origin: T::RuntimeOrigin, - netuid: u16, - ) -> DispatchResult { + pub fn do_deregister(origin: T::RuntimeOrigin, netuid: u16) -> DispatchResult { // --- 1. Check that the caller has signed the transaction. let key = ensure_signed(origin.clone())?; - ensure!( - Self::is_key_registered(netuid, &key), - Error::::NotRegistered - ); + ensure!(Self::is_key_registered(netuid, &key), Error::::NotRegistered); // --- 2. Ensure we are not exceeding the max allowed registrations per block. let uid: u16 = Self::get_uid_for_key(netuid, &key); Self::remove_module(netuid, uid); - ensure!( - !Self::is_key_registered(netuid, &key), - Error::::StillRegistered - ); + ensure!(!Self::is_key_registered(netuid, &key), Error::::StillRegistered); // --- 5. Ok and done. Ok(()) @@ -138,8 +121,6 @@ impl Pallet { return stake_amount >= (min_stake + min_burn) } - - pub fn get_min_stake_to_register(netuid: u16) -> u64 { let mut min_stake: u64 = Self::get_min_stake(netuid); @@ -148,25 +129,18 @@ impl Pallet { let registrations_per_block: u16 = global_state.registrations_per_block; let max_registrations_per_block: u16 = global_state.max_registrations_per_block; - let mut factor = I32F32::from_num(registrations_per_block) / + let factor = I32F32::from_num(registrations_per_block) / I32F32::from_num(max_registrations_per_block); // convert factor to u8 - let mut factor = factor.to_num::(); + let factor = factor.to_num::(); // if factor is 0, then set it to 1 - for i in 0..factor { + for _ in 0..factor { min_stake = min_stake * 2; } - return min_stake - } - - pub fn vec_to_hash(vec_hash: Vec) -> H256 { - let de_ref_hash = &vec_hash; // b: &Vec - let de_de_ref_hash: &[u8] = &de_ref_hash; // c: &[u8] - let real_hash: H256 = H256::from_slice(de_de_ref_hash); - return real_hash + return min_stake; } // Determine which peer to prune from the network by finding the element with the lowest pruning @@ -175,7 +149,7 @@ impl Pallet { pub fn get_pruning_score_for_uid(netuid: u16, uid: u16) -> u64 { let vec: Vec = Self::get_emissions(netuid); - + if (uid as usize) < vec.len() { return vec[uid as usize] } else { @@ -187,26 +161,22 @@ impl Pallet { // If there are pending deregister uids, then return the first one. let pending_deregister_uids: Vec = Self::get_pending_deregister_uids(netuid); - + if pending_deregister_uids.len() > 0 { let uid: u16 = pending_deregister_uids[0]; if uid < n { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.pending_deregister_uids.remove(0); SubnetStateStorage::::insert(netuid, subnet_state); - - return uid + return uid; } - } let mut min_score: u64 = u64::MAX; let mut lowest_priority_uid: u16 = 0; - let mut prune_uids: Vec = Vec::new(); let current_block = Self::get_current_block_as_u64(); let immunity_period: u64 = Self::get_immunity_period(netuid) as u64; @@ -224,21 +194,20 @@ impl Pallet { lowest_priority_uid = module_uid_i; min_score = pruning_score; if min_score == 0 { - break + break; } } } } - return lowest_priority_uid + lowest_priority_uid } // Returns a random index in range 0..n. pub fn random_idx(n: u16) -> u16 { let block_number: u64 = Self::get_current_block_as_u64(); // take the modulos of the blocknumber - let idx: u16 = ((block_number % u16::MAX as u64) % (n as u64)) as u16; - return idx + ((block_number % u16::MAX as u64) % (n as u64)) as u16 } pub fn get_block_hash_from_u64(block_number: u64) -> H256 { @@ -262,17 +231,11 @@ impl Pallet { return real_hash; } - pub fn hash_to_vec(hash: H256) -> Vec { - let hash_as_bytes: &[u8] = hash.as_bytes(); - let hash_as_vec: Vec = hash_as_bytes.iter().cloned().collect(); - return hash_as_vec - } - pub fn add_subnet_from_registration( name: Vec, stake: u64, founder_key: &T::AccountId, - ) -> DispatchResult{ + ) -> DispatchResult { // use default parameters // let num_subnets: u16 = Self::num_subnets(); @@ -280,16 +243,18 @@ impl Pallet { // if we have not reached the max number of subnets, then we can start a new one if num_subnets >= max_subnets { let mut min_stake: u64 = u64::MAX; - let mut min_stake_netuid : u16 = max_subnets.saturating_sub(1); - for (netuid, subnet_state) in as IterableStorageMap>>::iter() { + let mut min_stake_netuid: u16 = max_subnets.saturating_sub(1); + for (netuid, subnet_state) in + as IterableStorageMap>>::iter() + { let net_stake = subnet_state.total_stake; - + if net_stake <= min_stake { min_stake = net_stake; min_stake_netuid = netuid; } } - ensure!(stake > min_stake , Error::::NotEnoughStakeToStartNetwork); + ensure!(stake > min_stake, Error::::NotEnoughStakeToStartNetwork); Self::remove_subnet(min_stake_netuid); } // if we have reached the max number of subnets, then we can start a new one if the stake is @@ -299,11 +264,8 @@ impl Pallet { params.name = name.clone(); let netuid = Self::add_subnet(params); - Self::set_founder(netuid, founder_key.clone()); + Self::set_founder(netuid, founder_key.clone()); Ok(()) } - } - - diff --git a/pallets/subspace/src/staking.rs b/pallets/subspace/src/staking.rs index faa7fa52b..740d758ea 100644 --- a/pallets/subspace/src/staking.rs +++ b/pallets/subspace/src/staking.rs @@ -1,5 +1,4 @@ use super::*; -use substrate_fixed::types::{I32F32, I64F64}; use frame_support::{storage::IterableStorageDoubleMap, IterableStorageMap}; @@ -25,8 +24,6 @@ impl Pallet { Ok(()) } - - pub fn do_transfer_multiple( origin: T::RuntimeOrigin, destinations: Vec, @@ -34,18 +31,22 @@ impl Pallet { ) -> dispatch::DispatchResult { let key = ensure_signed(origin.clone())?; let amounts_sum: u64 = amounts.iter().sum(); - ensure!(Self::has_enough_balance(&key, amounts_sum), Error::::NotEnoughBalanceToTransfer); + ensure!( + Self::has_enough_balance(&key, amounts_sum), + Error::::NotEnoughBalanceToTransfer + ); ensure!(amounts.len() == destinations.len(), Error::::DifferentLengths); for (i, m_key) in destinations.iter().enumerate() { - ensure!(Self::has_enough_balance(&key, amounts[i as usize]), Error::::NotEnoughBalanceToTransfer); + ensure!( + Self::has_enough_balance(&key, amounts[i as usize]), + Error::::NotEnoughBalanceToTransfer + ); Self::transfer_balance_to_account(&key, &m_key.clone(), amounts[i as usize]); } Ok(()) } - - pub fn do_remove_stake_multiple( origin: T::RuntimeOrigin, netuid: u16, @@ -110,23 +111,31 @@ impl Pallet { let module_stake_before_add: u64 = Self::get_stake_for_key(netuid, &module_key); Self::increase_stake(netuid, &key, &module_key, amount); - let removed_balance: bool = Self::remove_balance_from_account(&key, Self::u64_to_balance(amount).unwrap()); + let removed_balance: bool = + Self::remove_balance_from_account(&key, Self::u64_to_balance(amount).unwrap()); ensure!(removed_balance, Error::::BalanceNotRemoved); let stake_after_add: u64 = Self::get_stake_to_module(netuid, &key, &module_key.clone()); let balance_after_add: u64 = Self::get_balance_u64(&key); let module_stake_after_add = Self::get_stake_for_key(netuid, &module_key); - ensure!(stake_after_add == stake_before_add.saturating_add(amount), Error::::StakeNotAdded); - ensure!(balance_after_add == balance_before_add.saturating_sub(amount), Error::::BalanceNotRemoved); - ensure!(module_stake_after_add == module_stake_before_add.saturating_add(amount), Error::::StakeNotAdded); + ensure!( + stake_after_add == stake_before_add.saturating_add(amount), + Error::::StakeNotAdded + ); + ensure!( + balance_after_add == balance_before_add.saturating_sub(amount), + Error::::BalanceNotRemoved + ); + ensure!( + module_stake_after_add == module_stake_before_add.saturating_add(amount), + Error::::StakeNotAdded + ); // --- 5. Emit the staking event. log::info!("StakeAdded( key:{:?}, stake_to_be_added:{:?} )", key, amount); Self::deposit_event(Event::StakeAdded(key, module_key, amount)); - - // --- 6. Ok and return. Ok(()) } @@ -168,9 +177,18 @@ impl Pallet { let balance_after_remove: u64 = Self::get_balance_u64(&key); let module_stake_after_remove = Self::get_stake_for_key(netuid, &module_key); - ensure!(stake_after_remove == stake_before_remove.saturating_sub(amount), Error::::StakeNotRemoved); - ensure!(balance_after_remove == balance_before_remove.saturating_add(amount), Error::::BalanceNotAdded); - ensure!(module_stake_after_remove == module_stake_before_remove.saturating_sub(amount), Error::::StakeNotRemoved); + ensure!( + stake_after_remove == stake_before_remove.saturating_sub(amount), + Error::::StakeNotRemoved + ); + ensure!( + balance_after_remove == balance_before_remove.saturating_add(amount), + Error::::BalanceNotAdded + ); + ensure!( + module_stake_after_remove == module_stake_before_remove.saturating_sub(amount), + Error::::StakeNotRemoved + ); log::info!("StakeRemoved( key:{:?}, stake_to_be_removed:{:?} )", key, amount); Self::deposit_event(Event::StakeRemoved(key, module_key, amount)); @@ -187,29 +205,25 @@ impl Pallet { // Returns the total amount of stake in the staking table. pub fn total_stake() -> u64 { - let mut total_stake: u64 = 0; - for (netuid, subnet_state) in as IterableStorageMap>>::iter() { - total_stake += subnet_state.total_stake; - } - return total_stake + as IterableStorageMap>>::iter() + .map(|(_, state)| state.total_stake) + .sum() } // Returns the stake under the cold - hot pairing in the staking table. - // pub fn get_stake(netuid: u16, key: &T::AccountId) -> u64 { - return Stake::::get(netuid, key) + Stake::::get(netuid, key) } pub fn get_stakes(netuid: u16) -> Vec { - return Stake::::iter_prefix(netuid).map(|(_, v)| v).collect::>() + Stake::::iter_prefix(netuid).map(|(_, v)| v).collect::>() } // Returns the stake under the cold - hot pairing in the staking table. pub fn key_account_exists(netuid: u16, key: &T::AccountId) -> bool { - return Uids::::contains_key(netuid, &key) + Uids::::contains_key(netuid, &key) } - // Returns the delegation fee of a module pub fn get_delegation_fee(netuid: u16, module_key: &T::AccountId) -> Percent { DelegationFee::::get(netuid, module_key) @@ -223,19 +237,15 @@ impl Pallet { module_key: &T::AccountId, amount: u64, ) -> bool { - return Self::get_stake_to_module(netuid, key, module_key) >= amount + Self::get_stake_to_module(netuid, key, module_key) >= amount } pub fn get_self_stake(netuid: u16, key: &T::AccountId) -> u64 { - return Self::get_stake_to_module(netuid, key, key) + Self::get_stake_to_module(netuid, key, key) } pub fn get_stake_to_total(netuid: u16, key: &T::AccountId) -> u64 { - let mut total_stake_to: u64 = 0; - for (k, v) in Self::get_stake_to_vector(netuid, key) { - total_stake_to += v; - } - return total_stake_to + Self::get_stake_to_vector(netuid, key).iter().map(|(_, v)| v).sum() } pub fn get_stake_to_module(netuid: u16, key: &T::AccountId, module_key: &T::AccountId) -> u64 { @@ -246,11 +256,11 @@ impl Pallet { } } - return state_to + state_to } pub fn get_stake_to_vector(netuid: u16, key: &T::AccountId) -> Vec<(T::AccountId, u64)> { - return StakeTo::::get(netuid, key) + StakeTo::::get(netuid, key) } pub fn set_stake_to_vector( @@ -279,28 +289,15 @@ impl Pallet { netuid: u16, module_key: &T::AccountId, ) -> Vec<(T::AccountId, u64)> { - return StakeFrom::::get(netuid, module_key) - .into_iter() - .collect::>() - } - pub fn get_total_stake_from(netuid: u16, module_key: &T::AccountId) -> u64 { - let stake_from_vector: Vec<(T::AccountId, u64)> = - Self::get_stake_from_vector(netuid, module_key); - let mut total_stake_from: u64 = 0; - for (k, v) in stake_from_vector { - total_stake_from += v; - } - return total_stake_from + StakeFrom::::get(netuid, module_key) } + pub fn get_total_stake_from(netuid: u16, key: &T::AccountId) -> u64 { + Self::get_stake_from_vector(netuid, key).iter().map(|(_, v)| v).sum() + } pub fn get_total_stake_to(netuid: u16, key: &T::AccountId) -> u64 { - let mut stake_to_vector: Vec<(T::AccountId, u64)> = Self::get_stake_to_vector(netuid, key); - let mut total_stake_to: u64 = 0; - for (k, v) in stake_to_vector { - total_stake_to += v; - } - return total_stake_to + Self::get_stake_to_vector(netuid, key).iter().map(|(_, v)| v).sum() } // INCREASE @@ -313,9 +310,9 @@ impl Pallet { ) -> bool { let mut stake_from_vector: Vec<(T::AccountId, u64)> = Self::get_stake_from_vector(netuid, module_key); - + let mut found_key_in_from_vector: bool = false; - + for (i, (k, v)) in stake_from_vector.clone().iter().enumerate() { if *k == *key { stake_from_vector[i] = (k.clone(), (*v).saturating_add(amount)); @@ -346,17 +343,19 @@ impl Pallet { Self::set_stake_to_vector(netuid, key, stake_to_vector); Self::set_stake_from_vector(netuid, module_key, stake_from_vector); - Stake::::insert(netuid,module_key, + Stake::::insert( + netuid, + module_key, Stake::::get(netuid, module_key).saturating_add(amount), ); - + let mut subnet_state = SubnetStateStorage::::get(netuid); subnet_state.total_stake = subnet_state.total_stake.saturating_add(amount); SubnetStateStorage::::insert(netuid, subnet_state); - return true + true } pub fn decrease_stake( @@ -369,7 +368,6 @@ impl Pallet { let mut stake_from_vector: Vec<(T::AccountId, u64)> = Self::get_stake_from_vector(netuid, module_key).clone(); - // TO STAKE let mut idx_to_replace: usize = usize::MAX; let mut end_idx: usize = stake_from_vector.len() - 1; @@ -411,23 +409,24 @@ impl Pallet { stake_to_vector.remove(end_idx); } - // save the stake to vector Self::set_stake_from_vector(netuid, module_key, stake_from_vector); Self::set_stake_to_vector(netuid, key, stake_to_vector); // --- 8. We add the balancer to the key. If the above fails we will not credit this key. - Stake::::insert(netuid,module_key, + Stake::::insert( + netuid, + module_key, Stake::::get(netuid, module_key).saturating_sub(amount), ); - + let mut subnet_state = SubnetStateStorage::::get(netuid); subnet_state.total_stake = subnet_state.total_stake.saturating_sub(amount); SubnetStateStorage::::insert(netuid, subnet_state); - return true + true } // Decreases the stake on the cold - hot pairing by the amount while decreasing other counters. @@ -435,7 +434,7 @@ impl Pallet { pub fn remove_stake_from_storage(netuid: u16, module_key: &T::AccountId) { let stake_from_vector: Vec<(T::AccountId, u64)> = Self::get_stake_from_vector(netuid, module_key); - for (i, (delegate_key, delegate_stake_amount)) in stake_from_vector.iter().enumerate() { + for (delegate_key, delegate_stake_amount) in stake_from_vector.iter() { Self::decrease_stake(netuid, delegate_key, module_key, *delegate_stake_amount); Self::add_balance_to_account( delegate_key, @@ -456,13 +455,13 @@ impl Pallet { } pub fn add_balance_to_account_u64(key: &T::AccountId, amount: u64) { - T::Currency::deposit_creating(&key, Self::u64_to_balance(amount).unwrap()); // Infallibe + let _ = T::Currency::deposit_creating(&key, Self::u64_to_balance(amount).unwrap()); // Infallibe } pub fn add_balance_to_account( key: &T::AccountId, amount: <::Currency as Currency<::AccountId>>::Balance, ) { - T::Currency::deposit_creating(&key, amount); // Infallibe + let _ = T::Currency::deposit_creating(&key, amount); // Infallibe } pub fn transfer_balance_to_account( @@ -491,23 +490,22 @@ impl Pallet { pub fn can_remove_balance_from_account(key: &T::AccountId, amount_64: u64) -> bool { let amount_as_balance = Self::u64_to_balance(amount_64); if amount_as_balance.is_none() { - return false + return false; } let amount = amount_as_balance.unwrap(); let current_balance = Self::get_balance(key); if amount > current_balance { - return false + return false; } // This bit is currently untested. @todo let new_potential_balance = current_balance - amount; - let can_withdraw: bool = T::Currency::ensure_can_withdraw( + T::Currency::ensure_can_withdraw( &key, amount, WithdrawReasons::except(WithdrawReasons::TIP), new_potential_balance, ) - .is_ok(); - return can_withdraw + .is_ok() } pub fn get_balance( @@ -534,7 +532,6 @@ impl Pallet { return total_balance; } - pub fn has_enough_balance(key: &T::AccountId, amount: u64) -> bool { return Self::get_balance_u64(key) > amount || amount == 0 } @@ -573,7 +570,6 @@ impl Pallet { // get the least staked network pub fn least_staked_module_key(netuid: u16) -> T::AccountId { let mut min_stake: u64 = u64::MAX; - let mut min_stake_uid: u16 = 0; let mut module_key: T::AccountId = Self::get_subnet_founder(netuid); for (m_key, m_stake) in as IterableStorageDoubleMap>::iter_prefix(netuid) @@ -584,12 +580,11 @@ impl Pallet { } } - return module_key + module_key } pub fn least_staked_module_uid(netuid: u16) -> u16 { // least_staked_module_uid return Self::get_uid_for_key(netuid, &Self::least_staked_module_key(netuid)) } - } diff --git a/pallets/subspace/src/step.rs b/pallets/subspace/src/step.rs index e83fa029a..438b71719 100644 --- a/pallets/subspace/src/step.rs +++ b/pallets/subspace/src/step.rs @@ -1,11 +1,9 @@ use super::*; use crate::math::*; -use frame_support::{ - storage::{IterableStorageDoubleMap, IterableStorageMap}, -}; +use frame_support::storage::IterableStorageDoubleMap; use sp_runtime::BoundedVec; -use substrate_fixed::types::{I110F18, I32F32, I64F64, I96F32}; use sp_std::vec; +use substrate_fixed::types::{I32F32, I64F64}; impl Pallet { pub fn block_step() { @@ -29,7 +27,7 @@ impl Pallet { subnet_state.pending_emission += new_queued_emission; SubnetStateStorage::::insert(netuid, subnet_state); - + log::debug!("netuid_i: {:?} queued_emission: +{:?} ", netuid, new_queued_emission); Self::deregister_pending_uid(netuid); // deregister any pending uids @@ -57,14 +55,12 @@ impl Pallet { let n: u16 = Self::get_subnet_n(netuid); let current_block: u64 = Self::get_current_block_as_u64(); - let block_at_registration: Vec = Self::get_block_at_registration(netuid); if n == 0 { - // - return + // + return; } - // quadratic voting // let quadratic_voting: bool = Self::get_quadratic_voting(netuid); @@ -74,19 +70,17 @@ impl Pallet { // total_stake_u64 = total_stake_u64; // } - - - - // FOUNDER DIVIDENDS + // FOUNDER DIVIDENDS let founder_key = Self::get_founder(netuid); let is_founder_registered = Self::is_key_registered(netuid, &founder_key); - let founder_uid = u16::MAX; let mut founder_emission: u64 = 0; if is_founder_registered { - let founder_share : u16 = Self::get_founder_share(netuid); + let founder_share: u16 = Self::get_founder_share(netuid); if founder_share > 0 { - let founder_emission_ratio: I64F64 = I64F64::from_num(founder_share.min(100))/I64F64::from_num(100); - founder_emission = (founder_emission_ratio * I64F64::from_num(token_emission)).to_num::(); + let founder_emission_ratio: I64F64 = + I64F64::from_num(founder_share.min(100)) / I64F64::from_num(100); + founder_emission = + (founder_emission_ratio * I64F64::from_num(token_emission)).to_num::(); token_emission = token_emission.saturating_sub(founder_emission); } } @@ -95,9 +89,8 @@ impl Pallet { // == Stake == // =========== - let mut uid_key_tuples: Vec<(u16, T::AccountId)> = Self::get_uid_key_tuples(netuid); - let mut stake_64: Vec = vec![I64F64::from_num(0.0); n as usize]; - let mut total_stake_u64: u64 =Self::get_total_subnet_stake(netuid).clone(); + let uid_key_tuples: Vec<(u16, T::AccountId)> = Self::get_uid_key_tuples(netuid); + let mut total_stake_u64: u64 = Self::get_total_subnet_stake(netuid).clone(); if total_stake_u64 == 0 { total_stake_u64 = 1; } @@ -109,8 +102,12 @@ impl Pallet { .map(|(_, key)| Self::get_stake_for_key(netuid, key).min(max_stake)) .collect(); // clip it to the max stake - let mut stake_f64: Vec = stake_u64.iter().map(|x| I64F64::from_num(x.clone()) /I64F64::from_num(total_stake_u64)).collect(); - let mut stake : Vec = stake_f64.iter().map(|x| I32F32::from_num(x.clone())).collect(); + let stake_f64: Vec = stake_u64 + .iter() + .map(|x| I64F64::from_num(x.clone()) / I64F64::from_num(total_stake_u64)) + .collect(); + let mut stake: Vec = + stake_f64.iter().map(|x| I32F32::from_num(x.clone())).collect(); // Normalize active stake. inplace_normalize(&mut stake); @@ -124,11 +121,10 @@ impl Pallet { let min_weight_stake_f64: I64F64 = I64F64::from_num(global_params.min_weight_stake); - - for (uid_i, mut weights_i) in + for (uid_i, weights_i) in as IterableStorageDoubleMap>>::iter_prefix(netuid) { - let mut weight_changed : bool = false; + let mut weight_changed: bool = false; // watchout for the overflow let weight_age: u64 = current_block.saturating_sub(last_update_vector[uid_i as usize]); @@ -141,7 +137,8 @@ impl Pallet { if (pos as u16) <= subnet_params.max_allowed_weights && *uid_j < n { // okay , we passed the positioonal check, now check the weight let weight_f64 = I64F64::from_num(*weight_ij) / I64F64::from_num(u16::MAX); - let weight_stake = (stake_f64[uid_i as usize] * weight_f64) * I64F64::from_num(total_stake_u64); + let weight_stake = (stake_f64[uid_i as usize] * weight_f64) * + I64F64::from_num(total_stake_u64); if weight_stake > min_weight_stake_f64 { weights[uid_i as usize].push((*uid_j, *weight_ij)); } else { @@ -150,26 +147,27 @@ impl Pallet { } else { weight_changed = true; } + } } - } - - if weight_changed { // update the weights if it was changed >::insert(netuid, uid_i, weights[uid_i as usize].clone()); } } - - let mut weights : Vec> = weights.iter().map(|x| x.iter().map(|(uid, weight)| (*uid, u16_proportion_to_fixed(*weight))).collect()).collect(); - + let mut weights: Vec> = weights + .iter() + .map(|x| { + x.iter().map(|(uid, weight)| (*uid, u16_proportion_to_fixed(*weight))).collect() + }) + .collect(); // enabling self voting (if enabled) - if (!subnet_params.self_vote) { + if !subnet_params.self_vote { weights = mask_diag_sparse(&weights); } - + // Normalize remaining weights. inplace_row_normalize_sparse(&mut weights); @@ -190,12 +188,11 @@ impl Pallet { // If emission is zero, do an even split. if is_zero(&incentive) { // no weights set - for (uid_i, key) in uid_key_tuples.iter() { + for (uid_i, _) in uid_key_tuples.iter() { incentive[*uid_i as usize] = I32F32::from_num(1.0); } } - inplace_normalize(&mut incentive); // range: I32F32(0, 1) // ================================= @@ -205,46 +202,47 @@ impl Pallet { // trust that acts as a multiplier for the incentive let trust_ratio: u16 = Self::get_trust_ratio(netuid); if trust_ratio > 0 { - - let trust_share : I32F32 = I32F32::from_num(trust_ratio)/I32F32::from_num(100); - let incentive_share : I32F32 = I32F32::from_num(1.0).saturating_sub(trust_share); + let trust_share: I32F32 = I32F32::from_num(trust_ratio) / I32F32::from_num(100); + let incentive_share: I32F32 = I32F32::from_num(1.0).saturating_sub(trust_share); let mut trust: Vec = vec![I32F32::from_num(0.0); n as usize]; - for (i, weights_i) in weights.iter().enumerate() { for (j, weight_ij) in weights_i.iter() { // Compute trust scores: t_j = SUM(i) w_ij * s_i // result_j = SUM(i) vector_i * matrix_ij - if *weight_ij > 0 && - stake[i] > I32F32::from_num(subnet_params.min_stake) { + if *weight_ij > 0 && stake[i] > I32F32::from_num(subnet_params.min_stake) { trust[*j as usize] += I32F32::from_num(1.0); } } } inplace_normalize(&mut trust); - incentive = incentive.iter().zip(trust.iter()).map(|(inc, tru)| (inc * incentive_share) + (tru * trust_share)).collect(); - + incentive = incentive + .iter() + .zip(trust.iter()) + .map(|(inc, tru)| (inc * incentive_share) + (tru * trust_share)) + .collect(); + // save the trust into the trust vector let mut subnet_state = SubnetStateStorage::::get(netuid); subnet_state.trusts = BoundedVec::>::try_from( - trust.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>() - ).expect("too long vec"); - + trust.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>(), + ) + .expect("too long vec"); + SubnetStateStorage::::insert(netuid, subnet_state); } - // store the incentive let mut subnet_state = SubnetStateStorage::::get(netuid); subnet_state.incentives = BoundedVec::>::try_from( - incentive.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>() - ).expect("too long vec"); - - SubnetStateStorage::::insert(netuid, subnet_state); + incentive.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>(), + ) + .expect("too long vec"); + SubnetStateStorage::::insert(netuid, subnet_state); // ================================= // == Calculate Bonds== @@ -274,14 +272,12 @@ impl Pallet { } } - // Compute dividends: d_i = SUM(j) b_ij * inc_j. // range: I32F32(0, 1) // ================================= // == Dividends== // ================================= - let mut dividends: Vec = vec![I32F32::from_num(0.0); incentive.len()]; for (i, sparse_row) in bonds.iter().enumerate() { for (j, value) in sparse_row.iter() { @@ -295,7 +291,7 @@ impl Pallet { // If emission is zero, do an even split. if is_zero(÷nds) { // no weights set - for (uid_i, key) in uid_key_tuples.iter() { + for (uid_i, _) in uid_key_tuples.iter() { dividends[*uid_i as usize] = I32F32::from_num(1.0); } } @@ -305,26 +301,32 @@ impl Pallet { let mut subnet_state = SubnetStateStorage::::get(netuid); subnet_state.dividends = BoundedVec::>::try_from( - dividends.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>() - ).expect("too long vec"); - + dividends.iter().map(|xi| fixed_proportion_to_u16(*xi)).collect::>(), + ) + .expect("too long vec"); + SubnetStateStorage::::insert(netuid, subnet_state); // ================================= // == Emission== // ================================= - let mut incentive_ratio: I64F64 = I64F64::from_num(Self::get_incentive_ratio(netuid) as u64) / I64F64::from_num(100); + let incentive_ratio: I64F64 = + I64F64::from_num(Self::get_incentive_ratio(netuid) as u64) / I64F64::from_num(100); let dividend_ratio: I64F64 = I64F64::from_num(1.0) - incentive_ratio; let incentive_emission_float: Vec = incentive .clone() .iter() - .map(|x| I64F64::from_num(x.clone()) * I64F64::from_num(token_emission) * incentive_ratio) + .map(|x| { + I64F64::from_num(x.clone()) * I64F64::from_num(token_emission) * incentive_ratio + }) .collect(); let dividends_emission_float: Vec = dividends .clone() .iter() - .map(|x| I64F64::from_num(x.clone()) * I64F64::from_num(token_emission) * dividend_ratio) + .map(|x| { + I64F64::from_num(x.clone()) * I64F64::from_num(token_emission) * dividend_ratio + }) .collect(); let mut incentive_emission: Vec = @@ -333,25 +335,23 @@ impl Pallet { dividends_emission_float.iter().map(|e: &I64F64| e.to_num::()).collect(); let burn_rate: u16 = global_params.burn_rate; - let mut burn_amount_per_epoch : u64 = 0; + let mut burn_amount_per_epoch: u64 = 0; // get the float and convert to u64 if burn_rate > 0 { - let burn_rate_float : I64F64 = (I64F64::from_num(burn_rate)/I64F64::from_num(100)) * (I64F64::from_num(token_emission) / I64F64::from_num(n)); + let burn_rate_float: I64F64 = (I64F64::from_num(burn_rate) / I64F64::from_num(100)) * + (I64F64::from_num(token_emission) / I64F64::from_num(n)); burn_amount_per_epoch = burn_rate_float.to_num::(); } - if is_founder_registered { let founder_uid = Self::get_uid_for_key(netuid, &founder_key); - incentive_emission[founder_uid as usize] = incentive_emission[founder_uid as usize].saturating_add(founder_emission); + incentive_emission[founder_uid as usize] = + incentive_emission[founder_uid as usize].saturating_add(founder_emission); } - // burn the amount - + // burn the amount // Emission tuples ( uid_key_tuples, u64 emission) - let mut founder_share_added: bool = false; // avoid double counting the founder share for (module_uid, module_key) in uid_key_tuples.iter() { - // get the incentive emission for this key let mut owner_emission_incentive: u64 = incentive_emission[*module_uid as usize]; // if the owner is the founder, then increase the stake @@ -367,87 +367,90 @@ impl Pallet { // decrease the stake if there is remainder if burn_into_stake > 0 { Self::decrease_stake(netuid, module_key, module_key, burn_into_stake); - } - owner_emission_incentive = 0; - owner_dividends_emission = 0; - // skip the rest of the loop - } else { - // eat into incentive first and then into the incentive - if burn_amount_per_epoch > owner_emission_incentive { - owner_emission_incentive = owner_emission_incentive.saturating_sub(burn_amount_per_epoch); - // correct the burn amount - burn_amount_per_epoch = burn_amount_per_epoch.saturating_sub(owner_emission_incentive); - // apply the burn to the dividends from the owner - owner_dividends_emission = owner_dividends_emission.saturating_sub(burn_amount_per_epoch); - - } else { - // apply the burn to the emission only - owner_emission_incentive = owner_emission_incentive.saturating_sub(burn_amount_per_epoch); - burn_amount_per_epoch = 0; - } - // if the owner emission is less than the burn amount + continue; + } - if owner_dividends_emission > 0 { - // get the ownership emission for this key + // eat into incentive first and then into the incentive + if burn_amount_per_epoch > owner_emission_incentive { + owner_emission_incentive = + owner_emission_incentive.saturating_sub(burn_amount_per_epoch); + // correct the burn amount + burn_amount_per_epoch = + burn_amount_per_epoch.saturating_sub(owner_emission_incentive); + // apply the burn to the dividends from the owner + owner_dividends_emission = + owner_dividends_emission.saturating_sub(burn_amount_per_epoch); + } else { + // apply the burn to the emission only + owner_emission_incentive = + owner_emission_incentive.saturating_sub(burn_amount_per_epoch); + burn_amount_per_epoch = 0; + } + + // if the owner emission is less than the burn amount - let ownership_vector: Vec<(T::AccountId, I64F64)> = Self::get_ownership_ratios(netuid, module_key); - - let delegation_fee = Self::get_delegation_fee(netuid, module_key); - - // add the ownership - for (delegate_key, delegate_ratio) in ownership_vector.iter() { + if owner_dividends_emission > 0 { + // get the ownership emission for this key - // skip the owner as it is already added at the end - if delegate_key == module_key { - continue - } + let ownership_vector: Vec<(T::AccountId, I64F64)> = + Self::get_ownership_ratios(netuid, module_key); - // calculate the dividends from the owner - let mut dividends_from_delegate : u64 = (I64F64::from_num(owner_dividends_emission) * delegate_ratio).to_num::(); - - // calculate the delegation fee - let to_module: u64 = delegation_fee.mul_floor(dividends_from_delegate); - - // calculate the dividends from the owner - let to_delegate: u64 = dividends_from_delegate.saturating_sub(to_module); - - - Self::increase_stake(netuid, delegate_key, module_key, to_delegate); - owner_dividends_emission = owner_dividends_emission.saturating_sub(to_delegate); + let delegation_fee = Self::get_delegation_fee(netuid, module_key); + // add the ownership + for (delegate_key, delegate_ratio) in ownership_vector.iter() { + // skip the owner as it is already added at the end + if delegate_key == module_key { + continue } - } - + // calculate the dividends from the owner + let dividends_from_delegate: u64 = + (I64F64::from_num(owner_dividends_emission) * delegate_ratio) + .to_num::(); - owner_emission = owner_emission_incentive + owner_dividends_emission; - - // add the emisssion and rm the burn amount + // calculate the delegation fee + let to_module: u64 = delegation_fee.mul_floor(dividends_from_delegate); - if owner_emission > 0 { - // get the profit shares - let profit_share_emissions: Vec<(T::AccountId, u64)> = Self::get_profit_share_emissions(module_key.clone(), owner_emission); + // calculate the dividends from the owner + let to_delegate: u64 = dividends_from_delegate.saturating_sub(to_module); - // if there are profit shares, then increase the balance of the profit share key - if profit_share_emissions.len() > 0 { - // if there are profit shares, then increase the balance of the profit share key - for (profit_share_key, profit_share_emission) in profit_share_emissions.iter() { - // increase the balance of the profit share key - Self::increase_stake(netuid, profit_share_key, module_key, *profit_share_emission); - } - } else { - // increase it to the module key - Self::increase_stake(netuid, module_key, module_key, owner_emission); - } + Self::increase_stake(netuid, delegate_key, module_key, to_delegate); + owner_dividends_emission = owner_dividends_emission.saturating_sub(to_delegate); } } + owner_emission = owner_emission_incentive + owner_dividends_emission; + + // add the emisssion and rm the burn amount + + if owner_emission > 0 { + // get the profit shares + let profit_share_emissions: Vec<(T::AccountId, u64)> = + Self::get_profit_share_emissions(module_key.clone(), owner_emission); + + // if there are profit shares, then increase the balance of the profit share key + if profit_share_emissions.len() > 0 { + // if there are profit shares, then increase the balance of the profit share + // key + for (profit_share_key, profit_share_emission) in profit_share_emissions.iter() { + // increase the balance of the profit share key + Self::increase_stake( + netuid, + profit_share_key, + module_key, + *profit_share_emission, + ); + } + } else { + // increase it to the module key + Self::increase_stake(netuid, module_key, module_key, owner_emission); + } + } } - let mut zero_stake_uids : Vec = Vec::new(); - for (module_uid, module_key) in uid_key_tuples.iter() { let new_stake = Self::get_stake_for_key(netuid, module_key); if new_stake < subnet_params.min_stake { @@ -456,7 +459,6 @@ impl Pallet { } } - // calculate the total emission let emission: Vec = incentive_emission .iter() @@ -466,10 +468,9 @@ impl Pallet { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.emissions = BoundedVec::>::try_from( - emission - ).expect("too long vec"); - + subnet_state.emissions = + BoundedVec::>::try_from(emission).expect("too long vec"); + SubnetStateStorage::::insert(netuid, subnet_state); } @@ -485,12 +486,12 @@ impl Pallet { block_at_registration } - pub fn blocks_until_next_epoch(netuid: u16, tempo: u16, block_number: u64) -> u64 { if tempo == 0 { - return 0 + 0 + } else { + (block_number + netuid as u64) % (tempo as u64) } - return (block_number + netuid as u64) % (tempo as u64) } pub fn get_ownership_ratios_for_uid(netuid: u16, uid: u16) -> Vec<(T::AccountId, I64F64)> { @@ -503,7 +504,6 @@ impl Pallet { ) -> Vec<(T::AccountId, I64F64)> { let stake_from_vector: Vec<(T::AccountId, u64)> = Self::get_stake_from_vector(netuid, module_key); - let uid = Self::get_uid_for_key(netuid, module_key); let mut total_stake_from: I64F64 = I64F64::from_num(0); let mut ownership_vector: Vec<(T::AccountId, I64F64)> = Vec::new(); @@ -522,7 +522,7 @@ impl Pallet { ownership_vector.into_iter().map(|(k, v)| (k, v / total_stake_from)).collect(); } - return ownership_vector + ownership_vector } pub fn get_ownership_ratios_emission( @@ -539,8 +539,6 @@ impl Pallet { emission_vector.push((k, emission_for_delegate)); } - return emission_vector + emission_vector } - - } diff --git a/pallets/subspace/src/subnet.rs b/pallets/subspace/src/subnet.rs index 611925cd3..2975afa36 100644 --- a/pallets/subspace/src/subnet.rs +++ b/pallets/subspace/src/subnet.rs @@ -1,23 +1,16 @@ use super::*; -use codec::Compact; use frame_support::{ - pallet_prelude::{Decode, DispatchError, DispatchResult, Encode}, - storage::IterableStorageMap, - traits::Currency, - IterableStorageDoubleMap, + pallet_prelude::DispatchResult, storage::IterableStorageMap, IterableStorageDoubleMap, }; use sp_runtime::BoundedVec; -use crate::utils::is_vec_str; -use frame_system::ensure_root; -pub use sp_std::{vec, vec::Vec}; -use substrate_fixed::types::{I32F32, I64F64}; +pub use sp_std::vec::Vec; +use substrate_fixed::types::I64F64; extern crate alloc; impl Pallet { // Returns true if the subnetwork exists. // - pub fn do_remote_subnet(origin: T::RuntimeOrigin, netuid: u16) -> DispatchResult { let key = ensure_signed(origin)?; // --- 1. Ensure the network name does not already exist. @@ -37,8 +30,8 @@ impl Pallet { ) -> DispatchResult { let key = ensure_signed(origin)?; // only the founder can update the network on authority mode - - ensure!(is_vec_str(Self::get_vote_mode_subnet(netuid), "authority"), Error::::NotAuthorityMode); + + ensure!(Self::get_vote_mode_subnet(netuid) == b"authority", Error::::NotAuthorityMode); ensure!(Self::if_subnet_netuid_exists(netuid), Error::::SubnetNameAlreadyExists); ensure!(Self::is_subnet_founder(netuid, &key), Error::::NotFounder); ensure!(Self::if_subnet_netuid_exists(netuid), Error::::SubnetNameAlreadyExists); @@ -49,19 +42,23 @@ impl Pallet { Ok(()) } - - - pub fn check_subnet_params(params: SubnetParams) -> DispatchResult{ - // checks if params are valid + pub fn check_subnet_params(params: SubnetParams) -> DispatchResult { + // checks if params are valid let global_params = Self::global_params(); - // check valid tempo - ensure!(params.min_allowed_weights <= params.max_allowed_weights, Error::::InvalidMinAllowedWeights); - + // check valid tempo + ensure!( + params.min_allowed_weights <= params.max_allowed_weights, + Error::::InvalidMinAllowedWeights + ); + ensure!(params.min_allowed_weights >= 1, Error::::InvalidMinAllowedWeights); - ensure!(params.max_allowed_weights <= global_params.max_allowed_weights, Error::::InvalidMaxAllowedWeights); + ensure!( + params.max_allowed_weights <= global_params.max_allowed_weights, + Error::::InvalidMaxAllowedWeights + ); // the global params must be larger than the global min_stake ensure!(params.min_stake >= global_params.min_stake, Error::::InvalidMinStake); @@ -70,25 +67,22 @@ impl Pallet { ensure!(params.tempo > 0, Error::::InvalidTempo); - ensure!(params.max_weight_age > params.tempo as u64, Error::::InvalidMaxWeightAge); - + ensure!(params.max_weight_age > params.tempo as u64, Error::::InvalidMaxWeightAge); + // ensure the trust_ratio is between 0 and 100 ensure!(params.trust_ratio <= 100, Error::::InvalidTrustRatio); // ensure the vode_mode is in "authority", "stake" ensure!( - is_vec_str(params.vote_mode.clone(),"authority") || - is_vec_str(params.vote_mode.clone(),"stake"), - Error::::InvalidVoteMode); - Ok(()) - - - } - + params.vote_mode == b"authority" || params.vote_mode == b"stake", + Error::::InvalidVoteMode + ); + Ok(()) + } pub fn subnet_params(netuid: u16) -> SubnetParams { let subnet_state = SubnetStateStorage::::get(netuid); - + SubnetParams { immunity_period: subnet_state.immunity_period, min_allowed_weights: subnet_state.min_allowed_weights, @@ -109,11 +103,7 @@ impl Pallet { } } - - - - pub fn set_subnet_params(netuid: u16, mut params: SubnetParams) { - + pub fn set_subnet_params(netuid: u16, params: SubnetParams) { // TEMPO, IMMUNITY_PERIOD, MIN_ALLOWED_WEIGHTS, MAX_ALLOWED_WEIGHTS, MAX_ALLOWED_UIDS, // MAX_IMMUNITY_RATIO Self::set_founder(netuid, params.founder); @@ -131,12 +121,9 @@ impl Pallet { Self::set_vote_threshold_subnet(netuid, params.vote_threshold); Self::set_vote_mode_subnet(netuid, params.vote_mode); Self::set_self_vote(netuid, params.self_vote); - Self::set_incentive_ratio(netuid, params.incentive_ratio); - - + Self::set_incentive_ratio(netuid, params.incentive_ratio); } - pub fn if_subnet_exist(netuid: u16) -> bool { SubnetStateStorage::::get(netuid).name.len() > 0 } @@ -151,10 +138,8 @@ impl Pallet { subnet_state.min_stake = stake; SubnetStateStorage::::insert(netuid, subnet_state) - } - pub fn get_max_stake(netuid: u16) -> u64 { SubnetStateStorage::::get(netuid).max_stake } @@ -171,7 +156,9 @@ impl Pallet { pub fn least_staked_netuid() -> u16 { let mut min_stake: u64 = u64::MAX; let mut min_stake_netuid: u16 = u16::MAX; - for (netuid, subnet_state) in as IterableStorageMap>>::iter() { + for (netuid, subnet_state) in + as IterableStorageMap>>::iter() + { let net_stake = subnet_state.total_stake; if net_stake <= min_stake && net_stake > 0 { @@ -179,49 +166,46 @@ impl Pallet { min_stake_netuid = netuid; } } - return min_stake_netuid + min_stake_netuid } - pub fn address_vector(netuid: u16) -> Vec>{ - let mut addresses: Vec> = Vec::new(); - for (uid, address) in as IterableStorageDoubleMap>>::iter_prefix(netuid) { - addresses.push(address); - } - return addresses + pub fn address_vector(netuid: u16) -> Vec> { + as IterableStorageDoubleMap>>::iter_prefix(netuid) + .map(|(_, address)| address) + .collect() } - pub fn name_vector(netuid: u16) -> Vec>{ - let mut names: Vec> = Vec::new(); - for (uid, name) in as IterableStorageDoubleMap>>::iter_prefix(netuid) { - names.push(name); - } - return names + pub fn name_vector(netuid: u16) -> Vec> { + as IterableStorageDoubleMap>>::iter_prefix(netuid) + .map(|(_, name)| name) + .collect() } - // get the least staked network pub fn min_subnet_stake() -> u64 { let mut min_stake: u64 = u64::MAX; - for (netuid, subnet_state) in as IterableStorageMap>>::iter() { + for (_, subnet_state) in + as IterableStorageMap>>::iter() + { let net_stake = subnet_state.total_stake; - + if net_stake <= min_stake { min_stake = net_stake; } } - return min_stake + + min_stake } pub fn get_network_stake(netuid: u16) -> u64 { SubnetStateStorage::::get(netuid).total_stake } - - pub fn add_pending_deregistration_uid(netuid: u16, uid: u16) { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.pending_deregister_uids.try_push(uid); + // TODO: handle error + let _ = subnet_state.pending_deregister_uids.try_push(uid); SubnetStateStorage::::insert(netuid, subnet_state) } @@ -231,7 +215,7 @@ impl Pallet { Self::add_pending_deregistration_uid(netuid, uid); } } - + pub fn deregister_pending_uid(netuid: u16) { let mut subnet_state = SubnetStateStorage::::get(netuid); @@ -243,7 +227,6 @@ impl Pallet { Self::remove_module(netuid, uid); } SubnetStateStorage::::insert(netuid, subnet_state); - } } @@ -252,16 +235,16 @@ impl Pallet { if max_allowed_uids < n { // limit it at 256 at a time - let mut remainder_n: u16 = (n - max_allowed_uids); + let mut remainder_n = n - max_allowed_uids; let max_remainder = 256; - if remainder_n > max_remainder { + if remainder_n > max_remainder { // remove the modules in small amounts, as this can be a heavy load on the chain remainder_n = max_remainder; max_allowed_uids = n - remainder_n; } // remove the modules by adding the to the deregister queue for i in 0..remainder_n { - let next_uid: u16= n - 1 - i; + let next_uid: u16 = n - 1 - i; Self::remove_module(netuid, next_uid); } } @@ -273,8 +256,6 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - - pub fn set_name_subnet(netuid: u16, name: Vec) { // set the name if it doesnt exist let mut subnet_state = SubnetStateStorage::::get(netuid); @@ -284,8 +265,6 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - - pub fn uid_in_immunity(netuid: u16, uid: u16) -> bool { let block_at_registration: u64 = Self::get_module_registration_block(netuid, uid); let immunity_period: u64 = Self::get_immunity_period(netuid) as u64; @@ -294,7 +273,7 @@ impl Pallet { } pub fn default_subnet_params() -> SubnetParams { - // get an invalid + // get an invalid let default_netuid: u16 = Self::num_subnets() + 1; return Self::subnet_params(default_netuid) } @@ -320,7 +299,6 @@ impl Pallet { return Self::get_subnet_founder(netuid) == *key } - pub fn get_subnet_founder(netuid: u16) -> T::AccountId { return SubnetStateStorage::::get(netuid).founder } @@ -337,7 +315,6 @@ impl Pallet { SubnetStateStorage::::get(netuid).self_vote } - // pub fn total_balance() -> u64 { // let mut total_balance: u64 = 0; // // iterate through all of the accounts with balance (noo stake) @@ -349,14 +326,11 @@ impl Pallet { // } pub fn market_cap() -> u64 { - let total_stake: u64 = Self::total_stake(); - return total_stake + Self::total_stake() } pub fn get_unit_emission() -> u64 { - let global_state = GlobalStateStorage::::get(); - - return global_state.unit_emission + GlobalStateStorage::::get().unit_emission } pub fn set_unit_emission(unit_emission: u64) { @@ -367,7 +341,6 @@ impl Pallet { GlobalStateStorage::::put(global_state) } - pub fn get_unit_emission_per_block() -> u64 { return Self::get_unit_emission() * 4 } @@ -375,22 +348,20 @@ impl Pallet { // Returns the total amount of stake in the staking table. pub fn get_total_emission_per_block() -> u64 { let market_cap: u64 = Self::market_cap(); - let mut unit_emission: u64 = Self::get_unit_emission(); + let unit_emission: u64 = Self::get_unit_emission(); let mut emission_per_block: u64 = unit_emission; // assuming 8 second block times - let halving_total_stake_checkpoints: Vec = - vec![10_000_000, 20_000_000, 30_000_000, 40_000_000] - .iter() - .map(|x| x * unit_emission) - .collect(); - for (i, having_stake) in halving_total_stake_checkpoints.iter().enumerate() { + let halving_total_stake_checkpoints = [10_000_000, 20_000_000, 30_000_000, 40_000_000] + .iter() + .map(|x| x * unit_emission); + for (i, having_stake) in halving_total_stake_checkpoints.enumerate() { let halving_factor = 2u64.pow((i) as u32); - if market_cap < *having_stake { + if market_cap < having_stake { emission_per_block = emission_per_block / halving_factor; break } } - return emission_per_block + emission_per_block } pub fn get_total_subnet_balance(netuid: u16) -> u64 { let keys = Self::get_keys(netuid); @@ -401,7 +372,7 @@ impl Pallet { let subnet_stake: I64F64 = I64F64::from_num(Self::get_total_subnet_stake(netuid)); let total_stake: I64F64 = I64F64::from_num(Self::total_stake()); - let mut subnet_ratio: I64F64 = I64F64::from_num(0); + let subnet_ratio: I64F64; if total_stake > I64F64::from_num(0) { subnet_ratio = subnet_stake / total_stake; } else { @@ -424,7 +395,7 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state); - return token_emission + token_emission } pub fn get_subnet_emission(netuid: u16) -> u64 { @@ -435,7 +406,6 @@ impl Pallet { let mut global_state = GlobalStateStorage::::get(); // --- 1. Enfnsure that the network name does not already exist. let total_networks: u16 = global_state.total_subnets; - let max_networks = Self::get_global_max_allowed_subnets(); let netuid = total_networks; Self::set_subnet_params(netuid, params.clone()); @@ -454,23 +424,16 @@ impl Pallet { // --- 6. Emit the new network event. Self::deposit_event(Event::NetworkAdded(netuid, params.name.clone())); - return netuid + netuid } - + // Initializes a new subnetwork under netuid with parameters. - // pub fn if_subnet_name_exists(name: Vec) -> bool { - for (netuid, subnet_state) in SubnetStateStorage::::iter() { - if subnet_state.name == name { - return true - } - } - - return false + SubnetStateStorage::::iter().any(|(_, state)| state.name == name) } pub fn subnet_name_exists(name: Vec) -> bool { - return Self::if_subnet_name_exists(name.clone()).into() + return Self::if_subnet_name_exists(name.clone()) } pub fn if_subnet_netuid_exists(netuid: u16) -> bool { @@ -478,13 +441,10 @@ impl Pallet { } pub fn get_netuid_for_name(name: Vec) -> u16 { - for (netuid, subnet_state) in SubnetStateStorage::::iter() { - if name == subnet_state.name.into_inner() { - return netuid - } - } - - return u16::MAX + SubnetStateStorage::::iter() + .find(|(_, state)| state.name == name) + .map(|(netuid, _)| netuid) + .unwrap_or(u16::MAX) } pub fn get_subnet_name(netuid: u16) -> Vec { @@ -493,18 +453,17 @@ impl Pallet { pub fn is_network_founder(netuid: u16, key: &T::AccountId) -> bool { // Returns true if the account is the founder of the network. - let founder = Self::get_founder(netuid); - return founder == *key + Self::get_founder(netuid) == *key } pub fn remote_subnet_for_name(name: Vec) -> u16 { let netuid = Self::get_netuid_for_name(name.clone()); - return Self::remove_subnet(netuid) + Self::remove_subnet(netuid) } pub fn remove_netuid_stake_strorage(netuid: u16) { // --- 1. Erase network stake, and remove network from list of networks. - for (key, stated_amount) in + for (key, _) in as IterableStorageDoubleMap>::iter_prefix(netuid) { Self::remove_stake_from_storage(netuid, &key); @@ -522,24 +481,22 @@ impl Pallet { pub fn remove_subnet(netuid: u16) -> u16 { // --- 2. Ensure the network to be removed exists. if !Self::if_subnet_exist(netuid) { - return 0 + return 0; } - let name: Vec = Self::get_subnet_name(netuid); Self::remove_netuid_stake_strorage(netuid); - Name::::clear_prefix(netuid, u32::max_value(), None); - Address::::clear_prefix(netuid, u32::max_value(), None); - Uids::::clear_prefix(netuid, u32::max_value(), None); - Keys::::clear_prefix(netuid, u32::max_value(), None); + let _ = Name::::clear_prefix(netuid, u32::max_value(), None); + let _ = Address::::clear_prefix(netuid, u32::max_value(), None); + let _ = Uids::::clear_prefix(netuid, u32::max_value(), None); + let _ = Keys::::clear_prefix(netuid, u32::max_value(), None); // Remove consnesus vectors - Weights::::clear_prefix(netuid, u32::max_value(), None); + let _ = Weights::::clear_prefix(netuid, u32::max_value(), None); + + let _ = DelegationFee::::clear_prefix(netuid, u32::max_value(), None); + let _ = RegistrationBlock::::clear_prefix(netuid, u32::max_value(), None); - DelegationFee::::clear_prefix(netuid, u32::max_value(), None); - RegistrationBlock::::clear_prefix(netuid, u32::max_value(), None); - - // --- 2. Erase subnet parameters. SubnetStateStorage::::remove(netuid); @@ -553,16 +510,17 @@ impl Pallet { log::info!("NetworkRemoved( netuid:{:?} )", netuid); Self::deposit_event(Event::NetworkRemoved(netuid)); - return netuid + netuid } pub fn get_subnets() -> Vec> { let mut subnets_info = Vec::>::new(); - + for netuid in SubnetStateStorage::::iter_keys() { subnets_info.push(Self::subnet_info(netuid)); } - return subnets_info + + subnets_info } // Returns the number of filled slots on a network. @@ -587,16 +545,13 @@ impl Pallet { return Uids::::contains_key(netuid, key) } - - - - pub fn is_key_registered_on_any_network( key: &T::AccountId) -> bool { + pub fn is_key_registered_on_any_network(key: &T::AccountId) -> bool { for netuid in Self::netuids() { if Uids::::contains_key(netuid, key) { - return true + return true; } } - return false + false } // Returs the key under the network uid as a Result. Ok if the uid is taken. @@ -611,7 +566,6 @@ impl Pallet { return Uids::::get(netuid, key).unwrap_or(0) } - pub fn get_trust_ratio(netuid: u16) -> u16 { SubnetStateStorage::::get(netuid).trust_ratio } @@ -624,7 +578,6 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - pub fn get_quadratic_voting(netuid: u16) -> bool { SubnetStateStorage::::get(netuid).quadratic_voting } @@ -637,19 +590,9 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - - - - pub fn if_module_name_exists(netuid: u16, name: Vec) -> bool { - for (uid, _name) in - as IterableStorageDoubleMap>>::iter_prefix(netuid) - { - if _name == name { - return true - } - } - return false + as IterableStorageDoubleMap>>::iter_prefix(netuid) + .any(|(_, mod_name)| mod_name == name) } // Returns the stake of the uid on network or 0 if it doesnt exist. @@ -667,7 +610,7 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - + pub fn get_vote_mode_subnet(netuid: u16) -> Vec { Self::subnet_params(netuid).vote_mode } @@ -675,11 +618,12 @@ impl Pallet { pub fn set_vote_mode_subnet(netuid: u16, vote_mode: Vec) { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.vote_mode = BoundedVec::>::try_from(vote_mode).expect("too long vote mode"); + subnet_state.vote_mode = + BoundedVec::>::try_from(vote_mode).expect("too long vote mode"); SubnetStateStorage::::insert(netuid, subnet_state) } - + pub fn get_subnet_vote_threshold(netuid: u16) -> u16 { SubnetStateStorage::::get(netuid).vote_threshold } @@ -697,20 +641,14 @@ impl Pallet { number_of_subnets = number_of_subnets + 1; } - return number_of_subnets + number_of_subnets } pub fn netuids() -> Vec { - let mut netuids : Vec = Vec::new(); - - for netuid in SubnetStateStorage::::iter_keys() { - netuids.push(netuid); - } - - return netuids + SubnetStateStorage::::iter_keys().collect() } - pub fn random_netuid() -> u16{ + pub fn random_netuid() -> u16 { // get the number of subnets let netuids = Self::netuids(); // get a random number between 0 and number_of_subnets @@ -747,7 +685,7 @@ impl Pallet { pub fn get_registration_block_for_uid(netuid: u16, uid: u16) -> u64 { return RegistrationBlock::::get(netuid, uid) } - + pub fn get_incentive_ratio(netuid: u16) -> u16 { SubnetStateStorage::::get(netuid).incentive_ratio } @@ -776,20 +714,19 @@ impl Pallet { SubnetStateStorage::::insert(netuid, subnet_state) } - - pub fn get_burn_emission_per_epoch(netuid: u16) -> u64 { let burn_rate: u16 = Self::get_burn_rate(); let epoch_emission: u64 = Self::get_subnet_emission(netuid); let n: u16 = Self::get_subnet_n(netuid); // get the float and convert to u64 if n == 0 { - return 0 + return 0; } - let burn_rate_float : I64F64 = I64F64::from_num(burn_rate) / I64F64::from_num(n * 100); - let burn_emission_per_epoch: u64 = (I64F64::from_num(epoch_emission) * burn_rate_float).to_num::(); + let burn_rate_float: I64F64 = I64F64::from_num(burn_rate) / I64F64::from_num(n * 100); + let burn_emission_per_epoch: u64 = + (I64F64::from_num(epoch_emission) * burn_rate_float).to_num::(); - return burn_emission_per_epoch + burn_emission_per_epoch } pub fn set_registrations_this_block(registrations_this_block: u16) { @@ -815,10 +752,12 @@ impl Pallet { let mut updated_last_update_vec = Self::get_last_update(netuid); if (uid as usize) < updated_last_update_vec.len() { updated_last_update_vec[uid as usize] = last_update; - + let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.last_updates = BoundedVec::>::try_from(updated_last_update_vec).expect("too long vec"); + subnet_state.last_updates = + BoundedVec::>::try_from(updated_last_update_vec) + .expect("too long vec"); SubnetStateStorage::::insert(netuid, subnet_state); } @@ -826,34 +765,36 @@ impl Pallet { pub fn get_emission_for_key(netuid: u16, key: &T::AccountId) -> u64 { let uid = Self::get_uid_for_key(netuid, key); - return Self::get_emission_for_uid(netuid, uid) + Self::get_emission_for_uid(netuid, uid) } + pub fn get_emission_for_uid(netuid: u16, uid: u16) -> u64 { let emissions = Self::get_emissions(netuid); if (uid as usize) < emissions.len() { - return emissions[uid as usize] + emissions[uid as usize] } else { - return 0 + 0 } } + pub fn get_incentive_for_uid(netuid: u16, uid: u16) -> u16 { let incentives = Self::get_incentives(netuid); if (uid as usize) < incentives.len() { - return incentives[uid as usize] + incentives[uid as usize] } else { - return 0 + 0 } } - + pub fn get_dividends_for_uid(netuid: u16, uid: u16) -> u16 { let dividends = Self::get_dividends(netuid); if (uid as usize) < dividends.len() { - return dividends[uid as usize] + dividends[uid as usize] } else { - return 0 + 0 } } @@ -861,9 +802,9 @@ impl Pallet { let last_updates = Self::get_last_update(netuid); if (uid as usize) < last_updates.len() { - return last_updates[uid as usize] + last_updates[uid as usize] } else { - return 0 + 0 } } @@ -900,14 +841,12 @@ impl Pallet { return Self::get_current_block_as_u64() - Self::get_module_registration_block(netuid, uid) } - - pub fn get_immunity_period(netuid: u16) -> u16 { SubnetStateStorage::::get(netuid).immunity_period } + pub fn set_immunity_period(netuid: u16, immunity_period: u16) { let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.immunity_period = immunity_period; SubnetStateStorage::::insert(netuid, subnet_state) @@ -917,10 +856,10 @@ impl Pallet { let min_allowed_weights = SubnetStateStorage::::get(netuid).min_allowed_weights; let n = Self::get_subnet_n(netuid); // if n < min_allowed_weights, then return n - if (n < min_allowed_weights) { - return n + if n < min_allowed_weights { + n } else { - return min_allowed_weights + min_allowed_weights } } pub fn set_min_allowed_weights(netuid: u16, min_allowed_weights: u16) { @@ -935,14 +874,16 @@ impl Pallet { let max_allowed_weights = SubnetStateStorage::::get(netuid).max_allowed_weights; let n = Self::get_subnet_n(netuid); // if n < min_allowed_weights, then return n - return max_allowed_weights.min(n) + max_allowed_weights.min(n) } - pub fn set_max_allowed_weights(netuid: u16, mut max_allowed_weights: u16) { + + pub fn set_max_allowed_weights(netuid: u16, max_allowed_weights: u16) { let global_params = Self::global_params(); let mut subnet_state = SubnetStateStorage::::get(netuid); - subnet_state.max_allowed_weights = max_allowed_weights.min(global_params.max_allowed_weights); + subnet_state.max_allowed_weights = + max_allowed_weights.min(global_params.max_allowed_weights); SubnetStateStorage::::insert(netuid, subnet_state) } @@ -960,7 +901,7 @@ impl Pallet { for subnet_state in SubnetStateStorage::::iter_values() { total_n += subnet_state.n; } - return total_n + total_n } pub fn enough_space_for_n(n: u16) -> bool { @@ -979,100 +920,67 @@ impl Pallet { pub fn get_uids(netuid: u16) -> Vec { let n = Self::get_subnet_n(netuid); - return (0..n).collect() + (0..n).collect() } pub fn get_keys(netuid: u16) -> Vec { let uids: Vec = Self::get_uids(netuid); - let keys: Vec = - uids.iter().map(|uid| Self::get_key_for_uid(netuid, *uid)).collect(); - return keys + uids.iter().map(|uid| Self::get_key_for_uid(netuid, *uid)).collect() } pub fn get_uid_key_tuples(netuid: u16) -> Vec<(u16, T::AccountId)> { let n = Self::get_subnet_n(netuid); let mut uid_key_tuples = Vec::<(u16, T::AccountId)>::new(); - for uid in 0..n{ + for uid in 0..n { let key = Self::get_key_for_uid(netuid, uid); uid_key_tuples.push((uid, key)); } - return uid_key_tuples + uid_key_tuples } pub fn get_names(netuid: u16) -> Vec> { - let mut names = Vec::>::new(); - for (uid, name) in - as IterableStorageDoubleMap>>::iter_prefix(netuid) - { - names.push(name); - } - return names + as IterableStorageDoubleMap>>::iter_prefix(netuid) + .map(|(_, name)| name) + .collect() } pub fn get_addresses(netuid: u16) -> Vec { - let mut addresses = Vec::::new(); - for (key, uid) in - as IterableStorageDoubleMap>::iter_prefix(netuid) - { - addresses.push(key); - } - return addresses + as IterableStorageDoubleMap>::iter_prefix(netuid) + .map(|(key, _)| key) + .collect() } pub fn is_subnet_removed(netuid: u16) -> bool { - return Self::check_subnet_storage(netuid) + Self::check_subnet_storage(netuid) } - pub fn check_subnet_storage(netuid: u16) -> bool { - let n = Self::get_subnet_n(netuid); - let mut uids = Self::get_uids(netuid); - let mut keys = Self::get_keys(netuid); - let mut names = Self::get_names(netuid); - let mut addresses = Self::get_addresses(netuid); - let mut emissions = Self::get_emissions(netuid); - let mut incentives = Self::get_incentives(netuid); - let mut dividends = Self::get_dividends(netuid); - let mut last_update = Self::get_last_update(netuid); - - - if (n as usize) != uids.len() { - return false - } - if (n as usize) != keys.len() { - return false - } - if (n as usize) != names.len() { - return false - } - if (n as usize) != addresses.len() { - return false - } - if (n as usize) != emissions.len() { - return false - } - if (n as usize) != incentives.len() { - return false - } - if (n as usize) != dividends.len() { - return false - } - if (n as usize) != last_update.len() { - return false + let n = Self::get_subnet_n(netuid) as usize; + + if n != Self::get_uids(netuid).len() || + n != Self::get_keys(netuid).len() || + n != Self::get_names(netuid).len() || + n != Self::get_addresses(netuid).len() || + n != Self::get_emissions(netuid).len() || + n != Self::get_incentives(netuid).len() || + n != Self::get_dividends(netuid).len() || + n != Self::get_last_update(netuid).len() + { + return false; } // length of addresss let name_vector = Self::name_vector(netuid); - if (n as usize) != name_vector.len() { - return false + if n != name_vector.len() { + return false; } // length of addresss let address_vector = Self::address_vector(netuid); - if (n as usize) != address_vector.len() { - return false + if n != address_vector.len() { + return false; } - - return true + + true } pub fn get_emissions(netuid: u16) -> Vec { @@ -1106,7 +1014,6 @@ impl Pallet { return Keys::::contains_key(netuid, uid) } - pub fn get_max_weight_age(netuid: u16) -> u64 { SubnetStateStorage::::get(netuid).max_weight_age } diff --git a/pallets/subspace/src/utils.rs b/pallets/subspace/src/utils.rs deleted file mode 100644 index 72e4e67db..000000000 --- a/pallets/subspace/src/utils.rs +++ /dev/null @@ -1,30 +0,0 @@ -use substrate_fixed::{ - transcendental::exp, - types::{I32F32, I64F64}, -}; -use sp_std::{vec, vec::Vec}; - -#[allow(dead_code)] -fn string2vec(s: &str) -> Vec { - let mut v: Vec = Vec::new(); - for c in s.chars() { - v.push(c as u8); - } - return v; -} -#[allow(dead_code)] -pub fn is_string_equal(s1: &str, s2: &str) -> bool { - let v1: Vec = string2vec(s1); - let v2: Vec = string2vec(s2); - return v1 == v2; -} -#[allow(dead_code)] -pub fn is_string_vec(s1: &str, v2: Vec) -> bool { - let v1: Vec = string2vec(s1); - return v1 == v2.clone(); -} -#[allow(dead_code)] -pub fn is_vec_str(v1: Vec, s2: &str) -> bool { - let v2: Vec = string2vec(s2); - return v1 == v2.clone(); -} diff --git a/pallets/subspace/src/voting.rs b/pallets/subspace/src/voting.rs index 34f9825e7..8ce0ae3dc 100644 --- a/pallets/subspace/src/voting.rs +++ b/pallets/subspace/src/voting.rs @@ -1,409 +1,335 @@ -use core::ops::Add; - -use frame_support::pallet_prelude::DispatchResult; -use scale_info::prelude::string::String; use super::*; -use crate::utils::is_vec_str; +use frame_support::pallet_prelude::DispatchResult; impl Pallet { + pub fn do_unregister_voter(origin: T::RuntimeOrigin) -> DispatchResult { + let key = ensure_signed(origin)?; - pub fn do_unregister_voter( - origin: T::RuntimeOrigin, - ) -> DispatchResult { - let key = ensure_signed(origin)?; - - ensure!(Self::is_voter_registered(&key), Error::::VoterIsNotRegistered); - - Self::unregister_voter(&key); - - ensure!(!Self::is_voter_registered(&key), Error::::VoterIsRegistered); - - Ok(()) - } - - pub fn do_add_proposal( - origin: T::RuntimeOrigin, - mut proposal:Proposal, - ) -> DispatchResult { - let key = ensure_signed(origin)?; - // get the voting power of the proposal owner - if Self::is_voter_registered(&key.clone()) { - // unregister voter if they are already registered - Self::unregister_voter(&key.clone()); - } - - let proposal_id = Self::next_proposal_id(); - let voting_power = Self::get_voting_power(&key, proposal.clone()); - let mut voter_info = Voter2Info::::get(key.clone()); - - voter_info.proposal_id = proposal_id; - voter_info.participant_index = proposal.participants.len() as u16; - voter_info.votes = voting_power; - // register the voter to avoid double voting - proposal.participants.push(key.clone()); - proposal.votes = proposal.votes.saturating_add(voting_power); - - Self::check_proposal(proposal.clone())?; // check if proposal is valid - - // update the proposal - Voter2Info::::insert(key, voter_info); - Proposals::::insert(proposal_id, proposal); - - Self::check_proposal_approval(proposal_id); - Ok(()) - } - - - // GLOBAL LAND - - pub fn do_add_global_proposal( - origin: T::RuntimeOrigin, - // params - params: GlobalParams, - ) -> DispatchResult { - let mut proposal = Self::default_proposal(); - proposal.global_params = params; - proposal.mode = "global".as_bytes().to_vec(); - Self::do_add_proposal(origin, proposal)?; - Ok(()) - } - - // CUSTOM LAND - - pub fn do_add_custom_proposal( - origin: T::RuntimeOrigin, - // params - data: Vec, - ) -> DispatchResult { - let mut proposal = Self::default_proposal(); - proposal.data = data; - proposal.mode = "custom".as_bytes().to_vec(); - - Self::do_add_proposal(origin, proposal)?; - Ok(()) - } - - // SUBNET LAND - - pub fn do_add_subnet_proposal( - origin: T::RuntimeOrigin, - // params - netuid: u16, - params: SubnetParams, - ) -> DispatchResult { - let mut proposal = Self::default_proposal(); - - proposal.subnet_params = params; - proposal.netuid = netuid; - proposal.mode = "subnet".as_bytes().to_vec(); - - Self::do_add_proposal(origin, proposal)?; - - Ok(()) - } - - - pub fn num_subnet_proposals( - netuid: u16 - ) -> u64 { - let subnet_proposals = Self::get_subnet_proposals(netuid); - return subnet_proposals.len() as u64; - } - - - pub fn is_proposal_participant( - key: &T::AccountId, - proposal_id: u64, - ) -> bool { - let proposal: Proposal = Proposals::::get(proposal_id); - return proposal.participants.contains(key); - } - - - pub fn do_vote_proposal( - origin: T::RuntimeOrigin, - proposal_id: u64 - ) -> DispatchResult { - let key = ensure_signed(origin)?; - - ensure!(Self::proposal_exists(proposal_id), Error::::ProposalDoesNotExist); - - // if you vote the proposal on a subnet, you are no longer a participant - - if Self::is_voter_registered(&key.clone()) { - // unregister voter - Self::unregister_voter(&key.clone()); - } - - let mut proposal = Proposals::::get(proposal_id); - - - let mut voting_power : u64 = Self::get_voting_power(&key, proposal.clone()); - ensure!(voting_power > 0, Error::::VotingPowerIsZero); - - // register the voter to avoid double voting - - - let mut voter_info = Voter2Info::::get(key.clone()); - voter_info.proposal_id = proposal_id; - voter_info.participant_index = proposal.participants.len() as u16; - voter_info.votes = voting_power; - - // register the voter to avoid double voting - proposal.participants.push(key.clone()); - proposal.votes = proposal.votes.saturating_add(voting_power); - - // update the proposal - Voter2Info::::insert(key.clone(), voter_info); - Proposals::::insert(proposal_id, proposal); - - Self::check_proposal_approval(proposal_id); - - Ok(()) - } - pub fn num_proposals() -> u64 { - return Proposals::::iter().count() as u64; - } - - pub fn next_proposal_id() -> u64 { - let mut next_proposal_id: u64 = 0; - // add proposal id until it is not in the map - while Self::proposal_exists(next_proposal_id) { - next_proposal_id = next_proposal_id + 1; - } - return next_proposal_id; - } - - pub fn has_max_proposals() -> bool { - return Self::num_proposals() >= Self::get_max_proposals(); - } - - - pub fn check_proposal(proposal: Proposal) -> DispatchResult { - - // remove lowest voted proposal - if Self::has_max_proposals() { - let mut least_voted_proposal_id: u64 = u64::MAX; - let mut least_votes: u64 = u64::MAX; - - for (proposal_id, proposal) in Proposals::::iter() { - - // if proposal is accepted, remove it - if proposal.accepted || proposal.votes == 0{ - least_votes = 0; - least_voted_proposal_id = proposal_id; - break - } - - if proposal.votes < least_votes { - least_votes = proposal.votes; - least_voted_proposal_id = proposal_id; - } - } - - ensure!(proposal.votes > least_votes, Error::::TooFewVotesForNewProposal); - - // remove proposal participants - let proposal = Proposals::::get(least_voted_proposal_id); - // pop the participants - for participant in proposal.participants { - Voter2Info::::remove(participant); - } - Proposals::::remove(least_voted_proposal_id); - } - - let mode = proposal.mode.clone(); - - // check if proposal is valid - if is_vec_str(mode.clone(), "global") { - Self::check_global_params(proposal.global_params)?; - } else if is_vec_str(mode.clone(), "subnet") { - Self::check_subnet_params(proposal.subnet_params.clone())?; - // check if vote mode is valid - let subnet_params: SubnetParams = Self::subnet_params(proposal.netuid); - - ensure!( - is_vec_str(subnet_params.vote_mode.clone(),"stake") || - is_vec_str(subnet_params.vote_mode.clone(),"authority"), - Error::::InvalidVoteMode - ); - } else { - ensure!(proposal.data.len() > 0, Error::::InvalidProposalData); - } - // check if proposal is valid - ensure!(proposal.data.len() < 256, Error::::ProposalDataTooLarge); - // avoid an exploit with large data, cap it at 256 bytes - Ok(()) - } - - pub fn is_proposal_owner( - // check if the key is the owner of the proposal - key: &T::AccountId, - proposal_id: u64, - ) -> bool { - let proposal: Proposal = Proposals::::get(proposal_id); - if proposal.participants.len() == 0 { - return false; - } - return proposal.participants[0] == *key; - } - pub fn default_proposal() -> Proposal { - let mut proposal = Proposals::::get(u64::MAX); - return proposal; - } - - pub fn get_proposal( - proposal_id: u64, - ) -> Proposal { - return Proposals::::get(proposal_id); - } - - - pub fn unregister_voter(key: &T::AccountId) { - // unregister voter - - // get the proposal id for the voter - let voter_info = Self::get_voter_info(key); - // update the proposal votes - let mut proposal = Self::get_proposal(voter_info.proposal_id); - - // remove the voter from the participants - let index = voter_info.participant_index as usize; - proposal.participants.remove(index); - - // update the votes - proposal.votes = proposal.votes.saturating_sub(voter_info.votes); - - // remove proposal if there are no participants - if proposal.participants.len() == 0 || proposal.votes == 0 { - // remove proposal if there are no participants - Proposals::::remove(voter_info.proposal_id); - } else { - // update proposal - Proposals::::insert(voter_info.proposal_id, proposal); - } - - Voter2Info::::remove(key); - } - - - - pub fn is_voter_registered(key: &T::AccountId) -> bool { - // check if voter is registered - return Voter2Info::::contains_key(key); - } - - pub fn get_voter_info(key: &T::AccountId) -> VoterInfo{ - // get the proposal id for the voter - return Voter2Info::::get(key); - } - - - - pub fn get_voting_power( - key: &T::AccountId, - proposal: Proposal, - ) -> u64 { - let mut voting_power: u64 = 0; - if is_vec_str(proposal.mode.clone(),"subnet") { - // - voting_power = Self::get_total_stake_to(proposal.netuid, key); - } else { - // get all of the stake for the key - voting_power = Self::get_global_stake_to(key); - } - return voting_power; - } - - pub fn get_proposal_vote_threshold( - proposal_id: u64, - ) -> u64 { - let proposal: Proposal = Proposals::::get(proposal_id); - let mut vote_threshold: u64 = 0; - if is_vec_str(proposal.mode.clone(),"subnet") { - let total_stake = Self::get_total_subnet_stake(proposal.netuid); - vote_threshold = (total_stake * proposal.subnet_params.vote_threshold as u64) / 100; - } else { - let total_stake = Self::total_stake(); - vote_threshold = (total_stake * proposal.global_params.vote_threshold as u64) / 100; - } - return vote_threshold; - } - - - - pub fn check_proposal_approval(proposal_id: u64) { - - let proposal = Proposals::::get(proposal_id); - let mut stake_threshold: u64 = Self::get_proposal_vote_threshold(proposal_id); - if proposal.votes > stake_threshold { - // unregister all voters - - for participant in proposal.participants { - Voter2Info::::remove(participant); - } - Proposals::::mutate(proposal_id, |proposal| { - proposal.accepted = true; - proposal.participants = Vec::new(); - }); - - if is_vec_str(proposal.mode.clone(), "subnet") { - Self::set_subnet_params(proposal.netuid, proposal.subnet_params); - Self::deposit_event(Event::SubnetProposalAccepted(proposal_id, proposal.netuid)); - - } else if is_vec_str(proposal.mode.clone(), "global") { - Self::set_global_params(proposal.global_params); - Self::deposit_event(Event::GlobalProposalAccepted(proposal_id)); - } else { - Self::deposit_event(Event::CustomProposalAccepted(proposal_id)); - } - } - } - - - pub fn get_subnet_proposals( - netuid: u16 - ) -> Vec> { - let mut proposals: Vec> = Vec::new(); - for (proposal_id, proposal) in Proposals::::iter() { - if is_vec_str(proposal.mode.clone(), "subnet") && proposal.netuid == netuid { - proposals.push(proposal); - } - } - return proposals; - } - - pub fn get_global_proposals() -> Vec> { - let mut proposals: Vec> = Vec::new(); - for (proposal_id, proposal) in Proposals::::iter() { - if is_vec_str(proposal.mode.clone(), "global") { - proposals.push(proposal); - } - } - return proposals; - } - - - - pub fn num_global_proposals() -> u64 { - let global_proposals = Self::get_global_proposals(); - return global_proposals.len() as u64; - } - - - pub fn proposal_exists( - proposal_id: u64 - ) -> bool { - Proposals::::contains_key(proposal_id) - } - - pub fn is_vote_available( - key: &T::AccountId, - proposal_id: u64, - ) -> bool { - let proposal: Proposal = Proposals::::get(proposal_id); - let is_vote_available: bool = !proposal.participants.contains(key) && !proposal.accepted; - return is_vote_available; - } -} + ensure!(Self::is_voter_registered(&key), Error::::VoterIsNotRegistered); + + Self::unregister_voter(&key); + + ensure!(!Self::is_voter_registered(&key), Error::::VoterIsRegistered); + + Ok(()) + } + + pub fn do_add_proposal(origin: T::RuntimeOrigin, mut proposal: Proposal) -> DispatchResult { + let key = ensure_signed(origin)?; + // get the voting power of the proposal owner + if Self::is_voter_registered(&key.clone()) { + // unregister voter if they are already registered + Self::unregister_voter(&key.clone()); + } + let proposal_id = Self::next_proposal_id(); + let voting_power = Self::get_voting_power(&key, proposal.clone()); + let mut voter_info = Voter2Info::::get(key.clone()); + + voter_info.proposal_id = proposal_id; + voter_info.participant_index = proposal.participants.len() as u16; + voter_info.votes = voting_power; + // register the voter to avoid double voting + proposal.participants.push(key.clone()); + proposal.votes = proposal.votes.saturating_add(voting_power); + + Self::check_proposal(proposal.clone())?; // check if proposal is valid + + // update the proposal + Voter2Info::::insert(key, voter_info); + Proposals::::insert(proposal_id, proposal); + + Self::check_proposal_approval(proposal_id); + Ok(()) + } + + // GLOBAL LAND + + pub fn do_add_global_proposal( + origin: T::RuntimeOrigin, + // params + params: GlobalParams, + ) -> DispatchResult { + let mut proposal = Self::default_proposal(); + proposal.global_params = params; + proposal.mode = "global".as_bytes().to_vec(); + Self::do_add_proposal(origin, proposal)?; + Ok(()) + } + + // CUSTOM LAND + + pub fn do_add_custom_proposal( + origin: T::RuntimeOrigin, + // params + data: Vec, + ) -> DispatchResult { + let mut proposal = Self::default_proposal(); + proposal.data = data; + proposal.mode = "custom".as_bytes().to_vec(); + + Self::do_add_proposal(origin, proposal)?; + Ok(()) + } + + // SUBNET LAND + + pub fn do_add_subnet_proposal( + origin: T::RuntimeOrigin, + // params + netuid: u16, + params: SubnetParams, + ) -> DispatchResult { + let mut proposal = Self::default_proposal(); + + proposal.subnet_params = params; + proposal.netuid = netuid; + proposal.mode = "subnet".as_bytes().to_vec(); + + Self::do_add_proposal(origin, proposal)?; + + Ok(()) + } + + pub fn num_subnet_proposals(netuid: u16) -> u64 { + Self::get_subnet_proposals(netuid).len() as u64 + } + + pub fn is_proposal_participant(key: &T::AccountId, proposal_id: u64) -> bool { + Proposals::::get(proposal_id).participants.contains(key) + } + + pub fn do_vote_proposal(origin: T::RuntimeOrigin, proposal_id: u64) -> DispatchResult { + let key = ensure_signed(origin)?; + + ensure!(Self::proposal_exists(proposal_id), Error::::ProposalDoesNotExist); + + // if you vote the proposal on a subnet, you are no longer a participant + + if Self::is_voter_registered(&key.clone()) { + // unregister voter + Self::unregister_voter(&key.clone()); + } + + let mut proposal = Proposals::::get(proposal_id); + + let voting_power: u64 = Self::get_voting_power(&key, proposal.clone()); + ensure!(voting_power > 0, Error::::VotingPowerIsZero); + + // register the voter to avoid double voting + + let mut voter_info = Voter2Info::::get(key.clone()); + voter_info.proposal_id = proposal_id; + voter_info.participant_index = proposal.participants.len() as u16; + voter_info.votes = voting_power; + + // register the voter to avoid double voting + proposal.participants.push(key.clone()); + proposal.votes = proposal.votes.saturating_add(voting_power); + + // update the proposal + Voter2Info::::insert(key.clone(), voter_info); + Proposals::::insert(proposal_id, proposal); + + Self::check_proposal_approval(proposal_id); + + Ok(()) + } + pub fn num_proposals() -> u64 { + Proposals::::iter().count() as u64 + } + + pub fn next_proposal_id() -> u64 { + let mut next_proposal_id: u64 = 0; + // add proposal id until it is not in the map + while Self::proposal_exists(next_proposal_id) { + next_proposal_id = next_proposal_id + 1; + } + next_proposal_id + } + + pub fn has_max_proposals() -> bool { + Self::num_proposals() >= Self::get_max_proposals() + } + + pub fn check_proposal(proposal: Proposal) -> DispatchResult { + // remove lowest voted proposal + if Self::has_max_proposals() { + let mut least_voted_proposal_id: u64 = u64::MAX; + let mut least_votes: u64 = u64::MAX; + + for (proposal_id, proposal) in Proposals::::iter() { + // if proposal is accepted, remove it + if proposal.accepted || proposal.votes == 0 { + least_votes = 0; + least_voted_proposal_id = proposal_id; + break + } + + if proposal.votes < least_votes { + least_votes = proposal.votes; + least_voted_proposal_id = proposal_id; + } + } + + ensure!(proposal.votes > least_votes, Error::::TooFewVotesForNewProposal); + + // remove proposal participants + let proposal = Proposals::::get(least_voted_proposal_id); + // pop the participants + for participant in proposal.participants { + Voter2Info::::remove(participant); + } + Proposals::::remove(least_voted_proposal_id); + } + + let mode = proposal.mode.clone(); + + // check if proposal is valid + if mode == b"global" { + Self::check_global_params(proposal.global_params)?; + } else if mode == b"subnet" { + Self::check_subnet_params(proposal.subnet_params.clone())?; + // check if vote mode is valid + let subnet_params: SubnetParams = Self::subnet_params(proposal.netuid); + + ensure!( + subnet_params.vote_mode == b"stake" || subnet_params.vote_mode == b"authority", + Error::::InvalidVoteMode + ); + } else { + ensure!(proposal.data.len() > 0, Error::::InvalidProposalData); + } + // check if proposal is valid + ensure!(proposal.data.len() < 256, Error::::ProposalDataTooLarge); + // avoid an exploit with large data, cap it at 256 bytes + Ok(()) + } + + pub fn is_proposal_owner( + // check if the key is the owner of the proposal + key: &T::AccountId, + proposal_id: u64, + ) -> bool { + let proposal: Proposal = Proposals::::get(proposal_id); + !proposal.participants.is_empty() && proposal.participants[0] == *key + } + + pub fn default_proposal() -> Proposal { + Proposals::::get(u64::MAX) + } + + pub fn get_proposal(proposal_id: u64) -> Proposal { + return Proposals::::get(proposal_id); + } + + pub fn unregister_voter(key: &T::AccountId) { + // unregister voter + + // get the proposal id for the voter + let voter_info = Self::get_voter_info(key); + // update the proposal votes + let mut proposal = Self::get_proposal(voter_info.proposal_id); + + // remove the voter from the participants + let index = voter_info.participant_index as usize; + proposal.participants.remove(index); + + // update the votes + proposal.votes = proposal.votes.saturating_sub(voter_info.votes); + + // remove proposal if there are no participants + if proposal.participants.is_empty() || proposal.votes == 0 { + // remove proposal if there are no participants + Proposals::::remove(voter_info.proposal_id); + } else { + // update proposal + Proposals::::insert(voter_info.proposal_id, proposal); + } + + Voter2Info::::remove(key); + } + + pub fn is_voter_registered(key: &T::AccountId) -> bool { + // check if voter is registered + Voter2Info::::contains_key(key) + } + + pub fn get_voter_info(key: &T::AccountId) -> VoterInfo { + // get the proposal id for the voter + Voter2Info::::get(key) + } + + pub fn get_voting_power(key: &T::AccountId, proposal: Proposal) -> u64 { + if proposal.mode == b"subnet" { + Self::get_total_stake_to(proposal.netuid, key) + } else { + // get all of the stake for the key + Self::get_global_stake_to(key) + } + } + + pub fn get_proposal_vote_threshold(proposal_id: u64) -> u64 { + let proposal: Proposal = Proposals::::get(proposal_id); + if proposal.mode == b"subnet" { + let total_stake = Self::get_total_subnet_stake(proposal.netuid); + (total_stake * proposal.subnet_params.vote_threshold as u64) / 100 + } else { + let total_stake = Self::total_stake(); + (total_stake * proposal.global_params.vote_threshold as u64) / 100 + } + } + + pub fn check_proposal_approval(proposal_id: u64) { + let proposal = Proposals::::get(proposal_id); + let stake_threshold: u64 = Self::get_proposal_vote_threshold(proposal_id); + if proposal.votes > stake_threshold { + // unregister all voters + + for participant in proposal.participants { + Voter2Info::::remove(participant); + } + Proposals::::mutate(proposal_id, |proposal| { + proposal.accepted = true; + proposal.participants = Vec::new(); + }); + + if proposal.mode == b"subnet" { + Self::set_subnet_params(proposal.netuid, proposal.subnet_params); + Self::deposit_event(Event::SubnetProposalAccepted(proposal_id, proposal.netuid)); + } else if proposal.mode == b"global" { + Self::set_global_params(proposal.global_params); + Self::deposit_event(Event::GlobalProposalAccepted(proposal_id)); + } else { + Self::deposit_event(Event::CustomProposalAccepted(proposal_id)); + } + } + } + + pub fn get_subnet_proposals(netuid: u16) -> Vec> { + Proposals::::iter() + .filter(|(_, proposal)| proposal.mode == b"subnet" && proposal.netuid == netuid) + .map(|(_, proposal)| proposal) + .collect() + } + + pub fn get_global_proposals() -> Vec> { + Proposals::::iter() + .filter(|(_, proposal)| proposal.mode == b"global") + .map(|(_, proposal)| proposal) + .collect() + } + + pub fn num_global_proposals() -> u64 { + Self::get_global_proposals().len() as u64 + } + + pub fn proposal_exists(proposal_id: u64) -> bool { + Proposals::::contains_key(proposal_id) + } + + pub fn is_vote_available(key: &T::AccountId, proposal_id: u64) -> bool { + let proposal: Proposal = Proposals::::get(proposal_id); + proposal.participants.contains(key) && !proposal.accepted + } +} diff --git a/pallets/subspace/src/weights.rs b/pallets/subspace/src/weights.rs index b45456238..ca7017d6a 100644 --- a/pallets/subspace/src/weights.rs +++ b/pallets/subspace/src/weights.rs @@ -16,9 +16,9 @@ impl Pallet { // check if the stake per weight is greater than the stake let min_stake_per_weight: u64 = Self::get_min_weight_stake(); let min_stake_for_weights: u64 = min_stake_per_weight * uids.len() as u64; - + ensure!(stake >= min_stake_for_weights, Error::::NotEnoughStakePerWeight); - + ensure!(stake > 0, Error::::NotEnoughStaketoSetWeights); // --- 2. Check to see if this is a valid network. @@ -42,9 +42,9 @@ impl Pallet { let min_allowed_length: usize = Self::get_min_allowed_weights(netuid) as usize; let max_allowed_length: usize = Self::get_max_allowed_weights(netuid) as usize; - + let self_vote = Self::get_self_vote(netuid); - + if self_vote { ensure!(!Self::is_self_weight(uid, &uids, &values), Error::::NoSelfWeight); } @@ -82,10 +82,10 @@ impl Pallet { pub fn contains_invalid_uids(netuid: u16, uids: &Vec) -> bool { for uid in uids { if !Self::is_uid_exist_on_network(netuid, *uid) { - return true + return true; } } - return false + false } // Returns true if the passed uids have the same length of the passed values. @@ -96,13 +96,13 @@ impl Pallet { // Returns true if the items contain duplicates. fn has_duplicate_uids(items: &Vec) -> bool { let mut parsed: Vec = Vec::new(); - for item in items { + for &item in items { if parsed.contains(&item) { - return true + return true; } - parsed.push(item.clone()); + parsed.push(item); } - return false + false } // Returns True if the uids and weights are have a valid length for uid on network. @@ -111,55 +111,43 @@ impl Pallet { let n: usize = Self::get_subnet_n(netuid) as usize; // Check self weight. Allowed to set single value for self weight. if Self::is_self_weight(uid, uids, weights) { - return true + return true; } // Check if number of weights exceeds min. if weights.len() >= min_allowed_length { - return true + return true; } if weights.len() > n { - return true + return true; } - // To few weights. - return false + + // Too few weights. + false } // Implace normalizes the passed positive integer weights so that they sum to u16 max value. pub fn normalize_weights(mut weights: Vec) -> Vec { let sum: u64 = weights.iter().map(|x| *x as u64).sum(); - + if sum == 0 { - return weights + return weights; } weights.iter_mut().for_each(|x| { *x = (*x as u64 * u16::max_value() as u64 / sum) as u16; }); - return weights + weights } // Returns true if the uids and weights correspond to a self weight on the uid. - pub fn is_self_weight(uid: u16, uids: &Vec, weights: &Vec) -> bool { - if weights.len() != 1 { - return false - } - if uid != uids[0] { - return false - } - return true + pub fn is_self_weight(uid: u16, uids: &[u16], weights: &[u16]) -> bool { + weights.len() == 1 && uid == uids[0] } pub fn check_len_uids_within_allowed(netuid: u16, uids: &Vec) -> bool { - let min_allowed_length: usize = Self::get_min_allowed_weights(netuid) as usize; - let max_allowed_length: usize = Self::get_max_allowed_weights(netuid) as usize; - if uids.len() > max_allowed_length as usize { - return false - } - if uids.len() < min_allowed_length as usize { - return false - } - return true + uids.len() <= Self::get_max_allowed_weights(netuid) as usize && + uids.len() >= Self::get_min_allowed_weights(netuid) as usize } } diff --git a/pallets/subspace/tests/test_burn.rs b/pallets/subspace/tests/test_burn.rs index 5c43bb646..19b2c5c33 100644 --- a/pallets/subspace/tests/test_burn.rs +++ b/pallets/subspace/tests/test_burn.rs @@ -1,123 +1,117 @@ mod test_mock; -use frame_support::{ - assert_ok, - dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, -}; -use frame_system::Config; -use pallet_subspace::Error; +use frame_support::assert_ok; use sp_core::U256; -use test_mock::*; use sp_std::vec; +use test_mock::*; #[test] fn test_burn() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let n = 10; - - let initial_stake: u64 = 1000; - - let keys : Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); - let stakes : Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); + new_test_ext().execute_with(|| { + let netuid = 0; + let n = 10; - for i in 0..n { - assert_ok!(register_module(netuid, keys[i], stakes[i])); - let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); - println!("{:?}", stake_from_vector); - } + let initial_stake: u64 = 1000; - let voter_key = keys[1]; + let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); + let stakes: Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); - - // vote to avoid key[0] as we want to see the key[0] burn - let mut votes : Vec = vec![]; - let mut uids : Vec = vec![]; - for i in 0..n { - if i != 0 { - votes.push(1); - uids.push(i as u16); + for i in 0..n { + assert_ok!(register_module(netuid, keys[i], stakes[i])); + let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); + println!("{:?}", stake_from_vector); } - } - println!("{:?}", SubspaceModule::get_stake_for_key(netuid, &voter_key)); - assert_ok!(SubspaceModule::set_weights(get_origin(voter_key),netuid, uids, votes)); - let mut params = SubspaceModule::global_params(); - params.burn_rate = 100; - SubspaceModule::set_global_params(params); - params = SubspaceModule::global_params(); - println!("params: {:?}", params); - println!("burn : {:?}", SubspaceModule::get_burn_emission_per_epoch(netuid)); - let epochs = 10; - let mut previous_key_stake = SubspaceModule::get_total_stake_to(netuid,&keys[0]); - let dividends = SubspaceModule::get_dividends(netuid); - let incentives = SubspaceModule::get_incentives(netuid); - let emissions = SubspaceModule::get_emissions(netuid); - - println!("dividends: {:?} incentives: {:?} emissions: {:?}", - dividends, - incentives, - emissions); - - step_epoch(1); - - - let dividends = SubspaceModule::get_dividends(netuid); - let incentives = SubspaceModule::get_incentives(netuid); - let emissions = SubspaceModule::get_emissions(netuid); - - println!("dividends: {:?} incentives: {:?} emissions: {:?}", - dividends, - incentives, - emissions); - let key_stake = SubspaceModule::get_total_stake_to(netuid,&keys[0]); - println!("key_stake: {:?} prev_key_stake {:?}", key_stake, previous_key_stake); - assert!( previous_key_stake > key_stake , "key_stake: {:?} prev_key_stake {:?}", key_stake, previous_key_stake); - + let voter_key = keys[1]; + // vote to avoid key[0] as we want to see the key[0] burn + let mut votes: Vec = vec![]; + let mut uids: Vec = vec![]; + for i in 0..n { + if i != 0 { + votes.push(1); + uids.push(i as u16); + } + } + println!("{:?}", SubspaceModule::get_stake_for_key(netuid, &voter_key)); + assert_ok!(SubspaceModule::set_weights(get_origin(voter_key), netuid, uids, votes)); + let mut params = SubspaceModule::global_params(); + params.burn_rate = 100; + SubspaceModule::set_global_params(params); + params = SubspaceModule::global_params(); + println!("params: {:?}", params); + println!("burn : {:?}", SubspaceModule::get_burn_emission_per_epoch(netuid)); + let previous_key_stake = SubspaceModule::get_total_stake_to(netuid, &keys[0]); + let dividends = SubspaceModule::get_dividends(netuid); + let incentives = SubspaceModule::get_incentives(netuid); + let emissions = SubspaceModule::get_emissions(netuid); + + println!( + "dividends: {:?} incentives: {:?} emissions: {:?}", + dividends, incentives, emissions + ); + + step_epoch(1); + + let dividends = SubspaceModule::get_dividends(netuid); + let incentives = SubspaceModule::get_incentives(netuid); + let emissions = SubspaceModule::get_emissions(netuid); + + println!( + "dividends: {:?} incentives: {:?} emissions: {:?}", + dividends, incentives, emissions + ); + let key_stake = SubspaceModule::get_total_stake_to(netuid, &keys[0]); + println!("key_stake: {:?} prev_key_stake {:?}", key_stake, previous_key_stake); + assert!( + previous_key_stake > key_stake, + "key_stake: {:?} prev_key_stake {:?}", + key_stake, + previous_key_stake + ); }); } - #[test] fn test_min_burn() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let n = 10; - - let initial_stake: u64 = 1000; - - let keys : Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); - let stakes : Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); - - // founder register_module(netuid, keys[i]); - let founder_initial_stake = stakes[0]; - assert_ok!(register_module(netuid, keys[0], stakes[0])); - let founder_current_stake = SubspaceModule::get_total_stake_to(netuid,&keys[0]); - assert_eq!(founder_initial_stake, founder_current_stake, - "founder_initial_stake: {:?} founder_current_stake: {:?}", - founder_initial_stake, founder_current_stake); - - // set the burn min to 1000000000 - // register_module(netuid, keys[i]); - let mut params = SubspaceModule::global_params(); - params.min_burn = 100; - SubspaceModule::set_global_params(params.clone()); - params = SubspaceModule::global_params(); - for i in 1..n { - assert_ok!(register_module(netuid, keys[i], stakes[i])); - println!("params: {:?}", params); - - let key_stake_after = SubspaceModule::get_total_stake_to(netuid,&keys[i]); - assert_eq!(key_stake_after, stakes[i] - params.min_burn, - "key_stake_after: {:?} stakes[i]: {:?}", - key_stake_after, stakes[i]); - } - - - let voter_key = keys[1]; - + new_test_ext().execute_with(|| { + let netuid = 0; + let n = 10; + + let initial_stake: u64 = 1000; + + let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); + let stakes: Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); + + // founder register_module(netuid, keys[i]); + let founder_initial_stake = stakes[0]; + assert_ok!(register_module(netuid, keys[0], stakes[0])); + let founder_current_stake = SubspaceModule::get_total_stake_to(netuid, &keys[0]); + assert_eq!( + founder_initial_stake, founder_current_stake, + "founder_initial_stake: {:?} founder_current_stake: {:?}", + founder_initial_stake, founder_current_stake + ); + + // set the burn min to 1000000000 + // register_module(netuid, keys[i]); + let mut params = SubspaceModule::global_params(); + params.min_burn = 100; + SubspaceModule::set_global_params(params.clone()); + params = SubspaceModule::global_params(); + for i in 1..n { + assert_ok!(register_module(netuid, keys[i], stakes[i])); + println!("params: {:?}", params); + + let key_stake_after = SubspaceModule::get_total_stake_to(netuid, &keys[i]); + assert_eq!( + key_stake_after, + stakes[i] - params.min_burn, + "key_stake_after: {:?} stakes[i]: {:?}", + key_stake_after, + stakes[i] + ); + } + let voter_key = keys[1]; }); -} \ No newline at end of file +} diff --git a/pallets/subspace/tests/test_delegate_staking.rs b/pallets/subspace/tests/test_delegate_staking.rs index b5e66f29b..df6d02e07 100644 --- a/pallets/subspace/tests/test_delegate_staking.rs +++ b/pallets/subspace/tests/test_delegate_staking.rs @@ -37,7 +37,6 @@ use substrate_fixed::types::{I32F32, I64F64}; // }); // } - #[test] fn test_ownership_ratio() { new_test_ext().execute_with(|| { @@ -51,50 +50,84 @@ fn test_ownership_ratio() { let keys = SubspaceModule::get_keys(netuid); let voter_key = keys[0]; let miner_keys = keys[1..].to_vec(); - let miner_uids: Vec = miner_keys.iter().map(|k| SubspaceModule::get_uid_for_key(netuid, k)).collect(); + let miner_uids: Vec = + miner_keys.iter().map(|k| SubspaceModule::get_uid_for_key(netuid, k)).collect(); let miner_weights = vec![1; miner_uids.len()]; - - let delegate_keys: Vec = (0..num_modules).map(|i| U256::from(i + num_modules + 1)).collect(); for d in delegate_keys.iter() { add_balance(*d, stake_per_module + 1); } - let pre_delegate_stake_from_vector = SubspaceModule::get_stake_from_vector(netuid, &voter_key); + let pre_delegate_stake_from_vector = + SubspaceModule::get_stake_from_vector(netuid, &voter_key); assert_eq!(pre_delegate_stake_from_vector.len(), 1); // +1 for the module itself, +1 for the delegate key on for (i, d) in delegate_keys.iter().enumerate() { println!("DELEGATE KEY: {}", d); - assert_ok!(SubspaceModule::add_stake(get_origin(*d), netuid, voter_key, stake_per_module)); + assert_ok!(SubspaceModule::add_stake( + get_origin(*d), + netuid, + voter_key, + stake_per_module + )); let stake_from_vector = SubspaceModule::get_stake_from_vector(netuid, &voter_key); assert_eq!(stake_from_vector.len(), pre_delegate_stake_from_vector.len() + i + 1); } - let ownership_ratios: Vec<(U256, I64F64)> =SubspaceModule::get_ownership_ratios(netuid, &voter_key); + let ownership_ratios: Vec<(U256, I64F64)> = + SubspaceModule::get_ownership_ratios(netuid, &voter_key); assert_eq!(ownership_ratios.len(), delegate_keys.len() + 1); - let founder_tokens_before = SubspaceModule::get_balance(&voter_key) + SubspaceModule::get_stake_to_module(netuid, &voter_key, &voter_key); - - let delegate_balances_before = delegate_keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>(); - let delegate_stakes_before = delegate_keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)).collect::>(); - let delegate_total_tokens_before = delegate_balances_before.iter().zip(delegate_stakes_before.clone().into_iter()).map(|(a, x)| a + x).fold(0, |acc, x| acc + x); - - - let total_balance = keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_stake = keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_delegate_stake = delegate_keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_delegate_balance = delegate_keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_tokens_before = total_balance + total_stake + total_delegate_stake + total_delegate_balance; + let founder_tokens_before = SubspaceModule::get_balance(&voter_key) + + SubspaceModule::get_stake_to_module(netuid, &voter_key, &voter_key); + + let delegate_balances_before = delegate_keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>(); + let delegate_stakes_before = delegate_keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)) + .collect::>(); + let delegate_total_tokens_before = delegate_balances_before + .iter() + .zip(delegate_stakes_before.clone().into_iter()) + .map(|(a, x)| a + x) + .fold(0, |acc, x| acc + x); + + let total_balance = keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_stake = keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_delegate_stake = delegate_keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_delegate_balance = delegate_keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_tokens_before = + total_balance + total_stake + total_delegate_stake + total_delegate_balance; println!("total_tokens_before: {:?}", total_tokens_before); - println!("delegate_balances before: {:?}", delegate_balances_before); println!("delegate_stakes before: {:?}", delegate_stakes_before); println!("delegate_total_tokens before: {:?}", delegate_total_tokens_before); - - let result = SubspaceModule::set_weights( get_origin(voter_key), netuid, @@ -117,16 +150,31 @@ fn test_ownership_ratio() { println!("total_emissions: {:?}", total_emissions); - let delegate_balances = delegate_keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>(); - let delegate_stakes = delegate_keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)).collect::>(); - let delegate_total_tokens = delegate_balances.iter().zip(delegate_stakes.clone().into_iter()).map(|(a, x)| a + x).fold(0, |acc, x| acc + x); - let founder_tokens = SubspaceModule::get_balance(&voter_key) + SubspaceModule::get_stake_to_module(netuid, &voter_key, &voter_key); + let delegate_balances = delegate_keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>(); + let delegate_stakes = delegate_keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)) + .collect::>(); + let delegate_total_tokens = delegate_balances + .iter() + .zip(delegate_stakes.clone().into_iter()) + .map(|(a, x)| a + x) + .fold(0, |acc, x| acc + x); + let founder_tokens = SubspaceModule::get_balance(&voter_key) + + SubspaceModule::get_stake_to_module(netuid, &voter_key, &voter_key); let founder_new_tokens = founder_tokens - founder_tokens_before; - let delegate_new_tokens: Vec = delegate_stakes.iter().zip(delegate_stakes_before.clone().into_iter()).map(|(a, x)| a - x).collect::>(); + let delegate_new_tokens: Vec = delegate_stakes + .iter() + .zip(delegate_stakes_before.clone().into_iter()) + .map(|(a, x)| a - x) + .collect::>(); + let total_new_tokens = + founder_new_tokens + delegate_new_tokens.iter().fold(0, |acc, x| acc + x); - let total_new_tokens = founder_new_tokens + delegate_new_tokens.iter().fold(0, |acc, x| acc + x); - println!("owner_ratios: {:?}", ownership_ratios); println!("total_new_tokens: {:?}", total_new_tokens); println!("founder_tokens: {:?}", founder_tokens); @@ -136,21 +184,41 @@ fn test_ownership_ratio() { println!("founder_new_tokens: {:?}", founder_new_tokens); println!("delegate_new_tokens: {:?}", delegate_new_tokens); - let total_balance = keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_stake = keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_delegate_stake = delegate_keys.iter().map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_delegate_balance = delegate_keys.iter().map(|k| SubspaceModule::get_balance(k)).collect::>().iter().fold(0, |acc, x| acc + x); - let total_tokens_after = total_balance + total_stake + total_delegate_stake + total_delegate_balance; + let total_balance = keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_stake = keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_delegate_stake = delegate_keys + .iter() + .map(|k| SubspaceModule::get_stake_to_module(netuid, &k, &voter_key)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_delegate_balance = delegate_keys + .iter() + .map(|k| SubspaceModule::get_balance(k)) + .collect::>() + .iter() + .fold(0, |acc, x| acc + x); + let total_tokens_after = + total_balance + total_stake + total_delegate_stake + total_delegate_balance; let total_new_tokens = total_tokens_after - total_tokens_before; println!("total_tokens_after: {:?}", total_tokens_before); println!("total_new_tokens: {:?}", total_new_tokens); assert_eq!(total_new_tokens, total_emissions); - let stake_from_vector = SubspaceModule::get_stake_from_vector(netuid, &voter_key); let stake: u64 = SubspaceModule::get_stake(netuid, &voter_key); let sumed_stake: u64 = stake_from_vector.iter().fold(0, |acc, (a, x)| acc + x); let total_stake: u64 = SubspaceModule::get_total_subnet_stake(netuid); println!("stake_from_vector: {:?}", stake_from_vector); }); -} \ No newline at end of file +} diff --git a/pallets/subspace/tests/test_mock.rs b/pallets/subspace/tests/test_mock.rs index d3cb9bd4a..70b6ec226 100644 --- a/pallets/subspace/tests/test_mock.rs +++ b/pallets/subspace/tests/test_mock.rs @@ -72,9 +72,9 @@ impl pallet_balances::Config for Test { type WeightInfo = (); type MaxReserves = MaxReserves; type ReserveIdentifier = (); - type RuntimeHoldReason = (); - type FreezeIdentifier = (); - type MaxHolds = frame_support::traits::ConstU32<16>; + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxHolds = frame_support::traits::ConstU32<16>; type MaxFreezes = frame_support::traits::ConstU32<16>; } @@ -193,8 +193,7 @@ pub fn decrease_stake(netuid: u16, key: U256, stake: u64) { } pub fn get_origin(key: U256) -> RuntimeOrigin { - let origin = <::RuntimeOrigin>::signed(key); - return origin + <::RuntimeOrigin>::signed(key) } pub fn register_n_modules(netuid: u16, n: u16, stake: u64) { @@ -225,8 +224,7 @@ pub fn register_module(netuid: u16, key: U256, stake: u64) -> DispatchResult { add_balance(key, stake + 1); let balance = SubspaceModule::get_balance(&key); - let result = SubspaceModule::register(origin, network, name.clone(), address, stake, key); - return result + SubspaceModule::register(origin, network, name.clone(), address, stake, key) } #[allow(dead_code)] @@ -263,9 +261,6 @@ pub fn delegate_register_module( network, module_key, balance ); - let result = - SubspaceModule::register(origin, network, name.clone(), address, stake, module_key); - log::info!( "Register ok neuron: network: {:?}, module_key: {:?} key: {:?}", name.clone(), @@ -273,7 +268,7 @@ pub fn delegate_register_module( key ); - return result + SubspaceModule::register(origin, network, name.clone(), address, stake, module_key) } #[allow(dead_code)] diff --git a/pallets/subspace/tests/test_profit_share.rs b/pallets/subspace/tests/test_profit_share.rs index 6945498f3..39e3b6cf6 100644 --- a/pallets/subspace/tests/test_profit_share.rs +++ b/pallets/subspace/tests/test_profit_share.rs @@ -6,34 +6,36 @@ use frame_support::{ use frame_system::Config; use pallet_subspace::Error; use sp_core::U256; -use test_mock::*; use sp_std::vec; +use test_mock::*; /* TO DO SAM: write test for LatuUpdate after it is set */ #[test] fn test_add_profit_share() { - new_test_ext().execute_with(|| { - + new_test_ext().execute_with(|| { let netuid = 0; - let miner_key = U256::from(0); + let miner_key = U256::from(0); let voter_key = U256::from(1); - register_module(netuid, miner_key, 1_000_000_000); + register_module(netuid, miner_key, 1_000_000_000); register_module(netuid, voter_key, 1_000_000_000); - let miner_uid = SubspaceModule::get_uid_for_key(netuid,&miner_key); - let voter_uid = SubspaceModule::get_uid_for_key(netuid,&voter_key); + let miner_uid = SubspaceModule::get_uid_for_key(netuid, &miner_key); + let voter_uid = SubspaceModule::get_uid_for_key(netuid, &voter_key); - SubspaceModule::set_min_allowed_weights(netuid, 1); - let profit_sharer_keys = vec![U256::from(2), U256::from(3)]; - let shares = vec![2,2]; - let result = SubspaceModule::add_profit_shares(get_origin(miner_key), profit_sharer_keys.clone(), shares.clone()); + let shares = vec![2, 2]; + let result = SubspaceModule::add_profit_shares( + get_origin(miner_key), + profit_sharer_keys.clone(), + shares.clone(), + ); assert_ok!(result); let profit_shares = SubspaceModule::get_profit_shares(miner_key); - assert_eq!(profit_shares.len(), shares.len(), "profit shares not added"); + assert_eq!(profit_shares.len(), shares.len(), "profit shares not added"); println!("founder profit shares: {:?}", profit_shares); - let result = SubspaceModule::set_weights(get_origin(voter_key), netuid, vec![miner_uid], vec![1]); + let result = + SubspaceModule::set_weights(get_origin(voter_key), netuid, vec![miner_uid], vec![1]); assert_ok!(result); let params = SubspaceModule::subnet_params(netuid); @@ -41,8 +43,8 @@ fn test_add_profit_share() { let miner_emission = SubspaceModule::get_emission_for_key(netuid, &miner_key); let voter_emission = SubspaceModule::get_emission_for_key(netuid, &voter_key); assert_eq!(miner_emission, voter_emission, "emission not equal"); - assert!(miner_emission==0, "emission not equal"); - assert!(voter_emission==0, "emission not equal"); + assert!(miner_emission == 0, "emission not equal"); + assert!(voter_emission == 0, "emission not equal"); let miner_stake = SubspaceModule::get_stake_for_key(netuid, &miner_key); let voter_stake = SubspaceModule::get_stake_for_key(netuid, &voter_key); println!("miner stake before: {:?}", miner_stake); @@ -50,8 +52,8 @@ fn test_add_profit_share() { step_epoch(netuid); let miner_emission = SubspaceModule::get_emission_for_key(netuid, &miner_key); let voter_emission = SubspaceModule::get_emission_for_key(netuid, &voter_key); - assert!(miner_emission>0, "emission not equal"); - assert!(voter_emission>0, "emission not equal"); + assert!(miner_emission > 0, "emission not equal"); + assert!(voter_emission > 0, "emission not equal"); assert_eq!(miner_emission, voter_emission, "emission not equal"); println!("miner emission: {:?}", miner_emission); @@ -70,26 +72,24 @@ fn test_add_profit_share() { println!("profit share emissions: {:?}", profit_share_emissions); // check the profit sharers - let mut profit_share_balances : Vec = Vec::new(); + let mut profit_share_balances: Vec = Vec::new(); for profit_sharer_key in profit_sharer_keys.iter() { - - let profit_share_balance = SubspaceModule::get_stake_to_total(netuid, profit_sharer_key); + let profit_share_balance = + SubspaceModule::get_stake_to_total(netuid, profit_sharer_key); let stake_to_vector = SubspaceModule::get_stake_to_vector(netuid, profit_sharer_key); println!("profit share balance: {:?}", stake_to_vector); println!("profit share balance: {:?}", profit_share_balance); profit_share_balances.push(profit_share_balance); - assert!(profit_share_balances[0]>0, "profit share balance is zero"); + assert!(profit_share_balances[0] > 0, "profit share balance is zero"); } - // sum of profit shares should be equal to the emission - let sum_profit_share_balances : u64 = profit_share_balances.iter().sum(); + let sum_profit_share_balances: u64 = profit_share_balances.iter().sum(); let delta = 1000; - assert!(sum_profit_share_balances > miner_emission - delta || + assert!( + sum_profit_share_balances > miner_emission - delta || sum_profit_share_balances < miner_emission + delta, - "profit share balances do not add up to the emission"); - - - - }) -} \ No newline at end of file + "profit share balances do not add up to the emission" + ); + }) +} diff --git a/pallets/subspace/tests/test_registration.rs b/pallets/subspace/tests/test_registration.rs index fdb196f18..a33c196ed 100644 --- a/pallets/subspace/tests/test_registration.rs +++ b/pallets/subspace/tests/test_registration.rs @@ -1,10 +1,9 @@ use crate::test_mock::*; use frame_support::{ assert_ok, - dispatch::{DispatchInfo, GetDispatchInfo}, + dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, sp_runtime::DispatchError, traits::Currency, - dispatch::{DispatchClass, Pays}, }; use frame_system::Config; use ndarray::stack_new_axis; diff --git a/pallets/subspace/tests/test_staking.rs b/pallets/subspace/tests/test_staking.rs index feca99163..d50d401c1 100644 --- a/pallets/subspace/tests/test_staking.rs +++ b/pallets/subspace/tests/test_staking.rs @@ -266,8 +266,6 @@ fn test_delegate_stake() { }); } - - #[test] fn test_ownership_ratio() { new_test_ext().execute_with(|| { @@ -323,8 +321,6 @@ fn test_ownership_ratio() { }); } - - // #[test] fn test_min_stake() { new_test_ext().execute_with(|| { @@ -336,7 +332,7 @@ fn test_min_stake() { let keys = SubspaceModule::get_keys(netuid); // register_n_modules(netuid, num_modules, min_stake); - SubspaceModule::set_min_stake( netuid, min_stake - 100); + SubspaceModule::set_min_stake(netuid, min_stake - 100); // SubspaceModule::set_min_stake( netuid, min_stake - 100); @@ -358,10 +354,5 @@ fn test_min_stake() { step_block(1); let is_registered = SubspaceModule::is_registered(netuid, &keys[0]); assert_eq!(is_registered, false); - }); } - - - - diff --git a/pallets/subspace/tests/test_step.rs b/pallets/subspace/tests/test_step.rs index b3a8969e3..e3bd6cb66 100644 --- a/pallets/subspace/tests/test_step.rs +++ b/pallets/subspace/tests/test_step.rs @@ -10,8 +10,6 @@ use substrate_fixed::{ }; mod test_mock; - - fn check_network_stats(netuid: u16) { let emission_buffer: u64 = 1_000; // the numbers arent perfect but we want to make sure they fall within a range (10_000 / 2**64) @@ -84,12 +82,11 @@ fn test_dividends_same_stake() { // do a list of ones for weights let weight_uids: Vec = [2, 3].to_vec(); // do a list of ones for weights - let weight_values: Vec = [2,1].to_vec(); + let weight_values: Vec = [2, 1].to_vec(); set_weights(netuid, keys[0], weight_uids.clone(), weight_values.clone()); set_weights(netuid, keys[1], weight_uids.clone(), weight_values.clone()); - - let stakes_before : Vec = SubspaceModule::get_stakes(netuid); + let stakes_before: Vec = SubspaceModule::get_stakes(netuid); step_block(1); let incentives: Vec = SubspaceModule::get_incentives(netuid); let dividends: Vec = SubspaceModule::get_dividends(netuid); @@ -98,20 +95,30 @@ fn test_dividends_same_stake() { // evaluate votees assert!(incentives[2] > 0); - assert_eq!(dividends[2] , dividends[3]); - let delta : u64 = 100; - assert!((incentives[2] as u64) > (weight_values[0] as u64 * incentives[3] as u64) - delta); - assert!((incentives[2] as u64) < (weight_values[0] as u64 * incentives[3] as u64) + delta); + assert_eq!(dividends[2], dividends[3]); + let delta: u64 = 100; + assert!((incentives[2] as u64) > (weight_values[0] as u64 * incentives[3] as u64) - delta); + assert!((incentives[2] as u64) < (weight_values[0] as u64 * incentives[3] as u64) + delta); - assert!((emissions[2] as u64) > (weight_values[0] as u64 * emissions[3] as u64) - delta); - assert!((emissions[2] as u64) < (weight_values[0] as u64 * emissions[3] as u64) + delta); + assert!((emissions[2] as u64) > (weight_values[0] as u64 * emissions[3] as u64) - delta); + assert!((emissions[2] as u64) < (weight_values[0] as u64 * emissions[3] as u64) + delta); // evaluate voters - assert!(dividends[0] == dividends[1] , "dividends[0]: {} != dividends[1]: {}", dividends[0], dividends[1]); - assert!(dividends[0] == dividends[1] , "dividends[0]: {} != dividends[1]: {}", dividends[0], dividends[1]); - - assert_eq!(incentives[0],incentives[1]); - assert_eq!(dividends[2],dividends[3]); + assert!( + dividends[0] == dividends[1], + "dividends[0]: {} != dividends[1]: {}", + dividends[0], + dividends[1] + ); + assert!( + dividends[0] == dividends[1], + "dividends[0]: {} != dividends[1]: {}", + dividends[0], + dividends[1] + ); + + assert_eq!(incentives[0], incentives[1]); + assert_eq!(dividends[2], dividends[3]); println!("emissions: {:?}", emissions); @@ -147,7 +154,7 @@ fn test_dividends_diff_stake() { let n_list: Vec = vec![10, 50, 100, 1000]; let blocks_per_epoch_list: u64 = 1; let stake_per_module: u64 = 10_000; - let tempo : u16 = 10; + let tempo: u16 = 10; // SETUP NETWORK for i in 0..n { @@ -171,16 +178,15 @@ fn test_dividends_diff_stake() { // } let keys = SubspaceModule::get_keys(netuid); let uids = SubspaceModule::get_uids(netuid); - + // do a list of ones for weights let weight_uids: Vec = [2, 3].to_vec(); // do a list of ones for weights - let weight_values: Vec = [1,1].to_vec(); + let weight_values: Vec = [1, 1].to_vec(); set_weights(netuid, keys[0], weight_uids.clone(), weight_values.clone()); set_weights(netuid, keys[1], weight_uids.clone(), weight_values.clone()); - - let stakes_before : Vec = SubspaceModule::get_stakes(netuid); + let stakes_before: Vec = SubspaceModule::get_stakes(netuid); step_epoch(netuid); let incentives: Vec = SubspaceModule::get_incentives(netuid); let dividends: Vec = SubspaceModule::get_dividends(netuid); @@ -189,21 +195,21 @@ fn test_dividends_diff_stake() { // evaluate votees assert!(incentives[2] > 0); - assert_eq!(dividends[2] , dividends[3]); - let delta : u64 = 100; - assert!((incentives[2] as u64) > (weight_values[0] as u64 * incentives[3] as u64) - delta); - assert!((incentives[2] as u64) < (weight_values[0] as u64 * incentives[3] as u64) + delta); + assert_eq!(dividends[2], dividends[3]); + let delta: u64 = 100; + assert!((incentives[2] as u64) > (weight_values[0] as u64 * incentives[3] as u64) - delta); + assert!((incentives[2] as u64) < (weight_values[0] as u64 * incentives[3] as u64) + delta); - assert!((emissions[2] as u64) > (weight_values[0] as u64 * emissions[3] as u64) - delta); - assert!((emissions[2] as u64) < (weight_values[0] as u64 * emissions[3] as u64) + delta); + assert!((emissions[2] as u64) > (weight_values[0] as u64 * emissions[3] as u64) - delta); + assert!((emissions[2] as u64) < (weight_values[0] as u64 * emissions[3] as u64) + delta); // evaluate voters - let delta : u64 = 100; + let delta: u64 = 100; assert!((dividends[0] as u64) > (dividends[1] as u64 * 2) - delta); - assert!((dividends[0] as u64) < (dividends[1] as u64 * 2) + delta ); + assert!((dividends[0] as u64) < (dividends[1] as u64 * 2) + delta); - assert_eq!(incentives[0],incentives[1]); - assert_eq!(dividends[2],dividends[3]); + assert_eq!(incentives[0], incentives[1]); + assert_eq!(dividends[2], dividends[3]); println!("emissions: {:?}", emissions); @@ -230,7 +236,6 @@ fn test_dividends_diff_stake() { }); } - fn test_pruning() { new_test_ext().execute_with(|| { // CONSSTANTS @@ -480,8 +485,6 @@ fn test_blocks_until_epoch() { }); } - - #[test] fn test_incentives() { new_test_ext().execute_with(|| { @@ -499,7 +502,6 @@ fn test_incentives() { params.max_allowed_weights = n; params.tempo = 1; - let keys = SubspaceModule::get_keys(netuid); let uids = SubspaceModule::get_uids(netuid); @@ -519,7 +521,6 @@ fn test_incentives() { assert!(incentives[1] == incentives[2]); assert!(emissions[1] == emissions[2]); - // do a list of ones for weights let weight_values: Vec = [1, 2].to_vec(); @@ -532,19 +533,18 @@ fn test_incentives() { let emissions: Vec = SubspaceModule::get_emissions(netuid); // evaluate votees - let delta : u64 = 100; + let delta: u64 = 100; assert!(incentives[1] > 0); - assert!(emissions[2] > 2 * emissions[1] - delta && - emissions[2] < 2 * emissions[1] + delta , - "emissions[1]: {} != emissions[2]: {}", emissions[1], emissions[2]); - - - + assert!( + emissions[2] > 2 * emissions[1] - delta && emissions[2] < 2 * emissions[1] + delta, + "emissions[1]: {} != emissions[2]: {}", + emissions[1], + emissions[2] + ); }); } - #[test] fn test_trust() { new_test_ext().execute_with(|| { @@ -566,7 +566,6 @@ fn test_trust() { SubspaceModule::set_subnet_params(netuid, params.clone()); - let keys = SubspaceModule::get_keys(netuid); let uids = SubspaceModule::get_uids(netuid); @@ -582,27 +581,21 @@ fn test_trust() { step_block(1); let trust: Vec = SubspaceModule::get_trust(netuid); - let emission : Vec = SubspaceModule::get_emissions(netuid); - + let emission: Vec = SubspaceModule::get_emissions(netuid); // evaluate votees println!("trust: {:?}", trust); assert!(trust[1] as u32 > 0); - assert!(trust[2] as u32 > 2*(trust[1] as u32) - 10 ); + assert!(trust[2] as u32 > 2 * (trust[1] as u32) - 10); // evaluate votees println!("trust: {:?}", emission); - assert!(emission[1] > 0); - assert!(emission[2] > 2*(emission[1] ) - 1000 ); + assert!(emission[1] > 0); + assert!(emission[2] > 2 * (emission[1]) - 1000); // assert!(trust[2] as u32 < 2*(trust[1] as u32) ); - - }); } - - - // TODO: // #[test] // fn simulation_final_boss() { @@ -834,152 +827,137 @@ fn test_trust() { #[test] fn test_pending_deregistration() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let n = 20; - let initial_stake: u64 = 1000; - let keys : Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); - let stakes : Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); - - - for i in 0..n { - assert_ok!(register_module(netuid, keys[i], stakes[i])); - let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); - println!("{:?}", stake_from_vector); - } - // now we set the p. rams - let mut params = SubspaceModule::global_params(); - params.burn_rate = 100; - SubspaceModule::set_global_params(params.clone()); - let mut params = SubspaceModule::subnet_params(netuid); - params.min_stake = stakes[0]; - params.tempo = 10; - SubspaceModule::set_subnet_params(netuid, params.clone()); - - let subnet_emission = SubspaceModule::get_subnet_emission(netuid); - println!("subnet_emission: {:?}", subnet_emission); - - - let voter_key = keys[1]; - - - // vote to avoid key[0] as we want to see the key[0] burn - let mut votes : Vec = vec![]; - let mut uids : Vec = vec![]; - for i in 0..n { - if i != 0 { - votes.push(1); - uids.push(i as u16); - } - } - println!("{:?}", SubspaceModule::get_stake_for_key(netuid, &voter_key)); - assert_ok!(SubspaceModule::set_weights(get_origin(voter_key),netuid, uids, votes)); - - let stakes = SubspaceModule::get_stakes(netuid); - let total_stake_before = stakes.iter().sum::(); - println!("total_stake_before: {:?}", total_stake_before); - step_block(params.tempo); - - let params = SubspaceModule::subnet_params(netuid); - println!("params: {:?}", params); - - let emissions = SubspaceModule::get_emissions(netuid); - let total_emissions = emissions.iter().sum::(); - println!("total_emissions: {:?}", total_emissions); - println!("emissions: {:?}", emissions); - let stakes = SubspaceModule::get_stakes(netuid); - let total_stake_after = stakes.iter().sum::(); - println!("total_stake_after: {:?}", total_stake_after); - println!("staking: {:?}", stakes); - let key_stake = SubspaceModule::get_total_stake_to(netuid,&keys[1]); - let params = SubspaceModule::subnet_params(netuid); - let pending_deregister_uids = SubspaceModule::get_pending_deregister_uids(netuid); - let staking = SubspaceModule::get_stakes(netuid); - - println!("key_stake: {:?}", SubspaceModule::get_min_stake(netuid)); - println!("pending_deregister_uids: {:?}", pending_deregister_uids); - assert!(!pending_deregister_uids.contains(&1)); - assert!( key_stake > params.min_stake , "key_stake: {:?} params.min_stake {:?}", key_stake, params.min_stake); - - - }); -} - - + new_test_ext().execute_with(|| { + let netuid = 0; + let n = 20; + let initial_stake: u64 = 1000; + let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); + let stakes: Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); -#[test] -fn test_founder_share() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let n = 20; - let initial_stake: u64 = 1000; - let keys : Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); - let stakes : Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); - - - let founder_key = keys[0]; - for i in 0..n { - assert_ok!(register_module(netuid, keys[i], stakes[i])); - let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); - println!("{:?}", stake_from_vector); - } - SubspaceModule::set_founder_share(netuid, 50); - let founder_share = SubspaceModule::get_founder_share(netuid); - let founder_ratio: f64 = founder_share as f64 / 100.0; - - - let founder_stake_before = SubspaceModule::get_stake_for_key(netuid, &founder_key); - println!("founder_stake_before: {:?}", founder_stake_before); - // vote to avoid key[0] as we want to see the key[0] burn - step_epoch(netuid); - let total_emission = SubspaceModule::get_subnet_emission(netuid); - let expected_founder_share = (total_emission as f64 * founder_ratio) as u64; - let expected_emission = total_emission; - let emissions = SubspaceModule::get_emissions(netuid); - let dividends = SubspaceModule::get_dividends(netuid); - let incentives = SubspaceModule::get_incentives(netuid); - let total_dividends: u64 = dividends.iter().sum::() as u64; - let total_incentives : u64 = incentives.iter().sum::() as u64; - - println!("total_dividends: {:?}", total_dividends); - println!("total_incentives: {:?}", total_incentives); - let expected_emission_after_founder_share = expected_emission - expected_founder_share; - let founder_dividend_emission = ((dividends[0] as f64 / total_dividends as f64) * (expected_emission_after_founder_share/2) as f64) as u64; - let founder_incentive_emission = ((incentives[0] as f64 / total_incentives as f64) * (expected_emission_after_founder_share/2) as f64) as u64; - let founder_emission = founder_incentive_emission + founder_dividend_emission; - - println!("emissions: {:?}", emissions); - println!("dividends: {:?}", dividends); - println!("incentives: {:?}", incentives); - println!("founder_emission FAM: {:?}", founder_emission); - let calcualted_total_emission = emissions.iter().sum::(); + for i in 0..n { + assert_ok!(register_module(netuid, keys[i], stakes[i])); + let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); + println!("{:?}", stake_from_vector); + } + // now we set the p. rams + let mut params = SubspaceModule::global_params(); + params.burn_rate = 100; + SubspaceModule::set_global_params(params.clone()); + let mut params = SubspaceModule::subnet_params(netuid); + params.min_stake = stakes[0]; + params.tempo = 10; + SubspaceModule::set_subnet_params(netuid, params.clone()); + let subnet_emission = SubspaceModule::get_subnet_emission(netuid); + println!("subnet_emission: {:?}", subnet_emission); - let calculated_founder_share = SubspaceModule::get_stake_for_key(netuid, &founder_key) - founder_stake_before - founder_emission; - let delta: u64 = 1000; + let voter_key = keys[1]; - - println!("expected_emission: {:?}", expected_emission); - println!("total_emission: {:?}", total_emission); - assert!(expected_emission > calcualted_total_emission - delta ); - assert!(expected_emission < calcualted_total_emission + delta ); + // vote to avoid key[0] as we want to see the key[0] burn + let mut votes: Vec = vec![]; + let mut uids: Vec = vec![]; + for i in 0..n { + if i != 0 { + votes.push(1); + uids.push(i as u16); + } + } + println!("{:?}", SubspaceModule::get_stake_for_key(netuid, &voter_key)); + assert_ok!(SubspaceModule::set_weights(get_origin(voter_key), netuid, uids, votes)); - println!("calculated_founder_share: {:?}", calculated_founder_share); - println!("expected_founder_share: {:?}", expected_founder_share); - assert!(expected_founder_share > calculated_founder_share - delta ); - assert!(expected_founder_share < calculated_founder_share + delta ); + let stakes = SubspaceModule::get_stakes(netuid); + let total_stake_before = stakes.iter().sum::(); + println!("total_stake_before: {:?}", total_stake_before); + step_block(params.tempo); + let params = SubspaceModule::subnet_params(netuid); + println!("params: {:?}", params); + let emissions = SubspaceModule::get_emissions(netuid); + let total_emissions = emissions.iter().sum::(); + println!("total_emissions: {:?}", total_emissions); + println!("emissions: {:?}", emissions); + let stakes = SubspaceModule::get_stakes(netuid); + let total_stake_after = stakes.iter().sum::(); + println!("total_stake_after: {:?}", total_stake_after); + println!("staking: {:?}", stakes); + let key_stake = SubspaceModule::get_total_stake_to(netuid, &keys[1]); + let params = SubspaceModule::subnet_params(netuid); + let pending_deregister_uids = SubspaceModule::get_pending_deregister_uids(netuid); + let staking = SubspaceModule::get_stakes(netuid); + + println!("key_stake: {:?}", SubspaceModule::get_min_stake(netuid)); + println!("pending_deregister_uids: {:?}", pending_deregister_uids); + assert!(!pending_deregister_uids.contains(&1)); + assert!( + key_stake > params.min_stake, + "key_stake: {:?} params.min_stake {:?}", + key_stake, + params.min_stake + ); }); - - } +#[test] +fn test_founder_share() { + new_test_ext().execute_with(|| { + let netuid = 0; + let n = 20; + let initial_stake: u64 = 1000; + let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); + let stakes: Vec = (0..n).into_iter().map(|x| initial_stake * 1_000_000_000).collect(); + let founder_key = keys[0]; + for i in 0..n { + assert_ok!(register_module(netuid, keys[i], stakes[i])); + let stake_from_vector = SubspaceModule::get_stake_to_vector(netuid, &keys[i]); + println!("{:?}", stake_from_vector); + } + SubspaceModule::set_founder_share(netuid, 50); + let founder_share = SubspaceModule::get_founder_share(netuid); + let founder_ratio: f64 = founder_share as f64 / 100.0; + let founder_stake_before = SubspaceModule::get_stake_for_key(netuid, &founder_key); + println!("founder_stake_before: {:?}", founder_stake_before); + // vote to avoid key[0] as we want to see the key[0] burn + step_epoch(netuid); + let total_emission = SubspaceModule::get_subnet_emission(netuid); + let expected_founder_share = (total_emission as f64 * founder_ratio) as u64; + let expected_emission = total_emission; + let emissions = SubspaceModule::get_emissions(netuid); + let dividends = SubspaceModule::get_dividends(netuid); + let incentives = SubspaceModule::get_incentives(netuid); + let total_dividends: u64 = dividends.iter().sum::() as u64; + let total_incentives: u64 = incentives.iter().sum::() as u64; + + println!("total_dividends: {:?}", total_dividends); + println!("total_incentives: {:?}", total_incentives); + let expected_emission_after_founder_share = expected_emission - expected_founder_share; + let founder_dividend_emission = ((dividends[0] as f64 / total_dividends as f64) * + (expected_emission_after_founder_share / 2) as f64) as u64; + let founder_incentive_emission = ((incentives[0] as f64 / total_incentives as f64) * + (expected_emission_after_founder_share / 2) as f64) as u64; + let founder_emission = founder_incentive_emission + founder_dividend_emission; - - - + println!("emissions: {:?}", emissions); + println!("dividends: {:?}", dividends); + println!("incentives: {:?}", incentives); + println!("founder_emission FAM: {:?}", founder_emission); + let calcualted_total_emission = emissions.iter().sum::(); + + let calculated_founder_share = SubspaceModule::get_stake_for_key(netuid, &founder_key) - + founder_stake_before - + founder_emission; + let delta: u64 = 1000; + + println!("expected_emission: {:?}", expected_emission); + println!("total_emission: {:?}", total_emission); + assert!(expected_emission > calcualted_total_emission - delta); + assert!(expected_emission < calcualted_total_emission + delta); + + println!("calculated_founder_share: {:?}", calculated_founder_share); + println!("expected_founder_share: {:?}", expected_founder_share); + assert!(expected_founder_share > calculated_founder_share - delta); + assert!(expected_founder_share < calculated_founder_share + delta); + }); +} diff --git a/pallets/subspace/tests/test_subnets.rs b/pallets/subspace/tests/test_subnets.rs index e84bfa8eb..3ed0a9989 100644 --- a/pallets/subspace/tests/test_subnets.rs +++ b/pallets/subspace/tests/test_subnets.rs @@ -6,8 +6,8 @@ use frame_support::{ use frame_system::Config; use pallet_subspace::Error; use sp_core::U256; -use test_mock::*; use sp_std::vec; +use test_mock::*; /* TO DO SAM: write test for LatuUpdate after it is set */ @@ -21,13 +21,12 @@ fn test_add_subnets() { let mut n = 20; let num_subnets: u16 = n; - - for i in 0..num_subnets{ + for i in 0..num_subnets { register_module(i, U256::from(i), stake_per_module); for j in 0..n { if j != i { let n = SubspaceModule::get_subnet_n(i); - println!("registering module i:{} j:{} n:{}", i,j,n); + println!("registering module i:{} j:{} n:{}", i, j, n); register_module(i, U256::from(j), stake_per_module); } } @@ -42,30 +41,27 @@ fn test_add_subnets() { expected_subnets, "number of subnets is not equal to expected subnets" ); - } - - for netuid in 0..num_subnets { let total_stake = SubspaceModule::get_total_subnet_stake(netuid); let total_balance = SubspaceModule::get_total_subnet_balance(netuid); let total_tokens_before = total_stake + total_balance; - + let keys = SubspaceModule::get_keys(netuid); println!("total stake {}", total_stake); println!("total balance {}", total_balance); println!("total tokens before {}", total_tokens_before); - assert_eq!(keys.len() as u16, n); assert!(SubspaceModule::check_subnet_storage(netuid)); SubspaceModule::remove_subnet(netuid); assert_eq!(SubspaceModule::get_subnet_n(netuid), 0); assert!(SubspaceModule::check_subnet_storage(netuid)); - let total_tokens_after: u64 = keys.iter().map(|key| SubspaceModule::get_balance_u64(key)).sum(); + let total_tokens_after: u64 = + keys.iter().map(|key| SubspaceModule::get_balance_u64(key)).sum(); println!("total tokens after {}", total_tokens_after); assert_eq!(total_tokens_after, total_tokens_before); @@ -75,14 +71,10 @@ fn test_add_subnets() { expected_subnets, "number of subnets is not equal to expected subnets" ); - - } - }); } - fn test_set_single_temple(tempo: u16) { new_test_ext().execute_with(|| { // creates a subnet when you register a module @@ -100,13 +92,10 @@ fn test_set_single_temple(tempo: u16) { let tempo = 5; let min_stake = 1_000_000_000; - let result = SubspaceModule::set_subnet_params( - netuid, - params.clone() - ); + let result = SubspaceModule::set_subnet_params(netuid, params.clone()); let subnet_params = SubspaceModule::subnet_params(netuid); - + assert_eq!(subnet_params.tempo, tempo); assert_eq!(subnet_params.min_stake, min_stake); assert_eq!(subnet_params.max_allowed_uids, params.max_allowed_uids); @@ -299,8 +288,14 @@ fn test_set_max_allowed_uids_shrinking() { assert_ok!(result); let params = SubspaceModule::subnet_params(netuid); let mut n = SubspaceModule::get_subnet_n(netuid); - assert_eq!(params.max_allowed_uids, max_uids, "max allowed uids is not equal to expected max allowed uids"); - assert_eq!(params.max_allowed_uids, n, "min allowed weights is not equal to expected min allowed weights"); + assert_eq!( + params.max_allowed_uids, max_uids, + "max allowed uids is not equal to expected max allowed uids" + ); + assert_eq!( + params.max_allowed_uids, n, + "min allowed weights is not equal to expected min allowed weights" + ); let mut new_total_subnet_balance: u64 = 0; for key in og_keys.clone() { @@ -308,15 +303,14 @@ fn test_set_max_allowed_uids_shrinking() { new_total_subnet_balance + SubspaceModule::get_balance_u64(&key); } // let expected_total_subnet_balance: u64 = - // (extra_uids as u64) * (stake + 1) + max_uids as u64; // this is weitd, but we needed to add 1 to make sure that the stake is not 0 - // assert!( + // (extra_uids as u64) * (stake + 1) + max_uids as u64; // this is weitd, but we needed to + // add 1 to make sure that the stake is not 0 assert!( // new_total_subnet_balance == expected_total_subnet_balance, // "new total subnet balance {} is not equal to expected total subnet balance {}", // new_total_subnet_balance, // expected_total_subnet_balance // ); - n = SubspaceModule::get_subnet_n(netuid); let stake_vector: Vec = SubspaceModule::get_stakes(netuid); let calc_stake: u64 = stake_vector.iter().sum(); @@ -343,50 +337,54 @@ fn test_set_max_allowed_modules() { SubspaceModule::set_max_allowed_modules(max_allowed_modules); // set max_total modules - - for i in 1..(2*max_allowed_modules ) { + + for i in 1..(2 * max_allowed_modules) { assert_ok!(register_module(netuid, U256::from(i), stake)); n = SubspaceModule::get_subnet_n(netuid); println!("{} {} {:?}", n, SubspaceModule::global_n(), SubspaceModule::netuids()); - assert!(n <= max_allowed_modules,"subnet_n {:?} is not less than max_allowed_modules {:?}", n, max_allowed_modules); + assert!( + n <= max_allowed_modules, + "subnet_n {:?} is not less than max_allowed_modules {:?}", + n, + max_allowed_modules + ); } }) - } - - #[test] - fn test_global_max_allowed_subnets() { - new_test_ext().execute_with(|| { - let max_allowed_subnets: u16 = 100; - - let mut params = SubspaceModule::global_params().clone(); - params.max_allowed_subnets = max_allowed_subnets; - SubspaceModule::set_global_params(params); - let params = SubspaceModule::global_params(); - assert_eq!(params.max_allowed_subnets, max_allowed_subnets); - let mut stake: u64 = 1_000_000_000; - - // set max_total modules - - for i in 1..(2*max_allowed_subnets ) { - let netuid = i as u16; - stake = stake + i as u64; - let least_staked_netuid = SubspaceModule::least_staked_netuid(); - - if i > 1 { - println!("least staked netuid {}", least_staked_netuid); - assert!(SubspaceModule::if_subnet_exist(least_staked_netuid)); - } +} - assert_ok!(register_module(netuid, U256::from(i), stake)); - let n_subnets = SubspaceModule::num_subnets(); +#[test] +fn test_global_max_allowed_subnets() { + new_test_ext().execute_with(|| { + let max_allowed_subnets: u16 = 100; + let mut params = SubspaceModule::global_params().clone(); + params.max_allowed_subnets = max_allowed_subnets; + SubspaceModule::set_global_params(params); + let params = SubspaceModule::global_params(); + assert_eq!(params.max_allowed_subnets, max_allowed_subnets); + let mut stake: u64 = 1_000_000_000; - if i > max_allowed_subnets { - assert!(!SubspaceModule::if_subnet_exist(i)); - } - println!("n_subnets {}", n_subnets); - println!("max_allowed_subnets {}", max_allowed_subnets); - assert!(n_subnets <= max_allowed_subnets); + // set max_total modules + + for i in 1..(2 * max_allowed_subnets) { + let netuid = i as u16; + stake = stake + i as u64; + let least_staked_netuid = SubspaceModule::least_staked_netuid(); + + if i > 1 { + println!("least staked netuid {}", least_staked_netuid); + assert!(SubspaceModule::if_subnet_exist(least_staked_netuid)); } - }) - } \ No newline at end of file + + assert_ok!(register_module(netuid, U256::from(i), stake)); + let n_subnets = SubspaceModule::num_subnets(); + + if i > max_allowed_subnets { + assert!(!SubspaceModule::if_subnet_exist(i)); + } + println!("n_subnets {}", n_subnets); + println!("max_allowed_subnets {}", max_allowed_subnets); + assert!(n_subnets <= max_allowed_subnets); + } + }) +} diff --git a/pallets/subspace/tests/test_voting.rs b/pallets/subspace/tests/test_voting.rs index 0a406db42..6255430b8 100644 --- a/pallets/subspace/tests/test_voting.rs +++ b/pallets/subspace/tests/test_voting.rs @@ -6,232 +6,210 @@ use frame_support::{ use frame_system::Config; use pallet_subspace::Error; use sp_core::U256; -use test_mock::*; use sp_std::vec; +use test_mock::*; /* TO DO SAM: write test for LatuUpdate after it is set */ #[test] fn test_subnet_porposal() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let keys = vec![U256::from(0), U256::from(1), U256::from(2)]; - let stakes= vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; - - for (i, key) in keys.iter().enumerate() { - assert_ok!(register_module(netuid, *key, stakes[i])); - } - let mut params = SubspaceModule::subnet_params(netuid); - assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); - params.vote_mode = "stake".as_bytes().to_vec(); - println!("params: {:?}", params); - SubspaceModule::set_subnet_params(netuid, params.clone()); - let mut params = SubspaceModule::subnet_params(netuid); - let initial_tempo = params.tempo; - let final_tempo = 1000; - params.tempo = final_tempo; - - - - assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); - assert_ok!(SubspaceModule::do_add_subnet_proposal( - get_origin(keys[0]), - netuid, - params - )); - // we have not passed the threshold yet - let proposals = SubspaceModule::get_subnet_proposals(netuid); - - println!("proposals: {:?}", proposals); - - assert_eq!(proposals.len(), 1, "proposal not added"); - assert_eq!(proposals[0].votes, stakes[0], "proposal not added"); - - let proposal = SubspaceModule::get_proposal(0); - assert_eq!(proposal.netuid, netuid, "proposal not added"); - assert_eq!(proposal.accepted, false, "proposal not added"); - // now vote for the proposal - - assert_ok!(SubspaceModule::vote_proposal(get_origin(keys[1]), 0)); - let proposal = SubspaceModule::get_proposal(0); - assert_eq!(proposal.votes, stakes[0] + stakes[1], "proposal not voted"); - assert_eq!(proposal.accepted, true, "proposal not voted"); - - println!("proposal: {:?}", proposal); - - let params = SubspaceModule::subnet_params(netuid); - assert_eq!(params.tempo, final_tempo, "proposal not voted"); + new_test_ext().execute_with(|| { + let netuid = 0; + let keys = vec![U256::from(0), U256::from(1), U256::from(2)]; + let stakes = vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; - }); - -} - -#[test] -fn test_max_proposals() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let n = 100; - let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); - let mut stakes= vec![1_000_000_000; n]; - // increase incrementally to avoid overflow - let mut stakes = stakes.iter_mut().enumerate().map(|(i, x)| *x + i as u64).collect::>(); - - for (i, key) in keys.iter().enumerate() { - assert_ok!(register_module(netuid, *key, stakes[i])); - } - - let mut params = SubspaceModule::global_params(); - assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); - params.vote_mode = "stake".as_bytes().to_vec(); - params.max_proposals = (n / 2) as u64; - println!("params: {:?}", params); - SubspaceModule::set_global_params(params.clone()); - - assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); - let max_proposals = SubspaceModule::get_max_proposals(); - let modes = ["authority".as_bytes().to_vec(), "stake".as_bytes().to_vec()]; - - let mut subnet_params = SubspaceModule::subnet_params(netuid); - subnet_params.vote_mode = "stake".as_bytes().to_vec(); - SubspaceModule::set_subnet_params(netuid, subnet_params.clone()); - subnet_params = SubspaceModule::subnet_params(netuid); - assert_eq!(subnet_params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); - - for i in 0..n { - if i % 2 == 0 { - assert_ok!(SubspaceModule::do_add_global_proposal(get_origin(keys[i as usize]), params.clone())); - } else { - assert_ok!(SubspaceModule::do_add_subnet_proposal(get_origin(keys[i as usize]), netuid, subnet_params.clone())); - } - let num_proposals = SubspaceModule::num_proposals(); - let proposals = SubspaceModule::get_global_proposals(); - let has_max_proposals = SubspaceModule::has_max_proposals(); - // assert_eq!(max_proposals, (n - 1) as u64, "proposal not added"); - println!("max_proposals: {:?}", max_proposals); - println!("has_max_proposals: {:?}", has_max_proposals); - println!("num_proposals: {:?}", num_proposals); - println!("proposals: {:?}", proposals.len()); - - let num_subnet_proposals = SubspaceModule::num_subnet_proposals(netuid); - let num_global_proposals = SubspaceModule::num_global_proposals(); - assert_eq!(num_subnet_proposals + num_global_proposals, num_proposals, "proposal not added"); - - if num_proposals >= max_proposals { - assert_eq!(SubspaceModule::has_max_proposals(), true, "proposal not added"); - } else { - assert_eq!(SubspaceModule::has_max_proposals(), false, "proposal not added"); + for (i, key) in keys.iter().enumerate() { + assert_ok!(register_module(netuid, *key, stakes[i])); } + let mut params = SubspaceModule::subnet_params(netuid); + assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); + params.vote_mode = "stake".as_bytes().to_vec(); + println!("params: {:?}", params); + SubspaceModule::set_subnet_params(netuid, params.clone()); + let mut params = SubspaceModule::subnet_params(netuid); + let initial_tempo = params.tempo; + let final_tempo = 1000; + params.tempo = final_tempo; + + assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); + assert_ok!(SubspaceModule::do_add_subnet_proposal(get_origin(keys[0]), netuid, params)); + // we have not passed the threshold yet + let proposals = SubspaceModule::get_subnet_proposals(netuid); - assert!(proposals.len() as u64 <= max_proposals, "proposal not added"); - } + println!("proposals: {:?}", proposals); - assert_eq!(SubspaceModule::has_max_proposals(), true, "proposal not added"); - assert_eq!(SubspaceModule::num_proposals(), max_proposals, "proposal not added"); + assert_eq!(proposals.len(), 1, "proposal not added"); + assert_eq!(proposals[0].votes, stakes[0], "proposal not added"); + let proposal = SubspaceModule::get_proposal(0); + assert_eq!(proposal.netuid, netuid, "proposal not added"); + assert_eq!(proposal.accepted, false, "proposal not added"); + // now vote for the proposal + assert_ok!(SubspaceModule::vote_proposal(get_origin(keys[1]), 0)); + let proposal = SubspaceModule::get_proposal(0); + assert_eq!(proposal.votes, stakes[0] + stakes[1], "proposal not voted"); + assert_eq!(proposal.accepted, true, "proposal not voted"); - }); + println!("proposal: {:?}", proposal); + let params = SubspaceModule::subnet_params(netuid); + assert_eq!(params.tempo, final_tempo, "proposal not voted"); + }); } +#[test] +fn test_max_proposals() { + new_test_ext().execute_with(|| { + let netuid = 0; + let n = 100; + let keys: Vec = (0..n).into_iter().map(|x| U256::from(x)).collect(); + let mut stakes = vec![1_000_000_000; n]; + // increase incrementally to avoid overflow + let mut stakes = + stakes.iter_mut().enumerate().map(|(i, x)| *x + i as u64).collect::>(); + + for (i, key) in keys.iter().enumerate() { + assert_ok!(register_module(netuid, *key, stakes[i])); + } + let mut params = SubspaceModule::global_params(); + assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); + params.vote_mode = "stake".as_bytes().to_vec(); + params.max_proposals = (n / 2) as u64; + println!("params: {:?}", params); + SubspaceModule::set_global_params(params.clone()); + + assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); + let max_proposals = SubspaceModule::get_max_proposals(); + let modes = ["authority".as_bytes().to_vec(), "stake".as_bytes().to_vec()]; + + let mut subnet_params = SubspaceModule::subnet_params(netuid); + subnet_params.vote_mode = "stake".as_bytes().to_vec(); + SubspaceModule::set_subnet_params(netuid, subnet_params.clone()); + subnet_params = SubspaceModule::subnet_params(netuid); + assert_eq!(subnet_params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); + + for i in 0..n { + if i % 2 == 0 { + assert_ok!(SubspaceModule::do_add_global_proposal( + get_origin(keys[i as usize]), + params.clone() + )); + } else { + assert_ok!(SubspaceModule::do_add_subnet_proposal( + get_origin(keys[i as usize]), + netuid, + subnet_params.clone() + )); + } + let num_proposals = SubspaceModule::num_proposals(); + let proposals = SubspaceModule::get_global_proposals(); + let has_max_proposals = SubspaceModule::has_max_proposals(); + // assert_eq!(max_proposals, (n - 1) as u64, "proposal not added"); + println!("max_proposals: {:?}", max_proposals); + println!("has_max_proposals: {:?}", has_max_proposals); + println!("num_proposals: {:?}", num_proposals); + println!("proposals: {:?}", proposals.len()); + + let num_subnet_proposals = SubspaceModule::num_subnet_proposals(netuid); + let num_global_proposals = SubspaceModule::num_global_proposals(); + assert_eq!( + num_subnet_proposals + num_global_proposals, + num_proposals, + "proposal not added" + ); + + if num_proposals >= max_proposals { + assert_eq!(SubspaceModule::has_max_proposals(), true, "proposal not added"); + } else { + assert_eq!(SubspaceModule::has_max_proposals(), false, "proposal not added"); + } + + assert!(proposals.len() as u64 <= max_proposals, "proposal not added"); + } + assert_eq!(SubspaceModule::has_max_proposals(), true, "proposal not added"); + assert_eq!(SubspaceModule::num_proposals(), max_proposals, "proposal not added"); + }); +} #[test] fn test_global_porposal() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let keys = vec![U256::from(1), U256::from(2), U256::from(3)]; - let stakes= vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; - - // register on seperate subnets - for (i, key) in keys.iter().enumerate() { - register_module(netuid + i as u16 , *key, stakes[i]); - } - - let mut params = SubspaceModule::global_params(); - let initial_max_registrations_per_block = params.max_registrations_per_block; - let max_registrations_per_block = 1000; - - params.max_registrations_per_block = max_registrations_per_block; - assert_ok!(SubspaceModule::do_add_global_proposal(get_origin(keys[0]), - params - )); - - - - // we have not passed the threshold yet - let proposals = SubspaceModule::get_global_proposals(); - - assert_eq!(proposals.len(), 1, "proposal not added"); - assert_eq!(proposals[0].votes, stakes[0], "proposal not added"); - - let proposal = SubspaceModule::get_proposal(0); - assert_eq!(proposal.accepted, false, "proposal not added"); + new_test_ext().execute_with(|| { + let netuid = 0; + let keys = vec![U256::from(1), U256::from(2), U256::from(3)]; + let stakes = vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; + + // register on seperate subnets + for (i, key) in keys.iter().enumerate() { + register_module(netuid + i as u16, *key, stakes[i]); + } - // now vote for the proposal + let mut params = SubspaceModule::global_params(); + let initial_max_registrations_per_block = params.max_registrations_per_block; + let max_registrations_per_block = 1000; - assert_ok!(SubspaceModule::vote_proposal(get_origin(keys[1]), 0)); - let proposal = SubspaceModule::get_proposal(0); - assert_eq!(proposal.votes, stakes[0] + stakes[1], "proposal not voted"); - assert_eq!(proposal.accepted, true, "proposal not voted"); + params.max_registrations_per_block = max_registrations_per_block; + assert_ok!(SubspaceModule::do_add_global_proposal(get_origin(keys[0]), params)); - println!("proposal: {:?}", proposal); + // we have not passed the threshold yet + let proposals = SubspaceModule::get_global_proposals(); - let params = SubspaceModule::global_params(); - assert_eq!(params.max_registrations_per_block, max_registrations_per_block, "proposal not voted"); + assert_eq!(proposals.len(), 1, "proposal not added"); + assert_eq!(proposals[0].votes, stakes[0], "proposal not added"); + let proposal = SubspaceModule::get_proposal(0); + assert_eq!(proposal.accepted, false, "proposal not added"); - }); + // now vote for the proposal -} + assert_ok!(SubspaceModule::vote_proposal(get_origin(keys[1]), 0)); + let proposal = SubspaceModule::get_proposal(0); + assert_eq!(proposal.votes, stakes[0] + stakes[1], "proposal not voted"); + assert_eq!(proposal.accepted, true, "proposal not voted"); + println!("proposal: {:?}", proposal); + let params = SubspaceModule::global_params(); + assert_eq!( + params.max_registrations_per_block, max_registrations_per_block, + "proposal not voted" + ); + }); +} #[test] fn test_unvote() { - new_test_ext().execute_with(|| { - - let netuid = 0; - let keys = vec![U256::from(0), U256::from(1), U256::from(2)]; - let stakes= vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; - - for (i, key) in keys.iter().enumerate() { - assert_ok!(register_module(netuid, *key, stakes[i])); - } - let mut params = SubspaceModule::subnet_params(netuid); - assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); - params.vote_mode = "stake".as_bytes().to_vec(); - println!("params: {:?}", params); - SubspaceModule::set_subnet_params(netuid, params.clone()); - let mut params = SubspaceModule::subnet_params(netuid); - let initial_tempo = params.tempo; - let final_tempo = 1000; - params.tempo = final_tempo; - - assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); - assert_ok!(SubspaceModule::do_add_subnet_proposal(get_origin(keys[0]), netuid, - params - - )); - assert!(SubspaceModule::proposal_exists(0)); - assert!(SubspaceModule::is_proposal_owner(&keys[0], 0)); - assert_ok!(SubspaceModule::unvote_proposal(get_origin(keys[0]))); - - // we have not passed the threshold yet - let proposals = SubspaceModule::get_subnet_proposals(netuid); - - println!("proposals: {:?}", proposals); - - assert_eq!(proposals.len(), 0, "proposal not added"); - - }); - -} + new_test_ext().execute_with(|| { + let netuid = 0; + let keys = vec![U256::from(0), U256::from(1), U256::from(2)]; + let stakes = vec![1_000_000_000, 1_000_000_000, 1_000_000_000]; + for (i, key) in keys.iter().enumerate() { + assert_ok!(register_module(netuid, *key, stakes[i])); + } + let mut params = SubspaceModule::subnet_params(netuid); + assert_eq!(params.vote_mode, "authority".as_bytes().to_vec(), "vote mode not set"); + params.vote_mode = "stake".as_bytes().to_vec(); + println!("params: {:?}", params); + SubspaceModule::set_subnet_params(netuid, params.clone()); + let mut params = SubspaceModule::subnet_params(netuid); + let initial_tempo = params.tempo; + let final_tempo = 1000; + params.tempo = final_tempo; + + assert_eq!(params.vote_mode, "stake".as_bytes().to_vec(), "vote mode not set"); + assert_ok!(SubspaceModule::do_add_subnet_proposal(get_origin(keys[0]), netuid, params)); + assert!(SubspaceModule::proposal_exists(0)); + assert!(SubspaceModule::is_proposal_owner(&keys[0], 0)); + assert_ok!(SubspaceModule::unvote_proposal(get_origin(keys[0]))); + // we have not passed the threshold yet + let proposals = SubspaceModule::get_subnet_proposals(netuid); + println!("proposals: {:?}", proposals); + assert_eq!(proposals.len(), 0, "proposal not added"); + }); +} diff --git a/pallets/subspace/tests/weights.rs b/pallets/subspace/tests/weights.rs index ac1c2e632..6301c8f2a 100644 --- a/pallets/subspace/tests/weights.rs +++ b/pallets/subspace/tests/weights.rs @@ -14,8 +14,6 @@ use test_mock::*; pub fn set_weights() tests *****************************/ - - // Test ensures that uids -- weights must have the same size. #[test] fn test_weights_err_weights_vec_not_equal_size() { diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index d9d9f64ca..d37e9fec1 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] pallet-subspace = { version = "4.0.0-dev", default-features = false, path = "../pallets/subspace" } -subspace-runtime-api = { path = "../pallets/subspace/rpc/runtime-api", default-features = false } +subspace-runtime-api = { path = "../pallets/subspace/runtime-api", default-features = false } codec.workspace = true scale-info.workspace = true diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 8915f88e3..596d7607b 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -7,7 +7,7 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -use codec::{Encode, Decode}; +use codec::{Decode, Encode}; use pallet_grandpa::{ fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; @@ -18,21 +18,22 @@ use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{ - crypto::{KeyTypeId, ByteArray}, + crypto::{ByteArray, KeyTypeId}, OpaqueMetadata, H160, H256, U256, }; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ - AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify, - Dispatchable, IdentityLookup, PostDispatchInfoOf, UniqueSaturatedInto, DispatchInfoOf + AccountIdLookup, BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, + IdentifyAccount, IdentityLookup, NumberFor, One, PostDispatchInfoOf, UniqueSaturatedInto, + Verify, }, transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, - ApplyExtrinsicResult, MultiSignature, ConsensusEngineId, + ApplyExtrinsicResult, ConsensusEngineId, MultiSignature, }; use sp_std::{marker::PhantomData, prelude::*}; -use subspace_runtime_api::{ ModuleInfo, ModuleStats, ModuleParams }; +use subspace_runtime_api::{ModuleInfo, ModuleParams, ModuleStats}; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -42,12 +43,13 @@ use sp_version::RuntimeVersion; pub use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, KeyOwnerProofSystem, Randomness, - StorageInfo, FindAuthor, OnFinalize + ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, FindAuthor, KeyOwnerProofSystem, + OnFinalize, Randomness, StorageInfo, }, weights::{ constants::{ - BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, WEIGHT_REF_TIME_PER_MILLIS + BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_MILLIS, + WEIGHT_REF_TIME_PER_SECOND, }, IdentityFee, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, @@ -72,9 +74,7 @@ use fp_rpc::TransactionStatus; use pallet_ethereum::{ Call::transact, PostLogContent, Transaction as EthereumTransaction, TransactionAction, }; -use pallet_evm::{ - Account as EVMAccount, FeeCalculator, Runner, -}; +use pallet_evm::{Account as EVMAccount, FeeCalculator, Runner}; pub mod precompiles; use precompiles::FrontierPrecompiles; @@ -344,10 +344,8 @@ impl pallet_subspace::Config for Runtime { // EVM Support pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000; -pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( - WEIGHT_MILLISECS_PER_BLOCK * WEIGHT_REF_TIME_PER_MILLIS, - u64::MAX, -); +pub const MAXIMUM_BLOCK_WEIGHT: Weight = + Weight::from_parts(WEIGHT_MILLISECS_PER_BLOCK * WEIGHT_REF_TIME_PER_MILLIS, u64::MAX); pub const MAXIMUM_BLOCK_LENGTH: u32 = 5 * 1024 * 1024; impl pallet_evm_chain_id::Config for Runtime {} @@ -518,7 +516,6 @@ pub type Executive = frame_executive::Executive< AllPalletsWithSystem, >; - impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; @@ -555,9 +552,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - } + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -567,11 +563,10 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))) - } + ))), _ => None, } } @@ -803,7 +798,7 @@ impl_runtime_apis! { access_list: Option)>>, ) -> Result { use pallet_evm::GasWeightMapping; - + let config = if estimate { let mut config = ::config().clone(); config.estimate = true; diff --git a/runtime/src/precompiles.rs b/runtime/src/precompiles.rs index c312fe0af..5b753ac7a 100644 --- a/runtime/src/precompiles.rs +++ b/runtime/src/precompiles.rs @@ -18,17 +18,7 @@ where Self(Default::default()) } pub fn used_addresses() -> impl Iterator { - sp_std::vec![ - 1, - 2, - 3, - 4, - 5, - 1024, - 1025, - ] - .into_iter() - .map(hash) + sp_std::vec![1, 2, 3, 4, 5, 1024, 1025,].into_iter().map(hash) } } impl PrecompileSet for FrontierPrecompiles @@ -60,4 +50,4 @@ where fn hash(a: u64) -> H160 { H160::from_low_u64_be(a) -} \ No newline at end of file +}